From 1400a3ff97f9d01ab96f403fa3fa4f5470cfb41b Mon Sep 17 00:00:00 2001 From: javis-bot Date: Sat, 14 Nov 2026 10:01:53 +0900 Subject: [PATCH] fix(app): the LLM placement measures only what it can trust and keeps a game the 0 GiB step - a measurement whose short answer fails, or whose second card reading fails or shows nothing more held, is not kept: the model starts with expert-vram=0 and the next start measures again - measurements are kept per context and requests at once (/) and per card (its NVIDIA UUID), not by the card's size - a server on this app's port left from a run that ended badly is stopped before the card is read, so its memory is not counted as other programs' - the game placement falls back to 0 GiB of experts before pausing when 2 GiB leaves a game nothing Co-Authored-By: Claude Opus 5.5 --- app/src/admin.spec.md | 14 ++- app/src/placement.rs | 42 +++++--- app/src/strata.rs | 231 ++++++++++++++++++++++++++++++++++-------- docs/v2/roadmap.md | 2 +- 4 files changed, 230 insertions(+), 59 deletions(-) diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 78b0a38..b76a8cd 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -386,10 +386,16 @@ start it first, so nothing answers before the brain can, and stop it last. experts, the STT worker's share (2740 MiB: its model and ten speakers at once, M0 `stt`), the engine's margin (768 MiB) and the room for programs opened later (`game.otherRoomGb`, default 1 GB); the budget first holds the long-prompt staging, rounded down to 0.1 GiB, 0 when nothing is - left. What the model holds without experts is measured once per context and card (the first-run - self-check: a start with `expert-vram=0`, one short answer, then the card's memory again and the - staging from the engine log), kept in `config/llm-probe.json`; the real start then replaces that - server. Without a card nothing is set. The `llm` log tab gets the placement and what it came from. + left. What the model holds without experts is measured once per context, number of requests at + once and card (its NVIDIA UUID): the first-run self-check, a start with `expert-vram=0`, one + short answer, then the card's memory again and the staging from the engine log; kept in + `config/llm-probe.json` under `/`, and the real start then replaces that + server. A measurement whose answer or second reading fails (or shows nothing more held) is not + kept: the model starts with `expert-vram=0` and the next start measures again. A server of this + app's port that still answers before the start (left from a run that ended badly) is stopped + first, so it is not counted as other programs' memory. Without a card nothing is set. The game + placement (used by the switching that comes next) takes the reserve when it fits beside more + than 2 GiB of experts, else 2 GiB and the room that leaves, else 0 GiB and its room, else pause. The `llm` log tab gets the placement and what it came from. - **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` diff --git a/app/src/placement.rs b/app/src/placement.rs index 061da67..edb8662 100644 --- a/app/src/placement.rs +++ b/app/src/placement.rs @@ -19,12 +19,14 @@ pub const MIN_GAME_EXPERT_GIB: f64 = 2.0; pub const GAME_CONTEXT: u32 = 16384; /// What one start without experts at `context` showed on this PC (the first-run self-check). -#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Probe { pub context: u32, - /// The card's size when it was measured (another card means measuring again). - pub total_mib: i64, + /// Requests answered at once, which changes the engine's buffers. + pub parallel: u32, + /// The card measured (its NVIDIA UUID): another card means measuring again. + pub gpu: String, /// What the LLM held without experts. pub model_mib: i64, /// The long-prompt staging the expert budget holds first (engine log, "x.xx GiB staging"). @@ -58,16 +60,22 @@ pub fn normal(total_mib: i64, used_mib: i64, p: &Probe, other_room_mib: i64) -> } /// The game placement: experts get what is left after the game's reserve, but never less than the -/// smallest placement; then the game gets what that leaves (shown on the dashboard), and with no -/// room at all the LLM pauses. `p` is the probe at `GAME_CONTEXT`. +/// smallest placement (2 GiB); then the game gets what that leaves (shown on the dashboard). When +/// 2 GiB leaves a game nothing, no experts on the card (0 GiB) is the last step; with no room even +/// then the LLM pauses. `p` is the probe at `GAME_CONTEXT`. pub fn game(total_mib: i64, used_mib: i64, p: &Probe, reserve_mib: i64) -> GamePlacement { let expert = expert_budget_gib(total_mib, used_mib, p, reserve_mib); if expert >= MIN_GAME_EXPERT_GIB { return GamePlacement { expert_gib: expert, game_room_mib: reserve_mib, paused: false }; } + // Beside the model without experts (which already holds the staging): what 2 GiB adds. + let free = total_mib - used_mib - p.model_mib - STT_MIB - MARGIN_MIB; let extra = ((MIN_GAME_EXPERT_GIB - p.staging_gib) * 1024.0).max(0.0) as i64; - let room = total_mib - used_mib - p.model_mib - STT_MIB - MARGIN_MIB - extra; - GamePlacement { expert_gib: MIN_GAME_EXPERT_GIB, game_room_mib: room.max(0), paused: room <= 0 } + if free - extra > 0 { + return GamePlacement { expert_gib: MIN_GAME_EXPERT_GIB, game_room_mib: free - extra, paused: false }; + } + // The last step before pausing: no experts on the card (slower, but the game gets room). + GamePlacement { expert_gib: 0.0, game_room_mib: free.max(0), paused: free <= 0 } } /// The staging the engine log reports ("(1.10 GiB staging)"), else the usual 1.1 GiB. @@ -86,21 +94,23 @@ mod tests { /// included the STT model (1300 MiB), which the app starts after the LLM. const TOTAL: i64 = 16303; const OTHERS: i64 = 2760 - 1300; - const PROBE32: Probe = Probe { context: 32768, total_mib: TOTAL, model_mib: 9874, staging_gib: 1.1 }; + fn probe32() -> Probe { + Probe { context: 32768, parallel: 1, gpu: "GPU-test".into(), model_mib: 9874, staging_gib: 1.1 } + } #[test] fn the_normal_placement_is_the_one_m0_measured_with_room_for_the_stt() { // M0 got 1.5 GiB (the STT model counted as already held); the app counts it in the STT share. - assert_eq!(normal(TOTAL, OTHERS, &PROBE32, 1024), 1.5); + assert_eq!(normal(TOTAL, OTHERS, &probe32(), 1024), 1.5); // More room for other programs, fewer experts; no room at all, none. - assert!(normal(TOTAL, OTHERS, &PROBE32, 2048) < 1.5); - assert_eq!(normal(TOTAL, OTHERS + 8000, &PROBE32, 1024), 0.0); + assert!(normal(TOTAL, OTHERS, &probe32(), 2048) < 1.5); + assert_eq!(normal(TOTAL, OTHERS + 8000, &probe32(), 1024), 0.0); } #[test] fn a_game_gets_its_reserve_or_what_the_smallest_placement_leaves_or_the_llm_pauses() { // 16K saves about 0.7 GB of conversation memory (M0). - let probe16 = Probe { context: GAME_CONTEXT, model_mib: 9874 - 750, ..PROBE32 }; + let probe16 = Probe { context: GAME_CONTEXT, model_mib: 9874 - 750, ..probe32() }; // 8 GB does not fit on 16 GB: the smallest placement, and the game gets what is left. let g = game(TOTAL, OTHERS, &probe16, 8192); assert_eq!((g.expert_gib, g.paused), (MIN_GAME_EXPERT_GIB, false)); @@ -108,11 +118,15 @@ mod tests { assert_eq!(g.game_room_mib, expected); assert!(g.game_room_mib > 0 && g.game_room_mib < 8192); // A bigger card keeps the whole reserve, with more experts than the minimum. - let big = game(24 * 1024, OTHERS, &Probe { total_mib: 24 * 1024, ..probe16 }, 8192); + let big = game(24 * 1024, OTHERS, &probe16, 8192); assert_eq!(big.game_room_mib, 8192); assert!(big.expert_gib > MIN_GAME_EXPERT_GIB && !big.paused); + // No room beside 2 GiB but some beside none: the 0 GiB placement, before pausing. + let tight = game(TOTAL, 2960, &Probe { model_mib: 9124, ..probe16.clone() }, 8192); + assert_eq!((tight.expert_gib, tight.paused), (0.0, false)); + assert_eq!(tight.game_room_mib, TOTAL - 2960 - 9124 - STT_MIB - MARGIN_MIB); // Other programs already hold the card: no room for a game, the LLM pauses in one. - let full = game(TOTAL, OTHERS + 3000, &probe16, 8192); + let full = game(TOTAL, OTHERS + 4000, &probe16, 8192); assert!(full.paused); assert_eq!(full.game_room_mib, 0); } diff --git a/app/src/strata.rs b/app/src/strata.rs index 4e24720..55eaa07 100644 --- a/app/src/strata.rs +++ b/app/src/strata.rs @@ -72,12 +72,20 @@ fn placement_sets(expert_gib: f64) -> Vec { vec![format!("expert-vram={expert_gib}"), "prefill=2048".into()] } -/// Graphics memory `(used, total)` in MiB of the first NVIDIA card, from `nvidia-smi`; None without one. -pub type GpuReader = Arc Option<(i64, i64)> + Send + Sync>; +/// The first NVIDIA card: its UUID and graphics memory in MiB. +#[derive(Debug, Clone, PartialEq)] +pub struct Gpu { + pub id: String, + pub used_mib: i64, + pub total_mib: i64, +} -fn nvidia_memory() -> Option<(i64, i64)> { +/// Reads the card (`nvidia-smi`); None without one. +pub type GpuReader = Arc Option + Send + Sync>; + +fn nvidia_memory() -> Option { let mut cmd = std::process::Command::new("nvidia-smi"); - cmd.args(["--query-gpu=memory.used,memory.total", "--format=csv,noheader,nounits"]); + cmd.args(["--query-gpu=uuid,memory.used,memory.total", "--format=csv,noheader,nounits"]); #[cfg(windows)] { use std::os::windows::process::CommandExt; @@ -85,8 +93,8 @@ fn nvidia_memory() -> Option<(i64, i64)> { } let out = cmd.output().ok()?; let line = String::from_utf8_lossy(&out.stdout).lines().next()?.to_owned(); - let (used, total) = line.split_once(',')?; - Some((used.trim().parse().ok()?, total.trim().parse().ok()?)) + let mut f = line.split(',').map(str::trim); + Some(Gpu { id: f.next()?.to_owned(), used_mib: f.next()?.parse().ok()?, total_mib: f.next()?.parse().ok()? }) } /// The newest engine log under Strata's folder, its end only (the placement lines of the last start). @@ -167,16 +175,29 @@ pub async fn wait_ready(base: &str, timeout: Duration, cancel: &AtomicBool) -> R } } -/// One short answer, so the engine has made its buffers before its memory is read (M0 kit). -async fn warm_up(base: &str) { - let Ok(client) = reqwest::Client::builder().timeout(Duration::from_secs(60)).build() else { return }; +/// Whether a server answers `/models` at `base` (within 2 s). +async fn answers(base: &str) -> bool { + let Ok(client) = reqwest::Client::builder().timeout(Duration::from_secs(2)).build() else { return false }; + client.get(format!("{base}/models")).send().await.is_ok_and(|r| r.status().is_success()) +} + +/// One short answer, so the engine has made its buffers before its memory is read (M0 kit); an +/// error when the model gives none. +async fn warm_up(base: &str) -> Result<(), String> { + let client = reqwest::Client::builder().timeout(Duration::from_secs(60)).build().map_err(|e| e.to_string())?; let model = match client.get(format!("{base}/models")).send().await { Ok(r) => r.text().await.ok().and_then(|t| serde_json::from_str::(&t).ok()) .and_then(|v| v["data"][0]["id"].as_str().map(str::to_owned)), Err(_) => None, }; let body = json!({"model": model, "messages": [{"role": "user", "content": "안녕"}], "max_tokens": 8}); - let _ = client.post(format!("{base}/chat/completions")).header("content-type", "application/json").body(body.to_string()).send().await; + let r = client.post(format!("{base}/chat/completions")).header("content-type", "application/json") + .body(body.to_string()).send().await.map_err(|e| e.to_string())?; + if !r.status().is_success() { + return Err(format!("the model answered {}", r.status())); + } + let v: Value = serde_json::from_str(&r.text().await.map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; + v["choices"][0]["message"].is_object().then_some(()).ok_or_else(|| "the model gave no answer".into()) } /// The brain's settings (`config/brain.json`, the worker's `JARVIS_CONFIG_PATH`): the LLM, the @@ -241,7 +262,7 @@ impl Llm { self } - async fn read_gpu(&self) -> Option<(i64, i64)> { + async fn read_gpu(&self) -> Option { let gpu = self.gpu.clone()?; tokio::task::spawn_blocking(move || gpu()).await.ok().flatten() } @@ -251,34 +272,50 @@ impl Llm { } /// The expert budget's engine settings (none without a card): the normal placement from what - /// the card holds now and this PC's measurement without experts at this context, which the - /// first start makes once (a start without experts, then the real start replaces it). + /// the card holds now and this PC's measurement without experts at this context and number of + /// requests at once, which the first start makes once per card (a start without experts, then + /// the real start replaces it). A server left from an earlier run is stopped first, so it is not + /// counted as another program's memory. 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> { - let Some((used, total)) = self.read_gpu().await else { return Ok(vec![]) }; - let context = settings.llm.context; + if self.gpu.is_none() { + return Ok(vec![]); + } + if answers(base).await { + crate::info_log!("llm", "a server from an earlier run still answers; stopping it first"); + self.stop_server().await?; + } + 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 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(); - let known = all.get(&context.to_string()).and_then(|v| serde_json::from_value::(v.clone()).ok()) - .filter(|p| p.total_mib == total); + let known = all.get(&key).and_then(|v| serde_json::from_value::(v.clone()).ok()) + .filter(|p| p.gpu == card.id); let probe = match known { Some(p) => p, None => { - crate::info_log!("llm", "measuring the model without experts once (context {context})"); + 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?; - warm_up(base).await; - let after = self.read_gpu().await.map(|(u, _)| u).unwrap_or(used); - let p = crate::placement::Probe { context, total_mib: total, model_mib: (after - used).max(0), + 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 p = crate::placement::Probe { context, parallel, gpu: card.id.clone(), model_mib, staging_gib: crate::placement::staging_gib(&engine_log(&self.layout.strata_home())) }; - all.insert(context.to_string(), json!(p)); + all.insert(key, json!(p)); crate::datadir::write_atomic(&file, Value::Object(all).to_string().as_bytes()) .map_err(|e| format!("배치 측정값을 저장하지 못했습니다: {e}"))?; p } }; - let expert = crate::placement::normal(total, used, &probe, settings.game.other_room_mib()); - crate::info_log!("llm", "placement: experts {expert} GiB (card {total} MiB, held by others {used} MiB, model without experts {} MiB)", - probe.model_mib); + 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)) } @@ -533,12 +570,23 @@ mod tests { let port = listener.local_addr().unwrap().port(); let opened = Instant::now(); tokio::spawn(async move { + let mut listener = listener; while let Ok((mut s, _)) = listener.accept().await { if gone.as_ref().is_some_and(|g| g.exists()) { - return; // the listener closes: later connections are refused + // The listener closes: later connections are refused, until a launch serves + // again (removes `gone`). + drop(s); + drop(listener); + let g = gone.clone().unwrap(); + while g.exists() { + tokio::time::sleep(Duration::from_millis(50)).await; + } + listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap(); + continue; } let mut buf = [0u8; 1024]; - let _ = s.read(&mut buf).await; + let n = s.read(&mut buf).await.unwrap_or(0); + let post = buf[..n].starts_with(b"POST"); let m = *mode.lock().unwrap(); let (status, body) = match m { "hang" => { @@ -549,6 +597,8 @@ mod tests { continue; } "503" => ("503 Service Unavailable", r#"{"error":"loading model"}"#.to_owned()), + "nochat" if post => ("500 Internal Server Error", r#"{"error":"broken"}"#.to_owned()), + _ if post => ("200 OK", r#"{"choices":[{"message":{"content":"안녕하세요"}}]}"#.to_owned()), _ if opened.elapsed() >= delay => ("200 OK", format!(r#"{{"data":[{{"id":"{id}"}}]}}"#)), _ => ("200 OK", "{}".to_owned()), }; @@ -645,19 +695,14 @@ mod tests { #[tokio::test] async fn with_a_graphics_card_the_first_start_measures_the_llm_without_experts_then_places_them() { let l = layout("llm-place"); - let port = models_server_until("qwen-test", Duration::from_millis(0), Some(l.data.join("gone"))).await; + let port = server_after_launch(&l, "list").await; // The engine log, as Strata 0.1.59's qwen36 engine writes it. let log = l.strata_home().join("x.engine.log"); let exe = fake_strata(&l, &format!("rm -f '{}'; echo 'strata-q36: hybrid experts: 0 of 256 per layer in VRAM, bigger prompt chunks streamed (1.10 GiB staging); 7.1 s' >> '{}'; echo 'Strata is serving.'", l.data.join("gone").display(), log.display())); // The game PC in M0 (16303 MiB card, 1460 MiB held by other programs); the LLM without // experts held 9874 MiB. - let reads = Arc::new(std::sync::atomic::AtomicU32::new(0)); - let r2 = reads.clone(); - let llm = Llm::with_exe(l.clone(), exe).with_gpu(Arc::new(move || { - let n = r2.fetch_add(1, Ordering::SeqCst); - Some((if n == 1 { 1460 + 9874 } else { 1460 }, 16303)) - })); + let llm = Llm::with_exe(l.clone(), exe).with_gpu(card(&l, "GPU-test", 0)); let s = parse_settings(&json!({"llm": {"port": port}})).unwrap(); tokio::time::timeout(Duration::from_secs(20), llm.start(&s)).await.expect("starts").unwrap(); let calls = std::fs::read_to_string(l.data.join("calls")).unwrap(); @@ -667,20 +712,126 @@ mod tests { // The M0 kit's normal placement on that PC: 1.5 GiB of experts. assert!(launches[1].ends_with("--set expert-vram=1.5 --set prefill=2048"), "{}", launches[1]); let probe: Value = serde_json::from_str(&std::fs::read_to_string(l.data.join("config").join("llm-probe.json")).unwrap()).unwrap(); - assert_eq!(probe["32768"], json!({"context": 32768, "totalMib": 16303, "modelMib": 9874, "stagingGib": 1.1})); + assert_eq!(probe["32768/1"], json!({"context": 32768, "parallel": 1, "gpu": "GPU-test", "modelMib": 9874, "stagingGib": 1.1})); llm.stop().await.unwrap(); - // The next start reuses the measurement: one launch, placed at once (a new server, as the - // fake one does not come back after a stop). + // The next start reuses the measurement: one launch, placed at once. std::fs::remove_file(l.data.join("calls")).unwrap(); - let port2 = models_server_until("qwen-test", Duration::from_millis(0), None).await; - let s2 = parse_settings(&json!({"llm": {"port": port2}})).unwrap(); - tokio::time::timeout(Duration::from_secs(20), llm.start(&s2)).await.expect("starts").unwrap(); + tokio::time::timeout(Duration::from_secs(20), llm.start(&s)).await.expect("starts").unwrap(); let calls = std::fs::read_to_string(l.data.join("calls")).unwrap(); let launches: Vec<&str> = calls.lines().filter(|c| c.starts_with("launch --family")).collect(); assert_eq!(launches.len(), 1, "{calls}"); assert!(launches[0].ends_with("--set expert-vram=1.5 --set prefill=2048"), "{}", launches[0]); } + /// A fake card for `fake_placed`: 16303 MiB, 1460 MiB held by other programs (and by any + /// 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 { + let calls = l.data.join("calls"); + Arc::new(move || { + let c = std::fs::read_to_string(&calls).unwrap_or_default(); + let stopped = c.contains("launch --stop"); + let running = c.lines().last().is_some_and(|x| x.starts_with("launch --family")); + let used = 1460 + if running { 9874 } else if stopped { 0 } else { leftover }; + Some(Gpu { id: id.into(), used_mib: used, total_mib: 16303 }) + }) + } + + /// 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 { + 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.'", + 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 { + 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 { + 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() + } + + #[cfg(unix)] + #[tokio::test] + async fn a_failed_measurement_is_not_kept_and_the_model_starts_without_experts() { + // The card stops answering after the first read. + let l = layout("llm-place-fail"); + let port = server_after_launch(&l, "list").await; + let reads = Arc::new(std::sync::atomic::AtomicU32::new(0)); + let r2 = reads.clone(); + let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(Arc::new(move || { + (r2.fetch_add(1, Ordering::SeqCst) == 0).then(|| Gpu { id: "GPU-test".into(), used_mib: 1460, total_mib: 16303 }) + })); + let s = parse_settings(&json!({"llm": {"port": port}})).unwrap(); + tokio::time::timeout(Duration::from_secs(20), llm.start(&s)).await.expect("starts").unwrap(); + let l2 = launches(&l); + assert_eq!(l2.len(), 2, "{l2:?}"); + assert!(l2[1].ends_with("--set expert-vram=0 --set prefill=2048"), "{}", l2[1]); + assert!(!l.data.join("config").join("llm-probe.json").exists(), "nothing kept"); + llm.stop().await.unwrap(); + // The model does not answer the short question: not kept either. + let l = layout("llm-place-nochat"); + let port = server_after_launch(&l, "nochat").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(); + tokio::time::timeout(Duration::from_secs(20), llm.start(&s)).await.expect("starts").unwrap(); + assert!(launches(&l)[1].ends_with("--set expert-vram=0 --set prefill=2048")); + assert!(!l.data.join("config").join("llm-probe.json").exists(), "nothing kept"); + } + + #[cfg(unix)] + #[tokio::test] + async fn the_measurement_is_kept_per_requests_at_once_and_per_card() { + let l = layout("llm-place-keys"); + let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(card(&l, "GPU-a", 0)); + let port = server_after_launch(&l, "list").await; + let one = parse_settings(&json!({"llm": {"port": port}})).unwrap(); + llm.start(&one).await.unwrap(); + assert_eq!(launches(&l).len(), 2, "measured once"); + llm.stop().await.unwrap(); + // A chat channel that answers everything: two requests at once, measured again. + std::fs::remove_file(l.data.join("calls")).unwrap(); + let two = parse_settings(&json!({"llm": {"port": port}, "chatChannels": [{"id": "123456789012345678", "answer": "everything"}]})).unwrap(); + assert_eq!(parallel(&two), 2); + llm.start(&two).await.unwrap(); + assert_eq!(launches(&l).len(), 2, "measured for two at once"); + assert!(launches(&l)[0].contains("--parallel 2")); + llm.stop().await.unwrap(); + // Another card (same size): measured again. + std::fs::remove_file(l.data.join("calls")).unwrap(); + let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(card(&l, "GPU-b", 0)); + llm.start(&one).await.unwrap(); + assert_eq!(launches(&l).len(), 2, "measured for the new card"); + let probe: Value = serde_json::from_str(&std::fs::read_to_string(l.data.join("config").join("llm-probe.json")).unwrap()).unwrap(); + assert_eq!((probe["32768/1"]["gpu"].clone(), probe["32768/2"]["gpu"].clone()), (json!("GPU-b"), json!("GPU-a"))); + llm.stop().await.unwrap(); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_server_left_from_an_earlier_run_is_stopped_before_the_card_is_read() { + let l = layout("llm-place-left"); + // A server still answers on the port, holding 9874 MiB. + let port = models_server_until("qwen-test", Duration::from_millis(0), Some(l.data.join("gone"))).await; + let llm = Llm::with_exe(l.clone(), fake_placed(&l)).with_gpu(card(&l, "GPU-test", 9874)); + let s = parse_settings(&json!({"llm": {"port": port}})).unwrap(); + tokio::time::timeout(Duration::from_secs(30), llm.start(&s)).await.expect("starts").unwrap(); + let calls = std::fs::read_to_string(l.data.join("calls")).unwrap(); + assert!(calls.lines().next() == Some("launch --stop"), "stopped first: {calls}"); + let probe: Value = serde_json::from_str(&std::fs::read_to_string(l.data.join("config").join("llm-probe.json")).unwrap()).unwrap(); + assert_eq!(probe["32768/1"]["modelMib"], json!(9874), "the left server is not counted"); + assert!(launches(&l)[1].ends_with("--set expert-vram=1.5 --set prefill=2048"), "{:?}", launches(&l)); + llm.stop().await.unwrap(); + } + #[cfg(unix)] #[tokio::test] async fn a_cancel_during_the_download_stops_it_and_clears_the_server() { diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 7c97579..27950a9 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은 맥락·카드마다 처음 한 번 재서(`config/llm-probe.json`) 다시 씀. 게임PC M0 측정값으로 계산하면 M0와 같은 1.5GB. 게임 중 배치 계산(게임 몫 8GB를 못 비우면 최소 전문가 2GB와 남는 게임 몫, 그것도 안 되면 일시정지)도 넣음. 실제 게임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으로 켜며, 이전 실행에서 남은 서버는 먼저 끄고 잼. 게임PC M0 측정값으로 계산하면 M0와 같은 1.5GB. 게임 중 배치 계산(게임 몫 8GB를 못 비우면 최소 전문가 2GB와 남는 게임 몫, 그것도 안 되면 전문가 0GB, 그것도 안 되면 일시정지)도 넣음. 실제 게임PC 확인은 아직. 다음: 게임 감지에 따라 배치를 바꾸는 전환(답이 끝난 뒤 다시 시작, 그동안 요청 대기, 30초 뒤 되돌리기). | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 | M0에서 확인할 항목: