diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 88fa627..37eb9f5 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -192,8 +192,8 @@ reaches the screen. percentage, or `X of Y GB` for the model download; none on a line without progress), also before the services are up; a failure's reason in `note`. - `game`: the game that game mode is on for, `{name, reason}` (below, "Game detection"), or null. -- `performance`: the performance stage (normal, gaming, paused, and why) comes next in M7; until - then `null`. +- `performance`: `{stage, gameRoomMib}` from the LLM: `normal`, `gaming` (with the graphics memory + the game gets) or `paused` (below, "Performance stages"); null before the services run. The dashboard's state is built from the core's events alone (`Dashboard::on_event` with the time), so it is tested with made-up events. @@ -336,7 +336,34 @@ elsewhere it never sees a game). It never looks at the game's screen. - `game` (new section): `detect` (게임 감지, on by default), `games` (programs that are games, as file names, ".exe" may be left out) and `notGames` (programs that are never games); each list at most 100 names, no folders; `otherRoomGb` (0-8, default 1), the graphics memory the normal - placement leaves for programs opened later (above, "LLM"). Read when the services start. + placement leaves for programs opened later (above, "LLM"); `reserveGb` (0-32, default 8), the + graphics memory a game gets; `revertSeconds` (0-600, default 30), how long after a game ends the + normal stage comes back; `pauseInGame` (default off), stop the LLM while a game runs. Read when + the services start. + +## Performance stages (`app/src/perf.rs`, `app/src/services.rs`) + +`docs/v2/pc-features.md`, "단계" and "전환 규칙". While the services run, the app moves the LLM +between the normal placement and the game placement as games come and go (not with `llm.url`). + +- The stage wanted (checked every second): a game (game mode on) means the game stage at once, or + pause with `pauseInGame`; when it ends the normal stage comes back once `revertSeconds` have + passed with no game, so quitting and starting a game again does not move the model back and + forth. +- A change: the brain is told the LLM switches, with a notice for the first spoken request that + waits ("잠깐만요, 게임 모드로 바꾸는 중이에요", or "잠깐만요, 평소 모드로 돌아가는 중이에요" on the way + back; `voice_worker.spec.md`, "LLM switches"); the app waits until the brain has written the + answers in progress (at most 2 minutes), restarts the LLM in the new stage and tells the brain + it is ready (or paused). A restart that fails leaves the LLM `failed` on the dashboard and the + brain ready (its calls then fail); the stage is not tried again until the wanted stage changes. +- The game stage: context 16,384 (or the settings' smaller one), one request at a time, half the + engine's CPU threads (read from its log at the normal start, else a quarter of the logical CPUs), + and the game placement (`placement.rs`: the reserve beside more than 2 GiB of experts, else + 2 GiB, else 0 GiB, else pause), measured once at that context like the normal one. Every + placement of a run counts other programs' memory as it was when the services started (before + the LLM and the STT worker), not from a card that then also holds the worker and the game. +- Pause: the LLM stops (`llm` off, "게임 중 일시정지"); the brain answers nothing until the stage + changes. - The foreground program is a game, in this order: in `notGames`: no; in `games`: yes (`registered`); a browser (also the bot's Chrome), video player, the desktop, Discord, a launcher's own window or this app: no; under a launcher's game folder (the folder after @@ -568,7 +595,11 @@ the bot's tab, the focus staying in the program the user types into, no taskbar left after the stop, and the uninstall leaving no device, driver package, registry key or settings folder. Game detection (`tests/game_watch.rs`): a program started from a Steam game folder (also under a path with non-ASCII letters) or from a Battle.net game's install folder (a test uninstall entry) -turns game mode on with its name and off once it ends. On every system: game detection's rules +turns game mode on with its name and off once it ends. Performance stages (on every system, with a fake +Strata and card): a game moves the LLM to the game placement (measured once at 16K and one request, +2 GiB on the game PC's numbers, half the 16 engine threads) and back after the wait, pause stops +it, a card with no room for a game pauses, and the stage loop tells the brain switching (with the +notice), waits, restarts and tells it ready, also on the way back. On every system: game detection's rules (a borderless game, a maximised program, a browser's full-screen video, exclusive full screen, launcher folders and their own windows, Battle.net games by install folder and their uninstall entries, non-ASCII paths, the person's lists first, staying on until the game ends, diff --git a/app/src/control.rs b/app/src/control.rs index 96dfabe..d0ee3d5 100644 --- a/app/src/control.rs +++ b/app/src/control.rs @@ -275,7 +275,7 @@ impl Controller { view["system"] = json!(self.system().await); view["llm"] = self.host.llm(); view["game"] = status.get("game").cloned().unwrap_or(Value::Null); - view["performance"] = Value::Null; // the performance stages come next in M7 + view["performance"] = status.get("performance").cloned().unwrap_or(Value::Null); view } @@ -364,6 +364,7 @@ impl Running for crate::services::Services { "missed": crate::dashboard::missed_view(&missed, now), "browser": self.browser.view(), "game": self.game.view(), + "performance": self.llm.stage_view(), }) } } diff --git a/app/src/game.rs b/app/src/game.rs index f393854..1fa5e15 100644 --- a/app/src/game.rs +++ b/app/src/game.rs @@ -236,6 +236,11 @@ impl GameWatch { Self { state, stop, thread: Mutex::new(thread) } } + /// Whether game mode is on. + pub fn on(&self) -> bool { + self.state.lock().unwrap().current().is_some() + } + /// The game for the dashboard: `{name, reason}` or null. pub fn view(&self) -> serde_json::Value { serde_json::json!(self.state.lock().unwrap().current()) @@ -479,7 +484,7 @@ mod tests { use super::*; fn settings() -> GameSettings { - GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0 } + GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0, reserve_gb: 8.0, revert_seconds: 30, pause_in_game: false } } fn fg(path: &str, covers: bool, no_frame: bool, gpu: f64) -> Foreground { diff --git a/app/src/lib.rs b/app/src/lib.rs index bb79957..bcdab14 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -21,6 +21,7 @@ pub mod frames; pub mod install; pub mod logs; pub mod playback; +pub mod perf; pub mod placement; pub mod policy; pub mod receive; diff --git a/app/src/perf.rs b/app/src/perf.rs new file mode 100644 index 0000000..b5604bf --- /dev/null +++ b/app/src/perf.rs @@ -0,0 +1,79 @@ +//! The performance stages (`docs/v2/pc-features.md`, "자동 성능 조절" and "전환 규칙"; admin.spec.md, +//! "Performance stages"): which placement the LLM should run in, from game mode and time. The +//! switching itself (waiting for the answer in progress, restarting the LLM) is `services.rs`. + +use std::time::{Duration, Instant}; + +use serde::Serialize; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Stage { + Normal, + Gaming, + /// The LLM is stopped while a game runs (chosen, or no placement leaves the game room). + Paused, +} + +/// Picks the stage: a game means the game stage (or pause when the person chose it) at once; after +/// the game ends the normal stage comes back only once `revert_after` has passed, so quitting and +/// starting a game again does not move the model back and forth. +#[derive(Debug)] +pub struct Perf { + revert_after: Duration, + pause_in_game: bool, + game_since_off: Option, + current: Stage, +} + +impl Perf { + pub fn new(revert_after: Duration, pause_in_game: bool) -> Self { + Self { revert_after, pause_in_game, game_since_off: None, current: Stage::Normal } + } + + /// The stage wanted now, given whether a game runs. + pub fn target(&mut self, game: bool, now: Instant) -> Stage { + if game { + self.game_since_off = None; + self.current = if self.pause_in_game { Stage::Paused } else { Stage::Gaming }; + } else if self.current != Stage::Normal { + let since = *self.game_since_off.get_or_insert(now); + if now.duration_since(since) >= self.revert_after { + self.current = Stage::Normal; + self.game_since_off = None; + } + } + self.current + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_game_switches_at_once_and_its_end_only_after_the_wait() { + let t = Instant::now(); + let s = |n: u64| t + Duration::from_secs(n); + let mut p = Perf::new(Duration::from_secs(30), false); + assert_eq!(p.target(false, s(0)), Stage::Normal); + assert_eq!(p.target(true, s(1)), Stage::Gaming); + // The game ends: still the game stage for 30 s. + assert_eq!(p.target(false, s(2)), Stage::Gaming); + assert_eq!(p.target(false, s(31)), Stage::Gaming); + // Started again within the wait: nothing moves, and the wait starts over at the next end. + assert_eq!(p.target(true, s(32)), Stage::Gaming); + assert_eq!(p.target(false, s(40)), Stage::Gaming); + assert_eq!(p.target(false, s(69)), Stage::Gaming); + assert_eq!(p.target(false, s(70)), Stage::Normal); + assert_eq!(p.target(false, s(500)), Stage::Normal); + } + + #[test] + fn with_pause_chosen_a_game_pauses_the_llm() { + let t = Instant::now(); + let mut p = Perf::new(Duration::ZERO, true); + assert_eq!(p.target(true, t), Stage::Paused); + assert_eq!(p.target(false, t), Stage::Normal); + } +} diff --git a/app/src/services.rs b/app/src/services.rs index 40cfc21..5874410 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -24,7 +24,9 @@ pub struct Services { pub llm: Arc, pub browser: BrowserRun, /// Game detection while the services run (admin.spec.md, "Game detection"). - pub game: crate::game::GameWatch, + pub game: Arc, + /// Moves the LLM between the performance stages as games come and go. + pub perf: std::sync::Mutex>>, } /// The bot browser of a run (admin.spec.md, "Bot browser"). @@ -61,6 +63,11 @@ impl BrowserRun { impl Services { /// Stop everything; an error means the LLM's server may still run. pub async fn stop(&self) -> Result<(), String> { + let perf = self.perf.lock().unwrap().take(); + if let Some(p) = perf { + p.abort(); + let _ = p.await; + } self.game.stop(); self.core.close().await; self.worker.close(); @@ -113,6 +120,7 @@ async fn start_browser(data_dir: &Path, settings: &crate::settings::Settings) -> pub async fn start_services(data_dir: &Path, llm: Arc) -> Result> { let settings = load_settings(&data_dir.join("config").join("settings.json"))?; let game_settings = settings.game.clone(); + let perf_settings = settings.clone(); // The stored token (the setup wizard keeps it encrypted, admin.spec.md), else the environment. let secrets = crate::secrets::Secrets::new(&data_dir.join("config").join("secrets.dat")); let stored = secrets.get(crate::secrets::DISCORD_TOKEN)?; @@ -193,8 +201,76 @@ pub async fn start_services(data_dir: &Path, llm: Arc) -> Result) -> bool; + async fn wait_llm_idle(&self, t: std::time::Duration) -> bool; +} + +#[async_trait::async_trait] +impl LlmBrain for WorkerClient { + fn llm_state(&self, state: &str, notice: Option<&str>) -> bool { + WorkerClient::llm_state(self, state, notice) + } + async fn wait_llm_idle(&self, t: std::time::Duration) -> bool { + WorkerClient::wait_llm_idle(self, t).await + } +} + +/// What a request that waits for a switch hears once (voice_worker.spec.md, "LLM switches"). +fn switch_notice(stage: crate::perf::Stage) -> Option<&'static str> { + match stage { + crate::perf::Stage::Gaming => Some("잠깐만요, 게임 모드로 바꾸는 중이에요"), + crate::perf::Stage::Normal => Some("잠깐만요, 평소 모드로 돌아가는 중이에요"), + crate::perf::Stage::Paused => None, + } +} + +/// The performance stages (admin.spec.md, "Performance stages"): every second the stage wanted +/// from game mode (`perf.rs`); a change tells the brain the LLM switches, waits until the answers +/// in progress are written (at most 2 minutes), restarts the LLM in that stage (or stops it to +/// pause) and tells the brain it is ready (or paused). With `llm.url` nothing moves. +async fn perf_loop(settings: crate::settings::Settings, llm: Arc, worker: Arc, game: Arc bool + Send + Sync>) { + use crate::perf::{Perf, Stage}; + if settings.llm.url.is_some() { + return; + } + let mut perf = Perf::new(std::time::Duration::from_secs(settings.game.revert_seconds.into()), settings.game.pause_in_game); + let mut applied = Stage::Normal; + loop { + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + let want = perf.target(game(), std::time::Instant::now()); + if want == applied { + continue; + } + crate::info_log!("perf", "performance stage: {want:?}"); + worker.llm_state("switching", switch_notice(want)); + if !worker.wait_llm_idle(std::time::Duration::from_secs(120)).await { + crate::warn_log!("perf", "Warning: the brain did not finish its answers in 2 minutes; switching anyway"); + } + // Wanted is what counts as applied: a game stage that ends paused is not tried again. + applied = want; + match llm.switch(&settings, want).await { + Ok(Stage::Paused) => { + worker.llm_state("paused", None); + } + Ok(_) => { + worker.llm_state("ready", None); + } + Err(e) => { + crate::error_log!("perf", "the LLM did not come back in the {want:?} stage: {e}"); + worker.llm_state("ready", None); + } + } + } } /// The secret values the services get: the bot token and the MCP servers' environment values. @@ -220,6 +296,70 @@ async fn after_llm_stop(llm: &Llm, error: String) -> String { } } +#[cfg(test)] +mod perf_tests { + use super::*; + use crate::strata::tests::{card, fake_placed, launches, layout, server_after_launch}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Mutex; + use std::time::Duration; + + #[derive(Default)] + struct FakeBrain(Mutex>); + + #[async_trait::async_trait] + impl LlmBrain for FakeBrain { + fn llm_state(&self, state: &str, notice: Option<&str>) -> bool { + self.0.lock().unwrap().push(format!("{state}{}", notice.map(|n| format!(": {n}")).unwrap_or_default())); + true + } + async fn wait_llm_idle(&self, _t: Duration) -> bool { + self.0.lock().unwrap().push("waited".into()); + true + } + } + + #[cfg(unix)] + #[tokio::test] + async fn a_game_moves_the_llm_to_the_game_stage_and_its_end_moves_it_back() { + let l = layout("perf-loop"); + let port = server_after_launch(&l, "list").await; + let llm = Arc::new(Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(card(&l, "GPU-test", 0))); + let s = crate::settings::parse_settings(&serde_json::json!({"llm": {"port": port}, "game": {"revertSeconds": 0}})).unwrap(); + llm.start(&s).await.unwrap(); + let brain = Arc::new(FakeBrain::default()); + let game = Arc::new(AtomicBool::new(false)); + let g = game.clone(); + let task = tokio::spawn(perf_loop(s, llm.clone(), brain.clone(), Arc::new(move || g.load(Ordering::SeqCst)))); + std::fs::remove_file(l.data.join("calls")).unwrap(); + game.store(true, Ordering::SeqCst); + let until = |want: &'static str| { + let brain = brain.clone(); + async move { + for _ in 0..200 { + if brain.0.lock().unwrap().iter().filter(|m| m.as_str() == want).count() > 0 { + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + panic!("never {want}: {:?}", brain.0.lock().unwrap()); + } + }; + until("ready").await; + assert_eq!(*brain.0.lock().unwrap(), ["switching: 잠깐만요, 게임 모드로 바꾸는 중이에요", "waited", "ready"]); + assert!(launches(&l).last().unwrap().contains("--context 16384"), "{:?}", launches(&l)); + assert_eq!(llm.stage_view()["stage"], serde_json::json!("gaming")); + // The game ends (no wait set): back to the normal stage. + brain.0.lock().unwrap().clear(); + game.store(false, Ordering::SeqCst); + until("ready").await; + assert_eq!(brain.0.lock().unwrap()[0], "switching: 잠깐만요, 평소 모드로 돌아가는 중이에요"); + assert!(launches(&l).last().unwrap().contains("--context 32768")); + assert_eq!(llm.stage_view()["stage"], serde_json::json!("normal")); + task.abort(); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/app/src/settings.rs b/app/src/settings.rs index bb5768b..124cd24 100644 --- a/app/src/settings.rs +++ b/app/src/settings.rs @@ -109,12 +109,22 @@ pub struct GameSettings { pub not_games: Vec, /// Graphics memory the normal placement leaves for programs opened later (GB, default 1). pub other_room_gb: f64, + /// Graphics memory a game gets in the game stage (GB, default 8). + pub reserve_gb: f64, + /// How long after a game ends the normal stage comes back (seconds, default 30). + pub revert_seconds: u32, + /// Stop the LLM while a game runs (default off). + pub pause_in_game: bool, } impl GameSettings { pub fn other_room_mib(&self) -> i64 { (self.other_room_gb * 1024.0).round() as i64 } + + pub fn reserve_mib(&self) -> i64 { + (self.reserve_gb * 1024.0).round() as i64 + } } /// Background collection (admin.spec.md, "Background collection"); no targets by default. @@ -210,7 +220,7 @@ impl Default for Settings { features: FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false }, mcp_servers: vec![], collect: CollectSettings { keep_days: 30, targets: vec![] }, - game: GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0 }, + game: GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0, reserve_gb: 8.0, revert_seconds: 30, pause_in_game: false }, } } } @@ -571,15 +581,21 @@ fn parse_game(raw: &Map, d: &GameSettings) -> Result d.other_room_gb, - Some(v) => match v.as_f64() { - Some(n) if (0.0..=8.0).contains(&n) => n, - _ => return err("game.otherRoomGb must be a number 0-8 (GB)"), - }, + let gb = |key: &str, default: f64, max: f64| -> Result { + match g.and_then(|m| m.get(key)) { + None => Ok(default), + Some(v) => match v.as_f64() { + Some(n) if (0.0..=max).contains(&n) => Ok(n), + _ => err(format!("game.{key} must be a number 0-{max} (GB)")), + }, + } }; + let other_room_gb = gb("otherRoomGb", d.other_room_gb, 8.0)?; + let reserve_gb = gb("reserveGb", d.reserve_gb, 32.0)?; + let revert_seconds = get_uint(g, "revertSeconds", "game", d.revert_seconds, 0, 600)?; Ok(GameSettings { detect: get_bool(g, "detect", "game", d.detect)?, games: list("games", &d.games)?, - not_games: list("notGames", &d.not_games)?, other_room_gb }) + not_games: list("notGames", &d.not_games)?, other_room_gb, reserve_gb, revert_seconds, + pause_in_game: get_bool(g, "pauseInGame", "game", d.pause_in_game)? }) } fn parse_collect(raw: &Map, d: &CollectSettings) -> Result { @@ -851,11 +867,13 @@ mod tests { #[test] fn game_detection_settings_are_read_and_checked() { - assert_eq!(parse_settings(&json!({})).unwrap().game, GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0 }); - let s = parse_settings(&json!({"game": {"detect": false, "games": [" MyGame.exe ", ""], "notGames": ["obs64"], "otherRoomGb": 2.5}})).unwrap(); - assert_eq!(s.game, GameSettings { detect: false, games: vec!["MyGame.exe".into()], not_games: vec!["obs64".into()], other_room_gb: 2.5 }); + assert_eq!(parse_settings(&json!({})).unwrap().game, GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0, reserve_gb: 8.0, revert_seconds: 30, pause_in_game: false }); + let s = parse_settings(&json!({"game": {"detect": false, "games": [" MyGame.exe ", ""], "notGames": ["obs64"], "otherRoomGb": 2.5, "reserveGb": 6, "revertSeconds": 60, "pauseInGame": true}})).unwrap(); + assert_eq!(s.game, GameSettings { detect: false, games: vec!["MyGame.exe".into()], not_games: vec!["obs64".into()], other_room_gb: 2.5, + reserve_gb: 6.0, revert_seconds: 60, pause_in_game: true }); + assert_eq!(s.game.reserve_mib(), 6144); assert_eq!(s.game.other_room_mib(), 2560); - for bad in [json!({"game": {"games": ["C:\\x\\a.exe"]}}), json!({"game": {"notGames": "a"}}), json!({"game": {"detect": 1}}), json!({"game": {"otherRoomGb": 9}})] { + for bad in [json!({"game": {"games": ["C:\\x\\a.exe"]}}), json!({"game": {"notGames": "a"}}), json!({"game": {"detect": 1}}), json!({"game": {"otherRoomGb": 9}}), json!({"game": {"revertSeconds": 601}}), json!({"game": {"reserveGb": -1}})] { assert!(parse_settings(&bad).unwrap_err().0.contains("game."), "{bad}"); } } diff --git a/app/src/settings_edit.rs b/app/src/settings_edit.rs index 0719340..5c97ff4 100644 --- a/app/src/settings_edit.rs +++ b/app/src/settings_edit.rs @@ -134,6 +134,9 @@ pub fn fields() -> Vec { f("game.detect", Game, Bool, json!(true), "게임 감지"), f("game.games", Game, TextList { max_items: 100, nullable: false }, json!([]), "게임으로 볼 프로그램(파일 이름, 예: MyGame.exe)"), f("game.otherRoomGb", Game, Number { min: 0.0, max: 8.0 }, json!(1.0), "평소 다른 프로그램용으로 남길 VRAM(GB)"), + f("game.reserveGb", Game, Number { min: 0.0, max: 32.0 }, json!(8.0), "게임 중 게임용으로 비울 VRAM(GB)"), + f("game.revertSeconds", Game, Int { min: 0, max: 600 }, json!(30), "게임이 끝난 뒤 평소 배치로 돌아가기까지(초)"), + f("game.pauseInGame", Game, Bool, json!(false), "게임 중 일시정지(대답하지 않음)"), f("game.notGames", Game, TextList { max_items: 100, nullable: false }, json!([]), "게임이 아닌 프로그램(파일 이름)"), ] } diff --git a/app/src/strata.rs b/app/src/strata.rs index 4a557e7..fcfdd2f 100644 --- a/app/src/strata.rs +++ b/app/src/strata.rs @@ -12,6 +12,7 @@ use serde::Serialize; use serde_json::{json, Value}; use crate::install::{Ctx, Layout}; +use crate::perf::Stage; use crate::settings::Settings; /// The one model v2 runs (M0: Qwen3.6-35B-A3B UD-Q4_K_XL; docs/v2/roadmap.md). @@ -49,12 +50,12 @@ pub fn parallel(settings: &Settings) -> u32 { /// `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, sets: &[String]) -> Vec { +pub fn launch_args(layout: &Layout, settings: &Settings, conf: &Conf, sets: &[String]) -> 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()), + for (k, v) in [("--context", conf.context.to_string()), ("--vision", "off".into()), + ("--parallel", conf.parallel.to_string()), ("--access", "local".into()), ("--port", settings.llm.port.to_string())] { a.push(k.into()); a.push(v); @@ -67,6 +68,29 @@ pub fn launch_args(layout: &Layout, settings: &Settings, sets: &[String]) -> Vec a } +/// The context and requests at once of a stage: the settings' in the normal stage; in a game 16K +/// (or less when the settings ask for less) and one request at a time. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Conf { + pub context: u32, + pub parallel: u32, +} + +pub fn conf(settings: &Settings, stage: Stage) -> Conf { + match stage { + Stage::Gaming => Conf { context: crate::placement::GAME_CONTEXT.min(settings.llm.context), parallel: 1 }, + _ => Conf { context: settings.llm.context, parallel: parallel(settings) }, + } +} + +/// The engine's CPU threads from its log ("... on 16 CPU threads ..."). +fn cpu_threads(log: &str) -> Option { + log.lines().rev().find_map(|l| { + let i = l.find(" CPU threads")?; + l[..i].rsplit(' ').next()?.parse().ok() + }) +} + /// The engine settings for an expert budget (`placement.rs`) and the M0 kit's prompt chunk. fn placement_sets(expert_gib: f64) -> Vec { vec![format!("expert-vram={expert_gib}"), "prefill=2048".into()] @@ -228,6 +252,14 @@ pub struct Llm { stop_timeout: Duration, /// The graphics card's memory (none: Strata places the model itself). gpu: Option, + /// What other programs held when the services started (before the LLM and the STT worker): + /// every later placement of this run counts from it, not from a card that then also holds the + /// STT worker and a game. + baseline: Mutex>, + /// The engine's CPU threads in the normal stage; a game gets half. + threads: Mutex>, + /// The stage it runs in, and in a game the graphics memory the game gets. + stage: Mutex<(Stage, Option)>, } /// How long the model may take to answer after `strata launch` returned (it loads in about 15 s @@ -247,7 +279,14 @@ impl Llm { 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)), port: Mutex::new(0), - stop_timeout: Duration::from_secs(120), gpu: None } + stop_timeout: Duration::from_secs(120), gpu: None, baseline: Mutex::new(None), threads: Mutex::new(None), + stage: Mutex::new((Stage::Normal, None)) } + } + + /// `{stage, gameRoomMib}` for the dashboard. + pub fn stage_view(&self) -> Value { + let (stage, room) = *self.stage.lock().unwrap(); + json!({"stage": stage, "gameRoomMib": room}) } /// Place the model by the card's memory (`placement.rs`), read with `gpu`. @@ -272,19 +311,29 @@ impl Llm { /// counted as another program's memory (a stop that is not confirmed reads nothing: no /// experts). A measurement that fails is not kept: the model then starts without experts on /// the card. - async fn placement(&self, settings: &Settings, ctx: &Ctx, base: &str) -> Result, String> { + async fn placement(&self, settings: &Settings, ctx: &Ctx, base: &str, stage: Stage) -> Result>, String> { + let c = conf(settings, stage); + let workers = |sets: &mut Vec| if stage == Stage::Gaming { + let half = self.threads.lock().unwrap().map(|n| n / 2) + .unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get() as u32 / 4).unwrap_or(1)); + sets.push(format!("pool-workers={}", half.max(1))); + }; if self.gpu.is_none() { - return Ok(vec![]); + let mut sets = vec![]; + workers(&mut sets); + return Ok(Some(sets)); } // Whatever a server left from an earlier run does (answers, loads, stays silent), it holds // the card: stop it first and read the card only once the port is confirmed closed. if let Err(e) = self.stop_server_on(settings.llm.port).await { crate::warn_log!("llm", "Warning: a server left on the port did not stop ({e}); starting without experts on the card"); - return Ok(placement_sets(0.0)); + let mut sets = placement_sets(0.0); + workers(&mut sets); + return Ok(Some(sets)); } - let Some(card) = self.read_gpu().await else { return Ok(vec![]) }; - let (context, parallel) = (settings.llm.context, parallel(settings)); - let key = format!("{context}/{parallel}"); + let Some(card) = self.read_gpu().await else { return Ok(Some(vec![])) }; + let others = *self.baseline.lock().unwrap().get_or_insert(card.used_mib); + let key = format!("{}/{}", c.context, c.parallel); let file = self.probe_file(); let mut all: serde_json::Map = std::fs::read_to_string(&file).ok() .and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default(); @@ -293,16 +342,18 @@ impl Llm { let probe = match known { Some(p) => p, None => { - crate::info_log!("llm", "measuring the model without experts once (context {context}, {parallel} at once)"); - self.launch(settings, ctx, base, &placement_sets(0.0)).await?; + crate::info_log!("llm", "measuring the model without experts once (context {}, {} at once)", c.context, c.parallel); + self.launch(settings, ctx, base, &c, &placement_sets(0.0)).await?; let warmed = warm_up(base).await; let after = self.read_gpu().await.filter(|g| g.id == card.id); let model_mib = after.map(|g| g.used_mib - card.used_mib).unwrap_or(0); if let Err(e) = warmed.and_then(|()| if model_mib > 0 { Ok(()) } else { Err("the card's memory could not be read".into()) }) { crate::warn_log!("llm", "Warning: the measurement failed ({e}); starting without experts on the card"); - return Ok(placement_sets(0.0)); + let mut sets = placement_sets(0.0); + workers(&mut sets); + return Ok(Some(sets)); } - let p = crate::placement::Probe { context, parallel, gpu: card.id.clone(), model_mib, + let p = crate::placement::Probe { context: c.context, parallel: c.parallel, gpu: card.id.clone(), model_mib, staging_gib: crate::placement::staging_gib(&engine_log(&self.layout.strata_home())) }; all.insert(key, json!(p)); crate::datadir::write_atomic(&file, Value::Object(all).to_string().as_bytes()) @@ -310,15 +361,28 @@ impl Llm { p } }; - let expert = crate::placement::normal(card.total_mib, card.used_mib, &probe, settings.game.other_room_mib()); - crate::info_log!("llm", "placement: experts {expert} GiB (card {} MiB, held by others {} MiB, model without experts {} MiB)", - card.total_mib, card.used_mib, probe.model_mib); - Ok(placement_sets(expert)) + let expert = match stage { + Stage::Gaming => { + let g = crate::placement::game(card.total_mib, others, &probe, settings.game.reserve_mib()); + if g.paused { + crate::info_log!("llm", "placement: no room for a game beside the model; paused while the game runs"); + return Ok(None); + } + *self.stage.lock().unwrap() = (Stage::Gaming, Some(g.game_room_mib)); + g.expert_gib + } + _ => crate::placement::normal(card.total_mib, others, &probe, settings.game.other_room_mib()), + }; + crate::info_log!("llm", "placement ({stage:?}): experts {expert} GiB (card {} MiB, held by others {others} MiB, model without experts {} MiB)", + card.total_mib, probe.model_mib); + let mut sets = placement_sets(expert); + workers(&mut sets); + Ok(Some(sets)) } /// `strata launch` with `sets`, then wait until the model answers. - async fn launch(&self, settings: &Settings, ctx: &Ctx, base: &str, sets: &[String]) -> Result { - let args = launch_args(&self.layout, settings, sets); + async fn launch(&self, settings: &Settings, ctx: &Ctx, base: &str, c: &Conf, sets: &[String]) -> Result { + let args = launch_args(&self.layout, settings, c, sets); let refs: Vec<&str> = args.iter().map(String::as_str).collect(); ctx.run_in(&self.exe, &refs, Some(&self.layout.strata_home())).await?; wait_ready(base, READY_TIMEOUT, &self.cancel).await @@ -351,11 +415,47 @@ impl Llm { /// Start (or reuse) the LLM; returns its `/v1` address and model id. /// A cancel since the last `arm` (or before the first start) ends it before it runs anything. pub async fn start(&self, settings: &Settings) -> Result<(String, String), String> { + // A new run: other programs' memory is read afresh. + *self.baseline.lock().unwrap() = None; + *self.stage.lock().unwrap() = (Stage::Normal, None); + self.start_stage(settings, Stage::Normal).await.map(|r| r.expect("the normal stage never pauses")) + } + + /// Move the running LLM to `stage` (`perf.rs`): a restart with that stage's placement, or a stop + /// when it pauses (also a game stage with no room for the game). Returns the stage it ended in. + /// With `llm.url` nothing moves. + pub async fn switch(&self, settings: &Settings, stage: Stage) -> Result { + if settings.llm.url.is_some() { + return Ok(Stage::Normal); + } + if stage != Stage::Paused && self.start_stage(settings, stage).await?.is_some() { + return Ok(stage); + } + *self.port.lock().unwrap() = settings.llm.port; + self.stop().await?; + *self.stage.lock().unwrap() = (Stage::Paused, None); + self.set(LlmState::Off, Some("게임 중 일시정지".into())); + Ok(Stage::Paused) + } + + async fn start_stage(&self, settings: &Settings, stage: Stage) -> Result, String> { 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; + let result = self.start_inner(settings, stage).await; + if stage == Stage::Normal && result.as_ref().is_ok_and(Option::is_some) && self.gpu.is_some() { + if let Some(n) = cpu_threads(&engine_log(&self.layout.strata_home())) { + *self.threads.lock().unwrap() = Some(n); + } + } + if let Ok(Some(_)) = &result { + let mut st = self.stage.lock().unwrap(); + if stage == Stage::Normal { + *st = (Stage::Normal, None); + } + } match &result { - Ok((base, model)) => { + Ok(None) => {} + Ok(Some((base, model))) => { crate::info_log!("llm", "ready: {base} model={model}"); self.set(LlmState::Ready, None); } @@ -368,13 +468,14 @@ impl Llm { result } - async fn start_inner(&self, settings: &Settings) -> Result<(String, String), String> { + /// None: the stage pauses (nothing started). + async fn start_inner(&self, settings: &Settings, stage: Stage) -> Result, String> { if self.cancel.load(Ordering::SeqCst) { return Err("cancelled".into()); } if let Some(url) = &settings.llm.url { let model = wait_ready(url, URL_TIMEOUT, &self.cancel).await?; - return Ok((url.clone(), model)); + return Ok(Some((url.clone(), model))); } if !self.exe.exists() { return Err("Strata가 설치되어 있지 않습니다. 마법사의 모델 단계에서 설치해 주세요".into()); @@ -383,13 +484,16 @@ impl Llm { *self.active.lock().unwrap() = Some(ctx.clone()); *self.port.lock().unwrap() = settings.llm.port; let base = format!("http://127.0.0.1:{}/v1", settings.llm.port); - let ready = match self.placement(settings, &ctx, &base).await { - Ok(sets) => self.launch(settings, &ctx, &base, &sets).await, + let c = conf(settings, stage); + let ready = match self.placement(settings, &ctx, &base, stage).await { + Ok(Some(sets)) => self.launch(settings, &ctx, &base, &c, &sets).await.map(Some), + Ok(None) => Ok(None), Err(e) => Err(e), }; *self.active.lock().unwrap() = None; match ready { - Ok(model) => Ok((base, model)), + Ok(Some(model)) => Ok(Some((base, model))), + Ok(None) => Ok(None), // Nothing half-started stays on the graphics card; if it may have, say so. Err(e) => match self.stop_server().await { Ok(()) => Err(e), @@ -491,12 +595,12 @@ async fn wait_gone(base: &str, timeout: Duration) -> bool { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use crate::datadir::temp_dir; use crate::settings::{parse_settings, ChatChannelSettings}; - fn layout(tag: &str) -> Layout { + pub(crate) fn layout(tag: &str) -> Layout { Layout { data: temp_dir(tag), src: std::path::PathBuf::from("src") } } @@ -504,7 +608,7 @@ mod tests { 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 a = launch_args(&l, &s, &conf(&s, Stage::Normal), &[]); 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())); @@ -566,7 +670,7 @@ mod tests { /// `mode`: "list" answers, "hang" keeps the connection and says nothing, "503" is a server still /// loading. - async fn serve(id: &'static str, delay: Duration, gone: Option, mode: Arc>) -> u16 { + pub(crate) async fn serve(id: &'static str, delay: Duration, gone: Option, mode: Arc>) -> 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(); @@ -640,12 +744,12 @@ mod tests { /// A fake `strata`: `launch --stop` records itself and runs `stop_body` (by default it stops the /// server: the file `gone` appears); `launch ...` runs `launch_body`. #[cfg(unix)] - fn fake_strata(l: &Layout, launch_body: &str) -> std::path::PathBuf { + pub(crate) fn fake_strata(l: &Layout, launch_body: &str) -> std::path::PathBuf { fake_strata_stop(l, launch_body, &format!("touch '{}'", l.data.join("gone").display())) } #[cfg(unix)] - fn fake_strata_stop(l: &Layout, launch_body: &str, stop_body: &str) -> std::path::PathBuf { + pub(crate) fn fake_strata_stop(l: &Layout, launch_body: &str, stop_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(); @@ -734,7 +838,7 @@ mod tests { /// server still left over, `leftover` MiB, until a `launch --stop`), and 9874 MiB more while a /// Strata server runs (the calls file shows the last launch and stop). #[cfg(unix)] - fn card(l: &Layout, id: &'static str, leftover: i64) -> GpuReader { + pub(crate) fn card(l: &Layout, id: &'static str, leftover: i64) -> GpuReader { let calls = l.data.join("calls"); Arc::new(move || { let c = std::fs::read_to_string(&calls).unwrap_or_default(); @@ -747,21 +851,21 @@ mod tests { /// A fake Strata that serves on `port` again (removes `gone`) and writes the engine's staging line. #[cfg(unix)] - fn fake_placed(l: &Layout) -> std::path::PathBuf { + pub(crate) fn fake_placed(l: &Layout) -> std::path::PathBuf { let log = l.strata_home().join("x.engine.log"); - fake_strata(l, &format!("rm -f '{}'; echo 'strata-q36: hybrid experts: (1.10 GiB staging); 7.1 s' >> '{}'; echo 'Strata is serving.'", + fake_strata(l, &format!("rm -f '{}'; echo 'strata-q36: hybrid experts: 5 of 256 per layer in VRAM, the rest of a batch on 16 CPU threads (1.10 GiB staging); 7.1 s' >> '{}'; echo 'Strata is serving.'", l.data.join("gone").display(), log.display())) } /// A fake server on a free port that answers only once a launch serves (removes `gone`). #[cfg(unix)] - async fn server_after_launch(l: &Layout, mode: &'static str) -> u16 { + pub(crate) async fn server_after_launch(l: &Layout, mode: &'static str) -> u16 { std::fs::create_dir_all(&l.data).unwrap(); std::fs::write(l.data.join("gone"), "").unwrap(); serve("qwen-test", Duration::from_millis(0), Some(l.data.join("gone")), Arc::new(Mutex::new(mode))).await } - fn launches(l: &Layout) -> Vec { + pub(crate) fn launches(l: &Layout) -> Vec { std::fs::read_to_string(l.data.join("calls")).unwrap_or_default().lines() .filter(|c| c.starts_with("launch --family")).map(str::to_owned).collect() } @@ -841,6 +945,60 @@ mod tests { } } + #[cfg(unix)] + #[tokio::test] + async fn a_game_moves_the_llm_to_the_game_placement_and_back() { + let l = layout("llm-stage"); + let port = server_after_launch(&l, "list").await; + let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(card(&l, "GPU-test", 0)); + let s = parse_settings(&json!({"llm": {"port": port}})).unwrap(); + llm.start(&s).await.unwrap(); + assert_eq!(llm.stage_view(), json!({"stage": "normal", "gameRoomMib": null})); + std::fs::remove_file(l.data.join("calls")).unwrap(); + assert_eq!(tokio::time::timeout(Duration::from_secs(30), llm.switch(&s, Stage::Gaming)).await.unwrap().unwrap(), Stage::Gaming); + let g = launches(&l); + // Measured once at the game's context and one request, then the 2 GiB minimum (8 GB does not + // fit on 16 GB) with half the engine's 16 CPU threads. + assert_eq!(g.len(), 2, "{g:?}"); + assert!(g[0].contains("--context 16384") && g[0].contains("--parallel 1") && g[0].contains("--set expert-vram=0"), "{}", g[0]); + assert!(g[1].ends_with("--set expert-vram=2 --set prefill=2048 --set pool-workers=8"), "{}", g[1]); + let room = 16303 - 1460 - 9874 - crate::placement::STT_MIB - crate::placement::MARGIN_MIB - 921; + assert_eq!(llm.stage_view(), json!({"stage": "gaming", "gameRoomMib": room})); + assert_eq!(llm.status().state, LlmState::Ready); + // Back to normal: the run's first reading of other programs, the normal placement again. + std::fs::remove_file(l.data.join("calls")).unwrap(); + assert_eq!(llm.switch(&s, Stage::Normal).await.unwrap(), Stage::Normal); + let n = launches(&l); + assert_eq!(n.len(), 1, "{n:?}"); + assert!(n[0].contains("--context 32768") && n[0].ends_with("--set expert-vram=1.5 --set prefill=2048"), "{}", n[0]); + assert_eq!(llm.stage_view(), json!({"stage": "normal", "gameRoomMib": null})); + // Pause: the LLM stops. + assert_eq!(llm.switch(&s, Stage::Paused).await.unwrap(), Stage::Paused); + assert_eq!(llm.status().state, LlmState::Off); + assert_eq!(llm.stage_view()["stage"], json!("paused")); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_game_with_no_room_beside_the_model_pauses_the_llm() { + let l = layout("llm-stage-full"); + let port = server_after_launch(&l, "list").await; + let calls = l.data.join("calls"); + // A 12 GB card: the model fits, but not with any room for a game. + let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(Arc::new(move || { + let c = std::fs::read_to_string(&calls).unwrap_or_default(); + let running = c.lines().last().is_some_and(|x| x.starts_with("launch --family")); + Some(Gpu { id: "GPU-small".into(), used_mib: 1460 + if running { 9874 } else { 0 }, total_mib: 12288 }) + })); + let s = parse_settings(&json!({"llm": {"port": port}})).unwrap(); + llm.start(&s).await.unwrap(); + assert_eq!(llm.switch(&s, Stage::Gaming).await.unwrap(), Stage::Paused); + assert_eq!(llm.status().state, LlmState::Off); + assert_eq!(llm.stage_view(), json!({"stage": "paused", "gameRoomMib": null})); + let c = std::fs::read_to_string(l.data.join("calls")).unwrap(); + assert_eq!(c.lines().last(), Some("launch --stop")); + } + #[cfg(unix)] #[tokio::test] async fn a_left_server_that_does_not_stop_means_no_experts_and_nothing_measured() { diff --git a/app/src/worker_client.rs b/app/src/worker_client.rs index 8d60a25..2a1bb83 100644 --- a/app/src/worker_client.rs +++ b/app/src/worker_client.rs @@ -156,6 +156,8 @@ struct Inner { events: mpsc::UnboundedSender, ready: watch::Sender>, wake: Notify, + /// The brain finished the answers it was giving when the app said the LLM switches. + llm_idle: Notify, } #[derive(Clone)] @@ -174,6 +176,7 @@ impl WorkerClient { events, ready: watch::channel(None).0, wake: Notify::new(), + llm_idle: Notify::new(), }); (Self { inner }, rx) } @@ -351,6 +354,22 @@ impl WorkerClient { self.send_json(json!({"type": "addressed", "id": id, "user": user.to_string(), "text": text})) } + /// Tell the brain the LLM's state (voice_worker.spec.md, "LLM switches"): `switching` (start no + /// new LLM work, say `notice` once to the first spoken request that waits, report `llm_idle`), + /// `ready` (answer what waited) or `paused` (answer nothing until ready). + pub fn llm_state(&self, state: &str, notice: Option<&str>) -> bool { + let mut m = json!({"type": "llm", "state": state}); + if let Some(n) = notice { + m["notice"] = json!(n); + } + self.send_json(m) + } + + /// Wait until the brain reports `llm_idle` (also one that came before the wait), at most `t`. + pub async fn wait_llm_idle(&self, t: Duration) -> bool { + tokio::time::timeout(t, self.inner.llm_idle.notified()).await.is_ok() + } + /// Tell the brain a call is being said (a partial transcript), so it gets ready to answer it. pub fn prepare(&self, user: u64, text: &str) -> bool { self.send_json(json!({"type": "prepare", "user": user.to_string(), "text": text})) @@ -524,6 +543,10 @@ fn on_text(inner: &Inner, t: &str) { "partial" => serde_json::from_value(v).ok().map(WorkerEvent::Partial), "final" => serde_json::from_value(v).ok().map(WorkerEvent::Final), "chat_action" => serde_json::from_value(v).ok().map(WorkerEvent::ChatAction), + "llm_idle" => { + inner.llm_idle.notify_one(); + return; + } "reply_text" => { let id = v["id"].as_str().unwrap_or_default().to_owned(); let failed = v["failed"].as_bool().unwrap_or(true); diff --git a/app/tests/game_watch.rs b/app/tests/game_watch.rs index 456f3bc..8da7370 100644 --- a/app/tests/game_watch.rs +++ b/app/tests/game_watch.rs @@ -26,7 +26,7 @@ fn a_launcher_game_turns_game_mode_on_until_it_ends() { eprintln!("skipped: set JARVIS_TEST_GAME_EXE"); return; }; - let w = GameWatch::start(GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0 }); + let w = GameWatch::start(GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0, reserve_gb: 8.0, revert_seconds: 30, pause_in_game: false }); assert_eq!(w.view(), serde_json::Value::Null, "no game before it starts"); let mut game = std::process::Command::new(&exe).spawn().expect("the game starts"); let t0 = Instant::now(); diff --git a/app/tests/worker_client.rs b/app/tests/worker_client.rs index 01ad2b8..6858c23 100644 --- a/app/tests/worker_client.rs +++ b/app/tests/worker_client.rs @@ -414,3 +414,21 @@ async fn a_chat_reply_is_not_spoken_and_its_text_comes_back() { Got::Json(json!({"type": "reply_delivered", "id": "c2", "ok": false}))]); c.close(); } + +#[tokio::test] +async fn an_llm_switch_is_announced_and_the_client_waits_until_the_brain_is_idle() { + let w = FakeWorker::start(0).await; + let (c, _rx) = client(&w.url(), json!({})); + c.start(); + c.wait_ready(Duration::from_secs(2)).await.unwrap(); + assert!(c.llm_state("switching", Some("잠깐만요"))); + until(|| w.got().iter().any(|g| *g == Got::Json(json!({"type": "llm", "state": "switching", "notice": "잠깐만요"})))).await; + // Nothing idle yet: the wait gives up after its time. + assert!(!c.wait_llm_idle(Duration::from_millis(100)).await); + // The worker reports idle (before or while the app waits): the wait ends. + w.send(Message::text(json!({"type": "llm_idle"}).to_string())); + assert!(c.wait_llm_idle(Duration::from_secs(2)).await); + assert!(c.llm_state("ready", None)); + until(|| w.got().iter().any(|g| *g == Got::Json(json!({"type": "llm", "state": "ready"})))).await; + c.close(); +} diff --git a/app/ui/app.js b/app/ui/app.js index 152c269..d868a6e 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -410,6 +410,14 @@ async function displayDriverCard() { // ---- dashboard ---------------------------------------------------------------------------------- +/** The performance stage for the dashboard; in a game also the graphics memory the game gets. */ +function perfText(p) { + if (!p) return "평소"; + if (p.stage === "paused") return "일시정지 (게임 중)"; + if (p.stage === "gaming") return "게임 중" + (p.gameRoomMib != null ? ` · 게임에 ${(p.gameRoomMib / 1024).toFixed(1)} GB` : ""); + return "평소"; +} + const GAME_REASON = { fullscreen: () => "전체화면", borderless: () => "테두리 없는 창", registered: () => "직접 등록한 게임", launcher: (r) => `${r.launcher} 게임 폴더` }; @@ -471,7 +479,8 @@ function dashboardBody(d) { h("span", {}, `${g.usePercent}% · VRAM ${(g.vramUsedMb / 1024).toFixed(1)} / ${(g.vramTotalMb / 1024).toFixed(1)} GB`)]), h("span", { class: "k" }, "게임 모드"), h("span", { class: d.game ? "" : "muted" }, d.game ? `켜짐 (${d.game.name}, ${GAME_REASON[d.game.reason.kind]?.(d.game.reason) ?? d.game.reason.kind})` : "꺼짐"), - h("span", { class: "k" }, "성능 단계"), h("span", { class: "muted" }, d.performance ?? "평소")))), + h("span", { class: "k" }, "성능 단계"), h("span", { class: d.performance && d.performance.stage !== "normal" ? "" : "muted" }, + perfText(d.performance))))), h("div", { class: "grid" }, h("div", { class: "card" }, h("h2", {}, "실시간 자막"), h("div", { class: "captions" }, (d.captions || []).length ? d.captions.map((c) => h("div", { class: "cap" + (c.final ? "" : " partial") }, h("b", {}, c.name), c.text)) diff --git a/docs/llm_contexts.md b/docs/llm_contexts.md index 3481e22..e3609a6 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`, 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. +**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. In v2 the app also sets Strata's context per performance stage (`app/src/admin.spec.md`, "Performance stages"): the settings' `llm.context` (default 32,768 tokens) normally and 16,384 tokens with one request at a time while a game runs; while it switches the voice worker starts no LLM call (requests wait, at most 180 s, `voice_worker.spec.md` "LLM switches"), and while paused (a game with no room for the model) every brain call fails at once. --- diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 4912809..5faccd8 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -11,7 +11,7 @@ | 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%에 쓰던 것(데이터 폴더로). 마무리(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개 통과. 게임PC에서 UTF-8 옵션을 끈 상태(코드 페이지 949)로 다시 확인: 전체 설치 7단계, Strata의 대화 모델 22.9GB 다운로드(진행률 10.9%→90%로 표시)와 준비, 워커·디스코드 연결, 시험 봇 질문 5개 모두 소리로 답함(앱이 잰 전체 중앙값 4.0초), 정지 7초에 GPU 메모리 반환, 로그 485줄에 깨진 글자 없음. 남은 것: 설치 파일(NSIS), Strata가 VRAM을 거의 다 써서(15.8/16.3GB) 받아 적기와 GPU를 나누는 문제(M0의 STT 자리 남기기 배치, M7 성능 단계와 함께) | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인. 1단계 완료(2026-11-13): 관리 앱 "기능" 화면(`app/src/features.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Features and MCP servers"). 날씨·웹 검색·식단 기록 켜기/끄기(끄면 그 도구는 두뇌가 제안하지도 실행하지도 않음, 모델이 이름을 대도, 도구 찾기 도구로도 안 나옴), MCP 서버 추가·삭제·켜기/끄기(이름, 명령, 인자, 환경 변수 이름). API 키 같은 환경 변수 값은 암호화 저장소에만 두고 화면에는 저장 여부만, 로그에서는 가림, 서버를 지우면 값도 지움. 앱이 켤 때 값을 워커 환경으로만 넘기고 두뇌는 그 변수를 자기 환경에서 빼서 각 서버에 자기 값만 줌. 서버마다 연결 결과(도구 수, 실패 이유)는 디버그 없이도 LLM 로그 탭에 남음. 같은 작업에서 v2 두뇌가 v1의 PC 파일 도구(홈 폴더 읽기·쓰기·지우기)와 화면 캡처 도구를 쓰던 것을 뺌(음성·채팅 채널의 누구든 요청할 수 있었음, 화면 보기는 M7에서 권한과 함께). 이 서버에서 확인: 개발용 서버의 브라우저로 날씨를 끄고 MCP 서버(시험용 서버)와 키를 저장, 실제 서비스를 켜니 `brain.json`에 끈 도구와 서버만 있고 키는 없음, 워커가 "MCP server fake: 1 tool(s)"를 남기고 MCP 서버 프로세스만 키를 받음, 로그·설정 파일에 키 없음, 정지 때 MCP 서버도 꺼짐. 2단계 완료(2026-11-13): 예약 수집 틀(`app/src/collect.rs`, 워커 `src/voice_worker/collect.py`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Background collection"). 관리 앱 "백그라운드 수집" 화면에서 대상(사이트·검색어·RSS, 주기 15분~7일, 켜기/끄기)과 보관 기간(기본 30일)을 정하고 결과를 봄. 기본 대상은 없음. 기능 화면의 "백그라운드 수집" 스위치를 끄거나 켠 대상이 없으면 수집은 하지 않고 보관 기간이 지난 결과만 지움. 대소문자만 다른 대상 이름은 Windows에서 같은 폴더라 거절. 워커가 음성·두뇌와 따로 돌며, 사이트는 바뀌었을 때만, RSS·검색은 새 항목만 남김. 모든 요청은 공개 주소만 허용하고 검사한 그 주소로만 연결(DNS를 다시 물어 내부망으로 새는 것 막음, 리디렉트마다 다시 검사, 1MB, 전체 15초, 주소는 로그에 남기지 않음)하고, 모은 내용은 데이터 폴더 `collect/`에만 쓰며 두뇌나 로그로 가지 않음(로그에는 대상 이름과 개수만). 덕덕고가 봇 확인 화면을 주면 "결과 없음"이 아니라 실패로 남김. 이 서버에서 확인: 실제 인터넷의 RSS(hnrss 20개), Atom(cpython 10개), 검색어(10개), 사이트(1개) 수집, 내부 주소는 거절, 개발용 서버 화면에서 대상 저장·잘못된 이름 거절·결과 보기, 실제 서비스 시작으로 켠 대상만 워커에 넘어가 수집되고 정지 때 워커도 꺼짐. 3단계 첫 부분 완료(2026-11-13): 봇용 크롬(`app/src/browser.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Bot browser"). 설치 단계 `browser`가 Chrome for Testing 157(약 200MB, SHA-256 고정)을 데이터 폴더 `runtime/chrome`에 받고, 기능 화면의 "브라우저 제어(봇용 크롬)"가 켜져 있으면 서비스가 화면 없이(headless) 띄움(프로필 `browser/profile`, CDP는 빈 루프백 포트, 워커에 `JARVIS_BROWSER_CDP`). 크롬의 모든 연결은 앱의 중계기(루프백 프록시)를 거쳐 이름을 한 번만 풀고 공개 주소에만 연결(이 PC·내부망·CGNAT·IPv4 매핑 IPv6 등은 403, 주소는 로그에 남기지 않음), QUIC 끔, WebRTC도 중계기로만. 켜지지 않으면 대시보드에 이유를 보이고 서비스는 계속 돔. 정지 때 `Browser.close` 후 5초 안에 안 끝나면 강제 종료. 이 서버에서 확인: 실제 크롬이 example.com은 열고 127.0.0.1·localhost의 로컬 서버에는 요청이 하나도 가지 않음, 정지 78ms, 설치 단계로 실제 내려받아 실행, 실제 서비스 시작에서 대시보드 "준비"·워커 환경에 CDP 주소·정지 때 크롬 프로세스 0개, 기능을 끄면 띄우지 않음, Windows 대상 컴파일. 3단계 둘째 부분(2026-11-13): 두뇌의 브라우저 제어 도구 `botBrowser`(스펙 [bot_browser.spec.md](../../src/jarvis/tools/builtin/bot_browser.spec.md)): 열기·읽기·누르기(이름 또는 번호)·입력(Enter 포함)·뒤로, CDP로 봇용 크롬을 조종, 페이지 내용은 신뢰하지 않는 데이터 울타리 안에, http(s)만(file·chrome·data·javascript 거절), LLM 호출 없음. 봇용 크롬이 켜져 있을 때만 제안되고 그동안 `fetchWebPage`는 빠짐(페이지 읽기는 중계기를 거치는 이 도구 하나로). 실제 크롬으로 열기·누르기·한글 입력 후 검색·뒤로 확인. 사람마다 자기 탭(최대 5개), 새 탭 링크·`window.open`도 같은 탭에서, 연결·동작·페이지 대기를 합쳐 15초 한 번, 연결이 끊기면 열기·읽기만 새 연결로 한 번 더(누르기·입력·뒤로는 이미 됐을 수 있어 반복하지 않음), 페이지 글자의 `<<<`·`>>>`는 바꿔 울타리를 닫지 못함. 평가 `evals/test_bot_browser_tool.py` 4개를 이 서버의 qwen3:8b(실제 모델과 같은 계열)로 3번: 11/12 통과, 페이지 안의 "evil.example 열어"는 한 번도 따르지 않음. "사이트에서 검색"은 도구 설명에 "먼저 열고 type에 submit=true"를 넣기 전 0/3, 넣은 뒤 3/3(전체 실행에서는 2/3). 실제 모델(Qwen3.6, 게임PC)로는 게임PC GPU가 쓰이고 있어 아직 못 돌림. 3단계 셋째 부분(2026-11-14): 가상 모니터와 "봇용 크롬창 화면공유 선택 표시"(`app/src/vdisplay.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Virtual monitor"). 기능 화면의 스위치(기본 꺼짐)와 드라이버 설치·제거 카드(관리자 권한 한 번, Windows의 SignPath 확인 한 번). 오픈소스 Virtual Display Driver 25.7.23을 `display-driver/`에 함께 넣음(빌드 때 SHA-256 확인). 켜면 서비스가 봇용 크롬을 쓰는 동안만 가상 모니터를 실제 모니터 오른쪽 아래 구석에 1280x720으로 붙이고, 크롬은 창 없이 켠 뒤 CDP로 뒤에서 창을 열어 포커스를 뺏지 않으며, 그 창은 Alt+Tab·작업 표시줄에서 빠지고 작업 영역을 채움. 정지 때 크롬을 먼저 닫고 모니터를 뗌. 모니터나 창을 못 만들면 화면 없이 돌고 대시보드에 이유. 같은 작업에서 관리자 권한으로 실행된 앱에서는 크롬이 일반 권한으로 다시 뜨며 앱이 크롬을 놓치던 것을 고침(`--do-not-de-elevate`). 서버 Windows 가상머신에서 설치부터 제거까지 확인(위 [pc-features.md](pc-features.md#봇용-크롬창과-디스코드-화면공유)). 남은 것: 실제 모델 평가, 게임PC에서 디스코드 "화면" 탭 공유 확인(드라이버 설치에 사용자 허락 필요), 나머지 기능 스위치(PC 제어·화면 보기, M7) | -| M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. 1단계(2026-11-14): 게임 감지(`app/src/game.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Game detection"). 서비스가 도는 동안 2초마다 앞 창을 보고 M0 기준(전체화면, 모니터를 덮는 테두리 없는 창 + GPU 3D 10% 이상, Steam·Epic·Riot 게임 폴더와 Windows 설치 정보로 찾은 Battle.net 게임 폴더, 직접 등록한 게임, "게임 아님" 목록 우선, 브라우저·영상 플레이어·디스코드·런처 창 제외)으로 판단, 게임이 끝날 때까지 유지. 관리 앱 "게임 모드" 화면(감지 켜기/끄기, 두 목록)과 대시보드 "게임 모드: 켜짐 (이름, 이유)". 서버 Windows 가상머신에서 Steam 게임 폴더의 프로그램을 켜면 1.4초 뒤 켜짐, 끄면 2.0초 뒤 꺼짐. 한글 등이 섞인 경로의 Steam 게임과 Battle.net 게임(시험용 제거 항목)도 같은 시험으로 확인. GPU 사용률 기준(테두리 없는 창)은 GPU가 있는 게임PC에서 확인할 것. 2단계 첫 부분(2026-11-14): 평소 배치(`app/src/placement.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "LLM"). NVIDIA 카드가 있으면 M0 키트의 식대로 `--expert-vram`을 정해 STT 몫(2740MiB)·엔진 여유(768MiB)·다른 프로그램 여유(기본 1GB)를 남김(Strata 자동 배치가 STT 자리를 남기지 않던 M5의 문제). 전문가 없는 모델 VRAM은 맥락·동시 요청 수·카드(UUID)마다 처음 한 번 재서(`config/llm-probe.json`) 다시 씀. 측정이 실패하면 저장하지 않고 전문가 0으로 켜며, 이전 실행에서 남은 서버는 응답 상태와 상관없이 늘 먼저 끄고 포트가 닫힌 것을 확인한 뒤 잼(확인이 안 되면 재지 않고 전문가 0). 게임PC M0 측정값으로 계산하면 M0와 같은 1.5GB. 게임 중 배치 계산(게임 몫 8GB를 못 비우면 최소 전문가 2GB와 남는 게임 몫, 그것도 안 되면 전문가 0GB, 그것도 안 되면 일시정지)도 넣음. 실제 게임PC 확인은 아직. 다음: 게임 감지에 따라 배치를 바꾸는 전환(답이 끝난 뒤 다시 시작, 그동안 요청 대기, 30초 뒤 되돌리기). | +| M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. 1단계(2026-11-14): 게임 감지(`app/src/game.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Game detection"). 서비스가 도는 동안 2초마다 앞 창을 보고 M0 기준(전체화면, 모니터를 덮는 테두리 없는 창 + GPU 3D 10% 이상, Steam·Epic·Riot 게임 폴더와 Windows 설치 정보로 찾은 Battle.net 게임 폴더, 직접 등록한 게임, "게임 아님" 목록 우선, 브라우저·영상 플레이어·디스코드·런처 창 제외)으로 판단, 게임이 끝날 때까지 유지. 관리 앱 "게임 모드" 화면(감지 켜기/끄기, 두 목록)과 대시보드 "게임 모드: 켜짐 (이름, 이유)". 서버 Windows 가상머신에서 Steam 게임 폴더의 프로그램을 켜면 1.4초 뒤 켜짐, 끄면 2.0초 뒤 꺼짐. 한글 등이 섞인 경로의 Steam 게임과 Battle.net 게임(시험용 제거 항목)도 같은 시험으로 확인. GPU 사용률 기준(테두리 없는 창)은 GPU가 있는 게임PC에서 확인할 것. 2단계 첫 부분(2026-11-14): 평소 배치(`app/src/placement.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "LLM"). NVIDIA 카드가 있으면 M0 키트의 식대로 `--expert-vram`을 정해 STT 몫(2740MiB)·엔진 여유(768MiB)·다른 프로그램 여유(기본 1GB)를 남김(Strata 자동 배치가 STT 자리를 남기지 않던 M5의 문제). 전문가 없는 모델 VRAM은 맥락·동시 요청 수·카드(UUID)마다 처음 한 번 재서(`config/llm-probe.json`) 다시 씀. 측정이 실패하면 저장하지 않고 전문가 0으로 켜며, 이전 실행에서 남은 서버는 응답 상태와 상관없이 늘 먼저 끄고 포트가 닫힌 것을 확인한 뒤 잼(확인이 안 되면 재지 않고 전문가 0). 게임PC M0 측정값으로 계산하면 M0와 같은 1.5GB. 게임 중 배치 계산(게임 몫 8GB를 못 비우면 최소 전문가 2GB와 남는 게임 몫, 그것도 안 되면 전문가 0GB, 그것도 안 되면 일시정지)도 넣음. 실제 게임PC 확인은 아직. 2단계 둘째 부분(2026-11-14): 성능 단계 전환(`app/src/perf.rs`, `services.rs`, 워커 "LLM switches"). 게임이 감지되면 워커에 전환을 알리고, 하던 답이 끝나면 맥락 16K·동시 1개·CPU 작업자 절반·게임 배치로 LLM을 다시 켬. 그동안 들어온 요청은 기다리고, 처음 음성 요청에 "잠깐만요, 게임 모드로 바꾸는 중이에요"를 한 번 말함. 게임이 끝나고 30초 뒤(설정) 평소 배치로 되돌림. 게임 몫을 비울 수 없거나 "게임 중 일시정지"를 켜면 LLM을 멈추고 답하지 않음. 대시보드에 "성능 단계: 게임 중 · 게임에 X GB". 설정: 게임용 VRAM(8GB), 되돌리기 대기(30초), 게임 중 일시정지(끔). 실제 게임PC 확인은 아직. 다음: 게임 중 답하는 동안 부분 전사 멈추기(M0 `gamemode_tune` 결정). | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 | M0에서 확인할 항목: diff --git a/src/voice_worker/server.py b/src/voice_worker/server.py index ff5732d..9195575 100644 --- a/src/voice_worker/server.py +++ b/src/voice_worker/server.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import contextlib import hmac import ipaddress import itertools @@ -38,6 +39,15 @@ def is_loopback(host: str) -> bool: return False +# How long a request waits for the LLM to come back from a switch (a restart takes 30-50 s; the +# first game switch also measures once). +LLM_WAIT_S = 180.0 + + +class _LlmPaused(Exception): + """The app paused the LLM (a game runs): nothing is answered until it is ready again.""" + + class VoiceWorker: def __init__(self, token: str, transcriber: Transcriber | None, vad_factory: Callable[[], VadStream], tts_engine: TtsEngine | None = None, hello_timeout_s: float = 5.0, tick_s: float = 0.05, @@ -59,6 +69,16 @@ class VoiceWorker: # memory and delete confirmations ("the very next message") follow the order they asked. self.brain_lanes = {"voice": asyncio.Lock(), "chat": asyncio.Lock()} self.brain_people: dict[str, asyncio.Lock] = {} + # The LLM's state from the app (voice_worker.spec.md, "LLM switches"): while it switches or + # is paused no new brain work starts; the brain work running when a switch is announced + # finishes first, then the app is told the brain is idle. + self.llm_state = "ready" + self.llm_ready = asyncio.Event() + self.llm_ready.set() + self.llm_notice: str | None = None + self.llm_noticed = False + self.llm_active = 0 + self.llm_idle_to = None # the session to tell once nothing runs self.chat_timeout_s = chat_timeout_s self.delivery_timeout_s = delivery_timeout_s # a chat answer the app never reports: not posted # chat_action ids are unique across connections and worker runs, so a late answer from an @@ -320,7 +340,7 @@ class Session: "addressed": self._on_addressed, "rank": self._on_rank, "chat_channels": self._on_chat_channels, "chat_action_result": self._on_chat_action_result, "memory_config": self._on_memory_config, "reply_delivered": self._on_reply_delivered, - "prepare": self._on_prepare}.get(kind) + "prepare": self._on_prepare, "llm": self._on_llm}.get(kind) if handler is None: self.error("bad_message", f"unknown type: {kind!r}") return @@ -519,6 +539,56 @@ class Session: waiting[user] = waiting.get(user, 0) + 1 asyncio.get_running_loop().create_task(self._reply(rid, user, text, via, speak, early)) + def _on_llm(self, msg: dict) -> None: + state, notice = msg.get("state"), msg.get("notice") + if state not in ("switching", "ready", "paused") or not (notice is None or isinstance(notice, str)): + self.error("bad_message", "llm needs state switching|ready|paused and an optional string notice") + return + w = self.worker + w.llm_state = state + debug_log(f"llm {state}", "llm") + if state == "ready": + w.llm_notice, w.llm_idle_to = None, None + w.llm_ready.set() + return + w.llm_ready.clear() + if state == "switching": + w.llm_notice, w.llm_noticed = notice or None, False + w.llm_idle_to = self + self._llm_check_idle() + else: + w.llm_ready.set() # paused: waiting requests stop waiting and answer nothing + + def _llm_check_idle(self) -> None: + w = self.worker + if w.llm_state == "switching" and w.llm_active == 0 and w.llm_idle_to is not None: + to, w.llm_idle_to = w.llm_idle_to, None + to.send({"type": "llm_idle"}) + + @contextlib.asynccontextmanager + async def _llm(self, notice_id: str | None = None): + """Brain work that uses the LLM: it waits while the LLM switches (the first spoken request + that waits hears the notice once, under its own id), fails while paused, and counts as + running so a switch waits for it.""" + w = self.worker + while w.llm_state != "ready": + if w.llm_state == "paused": + raise _LlmPaused() + if notice_id and w.llm_notice and not w.llm_noticed: + w.llm_noticed = True + # The newline ends it as a sentence, so it is spoken now, not joined to the answer. + self._on_tts({"type": "tts", "id": notice_id, "text": w.llm_notice + "\n", "more": True}) + try: + await asyncio.wait_for(w.llm_ready.wait(), LLM_WAIT_S) + except asyncio.TimeoutError: + break # go on: the call fails on its own if the LLM is still away + w.llm_active += 1 + try: + yield + finally: + w.llm_active -= 1 + self._llm_check_idle() + def _on_prepare(self, msg: dict) -> None: """A call still being said: the brain gets ready for it. One prepare per user runs at a time; while it runs only the newest text waits, and one about the same as the last one prepared @@ -544,7 +614,8 @@ class Session: while text is not None and not self.closed: self.last_prepared[user] = text try: - await asyncio.to_thread(self.worker.brain.prepare, user, text, bool(self.chat_channels)) + async with self._llm(): + await asyncio.to_thread(self.worker.brain.prepare, user, text, bool(self.chat_channels)) except Exception as e: # the brain must never take the session down debug_log(f"brain prepare failed: {type(e).__name__}", "llm") newer, self.preparing[user] = self.preparing[user], None @@ -563,7 +634,8 @@ class Session: async def judge(): try: - yes = await asyncio.to_thread(self.worker.brain.addressed, user, text, list(self.settings.hotwords)) + async with self._llm(): + yes = await asyncio.to_thread(self.worker.brain.addressed, user, text, list(self.settings.hotwords)) except Exception as e: # the brain must never take the session down debug_log(f"brain addressed {qid} failed: {type(e).__name__}", "llm") yes = None @@ -585,7 +657,8 @@ class Session: async def rank(): try: - order = await asyncio.to_thread(self.worker.brain.rank, cands) + async with self._llm(): + order = await asyncio.to_thread(self.worker.brain.rank, cands) except Exception as e: debug_log(f"brain rank {qid} failed: {type(e).__name__}", "llm") order = None @@ -658,11 +731,14 @@ class Session: chat = ChatBridge(self, asyncio.get_running_loop(), turn, w.pending_deletes.setdefault(user, {})) \ if self.chat_channels else None try: - answer = await asyncio.to_thread(w.brain.reply, user, text, history, chat=chat) + async with self._llm(rid if speak else None): + answer = await asyncio.to_thread(w.brain.reply, user, text, history, chat=chat) except Exception as e: # the brain must never take the session down debug_log(f"brain reply {rid} failed: {type(e).__name__}", "llm") answer = None answer = (answer or "").strip() + if not answer and rid in self.tts_requests: + self._on_tts({"type": "tts", "id": rid, "text": "", "more": False}) # ends the notice's speech self.send({"type": "reply_text", "id": rid, "text": answer, "failed": not answer}) # The answer reaches them when spoken (tts_done) or when the app reports the post # (reply_delivered); an unspoken voice answer has nothing more to wait for. diff --git a/src/voice_worker/voice_worker.spec.md b/src/voice_worker/voice_worker.spec.md index cb2c482..0b22be7 100644 --- a/src/voice_worker/voice_worker.spec.md +++ b/src/voice_worker/voice_worker.spec.md @@ -348,6 +348,29 @@ still deleted (below). - Each run is a `notice` line (category `voice_worker`): the target's name and how many new items, or a `Warning` with the error's type. Never a URL, words or collected text. +### LLM switches (M7) + +The app restarts the LLM with another placement when a game starts or ends (app/src/admin.spec.md, +"Performance stages"). It tells the worker first and waits for the brain to be idle: + +``` +-> {"type": "llm", "state": "switching", "notice": "잠깐만요, 게임 모드로 바꾸는 중이에요"} // notice optional +<- {"type": "llm_idle"} // nothing that uses the LLM runs any more +-> {"type": "llm", "state": "ready"} // the LLM answers again +-> {"type": "llm", "state": "paused"} // the LLM is stopped (a game runs) +``` + +- Brain work that uses the LLM (`reply`, `prepare`, `addressed`, `rank`) counts as running from its + start to its end. On `switching` new work waits; `llm_idle` goes to the connection that sent + `switching` once nothing runs (at once when nothing does). On `ready` what waited goes on. +- The first spoken `reply` that waits during one switch hears the notice under its own id (its + answer follows in the same speech when ready); later ones wait without it. A notice ends with a + newline, so it is spoken at once and never joined to the answer. A request waits at most 180 s, + then goes on (its LLM call fails on its own if the LLM is still away). +- On `paused` brain work answers nothing at once (`reply_text` `failed`, judgements failed) until + `ready`; what waited for a switch stops waiting the same way. +- Any other `state`, or a notice that is not a string, is `bad_message`. + ### Errors `{"type": "error", "code": "...", "message": "...", "id": "..."}`. Codes: `bad_message` (unknown type, diff --git a/tests/test_voice_worker_brain.py b/tests/test_voice_worker_brain.py index aadbd3c..1e579c0 100644 --- a/tests/test_voice_worker_brain.py +++ b/tests/test_voice_worker_brain.py @@ -1130,3 +1130,96 @@ def test_worker_logs_name_their_service_so_the_app_puts_them_in_its_tab(store, m err = capfd.readouterr().err for cat, what in (("stt", "utterance end"), ("llm", "brain reply r1 failed"), ("tts", "tts sentence id=t1")): assert any(line.startswith(f"[{cat:^10}]") and what in line for line in err.splitlines()), (cat, err[-2000:]) + + +async def drain(ws, seconds): + """Every message that arrives within `seconds`.""" + out, end = [], asyncio.get_running_loop().time() + seconds + while (left := end - asyncio.get_running_loop().time()) > 0: + try: + raw = await asyncio.wait_for(ws.recv(), left) + except asyncio.TimeoutError: + break + out.append(raw if isinstance(raw, bytes) else json.loads(raw)) + return out + + +@pytest.mark.unit +def test_an_llm_switch_waits_for_the_answer_in_progress_then_holds_new_ones_with_one_notice(store): + """voice_worker.spec.md, "LLM switches": the app switches the LLM only once the brain is idle; + requests meanwhile wait, the first spoken one hears the notice once, and all are answered once + the LLM is ready.""" + import threading + release = threading.Event() + + def slow_first(user, text): + if text == "first": + release.wait(10) + return f"answer for {text}" + + tts = FakeTts() + + async def body(url): + async with connect(url) as ws: + await hello(ws) + await send(ws, type="voice_join", channel="vc1") + await send(ws, type="reply", id="r1", user="100", text="first", via="voice", speak=True) + await asyncio.sleep(0.1) + await send(ws, type="llm", state="switching", notice="잠깐만요, 바꾸는 중이에요") + # Not idle while the first answer is being written. + seen = [] + try: + seen += await asyncio.wait_for(recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "llm_idle"), 0.3) + idle_early = True + except asyncio.TimeoutError: + idle_early = False + release.set() + seen += await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "llm_idle") + # Two requests while switching: they wait; only the first spoken one hears the notice. + await send(ws, type="reply", id="r2", user="200", text="second", via="voice", speak=True) + await send(ws, type="reply", id="r3", user="300", text="third", via="voice", speak=True) + seen += await drain(ws, 0.4) + answered_while_switching = [m["id"] for m in seen if isinstance(m, dict) and m.get("type") == "reply_text"] + await send(ws, type="llm", state="ready") + seen += await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "tts_done" and m["id"] == "r3") + return idle_early, answered_while_switching, seen + + brain = FakeBrain(slow_first) + idle_early, early, seen = asyncio.run(with_worker(body, store=store, brain=brain, tts=tts)) + assert not idle_early, "idle only after the answer in progress" + assert "r2" not in early and "r3" not in early, "nothing new is answered while switching" + assert [c[1] for c in brain.calls] == ["first", "second", "third"] + assert tts.texts.count("잠깐만요, 바꾸는 중이에요") == 1, tts.texts + done = {m["id"]: m for m in seen if isinstance(m, dict) and m.get("type") == "tts_done"} + assert not done["r2"]["failed"] and not done["r3"]["failed"] + # r2 heard the notice, then its answer, under its own id. + assert tts.texts.index("잠깐만요, 바꾸는 중이에요") < tts.texts.index("answer for second") + + +@pytest.mark.unit +def test_while_paused_the_brain_answers_nothing(store): + async def body(url): + async with connect(url) as ws: + await hello(ws) + await send(ws, type="llm", state="switching") + await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "llm_idle") + await send(ws, type="llm", state="paused") + await send(ws, type="reply", id="r1", user="100", text="q", via="chat", speak=False) + return await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "reply_text") + + brain = FakeBrain() + seen = asyncio.run(with_worker(body, store=store, brain=brain)) + reply = [m for m in seen if isinstance(m, dict) and m.get("type") == "reply_text"][0] + assert reply["failed"] and brain.calls == [] + + +@pytest.mark.unit +def test_an_unknown_llm_state_is_refused(store): + async def body(url): + async with connect(url) as ws: + await hello(ws) + await send(ws, type="llm", state="maybe") + return await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "error") + + seen = asyncio.run(with_worker(body, store=store, brain=FakeBrain())) + assert [m for m in seen if isinstance(m, dict) and m.get("type") == "error"][0]["code"] == "bad_message"