diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index f1e29d1..6d83c16 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -92,8 +92,12 @@ STT, LLM and TTS lines go to `stt`, `llm`, `tts` by their worker category), `bro The dashboard's start and stop buttons, and the app binary itself, run the services through one `Controller` for the data folder: states `stopped`, `starting`, `running`, `stopping`, `failed` -(with the error, secrets masked). `start` from stopped or failed only, `stop` from running only; -`restart` is stop then start. A start that fails leaves nothing running. Starting reads the +(with the error, secrets masked). `start` from stopped or failed only, `stop` from running or +starting; `restart` is stop then start. A start that fails leaves nothing running. A stop while +starting cancels the start (the LLM's model download or load stops and its server is cleared) and +ends in `stopped` without an error; if the start finished anyway, what came up is stopped again. +The screens' `service_start` and `service_restart` return at once and the start runs in the +background (the first start downloads the model); the dashboard shows how it goes. Starting reads the settings and the stored token again, so saved changes take effect on the next start. Each start gets a new dashboard fed by that run's events; `stop` ends the feeding (and waits for it) before the dashboard is forgotten, so an event queued before the stop, or sent by an earlier run, never @@ -121,6 +125,9 @@ reaches the screen. who, why and how long ago, never the text. - `system`: memory in use and total, and per NVIDIA GPU its use and VRAM (from `nvidia-smi`, missing when there is none); sampled when the snapshot is taken, at most once a second. +- `llm`: the LLM's state (`off`, `starting`, `ready`, `failed`), whether the app runs it + (`managed`), and while starting Strata's last line and last percentage (the model download), + also before the services are up; a failure's reason in `note`. - `performance`: the performance stage (normal, gaming, paused, and why) comes with game detection in M7; until then `null`. @@ -142,8 +149,7 @@ on the game PC (`scripts/m0`). The steps, in order: | `strata` | Strata's own installer (`install.ps1`, `install.sh` elsewhere) with Strata's state, engine and components under `runtime/strata` and no PATH change | | `settings` | `voiceWorker` in the settings pointed at the worker venv's Python with `--melo-python --history memory/history.sqlite --brain` (other settings kept); the install is done only once this is written | -The LLM itself (Qwen3.6-35B-A3B, about 23 GB) is downloaded by Strata on its first start, which the -app runs next (M5, later step). +The LLM itself (Qwen3.6-35B-A3B, about 23 GB) is downloaded by Strata on its first start (below). - A finished step leaves `runtime/.done/` holding its version (the pin; for `worker_env` a hash of its requirement files), so later runs skip it and a new pin runs it again. Steps run one at a @@ -162,6 +168,33 @@ app runs next (M5, later step). +## LLM (`app/src/strata.rs`) + +The brain answers with one model, Qwen3.6-35B-A3B UD-Q4_K_XL through Strata (M0). The services +start it first, so nothing answers before the brain can, and stop it last. + +- **Strata from the data folder** (the default): `strata launch --family qwen36 --model ud-q4_k_xl + --data-dir models/llm --context --vision off --parallel --access local --port + --no-api-key --restart --yes --no-tui`, run like an install command (the layout's + environment, `runtime/strata` as the working folder, one process group, lines to the `llm` log + tab). It downloads the model on the first start, starts the engine and returns; the app then + waits (up to 30 minutes) until `/v1/models` lists the model and takes its id. `--restart` + replaces a server left with other choices; the same choices are reused. `--parallel` is 1 (faster + on a 16 GB card, M0) and 2 when a chat channel answers every message, so its answers do not wait + behind voice answers. Pictures are off until something in v2 sends one. Stopping the services + runs `strata launch --stop`; so does a failed or cancelled start, so nothing half-started keeps + graphics memory. Not installed: the start fails and says to run the install. +- **A server the app does not start**: with `llm.url` (an OpenAI-compatible `/v1` address, in the + settings file only) the app starts nothing; that server must list a model within 30 seconds. +- **Settings**: `llm.context` (default 32768 tokens per request, 4096-262144) and `llm.port` + (default 8080) on the model screen; `llm.url` (default none). +- **The brain's settings**: on every start the app writes `config/brain.json` (it owns the file): + `ollama_base_url` the LLM's `/v1`, `ollama_chat_model` the listed id, `db_path` + `memory/jarvis.db`; the worker gets it as `JARVIS_CONFIG_PATH`. Loading it writes nothing to the + home folder. + +## 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 back as Korean messages for the screen. The Tauri shell passes the screens' `invoke("admin", {command, args})` to it; the development server (below) does the same over loopback HTTP. @@ -176,7 +209,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | `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 | -| `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot | +| `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot; start and restart run in the background, stop also cancels a start | | `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 | @@ -190,13 +223,14 @@ administrator. The log hub writes to the data folder's `logs/` as soon as a fold Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. All text is Korean. - **First-run wizard** (while `firstRun`): data folder (free space, warning under 200 GB), PC check, - the model to download (the download itself is step 4 of M5), Discord bot (token check with the + the model to download, Discord bot (token check with the Message Content state and the invite link, then save), server and auto-join voice channel - pickers, wake words, then start. The model step shows the install (each step's state, download + pickers, wake words, then start (which says the first start downloads the LLM). The model step shows the install (each step's state, download bytes and last line; start, cancel, retry) and goes on only once everything is installed. Each step reached is saved, so a reload or a restart resumes at that step; only the last step's start finishes it. A stored token lets the bot step go on without entering it again. -- **Dashboard**: the snapshot every second; the header with start, restart and stop is rebuilt +- **Dashboard**: the snapshot every second; while the LLM starts, a card with its percentage and + Strata's last line, and stop in the header; the header with start, restart and stop is rebuilt only when the state changes, so a click is never lost to the refresh. Every screen change starts a new generation: an answer that arrives after the user moved to another screen is dropped. - **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델): built from `settings_fields`; only @@ -218,7 +252,12 @@ back to its default, keeping unknown keys, refusing a bad value or a result `par without touching the file; secrets round trip, file permissions on Unix, masking; log tabs from categories, query filters and follow, files per day and retention, error report bounds, zip size cap, redaction of stored secrets and token-shaped text; the controller's state rules with a fake -service starter; the dashboard from made-up events (captions replaced and cleared, latency stages +service starter, a stop while starting (cancelled, or finished and stopped again); the LLM +(launch arguments from the settings and inside the data folder, the second request slot for a chat +channel answering everything, the download percentage, the brain's settings file, a given server +used without Strata, Strata missing, a fake Strata that reports progress, returns, serves and is +stopped, is cancelled during its download and cleared, or fails with its last line; 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 commands (first run: folder then token, the token never returned whole, the wizard resumed at its step until finished, log files and the zip from the folder choice on, settings and logs through diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index cce2855..9e98b63 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -9,7 +9,7 @@ use std::sync::{Arc, Mutex}; use serde_json::{json, Map, Value}; -use crate::control::{Controller, ServicesHost}; +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}; @@ -89,7 +89,7 @@ impl AdminApi { 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 { data_dir: dir.path().to_path_buf() })).clone()) + Ok(c.get_or_insert_with(|| Controller::new(ServicesHost::new(dir.path().to_path_buf()))).clone()) } pub async fn call(&self, command: &str, args: Value) -> Result { @@ -193,9 +193,21 @@ impl AdminApi { crate::settings_edit::apply(&self.dir()?.settings_file(), &changes).map_err(|e| e.0)?; Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running})) } - "service_start" => self.controller()?.start().await.map(|_| json!({"ok": true})), + // 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" | "service_restart" => { + let c = self.controller()?; + let restart = command == "service_restart"; + let ok = if restart { c.state() == State::Running } else { matches!(c.state(), State::Stopped | State::Failed) }; + if !ok { + return Err(format!("cannot {} while {:?}", if restart { "restart" } else { "start" }, c.state()).to_lowercase()); + } + tokio::spawn(async move { + let _ = if restart { c.restart().await } else { c.start().await }; + }); + Ok(json!({"ok": true})) + } "service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})), - "service_restart" => self.controller()?.restart().await.map(|_| json!({"ok": true})), "dashboard" => Ok(self.controller()?.snapshot().await), "logs_query" => { let tab = args.get("tab").and_then(Value::as_str).filter(|t| !t.is_empty() && *t != "all"); diff --git a/app/src/control.rs b/app/src/control.rs index a394ddb..73e0329 100644 --- a/app/src/control.rs +++ b/app/src/control.rs @@ -37,6 +37,13 @@ pub trait Host: Send + Sync + 'static { async fn start(&self) -> Result<(Arc, mpsc::UnboundedReceiver), String>; /// Stored secrets, masked in error messages. fn secrets(&self) -> Vec; + /// Stop a start in progress (the LLM's first start downloads the model); `start` then returns + /// `Err("cancelled")` if it had not finished. + fn cancel_start(&self) {} + /// The LLM's state for the dashboard, also while starting. + fn llm(&self) -> Value { + Value::Null + } } struct Inner { @@ -47,6 +54,8 @@ struct Inner { /// one, so an event of an earlier run can never reach a later dashboard. dashboard: Arc>, feeder: Option>, + /// Stop was asked for while starting. + stop_asked: bool, } pub struct Controller { @@ -58,7 +67,7 @@ pub struct Controller { impl Controller { pub fn new(host: impl Host) -> Arc { Arc::new(Self { host: Box::new(host), inner: Mutex::new(Inner { state: State::Stopped, error: None, running: None, - dashboard: Arc::default(), feeder: None }), usage: tokio::sync::Mutex::new(None) }) + dashboard: Arc::default(), feeder: None, stop_asked: false }), usage: tokio::sync::Mutex::new(None) }) } pub fn state(&self) -> State { @@ -74,39 +83,62 @@ impl Controller { } i.state = State::Starting; i.error = None; + i.stop_asked = false; } crate::info_log!("app", "starting the services"); - match self.host.start().await { - Ok((running, mut events)) => { - let dash: Arc> = Arc::default(); - let d2 = dash.clone(); - let feeder = tokio::spawn(async move { - while let Some(ev) = events.recv().await { - d2.lock().unwrap().on_event(&ev, Instant::now()); + let started = self.host.start().await; + // The stop flag is read under the same lock that makes the state Running, so a stop asked + // for while starting is never lost. + let started = { + let mut i = self.inner.lock().unwrap(); + if std::mem::take(&mut i.stop_asked) { + i.state = State::Stopping; + started + } else { + return match started { + Ok((running, mut events)) => { + let dash: Arc> = Arc::default(); + let d2 = dash.clone(); + let feeder = tokio::spawn(async move { + while let Some(ev) = events.recv().await { + d2.lock().unwrap().on_event(&ev, Instant::now()); + } + }); + i.state = State::Running; + i.running = Some(running); + i.dashboard = dash; + i.feeder = Some(feeder); + Ok(()) } - }); - let mut i = self.inner.lock().unwrap(); - i.state = State::Running; - i.running = Some(running); - i.dashboard = dash; - i.feeder = Some(feeder); - Ok(()) - } - Err(e) => { - let e = crate::logs::redact(&e, &self.host.secrets()); - crate::error_log!("app", "the services did not start: {e}"); - let mut i = self.inner.lock().unwrap(); - i.state = State::Failed; - i.error = Some(e.clone()); - Err(e) + Err(e) => { + let e = crate::logs::redact(&e, &self.host.secrets()); + crate::error_log!("app", "the services did not start: {e}"); + i.state = State::Failed; + i.error = Some(e.clone()); + Err(e) + } + }; } + }; + // Stopped while starting: whatever came up goes down again. + if let Ok((running, _)) = started { + running.stop().await; } + self.inner.lock().unwrap().state = State::Stopped; + crate::info_log!("app", "start cancelled"); + Err("cancelled".into()) } - /// Stop from running; what was said is forgotten. + /// Stop from running, or cancel a start; what was said is forgotten. pub async fn stop(&self) -> Result<(), String> { let running = { let mut i = self.inner.lock().unwrap(); + if i.state == State::Starting { + i.stop_asked = true; + drop(i); + self.host.cancel_start(); + return Ok(()); + } if i.state != State::Running { return Err(format!("cannot stop while {:?}", i.state).to_lowercase()); } @@ -153,6 +185,7 @@ impl Controller { view["state"] = json!(state); view["error"] = json!(error); view["system"] = json!(self.system().await); + view["llm"] = self.host.llm(); view["performance"] = Value::Null; // game detection comes in M7 view } @@ -173,13 +206,21 @@ impl Controller { /// The real services from a data folder. pub struct ServicesHost { - pub data_dir: PathBuf, + data_dir: PathBuf, + llm: Arc, +} + +impl ServicesHost { + pub fn new(data_dir: PathBuf) -> Self { + let llm = Arc::new(crate::strata::Llm::new(&data_dir)); + Self { data_dir, llm } + } } #[async_trait] impl Host for ServicesHost { async fn start(&self) -> Result<(Arc, mpsc::UnboundedReceiver), String> { - let mut s = crate::services::start_services(&self.data_dir).await.map_err(|e| e.to_string())?; + let mut s = crate::services::start_services(&self.data_dir, self.llm.clone()).await.map_err(|e| e.to_string())?; let (tx, rx) = mpsc::unbounded_channel(); let mut events = std::mem::replace(&mut s.events, mpsc::unbounded_channel().1); tokio::spawn(async move { @@ -195,6 +236,14 @@ impl Host for ServicesHost { fn secrets(&self) -> Vec { crate::secrets::Secrets::new(&self.data_dir.join("config").join("secrets.dat")).values() } + + fn cancel_start(&self) { + self.llm.cancel(); + } + + fn llm(&self) -> Value { + json!(self.llm.status()) + } } #[async_trait] @@ -278,6 +327,56 @@ mod tests { (Controller::new(Shared(host.clone())), counts, host) } + /// A start that takes a while (the LLM's first start) and honours a cancel or ignores it. + struct SlowHost { + counts: Arc, + honours_cancel: bool, + cancelled: Arc, + } + #[async_trait] + impl Host for SlowHost { + async fn start(&self) -> Result<(Arc, mpsc::UnboundedReceiver), String> { + self.counts.starts.fetch_add(1, Ordering::SeqCst); + self.cancelled.store(false, Ordering::SeqCst); // as the LLM does: a cancel ends one start + for _ in 0..50 { + if self.honours_cancel && self.cancelled.load(Ordering::SeqCst) { + return Err("cancelled".into()); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + Ok((Arc::new(FakeRunning(self.counts.clone())), mpsc::unbounded_channel().1)) + } + fn secrets(&self) -> Vec { + vec![] + } + fn cancel_start(&self) { + self.cancelled.store(true, Ordering::SeqCst); + } + fn llm(&self) -> Value { + json!({"state": "starting", "percent": 12.5}) + } + } + + #[tokio::test] + async fn a_stop_while_starting_cancels_the_start_or_stops_what_came_up() { + for honours_cancel in [true, false] { + let counts = Arc::new(Counts::default()); + let c = Controller::new(SlowHost { counts: counts.clone(), honours_cancel, cancelled: Arc::default() }); + let c2 = c.clone(); + let start = tokio::spawn(async move { c2.start().await }); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(c.snapshot().await["llm"]["percent"], json!(12.5), "progress shows while starting"); + c.stop().await.unwrap(); + assert_eq!(start.await.unwrap().unwrap_err(), "cancelled"); + let s = c.snapshot().await; + assert_eq!((s["state"].clone(), s["error"].clone()), (json!("stopped"), Value::Null)); + // What came up anyway was stopped; a cancelled start left nothing to stop. + assert_eq!(counts.stops.load(Ordering::SeqCst), if honours_cancel { 0 } else { 1 }); + c.start().await.unwrap(); + assert_eq!(c.state(), State::Running, "it can start again"); + } + } + #[tokio::test] async fn start_and_stop_follow_the_state_rules() { let (c, counts, _) = controller(0); diff --git a/app/src/install.rs b/app/src/install.rs index 48310c9..52c288e 100644 --- a/app/src/install.rs +++ b/app/src/install.rs @@ -150,9 +150,21 @@ pub struct Ctx { status: Arc>>, index: usize, pub cancel: Arc, + /// The log tab its command lines go to. + tab: &'static str, } impl Ctx { + /// A context for commands outside the install (Strata's start and stop, `strata.rs`): their + /// lines go to log tab `tab`, the last one is `last_note`. + pub fn standalone(layout: Layout, tab: &'static str, cancel: Arc) -> Self { + let status = vec![StepStatus { id: tab.into(), label: String::new(), size_hint: String::new(), + state: StepState::Running, bytes: None, note: None }]; + Self { layout, status: Arc::new(Mutex::new(status)), index: 0, cancel, tab } + } + pub fn last_note(&self) -> Option { + self.status.lock().unwrap()[self.index].note.clone() + } pub fn note(&self, line: &str) { let line: String = line.chars().take(300).collect(); self.status.lock().unwrap()[self.index].note = Some(line); @@ -183,12 +195,12 @@ impl Ctx { cmd.process_group(0); let _ = std::fs::create_dir_all(self.layout.data.join("cache").join("tmp")); let name = program.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - crate::info_log!("install", "run {name} {}", args.first().copied().unwrap_or("")); + crate::info_log!(self.tab, "run {name} {}", args.first().copied().unwrap_or("")); let mut child = cmd.spawn().map_err(|e| format!("{name}을(를) 실행하지 못했습니다: {e}"))?; let (out, err) = (child.stdout.take().unwrap(), child.stderr.take().unwrap()); let last = Arc::new(Mutex::new(String::new())); let pump = |r: Box| { - let (last, status, index) = (last.clone(), self.status.clone(), self.index); + 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 { @@ -197,7 +209,7 @@ impl Ctx { continue; } if let Some(hub) = crate::logs::installed() { - hub.push(crate::logs::Level::Info, "install", &l); + hub.push(crate::logs::Level::Info, tab, &l); } status.lock().unwrap()[index].note = Some(l.chars().take(300).collect()); *last.lock().unwrap() = l; @@ -329,7 +341,8 @@ impl Installer { st[i].bytes = None; } crate::info_log!("install", "step {} started", step.id()); - let ctx = Ctx { layout: self.layout.clone(), status: self.status.clone(), index: i, cancel: self.cancel.clone() }; + let ctx = Ctx { layout: self.layout.clone(), status: self.status.clone(), index: i, cancel: self.cancel.clone(), + tab: "install" }; let result = step.run(&ctx).await; let mut st = self.status.lock().unwrap(); match result { @@ -657,7 +670,7 @@ mod tests { let i = Installer::new(l.clone(), vec![]); 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.clone(), status: status.clone(), index: 0, cancel: i.cancel.clone() }; + let ctx = Ctx { layout: l.clone(), status: status.clone(), index: 0, cancel: i.cancel.clone(), tab: "install" }; ctx.run(Path::new("sh"), &["-c", "echo one; echo two; echo $UV_CACHE_DIR"]).await.unwrap(); let note = status.lock().unwrap()[0].note.clone().unwrap(); assert!(note.ends_with("cache/uv") && note.starts_with(&l.data.to_string_lossy().to_string()), "{note}"); @@ -680,7 +693,7 @@ mod tests { let status = Arc::new(Mutex::new(vec![StepStatus { id: "x".into(), label: "".into(), size_hint: "".into(), state: StepState::Running, bytes: None, note: None }])); let cancel = Arc::new(AtomicBool::new(false)); - let ctx = Ctx { layout: l.clone(), status, index: 0, cancel: cancel.clone() }; + let ctx = Ctx { layout: l.clone(), status, index: 0, cancel: cancel.clone(), tab: "install" }; let pidfile = l.data.join("child.pid"); let script = format!("sleep 60 & echo $! > {}; wait", pidfile.display()); let c2 = cancel.clone(); @@ -709,7 +722,7 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); 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.clone(), status: status.clone(), index: 0, cancel: Arc::new(AtomicBool::new(false)) }; + let ctx = Ctx { layout: l.clone(), status: status.clone(), index: 0, cancel: Arc::new(AtomicBool::new(false)), tab: "install" }; ctx.run_in(Path::new("sh"), &["-c", "touch made && pwd"], Some(&dir)).await.unwrap(); assert!(dir.join("made").exists()); } diff --git a/app/src/lib.rs b/app/src/lib.rs index bc3fbe2..c199db3 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -23,6 +23,7 @@ pub mod services; pub mod settings; pub mod settings_edit; pub mod speakers; +pub mod strata; pub mod system; pub mod worker_client; pub mod worker_process; diff --git a/app/src/main.rs b/app/src/main.rs index 6b64e14..763432c 100644 --- a/app/src/main.rs +++ b/app/src/main.rs @@ -19,7 +19,7 @@ async fn main() { let hub = jarvis_app::logs::LogHub::new(Some(&logs_dir)); hub.set_secrets(jarvis_app::secrets::Secrets::new(&data_dir.join("config").join("secrets.dat")).values()); jarvis_app::logs::install(hub); - let controller = Controller::new(ServicesHost { data_dir }); + let controller = Controller::new(ServicesHost::new(data_dir)); if controller.start().await.is_err() { std::process::exit(1); } diff --git a/app/src/services.rs b/app/src/services.rs index bd2c51b..7311de5 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -1,7 +1,8 @@ -//! Starts everything the app runs: the voice worker process, the connection to it, and the Discord -//! core. Used by the app binary (and the Tauri shell from M5). +//! Starts everything the app runs: the LLM (`strata.rs`), the voice worker process, the connection +//! to it, and the Discord core. Used by the app binary (and the Tauri shell from M5). use std::path::Path; +use std::sync::Arc; use serde_json::Value; use tokio::sync::mpsc; @@ -9,6 +10,7 @@ use tokio::sync::mpsc; use crate::conversation::{self, Conversation}; use crate::discord::{CoreEvent, DiscordCore}; use crate::settings::load_settings; +use crate::strata::Llm; use crate::worker_client::{WorkerClient, WorkerClientOptions}; use crate::worker_process::{ProcessEvent, WorkerProcess, WorkerProcessOptions}; @@ -19,6 +21,7 @@ pub struct Services { pub worker_process: WorkerProcess, /// The conversation's missed requests, for the dashboard. pub missed: conversation::MissedLog, + pub llm: Arc, } impl Services { @@ -26,10 +29,13 @@ impl Services { self.core.close().await; self.worker.close(); self.worker_process.stop().await; + self.llm.stop().await; } } -pub async fn start_services(data_dir: &Path) -> Result> { +/// Start the services; the LLM first (its first start downloads the model), so nothing answers +/// before the brain can. A failure stops what already started. +pub async fn start_services(data_dir: &Path, llm: Arc) -> Result> { let settings = load_settings(&data_dir.join("config").join("settings.json"))?; // The stored token (the setup wizard keeps it encrypted, admin.spec.md), else the environment. let stored = crate::secrets::Secrets::new(&data_dir.join("config").join("secrets.dat")) @@ -39,6 +45,15 @@ pub async fn start_services(data_dir: &Path) -> Result std::env::var("JARVIS_DISCORD_TOKEN").map_err(|_| "no bot token: set it in the app or JARVIS_DISCORD_TOKEN")?, }; + let (base_url, model) = llm.start(&settings).await?; + let brain_config = match crate::strata::write_brain_config(data_dir, &base_url, &model) { + Ok(f) => f, + Err(e) => { + llm.stop().await; + return Err(format!("could not write the brain settings: {e}").into()); + } + }; + let w = &settings.voice_worker; let mut wopts = WorkerProcessOptions::new(&w.python, &w.cwd, w.args.clone()); // With the installed runtime, the worker's models, caches and temp files stay in the data folder. @@ -46,7 +61,14 @@ pub async fn start_services(data_dir: &Path) -> Result p, + Err(e) => { + llm.stop().await; + return Err(e.into()); + } + }; let mut process_events = worker_process.subscribe(); worker_process.start(); let mut opts = WorkerClientOptions::new(worker_process.url(), worker_process.token.clone()); @@ -79,8 +101,9 @@ pub async fn start_services(data_dir: &Path) -> Result, } +/// The LLM (admin.spec.md, "LLM"): the app starts Strata on `port`, or uses a server already +/// running at `url` (an OpenAI-compatible `/v1` address) and starts nothing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LlmSettings { + pub url: Option, + pub port: u16, + /// Tokens the model keeps at once (each request's share). + pub context: u32, +} + #[derive(Debug, Clone, PartialEq)] pub struct Settings { pub discord: DiscordSettings, @@ -84,6 +94,7 @@ pub struct Settings { /// The voice worker's memory settings (voice_worker.spec.md, "Memory settings"), sent in its /// `hello`; the worker validates them, the settings screens check them first (admin.spec.md). pub memory: Map, + pub llm: LlmSettings, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -126,6 +137,7 @@ impl Default for Settings { chat_wake_words: None, response: PolicySettings::default(), memory: Map::new(), + llm: LlmSettings { url: None, port: 8080, context: 32768 }, } } } @@ -399,9 +411,34 @@ pub fn parse_settings(raw: &Value) -> Result { Some(Value::Object(m)) => m.clone(), Some(_) => return err("memory must be an object"), }, + llm: parse_llm(raw, &d.llm)?, }) } +fn parse_llm(raw: &Map, d: &LlmSettings) -> Result { + let l = section(raw, "llm")?; + let url = match l.and_then(|m| m.get("url")) { + None | Some(Value::Null) => None, + Some(Value::String(s)) if s.starts_with("http://") || s.starts_with("https://") => Some(s.trim_end_matches('/').to_owned()), + Some(_) => return err("llm.url must be an http(s) address or null"), + }; + let port = match l.and_then(|m| m.get("port")) { + None => d.port, + Some(v) => match v.as_u64() { + Some(n @ 1024..=65535) => n as u16, + _ => return err("llm.port must be an integer 1024-65535"), + }, + }; + let context = match l.and_then(|m| m.get("context")) { + None => d.context, + Some(v) => match v.as_u64() { + Some(n @ 4096..=262144) => n as u32, + _ => return err("llm.context must be an integer 4096-262144"), + }, + }; + Ok(LlmSettings { url, port, context }) +} + /// Read and validate the settings file. A missing file means all defaults. pub fn load_settings(path: &Path) -> Result { let text = match std::fs::read_to_string(path) { diff --git a/app/src/settings_edit.rs b/app/src/settings_edit.rs index 3f8b63c..c068911 100644 --- a/app/src/settings_edit.rs +++ b/app/src/settings_edit.rs @@ -107,6 +107,9 @@ 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"), "받아 적을 언어(비우면 자동)"), + // 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 new file mode 100644 index 0000000..3871853 --- /dev/null +++ b/app/src/strata.rs @@ -0,0 +1,407 @@ +//! The LLM the brain answers with (`app/src/admin.spec.md`, "LLM"): the app starts the installed +//! Strata from the data folder with the M0 kit's choices, waits until the model answers, and stops +//! it with the services. Strata downloads the model (about 23 GB) on its first start; the dashboard +//! shows how far it got. With `llm.url` the app uses that server instead and starts nothing. + +use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use serde::Serialize; +use serde_json::{json, Value}; + +use crate::install::{Ctx, Layout}; +use crate::settings::Settings; + +/// The one model v2 runs (M0: Qwen3.6-35B-A3B UD-Q4_K_XL; docs/v2/roadmap.md). +pub const FAMILY: &str = "qwen36"; +pub const MODEL: &str = "ud-q4_k_xl"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum LlmState { + Off, + Starting, + Ready, + Failed, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LlmStatus { + pub state: LlmState, + /// Strata's own server (false: `llm.url`). + pub managed: bool, + /// The last percentage Strata printed while starting (the model download). + pub percent: Option, + /// Strata's last line while starting, or why it failed. + pub note: Option, +} + +/// Requests answered at once: one is faster on a 16 GB card (M0), two only when a chat channel +/// answers every message (so its answers do not wait behind the voice answers). +pub fn parallel(settings: &Settings) -> u32 { + if settings.chat_channels.iter().any(|c| c.answer_all) { 2 } else { 1 } +} + +/// `strata launch` for the services: the M0 kit's normal placement, models in `models/llm`, this +/// computer only. No pictures yet (nothing in v2 sends one; reading them takes graphics memory). +/// `--restart` replaces a server started with other choices; the same choices are reused. +pub fn launch_args(layout: &Layout, settings: &Settings) -> Vec { + let models = layout.data.join("models").join("llm").to_string_lossy().into_owned(); + let mut a: Vec = ["launch", "--family", FAMILY, "--model", MODEL, "--data-dir"].map(String::from).into(); + a.push(models); + for (k, v) in [("--context", settings.llm.context.to_string()), ("--vision", "off".into()), + ("--parallel", parallel(settings).to_string()), ("--access", "local".into()), + ("--port", settings.llm.port.to_string())] { + a.push(k.into()); + a.push(v); + } + a.extend(["--no-api-key", "--restart", "--yes", "--no-tui"].map(String::from)); + a +} + +/// The last `NN%` or `NN.N%` in a line. +pub fn percent(line: &str) -> Option { + let b = line.as_bytes(); + let mut found = None; + for (i, _) in line.match_indices('%') { + let mut s = i; + while s > 0 && (b[s - 1].is_ascii_digit() || b[s - 1] == b'.') { + s -= 1; + } + if let Ok(n) = line[s..i].parse::() { + if (0.0..=100.0).contains(&n) { + found = Some(n); + } + } + } + found +} + +/// Wait until `base` (`.../v1`) lists a model; returns its id. Stops early on `cancel`. +pub async fn wait_ready(base: &str, timeout: Duration, cancel: &AtomicBool) -> Result { + let client = reqwest::Client::builder().timeout(Duration::from_secs(5)).build().map_err(|e| e.to_string())?; + let until = Instant::now() + timeout; + loop { + if cancel.load(Ordering::Relaxed) { + return Err("cancelled".into()); + } + if let Ok(r) = client.get(format!("{base}/models")).send().await { + if let Ok(v) = r.text().await.map(|t| serde_json::from_str::(&t).unwrap_or_default()) { + if let Some(id) = v["data"][0]["id"].as_str() { + return Ok(id.to_owned()); + } + } + } + if Instant::now() >= until { + return Err(format!("대화 모델이 {}초 안에 준비되지 않았습니다 ({base})", timeout.as_secs())); + } + tokio::time::sleep(Duration::from_millis(500)).await; + } +} + +/// The brain's settings (`config/brain.json`, the worker's `JARVIS_CONFIG_PATH`): the LLM and the +/// memory database inside the data folder. The app owns this file and writes it on every start. +pub fn write_brain_config(data: &Path, base_url: &str, model: &str) -> Result { + let file = data.join("config").join("brain.json"); + let cfg = json!({ + "ollama_base_url": base_url, + "ollama_chat_model": model, + "db_path": data.join("memory").join("jarvis.db").to_string_lossy(), + "_config_version": 1, + }); + let mut text = serde_json::to_string_pretty(&cfg).unwrap(); + text.push('\n'); + crate::datadir::write_atomic(&file, text.as_bytes()).map_err(|e| e.to_string())?; + Ok(file) +} + +/// One LLM for the services: Strata from the layout, or the server at `llm.url`. +pub struct Llm { + layout: Layout, + /// The program run as Strata (the installed one; a script in tests). + exe: std::path::PathBuf, + status: Mutex, + active: Mutex>>, + cancel: Arc, +} + +/// How long the model may take to answer after `strata launch` returned (it loads in about 15 s +/// on the game PC; the first start may also tune). +const READY_TIMEOUT: Duration = Duration::from_secs(30 * 60); +/// A server the app does not start must already answer. +const URL_TIMEOUT: Duration = Duration::from_secs(30); + +impl Llm { + pub fn new(data: &Path) -> Self { + // Only the data folder matters here (the Python sources are the install's business). + let layout = Layout { data: data.to_path_buf(), src: std::path::PathBuf::new() }; + let exe = layout.strata_exe(); + Self::with_exe(layout, exe) + } + + pub fn with_exe(layout: Layout, exe: std::path::PathBuf) -> Self { + Self { layout, exe, status: Mutex::new(LlmStatus { state: LlmState::Off, managed: false, percent: None, note: None }), + active: Mutex::new(None), cancel: Arc::new(AtomicBool::new(false)) } + } + + pub fn status(&self) -> LlmStatus { + let mut s = self.status.lock().unwrap().clone(); + if let Some(ctx) = self.active.lock().unwrap().as_ref() { + s.note = ctx.last_note(); + if let Some(p) = s.note.as_deref().and_then(percent) { + // Kept in the status, so the bar does not vanish on a line without one. + self.status.lock().unwrap().percent = Some(p); + } + s.percent = self.status.lock().unwrap().percent; + } + s + } + + fn set(&self, state: LlmState, note: Option) { + let mut s = self.status.lock().unwrap(); + s.state = state; + if state != LlmState::Starting { + s.note = note; + } + } + + /// Start (or reuse) the LLM; returns its `/v1` address and model id. + pub async fn start(&self, settings: &Settings) -> Result<(String, String), String> { + self.cancel.store(false, Ordering::SeqCst); + let managed = settings.llm.url.is_none(); + *self.status.lock().unwrap() = LlmStatus { state: LlmState::Starting, managed, percent: None, note: None }; + let result = self.start_inner(settings).await; + match &result { + Ok((base, model)) => { + crate::info_log!("llm", "ready: {base} model={model}"); + self.set(LlmState::Ready, None); + } + Err(e) if e == "cancelled" => self.set(LlmState::Off, None), + Err(e) => { + crate::error_log!("llm", "did not start: {e}"); + self.set(LlmState::Failed, Some(e.clone())); + } + } + result + } + + async fn start_inner(&self, settings: &Settings) -> Result<(String, String), String> { + if let Some(url) = &settings.llm.url { + let model = wait_ready(url, URL_TIMEOUT, &self.cancel).await?; + return Ok((url.clone(), model)); + } + if !self.exe.exists() { + return Err("Strata가 설치되어 있지 않습니다. 마법사의 모델 단계에서 설치해 주세요".into()); + } + let ctx = Arc::new(Ctx::standalone(self.layout.clone(), "llm", self.cancel.clone())); + *self.active.lock().unwrap() = Some(ctx.clone()); + let args = launch_args(&self.layout, settings); + let refs: Vec<&str> = args.iter().map(String::as_str).collect(); + let home = self.layout.strata_home(); + let ran = ctx.run_in(&self.exe, &refs, Some(&home)).await; + let base = format!("http://127.0.0.1:{}/v1", settings.llm.port); + let ready = match ran { + Ok(()) => wait_ready(&base, READY_TIMEOUT, &self.cancel).await, + Err(e) => Err(e), + }; + *self.active.lock().unwrap() = None; + if ready.is_err() { + // Nothing half-started stays on the graphics card. + self.stop_server().await; + } + Ok((base, ready?)) + } + + /// Stop a start in progress (the download resumes on the next start). + pub fn cancel(&self) { + self.cancel.store(true, Ordering::SeqCst); + } + + /// Stop the server this app started (nothing for `llm.url`). + pub async fn stop(&self) { + let managed = self.status.lock().unwrap().managed; + if managed { + self.stop_server().await; + } + self.set(LlmState::Off, None); + } + + async fn stop_server(&self) { + if !self.exe.exists() { + return; + } + let ctx = Ctx::standalone(self.layout.clone(), "llm", Arc::new(AtomicBool::new(false))); + let home = self.layout.strata_home(); + let stop = ctx.run_in(&self.exe, &["launch", "--stop"], Some(&home)); + match tokio::time::timeout(Duration::from_secs(120), stop).await { + Ok(Ok(())) => { crate::info_log!("llm", "stopped"); } + Ok(Err(e)) => { crate::warn_log!("llm", "stop failed: {e}"); } + Err(_) => { crate::warn_log!("llm", "stop timed out"); } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::datadir::temp_dir; + use crate::settings::{parse_settings, ChatChannelSettings}; + + fn layout(tag: &str) -> Layout { + Layout { data: temp_dir(tag), src: std::path::PathBuf::from("src") } + } + + #[test] + fn the_launch_keeps_the_model_in_the_data_folder_and_follows_the_settings() { + let l = layout("llm1"); + let s = parse_settings(&json!({"llm": {"context": 16384, "port": 8099}})).unwrap(); + let a = launch_args(&l, &s); + let after = |k: &str| a[a.iter().position(|x| x == k).unwrap() + 1].clone(); + assert!(Path::new(&after("--data-dir")).starts_with(&l.data)); + assert_eq!((after("--context"), after("--port"), after("--parallel")), ("16384".into(), "8099".into(), "1".into())); + assert_eq!(after("--access"), "local"); + assert!(a.iter().any(|x| x == "--no-tui") && a.iter().any(|x| x == "--yes")); + } + + #[test] + fn a_chat_channel_answering_everything_gets_a_second_request_slot() { + 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 }); + assert_eq!(parallel(&s), 2); + } + + #[test] + fn the_progress_is_the_last_percentage_on_a_line() { + assert_eq!(percent("Downloading 3 of 5: 41.5% (9.6 GB of 23.1 GB)"), Some(41.5)); + assert_eq!(percent("50% done, now 75%"), Some(75.0)); + assert_eq!(percent("Loading the model… 15 s"), None); + } + + #[test] + fn the_brain_config_points_at_the_llm_and_keeps_memory_in_the_data_folder() { + let l = layout("llm2"); + let f = write_brain_config(&l.data, "http://127.0.0.1:8080/v1", "m").unwrap(); + let v: Value = serde_json::from_str(&std::fs::read_to_string(f).unwrap()).unwrap(); + assert_eq!(v["ollama_base_url"], "http://127.0.0.1:8080/v1"); + assert_eq!(v["ollama_chat_model"], "m"); + assert!(Path::new(v["db_path"].as_str().unwrap()).starts_with(&l.data)); + } + + /// A tiny `/v1/models` server answering with `id`, after `delay`. + async fn models_server(id: &'static str, delay: Duration) -> u16 { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let opened = Instant::now(); + tokio::spawn(async move { + while let Ok((mut s, _)) = listener.accept().await { + let mut buf = [0u8; 1024]; + let _ = s.read(&mut buf).await; + let body = if opened.elapsed() >= delay { format!(r#"{{"data":[{{"id":"{id}"}}]}}"#) } else { "{}".into() }; + let _ = s.write_all(format!("HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len()).as_bytes()).await; + } + }); + port + } + + #[tokio::test] + async fn a_given_server_is_used_without_starting_strata() { + let port = models_server("given-model", Duration::ZERO).await; + let l = layout("llm3"); + let llm = Llm::new(&l.data); + let s = parse_settings(&json!({"llm": {"url": format!("http://127.0.0.1:{port}/v1")}})).unwrap(); + let (base, model) = llm.start(&s).await.unwrap(); + assert_eq!((base.as_str(), model.as_str()), (format!("http://127.0.0.1:{port}/v1").as_str(), "given-model")); + assert_eq!(llm.status().state, LlmState::Ready); + assert!(!llm.status().managed); + } + + #[tokio::test] + async fn without_strata_installed_the_start_fails_with_a_reason() { + let llm = Llm::new(&layout("llm4").data); + let e = llm.start(&Settings::default()).await.unwrap_err(); + assert!(e.contains("Strata"), "{e}"); + assert_eq!(llm.status().state, LlmState::Failed); + assert_eq!(llm.status().note.as_deref(), Some(e.as_str())); + } + + /// A fake `strata`: `launch --stop` records itself; `launch ...` prints progress and returns. + #[cfg(unix)] + fn fake_strata(l: &Layout, launch_body: &str) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let exe = l.data.join("fake-strata"); + std::fs::create_dir_all(l.strata_home()).unwrap(); + let log = l.data.join("calls"); + std::fs::write(&exe, format!("#!/bin/sh\necho \"$@\" >> '{}'\nif [ \"$2\" = --stop ]; then exit 0; fi\n{launch_body}\n", + log.display())).unwrap(); + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); + exe + } + + #[cfg(unix)] + #[tokio::test] + async fn strata_starts_reports_its_download_waits_for_the_model_and_stops() { + let port = models_server("qwen-test", Duration::from_millis(300)).await; + let l = layout("llm5"); + let exe = fake_strata(&l, "echo 'Downloading: 12.5%'; sleep 1; echo 'Downloading: 100%'; echo 'Strata is serving.'"); + let llm = Arc::new(Llm::with_exe(l.clone(), exe)); + let s = parse_settings(&json!({"llm": {"port": port}})).unwrap(); + let l2 = llm.clone(); + let s2 = s.clone(); + let run = tokio::spawn(async move { l2.start(&s2).await }); + let mut seen = None; + for _ in 0..40 { + tokio::time::sleep(Duration::from_millis(50)).await; + let st = llm.status(); + if st.percent.is_some() { + seen = Some(st); + break; + } + } + let st = seen.expect("progress while starting"); + assert_eq!((st.state, st.percent), (LlmState::Starting, Some(12.5))); + let (base, model) = run.await.unwrap().unwrap(); + assert_eq!((base, model.as_str()), (format!("http://127.0.0.1:{port}/v1"), "qwen-test")); + assert_eq!(llm.status().state, LlmState::Ready); + llm.stop().await; + let calls = std::fs::read_to_string(l.data.join("calls")).unwrap(); + assert!(calls.lines().next().unwrap().starts_with("launch --family"), "{calls}"); + assert_eq!(calls.lines().last(), Some("launch --stop")); + assert_eq!(llm.status().state, LlmState::Off); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_cancel_during_the_download_stops_it_and_clears_the_server() { + let l = layout("llm6"); + let exe = fake_strata(&l, "echo 'Downloading: 1%'; sleep 30"); + let llm = Arc::new(Llm::with_exe(l.clone(), exe)); + let l2 = llm.clone(); + let run = tokio::spawn(async move { l2.start(&Settings::default()).await }); + tokio::time::sleep(Duration::from_millis(400)).await; + let t = Instant::now(); + llm.cancel(); + assert_eq!(run.await.unwrap().unwrap_err(), "cancelled"); + assert!(t.elapsed() < Duration::from_secs(5)); + assert_eq!(llm.status().state, LlmState::Off); + let calls = std::fs::read_to_string(l.data.join("calls")).unwrap(); + assert_eq!(calls.lines().last(), Some("launch --stop")); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_failed_launch_shows_strata_s_last_line() { + let l = layout("llm7"); + let exe = fake_strata(&l, "echo 'Not enough disk space for the model' >&2; exit 4"); + let llm = Llm::with_exe(l, exe); + let e = llm.start(&Settings::default()).await.unwrap_err(); + assert!(e.contains("Not enough disk space"), "{e}"); + assert_eq!(llm.status().state, LlmState::Failed); + } +} diff --git a/app/tests/live_round_trip.rs b/app/tests/live_round_trip.rs index 3877064..fa61b1a 100644 --- a/app/tests/live_round_trip.rs +++ b/app/tests/live_round_trip.rs @@ -12,7 +12,7 @@ //! JARVIS_LIVE_ROUND_TRIP=1 JARVIS_LIVE_BOT_TOKEN=... JARVIS_LIVE_SPEAKER_TOKEN=... \ //! JARVIS_LIVE_GUILD= JARVIS_LIVE_VOICE_CHANNEL= \ //! JARVIS_VOICE_PYTHON= JARVIS_MELO_PYTHON= \ -//! JARVIS_CONFIG_PATH= \ +//! JARVIS_LIVE_LLM_URL= \ //! JARVIS_LIVE_QUESTIONS= [JARVIS_LIVE_ROUNDS=2] \ //! cargo test --release --test live_round_trip -- --nocapture //! @@ -28,6 +28,7 @@ use async_trait::async_trait; use jarvis_app::discord::CoreEvent; use jarvis_app::receive::{opus_payload, OpusFrames, SpeakerStream}; use jarvis_app::services::start_services; +use jarvis_app::strata::Llm; use jarvis_app::worker_client::{WorkerClient, WorkerClientOptions}; use serde_json::{json, Value}; use serenity::all::{ChannelId, Client, Context, EventHandler, GatewayIntents, GuildId, Ready, UserId}; @@ -174,7 +175,7 @@ async fn conversation_round_trip_on_real_discord() { let voice: u64 = env("JARVIS_LIVE_VOICE_CHANNEL").parse().unwrap(); let rounds: usize = std::env::var("JARVIS_LIVE_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(2); let questions = PathBuf::from(env("JARVIS_LIVE_QUESTIONS")); - env("JARVIS_CONFIG_PATH"); // the worker's brain reads it + env("JARVIS_LIVE_LLM_URL"); // the services point the brain at it (llm.url) let root = Path::new(env!("CARGO_MANIFEST_DIR")); // The speaker bot first: it checks the channel is free before anything joins. @@ -212,9 +213,10 @@ async fn conversation_round_trip_on_real_discord() { // The "person" here is a bot, so bots must be heard. "voice": {"listenToBots": true}, "voiceWorker": {"python": env("JARVIS_VOICE_PYTHON"), "cwd": root.join("../src"), "args": args}, + "llm": {"url": env("JARVIS_LIVE_LLM_URL")}, })).unwrap()).unwrap(); std::env::set_var("JARVIS_DISCORD_TOKEN", &bot_token); - let services = tokio::time::timeout(Duration::from_secs(300), start_services(&data)).await + let services = tokio::time::timeout(Duration::from_secs(300), start_services(&data, Arc::new(Llm::new(&data)))).await .expect("services start in time").expect("services start"); services.worker.wait_ready(Duration::from_secs(240)).await.expect("worker ready"); let core = services.core.clone(); diff --git a/app/ui/app.js b/app/ui/app.js index 5b423f5..dd29b1f 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -242,21 +242,33 @@ function dashboardHeader(d) { h("h1", { style: "margin:0" }, "대시보드"), h("div", { class: "row" }, h("span", { class: "badge " + cls }, label), d.state === "running" ? [act("service_restart", "다시 시작"), act("service_stop", "정지")] + : d.state === "starting" ? act("service_stop", "정지") : act("service_start", "시작", true))), d.error ? h("div", { class: "card", style: "border-color:var(--bad);margin-bottom:12px" }, d.error) : null); } +const LLM = { off: "꺼짐", starting: "준비 중", ready: "준비", failed: "실패" }; + function dashboardBody(d) { const med = d.latency?.median ?? {}; const s = (ms) => (ms == null ? "–" : (ms / 1000).toFixed(2) + "초"); const w = d.worker; + const llm = d.llm; + const pct = llm?.percent != null ? ` ${llm.percent}%` : ""; return h("div", {}, + llm?.state === "starting" ? h("div", { class: "card", style: "margin-bottom:12px" }, + h("h2", {}, "대화 모델 준비 중" + pct), + h("div", { class: "small muted" }, llm.managed + ? "처음 시작할 때는 대화 모델(약 23GB)을 받느라 오래 걸릴 수 있습니다. 그동안 정지할 수 있습니다." + : "설정한 대화 모델 서버의 응답을 기다리고 있습니다."), + llm.note ? h("div", { class: "small", style: "margin-top:6px;word-break:break-all" }, llm.note) : null) : null, h("div", { class: "grid" }, h("div", { class: "card" }, h("h2", {}, "연결"), h("div", { class: "kv" }, h("span", { class: "k" }, "디스코드"), h("span", {}, d.discord ?? "연결 안 됨"), h("span", { class: "k" }, "음성 워커"), h("span", {}, w ? (w.connected ? "연결됨" : "연결 안 됨") : "–"), h("span", { class: "k" }, "STT / TTS"), h("span", {}, w ? `${w.sttReady ? "준비" : "–"} / ${w.ttsReady ? "준비" : "–"}` : "–"), - h("span", { class: "k" }, "워커 재시작"), h("span", {}, w?.restarts ?? "–"))), + h("span", { class: "k" }, "워커 재시작"), h("span", {}, w?.restarts ?? "–"), + h("span", { class: "k" }, "대화 모델"), h("span", {}, llm ? (LLM[llm.state] ?? llm.state) : "–"))), h("div", { class: "card" }, h("h2", {}, "음성 채널"), h("div", {}, d.voiceChannel ? `채널 ${d.voiceChannel}` : "들어가 있지 않음"), h("div", { class: "small muted", style: "margin-top:6px" }, @@ -521,7 +533,7 @@ async function wizard(status) { })]; }, async () => [h("h2", {}, "준비됐습니다"), - h("p", {}, "시작하면 봇이 디스코드에 연결되고, 처음 시작할 때 서버에 슬래시 명령을 등록합니다."), + h("p", {}, "시작하면 대화 모델을 켜고 봇이 디스코드에 연결되며, 처음 시작할 때 서버에 슬래시 명령을 등록합니다. 처음에는 대화 모델(약 23GB)을 받아서 오래 걸립니다. 진행 상황은 대시보드에 나옵니다."), nav(true, async () => { try { await api("wizard_finish"); } catch (e) { return fail(e); } root.hidden = true; diff --git a/docs/llm_contexts.md b/docs/llm_contexts.md index 5bf85c0..90fad66 100644 --- a/docs/llm_contexts.md +++ b/docs/llm_contexts.md @@ -2,7 +2,7 @@ Every distinct LLM call in Jarvis, what feeds it, what consumes it, and how it is gated. This is the reference for optimising the app's main bottleneck (LLM latency). Keep it in sync with the code — see the note at the bottom. -**Transport (all contexts below).** `ollama_base_url` selects the API. A URL that ends in `/v1` (v2: Strata at `http://127.0.0.1:8080/v1`; also llama.cpp or Ollama's own `/v1`) uses the OpenAI-compatible API: chat goes to `/chat/completions`, embeddings to `/embeddings`, and the warm-up is a one-token chat completion. Any other URL uses Ollama's `/api/chat`, `/api/generate` and `/api/embeddings`. The conversion lives in `src/jarvis/llm.py` only: callers keep sending Ollama-shaped messages and reading Ollama-shaped responses (`message.content`, `message.tool_calls` with dict arguments, `message.thinking` from `reasoning_content`). On the OpenAI path `num_ctx` and `keep_alive` are not sent (the server owns its context size and residency), `num_predict` becomes `max_tokens`, and the thinking switch becomes `chat_template_kwargs.enable_thinking`. The `num_ctx: 8192` limits listed below apply to the Ollama path. Ollama's own `/v1` ignores `num_ctx` and runs at its default context (2,048 tokens here), which cuts the system prompt; to test the OpenAI path on Ollama use a model tag created with a larger `num_ctx`. A server with no embedding model (Strata) answers `/embeddings` with an error and every embedding consumer fails open to its text path. +**Transport (all contexts below).** `ollama_base_url` selects the API. A URL that ends in `/v1` (v2: Strata at `http://127.0.0.1:8080/v1`, which the app starts and writes with the model id Strata lists into the brain's `config/brain.json`, `app/src/strata.rs`; also llama.cpp or Ollama's own `/v1`) uses the OpenAI-compatible API: chat goes to `/chat/completions`, embeddings to `/embeddings`, and the warm-up is a one-token chat completion. Any other URL uses Ollama's `/api/chat`, `/api/generate` and `/api/embeddings`. The conversion lives in `src/jarvis/llm.py` only: callers keep sending Ollama-shaped messages and reading Ollama-shaped responses (`message.content`, `message.tool_calls` with dict arguments, `message.thinking` from `reasoning_content`). On the OpenAI path `num_ctx` and `keep_alive` are not sent (the server owns its context size and residency), `num_predict` becomes `max_tokens`, and the thinking switch becomes `chat_template_kwargs.enable_thinking`. The `num_ctx: 8192` limits listed below apply to the Ollama path. Ollama's own `/v1` ignores `num_ctx` and runs at its default context (2,048 tokens here), which cuts the system prompt; to test the OpenAI path on Ollama use a model tag created with a larger `num_ctx`. A server with no embedding model (Strata) answers `/embeddings` with an error and every embedding consumer fails open to its text path. --- diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index ba5b65a..f89d26d 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를 직접 띄우는 다음 부분에서 받음 | +| 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로 함 | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 | diff --git a/src/jarvis/config.py b/src/jarvis/config.py index 3e5233a..51db433 100644 --- a/src/jarvis/config.py +++ b/src/jarvis/config.py @@ -60,9 +60,10 @@ def _default_dictation_hotkey() -> str: return "ctrl+alt" -def _default_db_path() -> str: +def _default_db_path(create: bool = True) -> str: base = Path.home() / ".local" / "share" / "jarvis" - base.mkdir(parents=True, exist_ok=True) + if create: + base.mkdir(parents=True, exist_ok=True) return str(base / "jarvis.db") @@ -386,7 +387,9 @@ def get_default_config() -> Dict[str, Any]: """Returns the default configuration values.""" return { # Database & Storage - "db_path": _default_db_path(), + # Not created here: a config naming its own database (the v2 app's) writes nothing to the + # home folder; the database creates its folder when it opens (memory/db.py). + "db_path": _default_db_path(create=False), "sqlite_vss_path": None, # LLM & AI Models diff --git a/tests/test_config_db_path.py b/tests/test_config_db_path.py new file mode 100644 index 0000000..dfb4780 --- /dev/null +++ b/tests/test_config_db_path.py @@ -0,0 +1,28 @@ +"""A config that names its own database writes nothing to the home folder. + +The v2 app gives the brain a config (``JARVIS_CONFIG_PATH``) whose ``db_path`` is inside the app's +data folder (app/src/admin.spec.md, "LLM"); loading it must not create the default +``~/.local/share/jarvis`` folder as a side effect. +""" + +import json + +from jarvis.config import load_settings + + +def test_an_own_db_path_leaves_the_home_folder_alone(tmp_path, monkeypatch): + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + data = tmp_path / "data" + cfg = data / "config" / "brain.json" + cfg.parent.mkdir(parents=True) + db = data / "memory" / "jarvis.db" + cfg.write_text(json.dumps({"db_path": str(db), "_config_version": 1}), encoding="utf-8") + monkeypatch.setenv("JARVIS_CONFIG_PATH", str(cfg)) + + settings = load_settings() + + assert settings.db_path == str(db) + assert list(home.iterdir()) == []