From c9101e0d6ae647c90ef28eb9261d3522dbad9eee Mon Sep 17 00:00:00 2001 From: javis-bot Date: Sat, 14 Nov 2026 09:08:50 +0900 Subject: [PATCH] feat(app): game detection for the performance stages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - while the services run the app looks at the foreground window every 2 s (Windows): the person's notGames and games lists first, never a browser, video player, the desktop, Discord, a launcher's own window or this app; a program under a Steam, Epic, Riot or Battle.net game folder, exclusive full screen, or a window covering a monitor without title bar or border whose process uses at least 10% of the GPU's 3D engine (the M0 rule) is a game - game mode stays until that game's process ends, also behind other windows; the dashboard shows "게임 모드: 켜짐 (name, reason)" and the game log tab its changes - a 게임 모드 settings screen (detection on/off, the two lists) - checked on the win-ci VM: a program in a Steam game folder turned it on after 1.4 s and off 2.0 s after it ended Co-Authored-By: Claude Opus 5.5 --- app/Cargo.toml | 2 +- app/src/admin.spec.md | 34 ++- app/src/control.rs | 4 +- app/src/game.rs | 456 +++++++++++++++++++++++++++++++++++++++ app/src/lib.rs | 1 + app/src/services.rs | 7 +- app/src/settings.rs | 36 ++++ app/src/settings_edit.rs | 5 + app/tests/game_watch.rs | 42 ++++ app/ui/app.js | 7 +- app/ui/index.html | 1 + docs/v2/roadmap.md | 2 +- 12 files changed, 588 insertions(+), 9 deletions(-) create mode 100644 app/src/game.rs create mode 100644 app/tests/game_watch.rs diff --git a/app/Cargo.toml b/app/Cargo.toml index c7041c2..01a9d37 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -45,7 +45,7 @@ codegen-units = 4 strip = "symbols" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security_Cryptography", "Win32_System_SystemInformation", "Win32_Devices_DeviceAndDriverInstallation", "Win32_Graphics_Gdi", "Win32_UI_WindowsAndMessaging", "Win32_System_Registry", "Win32_UI_Shell", "Win32_System_Threading"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security_Cryptography", "Win32_System_SystemInformation", "Win32_Devices_DeviceAndDriverInstallation", "Win32_Graphics_Gdi", "Win32_UI_WindowsAndMessaging", "Win32_System_Registry", "Win32_UI_Shell", "Win32_System_Threading", "Win32_System_Performance"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 84422a2..95d6493 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -191,8 +191,9 @@ reaches the screen. (`managed`), and while starting Strata's last line and how far that line says it got (its 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`. -- `performance`: the performance stage (normal, gaming, paused, and why) comes with game - detection in M7; until then `null`. +- `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`. 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. @@ -326,6 +327,27 @@ the browser runs headless with a note. - If the monitor or the window cannot be made, the browser runs headless and the dashboard's `browser` note says why ("가상 모니터 없이 실행: ..."). +## Game detection (`app/src/game.rs`) + +`docs/v2/pc-features.md`, "게임 감지 기준". Whether a game runs, for the performance stages (next +in M7). While the services run, the app looks at the foreground window every 2 s (Windows only; +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. Read when the services start. +- 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 (`\steamapps\common\`, + `\epic games\`, `\riot games\`, `\battle.net\`): yes (`launcher`, with the launcher's name); + Windows reports a full-screen Direct3D program (`fullscreen`): yes; its window covers one monitor + completely, has no title bar or sizing border, and its process uses at least 10% of the GPU's 3D + engine (`borderless`, the M0 check's rule): yes. +- Once seen, game mode stays until that game's process ends, also while another window is in + front; with `detect` off it is off. The name is the game's folder under the launcher folder, else + the program's name without ".exe". The `game` log tab gets "game mode on: name (reason)" and + "game mode off". + ## LLM (`app/src/strata.rs`) The brain answers with one model, Qwen3.6-35B-A3B UD-Q4_K_XL through Strata (M0). The services @@ -428,7 +450,7 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A Strata's last line, and stop in the header; the header with start, restart and stop is rebuilt only when the state changes, so a click is never lost to the refresh. Every screen change starts a new generation: an answer that arrives after the user moved to another screen is dropped. -- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델, 기능, 백그라운드 수집): built from `settings_fields`; only +- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델, 기능, 백그라운드 수집, 게임 모드): built from `settings_fields`; only changed fields are sent; the server and voice channel are pickers (choosing another server clears the voice channel and lists only that server's channels); the chat channels are a table with their switches; the bot screen also changes the token; the 기능 screen has the feature @@ -518,7 +540,11 @@ settings folder and the next install giving one working device, the monitor off while the bot browser runs and off after, one Chrome window there filling the work area and holding the bot's tab, the focus staying in the program the user types into, no taskbar button, no Chrome left after the stop, and the uninstall leaving no device, driver package, registry key or settings -folder. On every system: a removal forgets the driver only when no device is left and the package +folder. Game detection (`tests/game_watch.rs`): a program started from a Steam game folder turns +game mode on with the folder's name and off once it ends. 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, the person's lists first, staying on until the game ends, +detection off) and its settings. A removal forgets the driver only when no device is left and the package is gone or was not in the store; a failed install forgets it only under the same rule (and never when it was ours before), reporting both reasons otherwise; a leftover offers removal; driver tasks refused while the services start, and a start (and a second task) refused while one runs, also after it failed. On Linux the same window test runs on an X display (one window at the given place and diff --git a/app/src/control.rs b/app/src/control.rs index a00d3d4..96dfabe 100644 --- a/app/src/control.rs +++ b/app/src/control.rs @@ -274,7 +274,8 @@ impl Controller { view["error"] = json!(error); view["system"] = json!(self.system().await); view["llm"] = self.host.llm(); - view["performance"] = Value::Null; // game detection comes in M7 + view["game"] = status.get("game").cloned().unwrap_or(Value::Null); + view["performance"] = Value::Null; // the performance stages come next in M7 view } @@ -362,6 +363,7 @@ impl Running for crate::services::Services { .map(|(id, name)| json!({"id": id.to_string(), "name": name})).collect::>(), "missed": crate::dashboard::missed_view(&missed, now), "browser": self.browser.view(), + "game": self.game.view(), }) } } diff --git a/app/src/game.rs b/app/src/game.rs new file mode 100644 index 0000000..7f670e5 --- /dev/null +++ b/app/src/game.rs @@ -0,0 +1,456 @@ +//! Game detection (`docs/v2/pc-features.md`, "게임 감지 기준"; admin.spec.md, "Game detection"): +//! whether a game runs, from the foreground window, Windows' full-screen state and where the +//! program lives. It drives the performance stages (M7). Nothing here looks at the game's screen. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde::Serialize; + +use crate::settings::GameSettings; + +/// How often the foreground is looked at. +const EVERY: Duration = Duration::from_secs(2); +/// A borderless window counts as a game when its process uses at least this much of the GPU's 3D +/// engine (the M0 `games` check's threshold). +const MIN_GPU_3D: f64 = 10.0; + +/// Programs that are never games: browsers (also the bot's Chrome), video players, the desktop, +/// Discord, launchers' own windows and this app. +const NOT_GAMES: &[&str] = &[ + "chrome.exe", "msedge.exe", "firefox.exe", "opera.exe", "brave.exe", "whale.exe", "vivaldi.exe", + "msedgewebview2.exe", "vlc.exe", "potplayer.exe", "potplayermini.exe", "potplayermini64.exe", "mpc-hc.exe", + "mpc-hc64.exe", "mpc-be64.exe", "wmplayer.exe", "video.ui.exe", "explorer.exe", "discord.exe", "jarvis.exe", + "steam.exe", "steamwebhelper.exe", "epicgameslauncher.exe", "epicwebhelper.exe", "riotclientservices.exe", + "riot client.exe", "riotclientux.exe", "riotclientuxrender.exe", "leagueclient.exe", "leagueclientux.exe", + "leagueclientuxrender.exe", "battle.net.exe", "agent.exe", +]; + +/// Launcher game folders: a program under one counts as a game whatever its window looks like. +const LAUNCHERS: &[(&str, &str)] = &[ + ("\\steamapps\\common\\", "Steam"), + ("\\epic games\\", "Epic"), + ("\\riot games\\", "Riot"), + ("\\battle.net\\", "Battle.net"), +]; + +/// The foreground window as Windows reports it. +#[derive(Debug, Clone, PartialEq)] +pub struct Foreground { + pub pid: u32, + /// The program's full path. + pub path: String, + /// The window covers one monitor completely. + pub covers_monitor: bool, + /// No title bar and no sizing border. + pub no_frame: bool, + /// The process's use of the GPU's 3D engine, in percent. + pub gpu_3d: f64, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Snapshot { + pub foreground: Option, + /// Windows says a full-screen Direct3D program runs (exclusive full screen). + pub d3d_fullscreen: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", content = "launcher", rename_all = "camelCase")] +pub enum Reason { + Fullscreen, + Borderless, + Launcher(&'static str), + Registered, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Detected { + #[serde(skip)] + pub pid: u32, + pub name: String, + pub reason: Reason, +} + +fn file_name(path: &str) -> String { + path.rsplit(['\\', '/']).next().unwrap_or(path).to_lowercase() +} + +/// Whether `name` (a program's file name, lower case) is in `list`; list entries may leave out ".exe". +fn listed(name: &str, list: &[String]) -> bool { + list.iter().map(|e| e.trim().to_lowercase()).any(|e| e == name || format!("{e}.exe") == name) +} + +/// Why the foreground program is a game, or `None`. +pub fn classify(fg: &Foreground, d3d_fullscreen: bool, s: &GameSettings) -> Option { + let name = file_name(&fg.path); + if listed(&name, &s.not_games) { + return None; + } + if listed(&name, &s.games) { + return Some(Reason::Registered); + } + if NOT_GAMES.contains(&name.as_str()) { + return None; + } + let path = fg.path.to_lowercase().replace('/', "\\"); + if let Some((_, launcher)) = LAUNCHERS.iter().find(|(dir, _)| path.contains(dir)) { + return Some(Reason::Launcher(launcher)); + } + if d3d_fullscreen { + return Some(Reason::Fullscreen); + } + (fg.covers_monitor && fg.no_frame && fg.gpu_3d >= MIN_GPU_3D).then_some(Reason::Borderless) +} + +/// A game's name for the dashboard: its folder under a launcher's game folder, else the program's +/// name without ".exe". +pub fn display_name(path: &str) -> String { + let lower = path.to_lowercase().replace('/', "\\"); + for (dir, _) in LAUNCHERS { + if let Some(i) = lower.find(dir) { + let rest = &path[i + dir.len()..]; + if let Some(folder) = rest.split(['\\', '/']).next().filter(|f| !f.is_empty()) { + return folder.to_owned(); + } + } + } + let name = path.rsplit(['\\', '/']).next().unwrap_or(path); + name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name).to_owned() +} + +/// The game mode: once a game is seen it stays until its process ends, also while another window +/// is in front (the game still holds its video memory). +#[derive(Default)] +pub struct GameState { + current: Option, +} + +impl GameState { + /// Look at `snap`; `alive(pid)` says whether a process still runs. Returns the new state when + /// it changed. + pub fn update(&mut self, snap: &Snapshot, s: &GameSettings, alive: impl Fn(u32) -> bool) -> Option> { + if !s.detect { + return self.current.take().map(|_| None); + } + if self.current.as_ref().is_some_and(|d| alive(d.pid)) { + return None; + } + let next = snap.foreground.as_ref().and_then(|fg| { + classify(fg, snap.d3d_fullscreen, s).map(|reason| Detected { pid: fg.pid, name: display_name(&fg.path), reason }) + }); + if next == self.current { + return None; + } + self.current = next.clone(); + Some(next) + } + + pub fn current(&self) -> Option<&Detected> { + self.current.as_ref() + } +} + +/// Watches for games every two seconds while the services run (Windows only; elsewhere it never +/// sees one). +pub struct GameWatch { + state: Arc>, + stop: Arc, + thread: Mutex>>, +} + +impl GameWatch { + pub fn start(settings: GameSettings) -> Self { + let (state, stop) = (Arc::new(Mutex::new(GameState::default())), Arc::new(AtomicBool::new(false))); + let thread = (cfg!(windows) && settings.detect).then(|| { + let (state, stop) = (state.clone(), stop.clone()); + std::thread::spawn(move || { + let mut probe = probe::Probe::new(); + while !stop.load(Ordering::SeqCst) { + let snap = probe.snapshot(); + let changed = state.lock().unwrap().update(&snap, &settings, probe::alive); + match changed { + Some(Some(d)) => { + crate::info_log!("game", "game mode on: {} ({:?})", d.name, d.reason); + } + Some(None) => { + crate::info_log!("game", "game mode off"); + } + None => {} + } + // Short sleeps, so a stop does not wait for the whole interval. + for _ in 0..(EVERY.as_millis() / 100) { + if stop.load(Ordering::SeqCst) { + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + } + }) + }); + Self { state, stop, thread: Mutex::new(thread) } + } + + /// The game for the dashboard: `{name, reason}` or null. + pub fn view(&self) -> serde_json::Value { + serde_json::json!(self.state.lock().unwrap().current()) + } + + pub fn stop(&self) { + self.stop.store(true, Ordering::SeqCst); + if let Some(t) = self.thread.lock().unwrap().take() { + let _ = t.join(); + } + } +} + +#[cfg(not(windows))] +mod probe { + use super::Snapshot; + + pub struct Probe; + + impl Probe { + pub(super) fn new() -> Self { + Probe + } + + pub fn snapshot(&mut self) -> Snapshot { + Snapshot::default() + } + } + + pub fn alive(_pid: u32) -> bool { + false + } +} + +#[cfg(windows)] +mod probe { + use super::{Foreground, Snapshot}; + use windows_sys::Win32::Foundation::{CloseHandle, HWND, RECT, WAIT_TIMEOUT}; + use windows_sys::Win32::Graphics::Gdi::{GetMonitorInfoW, MonitorFromWindow, MONITORINFO, MONITOR_DEFAULTTONEAREST}; + use windows_sys::Win32::System::Performance::*; + use windows_sys::Win32::System::Threading::{ + OpenProcess, QueryFullProcessImageNameW, WaitForSingleObject, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, + PROCESS_SYNCHRONIZE, + }; + use windows_sys::Win32::UI::Shell::{SHQueryUserNotificationState, QUNS_RUNNING_D3D_FULL_SCREEN}; + use windows_sys::Win32::UI::WindowsAndMessaging::*; + + /// The GPU 3D engine counters (PDH), kept open: the rate needs two samples. + pub struct Probe { + query: PDH_HQUERY, + counter: PDH_HCOUNTER, + } + + impl Probe { + pub(super) fn new() -> Self { + let mut query: PDH_HQUERY = std::ptr::null_mut(); + let mut counter: PDH_HCOUNTER = std::ptr::null_mut(); + let path: Vec = "\\GPU Engine(*engtype_3D)\\Utilization Percentage".encode_utf16().chain(Some(0)).collect(); + // SAFETY: plain PDH calls with out pointers to locals; a failure leaves zeros, which + // `gpu_3d` treats as "no counters". + unsafe { + if PdhOpenQueryW(std::ptr::null(), 0, &mut query) == 0 { + PdhAddEnglishCounterW(query, path.as_ptr(), 0, &mut counter); + PdhCollectQueryData(query); + } + } + Self { query, counter } + } + + /// 3D engine use of process `pid` in percent, summed over its engines. + fn gpu_3d(&mut self, pid: u32) -> f64 { + if self.query.is_null() || self.counter.is_null() { + return 0.0; + } + let (mut size, mut count) = (0u32, 0u32); + // SAFETY: the documented two-call pattern: the first call asks for the buffer size, + // the second fills a buffer of that many bytes, aligned for the items. + unsafe { + if PdhCollectQueryData(self.query) != 0 { + return 0.0; + } + PdhGetFormattedCounterArrayW(self.counter, PDH_FMT_DOUBLE, &mut size, &mut count, std::ptr::null_mut()); + if size == 0 { + return 0.0; + } + let mut buf = vec![0u64; (size as usize).div_ceil(8)]; + let items = buf.as_mut_ptr() as *mut PDH_FMT_COUNTERVALUE_ITEM_W; + if PdhGetFormattedCounterArrayW(self.counter, PDH_FMT_DOUBLE, &mut size, &mut count, items) != 0 { + return 0.0; + } + let prefix = format!("pid_{pid}_"); + (0..count as usize).map(|i| &*items.add(i)) + .filter(|it| wide_str(it.szName).starts_with(&prefix)) + .map(|it| it.FmtValue.Anonymous.doubleValue) + .sum() + } + } + + pub fn snapshot(&mut self) -> Snapshot { + // SAFETY: plain query. + let mut state = 0; + let d3d_fullscreen = unsafe { SHQueryUserNotificationState(&mut state) } == 0 && state == QUNS_RUNNING_D3D_FULL_SCREEN; + let foreground = foreground().map(|(pid, path, covers_monitor, no_frame)| { + Foreground { pid, path, covers_monitor, no_frame, gpu_3d: self.gpu_3d(pid) } + }); + Snapshot { foreground, d3d_fullscreen } + } + } + + impl Drop for Probe { + fn drop(&mut self) { + if !self.query.is_null() { + // SAFETY: the query this probe opened. + unsafe { PdhCloseQuery(self.query) }; + } + } + } + + unsafe fn wide_str(p: *const u16) -> String { + if p.is_null() { + return String::new(); + } + let mut n = 0; + // SAFETY: PDH gives NUL-terminated names that live as long as the buffer. + while unsafe { *p.add(n) } != 0 { + n += 1; + } + String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(p, n) }) + } + + /// The foreground window's process, program path, whether it covers its monitor and whether + /// it has no title bar or sizing border. + fn foreground() -> Option<(u32, String, bool, bool)> { + // SAFETY: plain window queries on the foreground window; buffers are sized as passed and + // the process handle is closed. + unsafe { + let hwnd: HWND = GetForegroundWindow(); + if hwnd.is_null() { + return None; + } + let mut pid = 0; + GetWindowThreadProcessId(hwnd, &mut pid); + let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if h.is_null() { + return None; + } + let mut buf = [0u16; 1024]; + let mut len = buf.len() as u32; + let ok = QueryFullProcessImageNameW(h, PROCESS_NAME_WIN32, buf.as_mut_ptr(), &mut len) != 0; + CloseHandle(h); + if !ok { + return None; + } + let path = String::from_utf16_lossy(&buf[..len as usize]); + let mut r: RECT = std::mem::zeroed(); + GetWindowRect(hwnd, &mut r); + let mut mi = MONITORINFO { cbSize: std::mem::size_of::() as u32, ..Default::default() }; + GetMonitorInfoW(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &mut mi); + let m = mi.rcMonitor; + let covers = r.left <= m.left && r.top <= m.top && r.right >= m.right && r.bottom >= m.bottom; + let style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32; + let no_frame = style & WS_CAPTION != WS_CAPTION && style & WS_THICKFRAME == 0; + Some((pid, path, covers, no_frame)) + } + } + + /// Whether process `pid` still runs. + pub fn alive(pid: u32) -> bool { + // SAFETY: a handle only to wait on, closed at once. + unsafe { + let h = OpenProcess(PROCESS_SYNCHRONIZE, 0, pid); + if h.is_null() { + return false; + } + let running = WaitForSingleObject(h, 0) == WAIT_TIMEOUT; + CloseHandle(h); + running + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn settings() -> GameSettings { + GameSettings { detect: true, games: vec![], not_games: vec![] } + } + + fn fg(path: &str, covers: bool, no_frame: bool, gpu: f64) -> Foreground { + Foreground { pid: 7, path: path.into(), covers_monitor: covers, no_frame, gpu_3d: gpu } + } + + #[test] + fn a_borderless_game_is_a_game_and_a_maximised_program_or_video_is_not() { + let s = settings(); + // A borderless game outside any launcher folder (the M0 check: covers, no frame, GPU >= 10%). + assert_eq!(classify(&fg(r"D:\Games\Hades\Hades.exe", true, true, 45.0), false, &s), Some(Reason::Borderless)); + // Too little 3D work: a borderless tool, not a game. + assert_eq!(classify(&fg(r"D:\Tools\kiosk.exe", true, true, 3.0), false, &s), None); + // A maximised program has a title bar. + assert_eq!(classify(&fg(r"C:\Windows\notepad.exe", true, false, 0.0), false, &s), None); + // A browser's full-screen video, even with the GPU busy. + assert_eq!(classify(&fg(r"C:\Program Files\Google\Chrome\Application\chrome.exe", true, true, 60.0), false, &s), None); + // Exclusive full screen. + assert_eq!(classify(&fg(r"D:\Games\Old\old.exe", true, true, 0.0), true, &s), Some(Reason::Fullscreen)); + } + + #[test] + fn launcher_folders_make_a_game_whatever_the_window_and_name_it_by_its_folder() { + let s = settings(); + let valorant = r"C:\Riot Games\VALORANT\live\ShooterGame\Binaries\Win64\VALORANT-Win64-Shipping.exe"; + assert_eq!(classify(&fg(valorant, false, false, 0.0), false, &s), Some(Reason::Launcher("Riot"))); + assert_eq!(display_name(valorant), "VALORANT"); + let steam = r"D:\SteamLibrary\steamapps\common\Stardew Valley\Stardew Valley.exe"; + assert_eq!(classify(&fg(steam, false, false, 0.0), false, &s), Some(Reason::Launcher("Steam"))); + assert_eq!(display_name(steam), "Stardew Valley"); + // The launchers' own windows are not games. + assert_eq!(classify(&fg(r"C:\Riot Games\Riot Client\RiotClientServices.exe", true, true, 20.0), false, &s), None); + assert_eq!(display_name(r"D:\Games\Hades\Hades.exe"), "Hades"); + } + + #[test] + fn the_persons_lists_come_first() { + let mut s = settings(); + s.games = vec!["MyGame".into()]; + s.not_games = vec!["Hades.exe".into()]; + assert_eq!(classify(&fg(r"D:\x\mygame.exe", false, false, 0.0), false, &s), Some(Reason::Registered)); + assert_eq!(classify(&fg(r"D:\Games\Hades\Hades.exe", true, true, 90.0), true, &s), None, "not a game, whatever it does"); + s.games = vec!["chrome".into()]; + assert_eq!(classify(&fg(r"C:\c\chrome.exe", false, false, 0.0), false, &s), Some(Reason::Registered)); + } + + #[test] + fn game_mode_stays_until_the_game_ends_and_detection_off_turns_it_off() { + let mut s = settings(); + let mut g = GameState::default(); + let game = Snapshot { foreground: Some(fg(r"D:\Games\Hades\Hades.exe", true, true, 50.0)), d3d_fullscreen: false }; + let desk = Snapshot { foreground: Some(fg(r"C:\Windows\explorer.exe", true, true, 0.0)), d3d_fullscreen: false }; + let on = g.update(&game, &s, |_| true).expect("changed").expect("a game"); + assert_eq!((on.name.as_str(), on.reason.clone()), ("Hades", Reason::Borderless)); + // Alt+Tab to the desktop: still on while the game runs. + assert_eq!(g.update(&desk, &s, |_| true), None); + assert!(g.current().is_some()); + // The game ended: off. + assert_eq!(g.update(&desk, &s, |_| false), Some(None)); + assert_eq!(g.update(&desk, &s, |_| false), None, "no change, no event"); + // Detection off: nothing, and a game on turns off. + g.update(&game, &s, |_| true); + s.detect = false; + assert_eq!(g.update(&game, &s, |_| true), Some(None)); + assert_eq!(g.update(&game, &s, |_| true), None); + } + + #[test] + fn the_dashboard_gets_the_name_and_the_reason() { + let d = Detected { pid: 1, name: "VALORANT".into(), reason: Reason::Launcher("Riot") }; + assert_eq!(serde_json::to_value(&d).unwrap(), + serde_json::json!({"name": "VALORANT", "reason": {"kind": "launcher", "launcher": "Riot"}})); + assert_eq!(serde_json::to_value(Reason::Borderless).unwrap(), serde_json::json!({"kind": "borderless"})); + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index e1766d7..dd791d6 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -16,6 +16,7 @@ pub mod discord_setup; pub mod download; pub mod earcon; pub mod features; +pub mod game; pub mod frames; pub mod install; pub mod logs; diff --git a/app/src/services.rs b/app/src/services.rs index ffec0c7..40cfc21 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -23,6 +23,8 @@ pub struct Services { pub missed: conversation::MissedLog, pub llm: Arc, pub browser: BrowserRun, + /// Game detection while the services run (admin.spec.md, "Game detection"). + pub game: crate::game::GameWatch, } /// The bot browser of a run (admin.spec.md, "Bot browser"). @@ -59,6 +61,7 @@ impl BrowserRun { impl Services { /// Stop everything; an error means the LLM's server may still run. pub async fn stop(&self) -> Result<(), String> { + self.game.stop(); self.core.close().await; self.worker.close(); self.worker_process.stop().await; @@ -109,6 +112,7 @@ async fn start_browser(data_dir: &Path, settings: &crate::settings::Settings) -> /// before the brain can. A failure stops what already started. pub async fn start_services(data_dir: &Path, llm: Arc) -> Result> { let settings = load_settings(&data_dir.join("config").join("settings.json"))?; + let game_settings = settings.game.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)?; @@ -189,7 +193,8 @@ pub async fn start_services(data_dir: &Path, llm: Arc) -> Result, + pub not_games: Vec, +} + /// Background collection (admin.spec.md, "Background collection"); no targets by default. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CollectSettings { @@ -146,6 +155,7 @@ pub struct Settings { pub features: FeatureSettings, pub mcp_servers: Vec, pub collect: CollectSettings, + pub game: GameSettings, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -192,6 +202,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![] }, } } } @@ -516,6 +527,7 @@ pub fn parse_settings(raw: &Value) -> Result { }, mcp_servers: parse_mcp_servers(raw)?, collect: parse_collect(raw, &d.collect)?, + game: parse_game(raw, &d.game)?, }) } @@ -541,6 +553,20 @@ fn get_uint(m: Option<&Map>, key: &str, path: &str, default: u32, } } +fn parse_game(raw: &Map, d: &GameSettings) -> Result { + let g = section(raw, "game")?; + let list = |key: &str, default: &[String]| -> Result, SettingsError> { + let v: Vec = get_str_list(g, key, "game", default)?.into_iter().map(|e| e.trim().to_owned()) + .filter(|e| !e.is_empty()).collect(); + if v.len() > 100 || v.iter().any(|e| e.chars().count() > 100 || e.contains(['\\', '/'])) { + return err(format!("game.{key} must be at most 100 program names (no folders)")); + } + Ok(v) + }; + Ok(GameSettings { detect: get_bool(g, "detect", "game", d.detect)?, games: list("games", &d.games)?, + not_games: list("notGames", &d.not_games)? }) +} + fn parse_collect(raw: &Map, d: &CollectSettings) -> Result { let c = section(raw, "collect")?; let keep_days = get_uint(c, "keepDays", "collect", d.keep_days, 1, 365)?; @@ -808,6 +834,16 @@ 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![] }); + let s = parse_settings(&json!({"game": {"detect": false, "games": [" MyGame.exe ", ""], "notGames": ["obs64"]}})).unwrap(); + assert_eq!(s.game, GameSettings { detect: false, games: vec!["MyGame.exe".into()], not_games: vec!["obs64".into()] }); + for bad in [json!({"game": {"games": ["C:\\x\\a.exe"]}}), json!({"game": {"notGames": "a"}}), json!({"game": {"detect": 1}})] { + assert!(parse_settings(&bad).unwrap_err().0.contains("game."), "{bad}"); + } + } + #[test] fn features_and_mcp_servers_are_read_and_checked() { let s = parse_settings(&json!({})); diff --git a/app/src/settings_edit.rs b/app/src/settings_edit.rs index 401951b..04bf749 100644 --- a/app/src/settings_edit.rs +++ b/app/src/settings_edit.rs @@ -21,6 +21,7 @@ pub enum Screen { Model, Features, Collect, + Game, } #[derive(Debug, Clone, PartialEq, serde::Serialize)] @@ -129,6 +130,10 @@ pub fn fields() -> Vec { // Background collection (admin.spec.md, "Background collection"): no targets by default. f("collect.targets", Collect, CollectTargets, json!([]), "수집 대상"), f("collect.keepDays", Collect, Int { min: 1, max: 365 }, json!(30), "보관 기간(일)"), + // Game detection (admin.spec.md, "Game detection"). + f("game.detect", Game, Bool, json!(true), "게임 감지"), + f("game.games", Game, TextList { max_items: 100, nullable: false }, json!([]), "게임으로 볼 프로그램(파일 이름, 예: MyGame.exe)"), + f("game.notGames", Game, TextList { max_items: 100, nullable: false }, json!([]), "게임이 아닌 프로그램(파일 이름)"), ] } diff --git a/app/tests/game_watch.rs b/app/tests/game_watch.rs new file mode 100644 index 0000000..f7a13b7 --- /dev/null +++ b/app/tests/game_watch.rs @@ -0,0 +1,42 @@ +//! Game detection on Windows (admin.spec.md, "Game detection"): a program started from a launcher's +//! game folder turns game mode on with the folder's name, and off once it ends. Runs only with +//! `JARVIS_TEST_GAME_EXE=\>`; elsewhere it skips. + +use std::time::{Duration, Instant}; + +use jarvis_app::game::GameWatch; +use jarvis_app::settings::GameSettings; + +fn wait_for(w: &GameWatch, want: impl Fn(&serde_json::Value) -> bool, secs: u64) -> serde_json::Value { + let until = Instant::now() + Duration::from_secs(secs); + loop { + let v = w.view(); + if want(&v) || Instant::now() > until { + return v; + } + std::thread::sleep(Duration::from_millis(200)); + } +} + +#[test] +fn a_launcher_game_turns_game_mode_on_until_it_ends() { + let Ok(exe) = std::env::var("JARVIS_TEST_GAME_EXE") else { + eprintln!("skipped: set JARVIS_TEST_GAME_EXE"); + return; + }; + let w = GameWatch::start(GameSettings { detect: true, games: vec![], not_games: vec![] }); + 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(); + let on = wait_for(&w, |v| !v.is_null(), 15); + eprintln!("on after {:?}: {on}", t0.elapsed()); + let folder = std::path::Path::new(&exe).parent().unwrap().file_name().unwrap().to_string_lossy().into_owned(); + assert_eq!(on, serde_json::json!({"name": folder, "reason": {"kind": "launcher", "launcher": "Steam"}})); + game.kill().unwrap(); + let _ = game.wait(); + let t1 = Instant::now(); + let off = wait_for(&w, |v| v.is_null(), 10); + eprintln!("off after {:?}: {off}", t1.elapsed()); + assert_eq!(off, serde_json::Value::Null, "game mode ends with the game"); + w.stop(); +} diff --git a/app/ui/app.js b/app/ui/app.js index a25c436..152c269 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -410,6 +410,9 @@ async function displayDriverCard() { // ---- dashboard ---------------------------------------------------------------------------------- +const GAME_REASON = { fullscreen: () => "전체화면", borderless: () => "테두리 없는 창", registered: () => "직접 등록한 게임", + launcher: (r) => `${r.launcher} 게임 폴더` }; + /** The header with the start/stop buttons; rebuilt only when the state changes, so a click is not * lost to the once-a-second refresh of the cards. */ function dashboardHeader(d) { @@ -466,6 +469,8 @@ function dashboardBody(d) { h("span", { class: "k" }, "RAM"), h("span", {}, d.system?.ramTotalMb ? `${(d.system.ramUsedMb / 1024).toFixed(1)} / ${(d.system.ramTotalMb / 1024).toFixed(1)} GB` : "–"), (d.system?.gpus || []).flatMap((g) => [h("span", { class: "k" }, g.name.replace("NVIDIA GeForce ", "")), 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("div", { class: "grid" }, h("div", { class: "card" }, h("h2", {}, "실시간 자막"), h("div", { class: "captions" }, @@ -565,7 +570,7 @@ async function show(name) { if (name === "dashboard") { screen.replaceChildren(); await refresh(); ticker = setInterval(refresh, 1000); return; } if (name === "logs") { const l = logsScreen(); screen.replaceChildren(l.view); ticker = setInterval(l.tick, 1000); return; } const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능", - collect: "백그라운드 수집" }; + collect: "백그라운드 수집", game: "게임 모드" }; const extra = name === "bot" ? await tokenCard() : name === "features" ? await displayDriverCard() : null; const view = await settingsScreen(name, titles[name], extra); if (name === "collect") view.append(await collectResults()); diff --git a/app/ui/index.html b/app/ui/index.html index a9586bc..27aec31 100644 --- a/app/ui/index.html +++ b/app/ui/index.html @@ -19,6 +19,7 @@ +
diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index e93caaf..9b15c11 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 제어와 화면 보기 | 아래 목록에 있습니다. | +| 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·Battle.net 게임 폴더, 직접 등록한 게임, "게임 아님" 목록 우선, 브라우저·영상 플레이어·디스코드·런처 창 제외)으로 판단, 게임이 끝날 때까지 유지. 관리 앱 "게임 모드" 화면(감지 켜기/끄기, 두 목록)과 대시보드 "게임 모드: 켜짐 (이름, 이유)". 서버 Windows 가상머신에서 Steam 게임 폴더의 프로그램을 켜면 1.4초 뒤 켜짐, 끄면 2.0초 뒤 꺼짐. GPU 사용률 기준(테두리 없는 창)은 GPU가 있는 게임PC에서 확인할 것. 다음: 자동 성능 조절(평소·게임 중 배치 전환). | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 | M0에서 확인할 항목: