diff --git a/app/Cargo.toml b/app/Cargo.toml index 8b03254..c7041c2 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -35,13 +35,17 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "std" zip = { version = "9", default-features = false, features = ["deflate"] } unicode-normalization = "0.1" +[[test]] +name = "vdisplay_elevated" +harness = false + [profile.release] lto = "thin" 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"] } +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"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/app/shell/package.sh b/app/shell/package.sh index 7bc2322..0ee863a 100755 --- a/app/shell/package.sh +++ b/app/shell/package.sh @@ -1,7 +1,8 @@ #!/bin/sh # Build the Windows management app from Linux and lay it out ready to zip (admin.spec.md, "Windows build"): -# Jarvis/jarvis.exe, Jarvis/WebView2Loader.dll, Jarvis/python-src/{voice_worker,jarvis} -# Needs the x86_64-pc-windows-gnu Rust target, mingw-w64 and cmake (for Opus). +# Jarvis/jarvis.exe, Jarvis/WebView2Loader.dll, Jarvis/python-src/{voice_worker,jarvis}, +# Jarvis/display-driver/ (Virtual Display Driver 25.7.23, MIT, SignPath-signed; "Virtual monitor") +# Needs the x86_64-pc-windows-gnu Rust target, mingw-w64, cmake (for Opus), curl and unzip. # app/shell/package.sh set -eu here=$(cd "$(dirname "$0")" && pwd) @@ -17,4 +18,16 @@ for pkg in voice_worker jarvis; do (cd "$here/../../src" && find "$pkg" -name __pycache__ -prune -o -name '*.spec.md' -prune -o -type f -print) | while read -r f; do mkdir -p "$out/Jarvis/python-src/$(dirname "$f")"; cp "$here/../../src/$f" "$out/Jarvis/python-src/$f"; done done +# The virtual monitor's driver, pinned by hash; its sample settings file is not used (the app +# writes its own). +vdd_url=https://github.com/VirtualDrivers/Virtual-Display-Driver/releases/download/25.7.23/VirtualDisplayDriver-x86.Driver.Only.zip +vdd_sha=e24210692b442b39af763536330ce78b423f19342b7a7792c26de3944e418b3a +vdd_zip="$target/vdd-25.7.23.zip" +[ -f "$vdd_zip" ] || curl -fsSL -o "$vdd_zip" "$vdd_url" +echo "$vdd_sha $vdd_zip" | sha256sum -c - >/dev/null || { rm -f "$vdd_zip"; echo "display driver hash mismatch" >&2; exit 1; } +tmp=$(mktemp -d "$target/vdd.XXXXXX") +unzip -q "$vdd_zip" -d "$tmp" +mkdir -p "$out/Jarvis/display-driver" +cp "$tmp/VirtualDisplayDriver/MttVDD.inf" "$tmp/VirtualDisplayDriver/mttvdd.cat" "$tmp/VirtualDisplayDriver/MttVDD.dll" "$out/Jarvis/display-driver/" +rm -rf "$tmp" echo "$out/Jarvis" diff --git a/app/shell/src/main.rs b/app/shell/src/main.rs index 59289c7..51447da 100644 --- a/app/shell/src/main.rs +++ b/app/shell/src/main.rs @@ -4,6 +4,7 @@ //! if that cannot be confirmed the window stays open and says so, and closing it again quits. //! //! jarvis [--location FILE] +//! jarvis --display-driver install|uninstall --result FILE (elevated, started by the app) #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] @@ -36,6 +37,10 @@ fn arg(name: &str) -> Option { } fn main() { + // The elevated half of installing or removing the virtual monitor's driver: no window. + if let Some(code) = jarvis_app::vdisplay::elevated_main(&std::env::args().collect::>()) { + std::process::exit(code); + } let location = arg("--location").map(PathBuf::from).or_else(jarvis_app::datadir::default_location_file) .expect("no location file path: pass --location"); // Log files go to the data folder once there is one; until then memory only. diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 03e50e8..48d5942 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -61,7 +61,9 @@ manages the MCP servers it connects. - `features` (new section): `weather` (`getWeather`), `webSearch` (`webSearch`, `fetchWebPage`) and `meals` (`logMeal`, `fetchMeals`, `deleteMeal`), each on by default; `collect` (background collection, below; no brain tool) and `browser` (the bot browser, below "Bot browser", and its - brain tool `botBrowser`, `src/jarvis/tools/builtin/bot_browser.spec.md`), also on by default. The tools of a feature that + brain tool `botBrowser`, `src/jarvis/tools/builtin/bot_browser.spec.md`), also on by default; + `browserShare` (봇용 크롬창 화면공유 선택 표시, the bot browser on the virtual monitor, below + "Virtual monitor"), off by default. The tools of a feature that is off go into the brain's `disabled_tools`: they are neither offered nor run (`voice_worker.spec.md`, "Tools"). The other features of the 기능 screen (PC control, screen viewing) come with their milestone (M7). @@ -236,8 +238,8 @@ The LLM itself (Qwen3.6-35B-A3B, about 23 GB) is downloaded by Strata on its fir ## Bot browser (`app/src/browser.rs`) `docs/v2/pc-features.md`, "백그라운드 크로미움으로 정보 수집" and "봇용 크롬창과 디스코드 화면공유". The -bot's own Chrome, in the data folder, driven over the Chrome DevTools Protocol (CDP). This part runs -it in the background (headless); the virtual monitor for screen sharing comes next (M6). +bot's own Chrome, in the data folder, driven over the Chrome DevTools Protocol (CDP). It runs in the +background (headless), or with `features.browserShare` in a window on the virtual monitor (below). - `features.browser` (브라우저 제어, on by default). With it on and the `browser` step installed, the services start the bot browser after the LLM and before the worker, and stop it after the @@ -265,7 +267,48 @@ it in the background (headless); the virtual monitor for screen sharing comes ne - Dashboard `browser`: `{state, note}` with `state` off, ready, failed (the note says why) or exited (it ended on its own). - Linux (development only): Ubuntu's AppArmor refuses Chrome's sandbox; `JARVIS_CHROME_NO_SANDBOX=1` - in the app's environment adds `--no-sandbox`. Windows always runs it sandboxed. + in the app's environment adds `--no-sandbox`. Windows always runs it sandboxed, with + `--do-not-de-elevate`: started by an app running as administrator, Chrome would otherwise start + again as the user and end the process the app holds, so the app could neither see nor stop it. + +## Virtual monitor (`app/src/vdisplay.rs`) + +`docs/v2/pc-features.md`, "봇용 크롬창과 디스코드 화면공유". With `features.browserShare` the bot +browser's window sits on a monitor that exists only for it, so the user can pick that monitor in +Discord's screen share ("화면" tab) while no real monitor shows the window. Windows only; elsewhere +the browser runs headless with a note. + +- **Driver**: the open-source Virtual Display Driver 25.7.23 (MIT, signed by the SignPath + Foundation), its `MttVDD.inf`, `mttvdd.cat` and `MttVDD.dll` in `display-driver/` next to + `jarvis.exe` (`package.sh` downloads the release zip and checks its SHA-256). Installing and + removing need the administrator once: the app starts itself elevated (`jarvis.exe + --display-driver install|uninstall --result FILE`, Windows asks), waits, and reads why it failed + from FILE. Install writes the driver's settings to `%ProgramData%\JarvisBot\display-driver\vdd_settings.xml` + (the driver runs as a system service that cannot read the data folder, so this is the one place + outside it; readable by users and LOCAL SERVICE, writable only by the system and administrators), + points the driver at it (`HKLM\SOFTWARE\MikeTheTech\VirtualDisplayDriver` `VDDPATH`), creates the + device (`Root\MttVDD`, display class) and installs the driver; Windows then asks once whether to + install software from the SignPath Foundation. The new monitor is taken off the desktop at once. + The settings: one monitor, one mode (1280x720 at 30 Hz), no custom EDID. When another program's + copy of the same driver is installed (its `VDDPATH` is not ours) the app refuses to install or + remove and never touches its monitors. Uninstall removes the device, the driver package, the + registry key and the settings folder. +- **On only while used**: a service start first takes the monitor off the desktop (left over from a + run that ended badly). With `browserShare` it then attaches the monitor (no administrator needed) + right of and below the rightmost real monitor, touching it only at that monitor's bottom-right + corner, so the mouse hardly reaches it and no real monitor overlaps it. The stop closes the + browser first and then takes the monitor off, so Windows never moves the window onto a real + monitor. +- **The window**: Chrome starts with `--no-startup-window` (no headless), and the app opens its one + window over CDP in the background (`Target.createTarget` with a new window at the monitor's place + and size), so it never takes the focus from the game or program the user is in. The window + then becomes a tool window (not in Alt+Tab, Win+Tab or the taskbar), fills the monitor's work + area (Windows may give the monitor a taskbar of its own) and goes behind all other windows, all + without activating it. It keeps drawing when covered (`--disable-backgrounding-occluded-windows`, + `--disable-renderer-backgrounding`, `--disable-background-timer-throttling`). The window holds + the first tab, which the bot never closes; the bot's tabs open in it, the newest in front. +- If the monitor or the window cannot be made, the browser runs headless and the dashboard's + `browser` note says why ("가상 모니터 없이 실행: ..."). ## LLM (`app/src/strata.rs`) @@ -344,6 +387,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | `discord_channel_info` `{id}` / `channel_sync_status` | a channel's Discord name and topic / each synced chat channel's last result (above) | | `collect_results` `{target, limit}` | `{targets, items}`: every target folder with results, and the collected items newest first (`target` null: every target; `limit` 1-500, default 100) | | `mcp_env_status` / `mcp_env_set` `{server, name, value}` | which MCP environment values are stored (`{server: {NAME: bool}}`, never the values) / store one (an empty value removes it); only for a saved server and name | +| `display_driver_status` / `display_driver_install` / `display_driver_uninstall` | the virtual monitor's driver: `{supported, installed, other}` (Windows only; `other`: another program's copy) / install or remove it elevated (above), then its status | | `install_status` / `install_start` / `install_cancel` | the install steps and their state, bytes and last line / run what is not done in the background / stop it | | `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back | @@ -374,7 +418,8 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A with their switches; the bot screen also changes the token; the 기능 screen has the feature switches and one card per MCP server (name, command, arguments and environment variable names one per line, on/off, delete), and for a saved server a password box per environment variable - that stores its value on its own. The 백그라운드 수집 screen has the targets (a table: name, kind, + that stores its value on its own; on Windows also a card for the virtual monitor's driver (its + state and an install or remove button). The 백그라운드 수집 screen has the targets (a table: name, kind, address or words, interval in minutes, on/off, delete), the keep days, and the results (the newest 100, filtered by any target that has results, each with its time, title, link and the start of its text shown as plain text). @@ -402,8 +447,8 @@ URL), so other local programs cannot drive it. runs the window says so; if it fails the window stays open with the reason, and closing it again quits anyway. Quitting another way (the system shutting down) runs the same shutdown. - `app/shell/package.sh ` builds it on Linux (`x86_64-pc-windows-gnu`, mingw-w64) and lays - out `Jarvis/`: `jarvis.exe`, `WebView2Loader.dll` and `python-src/` (the `voice_worker` and - `jarvis` packages, no caches or specs). The worker's default sources are `python-src` next to the + out `Jarvis/`: `jarvis.exe`, `WebView2Loader.dll`, `python-src/` (the `voice_worker` and + `jarvis` packages, no caches or specs) and `display-driver/` (the virtual monitor's driver). The worker's default sources are `python-src` next to the executable when it is there, else the repository's `src/`; the install reads its requirement files from the same place. The installer (NSIS) comes later; the folder runs as it is. @@ -449,4 +494,12 @@ downloads, install steps, logs; the Unix-only process tests excepted), and the w wizard's folder, PC check and install (`uv` and the worker venv installed, a cancel leaving no `uv` or Python process), the token stored DPAPI-encrypted, a start failing with its reason, the log screen, error copy, zip export, and closing the window ending the process with nothing written -to `%APPDATA%` or `%LOCALAPPDATA%`. +to `%APPDATA%` or `%LOCALAPPDATA%`. The virtual monitor (`tests/vdisplay_elevated.rs`, no harness: +started elevated, the same program is the elevated half; `tests/bot_browser.rs` with a screen): the +driver installed through the elevated start (Windows' SignPath question answered once) with the +settings folder's permissions, the monitor off after install, on at the rightmost monitor's corner +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 Linux the same window test runs on an X display (one window at the given place and +size, the bot's tab in it). diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index 7e71643..8faeeed 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -281,6 +281,18 @@ impl AdminApi { Ok(json!({"set": !value.is_empty(), "restartNeeded": self.controller()?.state() == crate::control::State::Running})) } + // The virtual monitor's driver (admin.spec.md, "Virtual monitor"): installing or + // removing it runs this app elevated once; Windows asks the user. + "display_driver_status" => Ok(json!(crate::vdisplay::status())), + "display_driver_install" | "display_driver_uninstall" => { + let action = if command == "display_driver_install" { "install" } else { "uninstall" }; + if let Err(e) = crate::vdisplay::run_elevated(action).await { + crate::warn_log!("admin", "Warning: display driver {action} failed: {e}"); + return Err(e); + } + crate::info_log!("admin", "display driver {action} done"); + Ok(json!(crate::vdisplay::status())) + } "collect_results" => { let target = args.get("target").and_then(Value::as_str).filter(|t| !t.is_empty()); let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(100).clamp(1, 500) as usize; diff --git a/app/src/browser.rs b/app/src/browser.rs index a9aa7cd..3f261ef 100644 --- a/app/src/browser.rs +++ b/app/src/browser.rs @@ -212,11 +212,11 @@ async fn refused(client: &mut TcpStream, why: &str) -> std::io::Result<()> { // ---- Chrome --------------------------------------------------------------------------------------- -/// The arguments the bot's Chrome runs with (headless, its profile, CDP on a free port, every -/// connection through the proxy on `proxy_port`). -pub fn chrome_args(profile: &Path, proxy_port: u16, no_sandbox: bool) -> Vec { +/// The arguments the bot's Chrome runs with (its profile, CDP on a free port, every connection +/// through the proxy on `proxy_port`): headless, or with `screen` a real window the app opens later +/// over CDP (admin.spec.md, "Virtual monitor"). +pub fn chrome_args(profile: &Path, proxy_port: u16, no_sandbox: bool, screen: bool) -> Vec { let mut a = vec![ - "--headless=new".to_owned(), format!("--user-data-dir={}", profile.display()), "--remote-debugging-port=0".into(), format!("--proxy-server=http://127.0.0.1:{proxy_port}"), @@ -235,7 +235,19 @@ pub fn chrome_args(profile: &Path, proxy_port: u16, no_sandbox: bool) -> Vec Result { + /// Start Chrome `exe` with profile folder `profile` and wait until CDP answers; with `screen`, + /// its one window sits there (the virtual monitor), opened without taking the focus and kept out + /// of Alt+Tab and the taskbar. + pub async fn start(exe: &Path, profile: &Path, screen: Option) -> Result { let proxy = EgressProxy::start(is_public).await.map_err(|e| format!("proxy: {e}"))?; std::fs::create_dir_all(profile).map_err(|e| e.to_string())?; let port_file = profile.join("DevToolsActivePort"); let _ = std::fs::remove_file(&port_file); let no_sandbox = cfg!(not(windows)) && std::env::var("JARVIS_CHROME_NO_SANDBOX").is_ok_and(|v| v == "1"); let mut cmd = tokio::process::Command::new(exe); - cmd.args(chrome_args(profile, proxy.port, no_sandbox)).stdin(std::process::Stdio::null()) + cmd.args(chrome_args(profile, proxy.port, no_sandbox, screen.is_some())).stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true); #[cfg(unix)] cmd.process_group(0); @@ -278,8 +292,35 @@ impl BotBrowser { } tokio::time::sleep(Duration::from_millis(200)).await; }; - crate::info_log!("browser", "bot browser ready (CDP on 127.0.0.1:{cdp_port})"); - Ok(Self { child: Mutex::new(Some(child)), proxy, cdp_port }) + let b = Self { child: Mutex::new(Some(child)), proxy, cdp_port }; + if let Some(r) = screen { + if let Err(e) = b.open_window(r).await { + b.stop().await; + return Err(e); + } + } + crate::info_log!("browser", "bot browser ready (CDP on 127.0.0.1:{cdp_port}{})", + if screen.is_some() { ", on the virtual monitor" } else { "" }); + Ok(b) + } + + /// The window on `r`: a background page in a new window (CDP), then out of the window switcher + /// and fitted to the monitor's work area. + /// It holds the first tab, which the bot never closes, so the window stays. + async fn open_window(&self, r: crate::vdisplay::Rect) -> Result<(), String> { + let ws = version(self.cdp_port).await.and_then(|v| v["webSocketDebuggerUrl"].as_str().map(str::to_owned)) + .ok_or("Chrome의 CDP 주소를 읽지 못했습니다")?; + cdp_call(&ws, serde_json::json!({"id": 1, "method": "Target.createTarget", "params": {"url": "about:blank", + "newWindow": true, "background": true, "left": r.x, "top": r.y, "width": r.w, "height": r.h}})).await + .map_err(|e| format!("Chrome 창을 열지 못했습니다: {e}"))?; + let pid = self.child.lock().unwrap().as_ref().and_then(|c| c.id()).unwrap_or(0); + for _ in 0..25 { + if cfg!(not(windows)) || crate::vdisplay::settle_windows(pid) > 0 { + return Ok(()); + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + Err("Chrome 창을 찾지 못했습니다".into()) } pub fn cdp_url(&self) -> String { @@ -323,6 +364,27 @@ async fn close_over_cdp(ws: &str) -> Result<(), String> { .map_err(|e| e.to_string()) } +/// One CDP call on the browser connection `ws`; its result, or the error Chrome gave (5 s at most). +async fn cdp_call(ws: &str, msg: serde_json::Value) -> Result { + use futures_util::{SinkExt, StreamExt}; + let id = msg["id"].clone(); + tokio::time::timeout(Duration::from_secs(5), async { + let (mut s, _) = tokio_tungstenite::connect_async(ws).await.map_err(|e| e.to_string())?; + s.send(tokio_tungstenite::tungstenite::Message::text(msg.to_string())).await.map_err(|e| e.to_string())?; + while let Some(m) = s.next().await { + let m = m.map_err(|e| e.to_string())?; + let Ok(v) = serde_json::from_str::(m.to_text().unwrap_or("")) else { continue }; + if v["id"] == id { + return match v.get("error") { + Some(e) => Err(e["message"].as_str().unwrap_or("error").to_owned()), + None => Ok(v["result"].clone()), + }; + } + } + Err("connection closed".to_owned()) + }).await.map_err(|_| "timeout".to_owned())? +} + async fn kill_tree(child: &mut tokio::process::Child) { if let Some(pid) = child.id() { #[cfg(unix)] @@ -437,13 +499,27 @@ mod tests { #[test] fn chrome_goes_through_the_proxy_with_its_own_profile() { - let a = chrome_args(Path::new("/d/browser/profile"), 4321, false); + let a = chrome_args(Path::new("/d/browser/profile"), 4321, false, false); for want in ["--headless=new", "--user-data-dir=/d/browser/profile", "--remote-debugging-port=0", "--proxy-server=http://127.0.0.1:4321", "--proxy-bypass-list=<-loopback>", "--disable-quic"] { assert!(a.iter().any(|x| x == want), "{want}"); } assert!(!a.iter().any(|x| x == "--no-sandbox")); - assert!(chrome_args(Path::new("/p"), 1, true).iter().any(|x| x == "--no-sandbox")); + assert!(chrome_args(Path::new("/p"), 1, true, false).iter().any(|x| x == "--no-sandbox")); + assert_eq!(a.iter().any(|x| x == "--do-not-de-elevate"), cfg!(windows), "the app keeps hold of Chrome on Windows"); + } + + #[test] + fn on_a_screen_chrome_has_a_window_it_opens_later_and_keeps_drawing_when_covered() { + let a = chrome_args(Path::new("/p"), 4321, false, true); + assert!(!a.iter().any(|x| x.starts_with("--headless"))); + // No window at start: the app opens it over CDP in the background, so it never takes focus. + assert!(a.iter().any(|x| x == "--no-startup-window")); + assert!(!a.iter().any(|x| x == "about:blank")); + for want in ["--disable-backgrounding-occluded-windows", "--disable-renderer-backgrounding", + "--proxy-server=http://127.0.0.1:4321", "--disable-quic"] { + assert!(a.iter().any(|x| x == want), "{want}"); + } } } diff --git a/app/src/features.rs b/app/src/features.rs index bba3be9..cfa11c2 100644 --- a/app/src/features.rs +++ b/app/src/features.rs @@ -102,9 +102,9 @@ mod tests { #[test] fn features_that_are_off_turn_their_tools_off() { - let all_on = FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true }; + let all_on = FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: true }; assert!(disabled_tools(&all_on).is_empty()); - let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false, collect: false, browser: false }); + let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false, collect: false, browser: false, browser_share: false }); assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal", "botBrowser"]); } diff --git a/app/src/lib.rs b/app/src/lib.rs index 9799a12..e1766d7 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -29,5 +29,6 @@ pub mod settings_edit; pub mod speakers; pub mod strata; pub mod system; +pub mod vdisplay; pub mod worker_client; pub mod worker_process; diff --git a/app/src/services.rs b/app/src/services.rs index 2d0d36e..ffec0c7 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -30,7 +30,8 @@ pub enum BrowserRun { /// Not started: the feature is off, or (with a note) it is not installed. Off(Option), Failed(String), - Running(Arc), + /// Running; the note says why it runs without the virtual monitor that was asked for. + Running(Arc, Option), } impl BrowserRun { @@ -39,15 +40,18 @@ impl BrowserRun { let (state, note) = match self { BrowserRun::Off(note) => ("off", note.clone()), BrowserRun::Failed(e) => ("failed", Some(e.clone())), - BrowserRun::Running(b) if b.running() => ("ready", None), - BrowserRun::Running(_) => ("exited", None), + BrowserRun::Running(b, note) if b.running() => ("ready", note.clone()), + BrowserRun::Running(_, note) => ("exited", note.clone()), }; serde_json::json!({"state": state, "note": note}) } + /// Stop the browser, then take the virtual monitor off the desktop (its window first, so + /// Windows never moves it onto a real monitor). pub async fn stop(&self) { - if let BrowserRun::Running(b) = self { + if let BrowserRun::Running(b, _) = self { b.stop().await; + crate::vdisplay::detach(); } } } @@ -63,9 +67,11 @@ impl Services { } } -/// Start the bot browser when its feature is on and it is installed; a failure leaves the services -/// running without it. +/// Start the bot browser when its feature is on and it is installed, on the virtual monitor when +/// sharing is on; a failure leaves the services running without it (or without the monitor). async fn start_browser(data_dir: &Path, settings: &crate::settings::Settings) -> BrowserRun { + // A monitor an earlier run left on goes off first. + crate::vdisplay::detach(); if !settings.features.browser { return BrowserRun::Off(None); } @@ -74,8 +80,24 @@ async fn start_browser(data_dir: &Path, settings: &crate::settings::Settings) -> crate::warn_log!("browser", "the bot browser is not installed"); return BrowserRun::Off(Some("설치되지 않음".into())); } - match crate::browser::BotBrowser::start(&layout.chrome_exe(), &crate::browser::profile_dir(data_dir)).await { - Ok(b) => BrowserRun::Running(Arc::new(b)), + let (exe, profile) = (layout.chrome_exe(), crate::browser::profile_dir(data_dir)); + let mut note = None; + if settings.features.browser_share { + let started = match crate::vdisplay::attach() { + Ok(r) => crate::browser::BotBrowser::start(&exe, &profile, Some(r)).await, + Err(e) => Err(e), + }; + match started { + Ok(b) => return BrowserRun::Running(Arc::new(b), None), + Err(e) => { + crate::vdisplay::detach(); + crate::warn_log!("browser", "Warning: no virtual monitor for the bot browser: {e}"); + note = Some(format!("가상 모니터 없이 실행: {e}")); + } + } + } + match crate::browser::BotBrowser::start(&exe, &profile, None).await { + Ok(b) => BrowserRun::Running(Arc::new(b), note), Err(e) => { crate::warn_log!("browser", "Warning: the bot browser did not start: {e}"); BrowserRun::Failed(e) @@ -120,7 +142,7 @@ pub async fn start_services(data_dir: &Path, llm: Arc) -> Result Result { meals: get_bool(f, "meals", "features", d.features.meals)?, collect: get_bool(f, "collect", "features", d.features.collect)?, browser: get_bool(f, "browser", "features", d.features.browser)?, + browser_share: get_bool(f, "browserShare", "features", d.features.browser_share)?, } }, mcp_servers: parse_mcp_servers(raw)?, @@ -807,13 +811,13 @@ mod tests { #[test] fn features_and_mcp_servers_are_read_and_checked() { let s = parse_settings(&json!({})); - assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true }); + assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false }); let s = parse_settings(&json!({ - "features": {"weather": false, "meals": false}, + "features": {"weather": false, "meals": false, "browserShare": true}, "mcpServers": [{"name": "brave", "command": "npx", "args": ["-y", "brave"], "env": ["BRAVE_API_KEY", " "]}, {"name": "time-2", "command": "uvx", "enabled": false}] })).unwrap(); - assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false, collect: true, browser: true }); + assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false, collect: true, browser: true, browser_share: true }); assert_eq!(s.mcp_servers, vec![ McpServerSettings { name: "brave".into(), command: "npx".into(), args: vec!["-y".into(), "brave".into()], env: vec!["BRAVE_API_KEY".into()], enabled: true }, diff --git a/app/src/settings_edit.rs b/app/src/settings_edit.rs index 5979097..401951b 100644 --- a/app/src/settings_edit.rs +++ b/app/src/settings_edit.rs @@ -124,6 +124,7 @@ pub fn fields() -> Vec { f("features.meals", Features, Bool, json!(true), "식단 기록"), f("features.collect", Features, Bool, json!(true), "백그라운드 수집"), f("features.browser", Features, Bool, json!(true), "브라우저 제어(봇용 크롬)"), + f("features.browserShare", Features, Bool, json!(false), "봇용 크롬창 화면공유 선택 표시(가상 모니터, Windows)"), f("mcpServers", Features, McpServers, json!([]), "MCP 서버"), // Background collection (admin.spec.md, "Background collection"): no targets by default. f("collect.targets", Collect, CollectTargets, json!([]), "수집 대상"), diff --git a/app/src/vdisplay.rs b/app/src/vdisplay.rs new file mode 100644 index 0000000..3fde306 --- /dev/null +++ b/app/src/vdisplay.rs @@ -0,0 +1,531 @@ +//! The virtual monitor the bot browser's window sits on, so the user can share it in Discord's +//! "Screen" tab while no real monitor shows it (admin.spec.md, "Virtual monitor"; +//! `docs/v2/pc-features.md`, "봇용 크롬창과 디스코드 화면공유"). +//! +//! The monitor comes from the open-source Virtual Display Driver (MIT, signed by the SignPath +//! Foundation), shipped next to `jarvis.exe` in `display-driver/`. Installing it needs the +//! administrator once (`--display-driver install`, started elevated by the app); turning the monitor +//! on and off does not: the app attaches it to the desktop only while the bot browser uses it. + +use std::path::{Path, PathBuf}; + +use serde::Serialize; + +/// The monitor's mode (the driver offers only this one): small enough to share cheaply. +pub const WIDTH: i32 = 1280; +pub const HEIGHT: i32 = 720; +pub const REFRESH: u32 = 30; +/// The adapter name the driver's INF gives its monitors. +pub const ADAPTER_NAME: &str = "Virtual Display Driver"; +pub const HARDWARE_ID: &str = "Root\\MttVDD"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct Rect { + pub x: i32, + pub y: i32, + pub w: i32, + pub h: i32, +} + +/// Where the virtual monitor goes: right of and below the rightmost real monitor, touching it only +/// at that monitor's bottom-right corner, so the mouse hardly ever wanders onto it and no real +/// monitor overlaps it (nothing reaches further right). +pub fn corner(real: &[Rect]) -> (i32, i32) { + real.iter() + .max_by_key(|r| (r.x + r.w, r.y + r.h)) + .map(|r| (r.x + r.w, r.y + r.h)) + .unwrap_or((0, 0)) +} + +/// The driver's settings file: one monitor with one mode, the driver's other options at their +/// defaults. +pub fn settings_xml() -> String { + format!( + "\r\n\r\n\ + 1\r\n\ + default\r\n\ + {REFRESH}\r\n\ + {WIDTH}{HEIGHT}{REFRESH}\r\n\ + falsefalsefalse\ + truefalsefalse\ + falsefalse\r\n\r\n" + ) +} + +/// Where the driver reads its settings: the driver runs as a system service, which cannot read a +/// data folder in the user's profile, so this is the one place outside the data folder. +pub fn config_dir() -> Option { + std::env::var_os("ProgramData").map(|p| PathBuf::from(p).join("JarvisBot").join("display-driver")) +} + +/// The driver files shipped with the app. +pub fn driver_dir() -> Option { + std::env::current_exe().ok()?.parent().map(|d| d.join("display-driver")) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct DriverStatus { + /// Windows only. + pub supported: bool, + /// Installed by this app (its settings folder is the driver's). + pub installed: bool, + /// Another program's copy of the same driver is installed; the app leaves it alone. + pub other: bool, +} + +#[cfg(not(windows))] +pub fn status() -> DriverStatus { + DriverStatus { supported: false, installed: false, other: false } +} + +#[cfg(not(windows))] +pub fn attach() -> Result { + Err("가상 모니터는 Windows에서만 씁니다".into()) +} + +#[cfg(not(windows))] +pub fn detach() {} + +#[cfg(not(windows))] +pub fn settle_windows(_pid: u32) -> usize { + 0 +} + +#[cfg(not(windows))] +pub async fn run_elevated(_action: &str) -> Result<(), String> { + Err("가상 모니터는 Windows에서만 씁니다".into()) +} + +/// `jarvis.exe --display-driver install|uninstall --result FILE`: the elevated half of +/// `run_elevated`; the outcome (empty, or why it failed) goes to FILE. `None` without the option. +pub fn elevated_main(args: &[String]) -> Option { + let i = args.iter().position(|a| a == "--display-driver")?; + let action = args.get(i + 1).map(String::as_str).unwrap_or(""); + let result = args.iter().position(|a| a == "--result").and_then(|j| args.get(j + 1)).map(PathBuf::from); + let outcome = match (action, driver_dir()) { + (_, None) => Err("앱 폴더를 찾지 못했습니다".to_owned()), + ("install", Some(d)) => install(&d), + ("uninstall", Some(d)) => uninstall(&d), + _ => Err(format!("알 수 없는 동작: {action}")), + }; + if let Some(f) = result { + let _ = std::fs::write(f, outcome.as_ref().err().map(String::as_str).unwrap_or("")); + } + Some(if outcome.is_ok() { 0 } else { 1 }) +} + +#[cfg(not(windows))] +fn install(_driver: &Path) -> Result<(), String> { + Err("가상 모니터는 Windows에서만 씁니다".into()) +} + +#[cfg(not(windows))] +fn uninstall(_driver: &Path) -> Result<(), String> { + Err("가상 모니터는 Windows에서만 씁니다".into()) +} + +#[cfg(windows)] +pub use win::{attach, detach, run_elevated, settle_windows, status}; +#[cfg(windows)] +use win::{install, uninstall}; + +#[cfg(windows)] +mod win { + use super::*; + use std::os::windows::ffi::OsStrExt; + use windows_sys::core::BOOL; + use windows_sys::Win32::Devices::DeviceAndDriverInstallation::*; + use windows_sys::Win32::Foundation::*; + use windows_sys::Win32::Graphics::Gdi::*; + use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ}; + use windows_sys::Win32::System::Threading::{GetExitCodeProcess, WaitForSingleObject, INFINITE}; + use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW}; + use windows_sys::Win32::UI::WindowsAndMessaging::*; + + const REG_KEY: &str = "SOFTWARE\\MikeTheTech\\VirtualDisplayDriver"; + + fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() + } + + fn wide_path(p: &Path) -> Vec { + p.as_os_str().encode_wide().chain(Some(0)).collect() + } + + fn text(buf: &[u16]) -> String { + String::from_utf16_lossy(&buf[..buf.iter().position(|&c| c == 0).unwrap_or(buf.len())]) + } + + struct Device { + name: [u16; 32], + string: String, + attached: bool, + } + + fn devices() -> Vec { + let mut out = vec![]; + for i in 0.. { + let mut dd = DISPLAY_DEVICEW { cb: std::mem::size_of::() as u32, ..Default::default() }; + // SAFETY: `dd` is a DISPLAY_DEVICEW with its size set, as the call requires. + if unsafe { EnumDisplayDevicesW(std::ptr::null(), i, &mut dd, 0) } == 0 { + break; + } + out.push(Device { name: dd.DeviceName, string: text(&dd.DeviceString), + attached: dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP != 0 }); + } + out + } + + fn current(name: &[u16; 32]) -> Option { + let mut dm = DEVMODEW { dmSize: std::mem::size_of::() as u16, ..Default::default() }; + // SAFETY: `name` is NUL-terminated (from EnumDisplayDevicesW) and `dm` has its size set. + if unsafe { EnumDisplaySettingsExW(name.as_ptr(), ENUM_CURRENT_SETTINGS, &mut dm, 0) } == 0 { + return None; + } + // SAFETY: for a display, the position variant of the union is the one Windows fills. + let pos = unsafe { dm.Anonymous1.Anonymous2.dmPosition }; + Some(Rect { x: pos.x, y: pos.y, w: dm.dmPelsWidth as i32, h: dm.dmPelsHeight as i32 }) + } + + /// Put the display at `rect`, or take it off the desktop with `None`, and keep that. + fn set_mode(name: &[u16; 32], rect: Option) -> Result<(), String> { + let mut dm = DEVMODEW { dmSize: std::mem::size_of::() as u16, ..Default::default() }; + // SAFETY: as in `current`; a failure leaves `dm` zeroed, which the fields below complete. + unsafe { EnumDisplaySettingsExW(name.as_ptr(), ENUM_REGISTRY_SETTINGS, &mut dm, 0) }; + let r = rect.unwrap_or(Rect { x: 0, y: 0, w: 0, h: 0 }); + dm.dmFields = DM_POSITION | DM_PELSWIDTH | DM_PELSHEIGHT; + dm.Anonymous1.Anonymous2 = DEVMODEW_0_1 { dmPosition: POINTL { x: r.x, y: r.y }, ..Default::default() }; + dm.dmPelsWidth = r.w as u32; + dm.dmPelsHeight = r.h as u32; + // SAFETY: valid NUL-terminated device name and DEVMODEW; null window and parameter. + let changed = unsafe { + ChangeDisplaySettingsExW(name.as_ptr(), &dm, std::ptr::null_mut(), CDS_UPDATEREGISTRY | CDS_NORESET, std::ptr::null()) + }; + // SAFETY: the documented "apply the stored changes" call: all null, no flags. + let applied = unsafe { ChangeDisplaySettingsExW(std::ptr::null(), std::ptr::null(), std::ptr::null_mut(), 0, std::ptr::null()) }; + if changed != DISP_CHANGE_SUCCESSFUL || applied != DISP_CHANGE_SUCCESSFUL { + return Err(format!("화면 설정을 바꾸지 못했습니다 ({changed}, {applied})")); + } + Ok(()) + } + + fn vdd_path() -> Option { + let mut buf = [0u16; 520]; + let mut size = (buf.len() * 2) as u32; + let (key, value) = (wide(REG_KEY), wide("VDDPATH")); + // SAFETY: valid NUL-terminated strings; `buf` holds `size` bytes. + let r = unsafe { + RegGetValueW(HKEY_LOCAL_MACHINE, key.as_ptr(), value.as_ptr(), RRF_RT_REG_SZ, std::ptr::null_mut(), + buf.as_mut_ptr().cast(), &mut size) + }; + (r == ERROR_SUCCESS).then(|| text(&buf)) + } + + fn ours() -> bool { + match (vdd_path(), config_dir()) { + (Some(p), Some(c)) => p.trim_end_matches('\\').eq_ignore_ascii_case(c.to_string_lossy().trim_end_matches('\\')), + _ => false, + } + } + + fn adapter() -> Option { + devices().into_iter().find(|d| d.string == ADAPTER_NAME) + } + + pub fn status() -> DriverStatus { + let present = adapter().is_some() || !hardware_devices(false).is_empty(); + let ours = ours(); + DriverStatus { supported: true, installed: ours && present, other: present && !ours } + } + + /// Put the virtual monitor on the desktop at `corner` and return where it is. + pub fn attach() -> Result { + if !ours() { + return Err("가상 모니터 드라이버가 설치되지 않았습니다".into()); + } + let v = adapter().ok_or("가상 모니터를 찾지 못했습니다")?; + let real: Vec = devices().iter().filter(|d| d.attached && d.string != ADAPTER_NAME) + .filter_map(|d| current(&d.name)).collect(); + let (x, y) = corner(&real); + set_mode(&v.name, Some(Rect { x, y, w: WIDTH, h: HEIGHT }))?; + current(&v.name).filter(|r| r.w > 0).ok_or_else(|| "가상 모니터가 켜지지 않았습니다".into()) + } + + /// Take the virtual monitor off the desktop (when it is ours and on it). + pub fn detach() { + if !ours() { + return; + } + if let Some(v) = adapter().filter(|d| d.attached) { + if let Err(e) = set_mode(&v.name, None) { + crate::warn_log!("browser", "Warning: the virtual monitor stays on: {e}"); + } + } + } + + struct Found { + pid: u32, + windows: Vec, + } + + unsafe extern "system" fn collect(hwnd: HWND, lparam: LPARAM) -> BOOL { + // SAFETY: `lparam` is the `Found` that `settle_windows` passes and outlives EnumWindows. + let found = unsafe { &mut *(lparam as *mut Found) }; + let mut pid = 0u32; + let mut class = [0u16; 64]; + // SAFETY: plain queries on a window handle EnumWindows gave; buffers are sized as passed. + unsafe { + GetWindowThreadProcessId(hwnd, &mut pid); + if pid == found.pid && IsWindowVisible(hwnd) != 0 && GetWindow(hwnd, GW_OWNER).is_null() + && GetClassNameW(hwnd, class.as_mut_ptr(), class.len() as i32) > 0 && text(&class) == "Chrome_WidgetWin_1" { + found.windows.push(hwnd); + } + } + 1 + } + + /// Make process `pid`'s top-level Chrome windows tool windows (not in Alt+Tab, Win+Tab or the + /// taskbar), fill their monitor's work area (Windows may give the virtual monitor a taskbar of + /// its own, which would cover the page's bottom) and put them behind all others, all without + /// activating them. Returns how many it made tool windows. + pub fn settle_windows(pid: u32) -> usize { + let mut found = Found { pid, windows: vec![] }; + // SAFETY: `collect` only reads windows and writes into `found`, which lives through the call. + unsafe { EnumWindows(Some(collect), &mut found as *mut Found as LPARAM) }; + let mut changed = 0; + for h in found.windows { + // SAFETY: style changes on a window of our own child process; hiding and showing it + // again is what makes the taskbar notice the new style. + unsafe { + let ex = GetWindowLongPtrW(h, GWL_EXSTYLE) as u32; + if ex & WS_EX_TOOLWINDOW == 0 { + ShowWindow(h, SW_HIDE); + SetWindowLongPtrW(h, GWL_EXSTYLE, ((ex | WS_EX_TOOLWINDOW) & !WS_EX_APPWINDOW) as isize); + ShowWindow(h, SW_SHOWNOACTIVATE); + changed += 1; + } + let mut mi = MONITORINFO { cbSize: std::mem::size_of::() as u32, ..Default::default() }; + if GetMonitorInfoW(MonitorFromWindow(h, MONITOR_DEFAULTTONEAREST), &mut mi) != 0 { + let w = mi.rcWork; + SetWindowPos(h, HWND_BOTTOM, w.left, w.top, w.right - w.left, w.bottom - w.top, SWP_NOACTIVATE); + } else { + SetWindowPos(h, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + } + } + } + changed + } + + /// The display-class devices with the driver's hardware ID (`present`: only those plugged in). + fn hardware_devices(present: bool) -> Vec { + let (set, list) = hardware_set(present); + if set != INVALID_HANDLE_VALUE as HDEVINFO { + // SAFETY: the list from `hardware_set`, no longer used. + unsafe { SetupDiDestroyDeviceInfoList(set) }; + } + list + } + + fn hardware_set(present: bool) -> (HDEVINFO, Vec) { + // SAFETY: a device list for the display class; destroyed by the callers that keep it. + let set = unsafe { SetupDiGetClassDevsW(&GUID_DEVCLASS_DISPLAY, std::ptr::null(), std::ptr::null_mut(), if present { DIGCF_PRESENT } else { 0 }) }; + let mut out = vec![]; + if set == INVALID_HANDLE_VALUE as HDEVINFO { + return (set, out); + } + for i in 0.. { + let mut di = SP_DEVINFO_DATA { cbSize: std::mem::size_of::() as u32, ..Default::default() }; + // SAFETY: `di` has its size set; the loop ends at the first index past the list. + if unsafe { SetupDiEnumDeviceInfo(set, i, &mut di) } == 0 { + break; + } + let mut buf = [0u16; 256]; + // SAFETY: `buf` holds the byte count passed. + let ok = unsafe { + SetupDiGetDeviceRegistryPropertyW(set, &di, SPDRP_HARDWAREID, std::ptr::null_mut(), buf.as_mut_ptr().cast(), + (buf.len() * 2) as u32, std::ptr::null_mut()) + }; + if ok != 0 && text(&buf).eq_ignore_ascii_case(HARDWARE_ID) { + out.push(di); + } + } + (set, out) + } + + fn run(cmd: &str, args: &[&str]) -> Result<(), String> { + use std::os::windows::process::CommandExt; + let s = std::process::Command::new(cmd).args(args).creation_flags(0x0800_0000) + .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status() + .map_err(|e| format!("{cmd}: {e}"))?; + if s.success() { Ok(()) } else { Err(format!("{cmd} failed ({s})")) } + } + + /// Elevated: settings folder, the driver's registry value, the device, and its driver. Windows + /// asks the user once whether to install software from the SignPath Foundation. + pub(super) fn install(driver: &Path) -> Result<(), String> { + let inf = driver.join("MttVDD.inf"); + if !inf.is_file() { + return Err("드라이버 파일이 없습니다 (display-driver\\MttVDD.inf)".into()); + } + let (present, ours) = (adapter().is_some() || !hardware_devices(false).is_empty(), ours()); + if present && !ours { + return Err("다른 프로그램이 설치한 가상 디스플레이 드라이버가 이미 있습니다".into()); + } + let dir = config_dir().ok_or("ProgramData 폴더를 찾지 못했습니다")?; + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + std::fs::write(dir.join("vdd_settings.xml"), settings_xml()).map_err(|e| e.to_string())?; + // Only the system, administrators, the driver's service account (LOCAL SERVICE) and users + // reading: no user can change what the driver reads. + let d = dir.to_string_lossy().into_owned(); + run("icacls", &[&d, "/inheritance:r", "/grant:r", "*S-1-5-18:(OI)(CI)F", "*S-1-5-32-544:(OI)(CI)F", + "*S-1-5-19:(OI)(CI)RX", "*S-1-5-32-545:(OI)(CI)RX"])?; + run("reg", &["add", &format!("HKLM\\{REG_KEY}"), "/v", "VDDPATH", "/t", "REG_SZ", "/d", &d, "/f"])?; + if hardware_devices(false).is_empty() { + create_device()?; + } + let (hw, inf_w) = (wide(HARDWARE_ID), wide_path(&inf)); + let mut reboot: BOOL = 0; + // SAFETY: valid NUL-terminated strings; no parent window. + if unsafe { UpdateDriverForPlugAndPlayDevicesW(std::ptr::null_mut(), hw.as_ptr(), inf_w.as_ptr(), INSTALLFLAG_FORCE, &mut reboot) } == 0 { + // SAFETY: plain call. + let e = unsafe { GetLastError() }; + return Err(if e == ERROR_CANCELLED { "드라이버 설치를 취소했습니다".into() } else { format!("드라이버를 설치하지 못했습니다 ({e})") }); + } + // The new monitor joins the desktop at once; it stays off until the bot browser uses it. + for _ in 0..50 { + if adapter().is_some_and(|a| a.attached) { + detach(); + break; + } + std::thread::sleep(std::time::Duration::from_millis(200)); + } + Ok(()) + } + + fn create_device() -> Result<(), String> { + let (name, hw) = (wide("Display"), { + let mut v: Vec = HARDWARE_ID.encode_utf16().collect(); + v.extend([0, 0]); + v + }); + // SAFETY: the devcon "install" sequence: a list, one generated device with the hardware ID, + // registered with the class installer; the list is destroyed on every path. + unsafe { + let set = SetupDiCreateDeviceInfoList(&GUID_DEVCLASS_DISPLAY, std::ptr::null_mut()); + if set == INVALID_HANDLE_VALUE as HDEVINFO { + return Err(format!("장치 목록을 만들지 못했습니다 ({})", GetLastError())); + } + let mut di = SP_DEVINFO_DATA { cbSize: std::mem::size_of::() as u32, ..Default::default() }; + let ok = SetupDiCreateDeviceInfoW(set, name.as_ptr(), &GUID_DEVCLASS_DISPLAY, std::ptr::null(), std::ptr::null_mut(), DICD_GENERATE_ID, &mut di) != 0 + && SetupDiSetDeviceRegistryPropertyW(set, &mut di, SPDRP_HARDWAREID, hw.as_ptr().cast(), (hw.len() * 2) as u32) != 0 + && SetupDiCallClassInstaller(DIF_REGISTERDEVICE, set, &di) != 0; + let e = GetLastError(); + SetupDiDestroyDeviceInfoList(set); + if ok { Ok(()) } else { Err(format!("가상 모니터 장치를 만들지 못했습니다 ({e})")) } + } + } + + /// Elevated: remove the device, the driver, the registry value and the settings folder; only + /// when this app installed it. + pub(super) fn uninstall(driver: &Path) -> Result<(), String> { + if !ours() { + return Err("이 앱이 설치한 가상 디스플레이 드라이버가 아닙니다".into()); + } + let (set, list) = hardware_set(false); + for di in &list { + // SAFETY: removing a device of the list `set`, which is destroyed after the loop. + unsafe { SetupDiCallClassInstaller(DIF_REMOVE, set, di) }; + } + if set != INVALID_HANDLE_VALUE as HDEVINFO { + // SAFETY: the list from `hardware_set`. + unsafe { SetupDiDestroyDeviceInfoList(set) }; + } + let inf = wide_path(&driver.join("MttVDD.inf")); + let mut reboot: BOOL = 0; + // SAFETY: valid NUL-terminated path; a driver not in the store is just a failure we ignore. + unsafe { DiUninstallDriverW(std::ptr::null_mut(), inf.as_ptr(), 0, &mut reboot) }; + let _ = run("reg", &["delete", &format!("HKLM\\{REG_KEY}"), "/f"]); + if let Some(dir) = config_dir() { + let _ = std::fs::remove_dir_all(&dir); + if let Some(parent) = dir.parent() { + let _ = std::fs::remove_dir(parent); + } + } + if hardware_devices(false).is_empty() { Ok(()) } else { Err("가상 모니터 장치를 지우지 못했습니다".into()) } + } + + /// Run `jarvis.exe --display-driver ` as administrator (Windows asks the user) and wait. + pub async fn run_elevated(action: &str) -> Result<(), String> { + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let result = std::env::temp_dir().join(format!("jarvis-display-{}.txt", std::process::id())); + let _ = std::fs::remove_file(&result); + let params = format!("--display-driver {action} --result \"{}\"", result.display()); + let code = tokio::task::spawn_blocking(move || -> Result { + let (verb, file, params) = (wide("runas"), wide_path(&exe), wide(¶ms)); + // SAFETY: SHELLEXECUTEINFOW is plain data; all zero is its documented empty state. + let mut info: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() }; + info.cbSize = std::mem::size_of::() as u32; + info.fMask = SEE_MASK_NOCLOSEPROCESS; + info.lpVerb = verb.as_ptr(); + info.lpFile = file.as_ptr(); + info.lpParameters = params.as_ptr(); + info.nShow = SW_HIDE; + // SAFETY: `info` is filled as documented and its strings live through the call; the + // process handle it returns is waited on and closed here. + unsafe { + if ShellExecuteExW(&mut info) == 0 { + let e = GetLastError(); + return Err(if e == ERROR_CANCELLED { "관리자 권한을 받지 못했습니다".into() } else { format!("관리자 권한으로 실행하지 못했습니다 ({e})") }); + } + WaitForSingleObject(info.hProcess, INFINITE); + let mut code = 1u32; + GetExitCodeProcess(info.hProcess, &mut code); + CloseHandle(info.hProcess); + Ok(code) + } + }).await.map_err(|e| e.to_string())??; + let why = std::fs::read_to_string(&result).unwrap_or_default(); + let _ = std::fs::remove_file(&result); + match code { + 0 => Ok(()), + _ if !why.is_empty() => Err(why), + c => Err(format!("드라이버 작업이 실패했습니다 (종료 코드 {c})")), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_monitor_touches_the_rightmost_monitor_only_at_its_corner() { + let one = [Rect { x: 0, y: 0, w: 1920, h: 1080 }]; + assert_eq!(corner(&one), (1920, 1080)); + // A second monitor left of the main one, and one above-right: the rightmost decides. + let three = [Rect { x: 0, y: 0, w: 2560, h: 1440 }, Rect { x: -1920, y: 0, w: 1920, h: 1080 }, + Rect { x: 2560, y: -400, w: 1080, h: 1920 }]; + let (x, y) = corner(&three); + assert_eq!((x, y), (3640, 1520)); + for r in &three { + assert!(r.x + r.w <= x, "no real monitor reaches into the virtual one"); + } + // Two equally far right: the lower corner, so neither overlaps. + let stacked = [Rect { x: 0, y: 0, w: 1920, h: 1080 }, Rect { x: 0, y: 1080, w: 1920, h: 1080 }]; + assert_eq!(corner(&stacked), (1920, 2160)); + } + + #[test] + fn the_driver_gets_one_monitor_with_the_one_mode() { + let x = settings_xml(); + assert!(x.contains("1")); + assert!(x.contains(&format!("{WIDTH}{HEIGHT}{REFRESH}"))); + assert_eq!(x.matches("").count(), 1); + assert!(x.contains("false"), "the driver never loads an EDID file from its folder"); + } + + #[test] + fn only_the_display_driver_option_runs_the_elevated_half() { + assert_eq!(elevated_main(&["jarvis".into(), "--location".into(), "x".into()]), None); + } +} diff --git a/app/tests/bot_browser.rs b/app/tests/bot_browser.rs index 421c9eb..b1fbec3 100644 --- a/app/tests/bot_browser.rs +++ b/app/tests/bot_browser.rs @@ -36,7 +36,7 @@ async fn the_bot_browser_reaches_public_pages_never_this_pc_and_stops() { }); let profile = std::env::temp_dir().join(format!("jarvis-bot-browser-{}", std::process::id())); - let b = BotBrowser::start(std::path::Path::new(&exe), &profile).await.expect("chrome starts"); + let b = BotBrowser::start(std::path::Path::new(&exe), &profile, None).await.expect("chrome starts"); assert!(b.running()); let client = reqwest::Client::builder().no_proxy().build().unwrap(); for url in [format!("http://127.0.0.1:{local}/"), format!("http://localhost:{local}/"), "https://example.com/".into()] { @@ -80,8 +80,80 @@ async fn the_browser_step_installs_a_chrome_that_starts() { assert!(installer.done("browser")); assert!(!data.join("cache").join("downloads").read_dir().map(|mut d| d.next().is_some()).unwrap_or(false), "the archive is removed after unpacking"); - let b = BotBrowser::start(&layout.chrome_exe(), &jarvis_app::browser::profile_dir(&data)).await.expect("starts"); + let b = BotBrowser::start(&layout.chrome_exe(), &jarvis_app::browser::profile_dir(&data), None).await.expect("starts"); assert!(b.running()); b.stop().await; let _ = std::fs::remove_dir_all(&data); } + +/// With a screen, Chrome starts without a window and the app opens exactly one, at the screen's +/// place and size; the page tab the bot opens joins it. Needs a display on Linux (`DISPLAY`); on +/// Windows the screen is the virtual monitor (its driver installed), on the desktop only meanwhile. +#[tokio::test] +async fn on_a_screen_the_bot_browser_has_one_window_at_the_monitor() { + let Ok(exe) = std::env::var("JARVIS_TEST_CHROME") else { + eprintln!("skipped: set JARVIS_TEST_CHROME"); + return; + }; + if cfg!(unix) && std::env::var_os("DISPLAY").is_none() { + eprintln!("skipped: no DISPLAY"); + return; + } + let profile = std::env::temp_dir().join(format!("jarvis-bot-browser-screen-{}", std::process::id())); + let screen = if cfg!(windows) { + let r = jarvis_app::vdisplay::attach().expect("the virtual monitor goes on"); + eprintln!("virtual monitor at {r:?}"); + r + } else { + jarvis_app::vdisplay::Rect { x: 40, y: 30, w: 1280, h: 720 } + }; + let b = BotBrowser::start(std::path::Path::new(&exe), &profile, Some(screen)).await.expect("chrome starts"); + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + let pages = |l: serde_json::Value| l.as_array().unwrap().iter().filter(|t| t["type"] == "page") + .map(|t| t["id"].as_str().unwrap().to_owned()).collect::>(); + let list: serde_json::Value = client.get(format!("http://127.0.0.1:{}/json/list", b.cdp_port)).send().await.unwrap() + .text().await.map(|t| serde_json::from_str(&t).unwrap()).unwrap(); + let first = pages(list); + assert_eq!(first.len(), 1, "one page in one window"); + client.put(format!("http://127.0.0.1:{}/json/new?about:blank", b.cdp_port)).send().await.unwrap(); + + // Each page's window over CDP: both tabs share the one window, at the screen's rectangle. + let ws: serde_json::Value = client.get(format!("http://127.0.0.1:{}/json/version", b.cdp_port)).send().await.unwrap() + .text().await.map(|t| serde_json::from_str(&t).unwrap()).unwrap(); + let (mut s, _) = tokio_tungstenite::connect_async(ws["webSocketDebuggerUrl"].as_str().unwrap()).await.unwrap(); + let list: serde_json::Value = client.get(format!("http://127.0.0.1:{}/json/list", b.cdp_port)).send().await.unwrap() + .text().await.map(|t| serde_json::from_str(&t).unwrap()).unwrap(); + let ids = pages(list); + assert_eq!(ids.len(), 2); + let mut windows = std::collections::HashSet::new(); + for (i, id) in ids.iter().enumerate() { + use futures_util::{SinkExt, StreamExt}; + let msg = serde_json::json!({"id": i + 1, "method": "Browser.getWindowForTarget", "params": {"targetId": id}}); + s.send(tokio_tungstenite::tungstenite::Message::text(msg.to_string())).await.unwrap(); + let r = loop { + let v: serde_json::Value = serde_json::from_str(s.next().await.unwrap().unwrap().to_text().unwrap()).unwrap(); + if v["id"] == i + 1 { break v["result"].clone(); } + }; + eprintln!("window: {r}"); + windows.insert(r["windowId"].as_i64().unwrap()); + let b = &r["bounds"]; + let (left, top, width, height) = (b["left"].as_i64().unwrap(), b["top"].as_i64().unwrap(), + b["width"].as_i64().unwrap(), b["height"].as_i64().unwrap()); + let (x, y, w, h) = (screen.x as i64, screen.y as i64, screen.w as i64, screen.h as i64); + if cfg!(windows) { + // Inside the monitor, filling it but for the monitor's own taskbar if Windows gave it one. + assert!(left >= x && top >= y && left + width <= x + w && top + height <= y + h, "{b}"); + assert!(width * height * 10 >= w * h * 8, "{b}"); + } else { + assert_eq!((left, top, width, height), (x, y, w, h)); + } + } + assert_eq!(windows.len(), 1, "the bot's tab opens in the same window"); + if std::env::var_os("JARVIS_TEST_HOLD").is_some() { + // Time for a look at the screen (the Windows check takes a screenshot meanwhile). + tokio::time::sleep(std::time::Duration::from_secs(8)).await; + } + b.stop().await; + jarvis_app::vdisplay::detach(); + let _ = std::fs::remove_dir_all(&profile); +} diff --git a/app/tests/vdisplay_elevated.rs b/app/tests/vdisplay_elevated.rs new file mode 100644 index 0000000..a30d79e --- /dev/null +++ b/app/tests/vdisplay_elevated.rs @@ -0,0 +1,23 @@ +//! Installing and removing the virtual monitor's driver through the app's elevated half +//! (admin.spec.md, "Virtual monitor"). Windows only, with the driver files in `display-driver/` next +//! to this program and `JARVIS_TEST_VDISPLAY=install` or `uninstall`; Windows asks for the +//! administrator (and on install whether to trust the SignPath Foundation). Elsewhere it skips. +//! No test harness: started elevated, this same program is the elevated half. + +fn main() { + let args: Vec = std::env::args().collect(); + if let Some(code) = jarvis_app::vdisplay::elevated_main(&args) { + std::process::exit(code); + } + let Ok(action) = std::env::var("JARVIS_TEST_VDISPLAY") else { + eprintln!("skipped: set JARVIS_TEST_VDISPLAY=install|uninstall"); + return; + }; + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + let outcome = rt.block_on(jarvis_app::vdisplay::run_elevated(&action)); + let status = jarvis_app::vdisplay::status(); + println!("{action}: {outcome:?} -> {status:?}"); + outcome.expect("the elevated half succeeds"); + assert_eq!(status.installed, action == "install"); + assert!(!status.other); +} diff --git a/app/ui/app.js b/app/ui/app.js index 4de01a6..ff81a6d 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -385,6 +385,28 @@ async function tokenCard() { } }, "확인 후 저장")), out); } +/** The virtual monitor's driver for "봇용 크롬창 화면공유 선택 표시" (Windows only). */ +async function displayDriverCard() { + const st = await api("display_driver_status"); + if (!st.supported) return null; + const label = h("span"); + const btn = h("button", { class: "btn" }); + const show = (s) => { + label.textContent = s.installed ? "설치됨" : s.other ? "다른 프로그램의 같은 드라이버가 있어 쓰지 않습니다" : "설치되지 않음"; + btn.textContent = s.installed ? "드라이버 제거" : "드라이버 설치"; + btn.disabled = s.other; + btn.onclick = async () => { + btn.disabled = true; + try { show(await api(s.installed ? "display_driver_uninstall" : "display_driver_install")); toast("완료했습니다"); } + catch (e) { fail(e); show(await api("display_driver_status")); } + }; + }; + show(st); + return h("div", { class: "card" }, h("h2", {}, "가상 모니터 드라이버"), + h("p", { class: "small muted" }, "봇용 크롬창을 실제 모니터에는 보이지 않는 가상 모니터에 두어, 디스코드 화면 공유의 \"화면\" 탭에서 고를 수 있게 합니다. 설치할 때 관리자 권한과 Windows의 장치 소프트웨어 설치 확인(SignPath Foundation)을 한 번 묻습니다."), + h("div", { class: "row" }, label, btn)); +} + // ---- dashboard ---------------------------------------------------------------------------------- /** The header with the start/stop buttons; rebuilt only when the state changes, so a click is not @@ -543,7 +565,7 @@ async function show(name) { 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: "백그라운드 수집" }; - const extra = name === "bot" ? await tokenCard() : null; + 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()); if (my === gen) screen.replaceChildren(view); diff --git a/docs/v2/pc-features.md b/docs/v2/pc-features.md index dd8874e..ab66fd6 100644 --- a/docs/v2/pc-features.md +++ b/docs/v2/pc-features.md @@ -271,12 +271,14 @@ LLM과 STT를 함께 켠 측정(M0 `gamemode_stt`, 게임 없음). STT를 먼저 **가상 모니터 방식**: 가상 모니터를 하나 만들고 봇용 크롬을 그 모니터에 둡니다. -- 가상 디스플레이 드라이버는 앱 설치 파일에 들어 있어야 합니다(다른 프로그램 설치를 전제로 하지 않음). 오픈소스 Virtual Display Driver(MIT, SignPath 재단 서명)를 함께 넣고, 앱이 가상 모니터 수를 바꿔 켜고 끕니다(사용자 선택). 설치 때 관리자 권한을 한 번 묻습니다(설치 승인받음). 대상은 x64 Windows 10/11(S 모드 제외)입니다. +- 가상 디스플레이 드라이버는 앱 설치 파일에 들어 있어야 합니다(다른 프로그램 설치를 전제로 하지 않음). 오픈소스 Virtual Display Driver(MIT, SignPath 재단 서명)를 함께 넣고, 앱이 가상 모니터를 켜고 끕니다(사용자 선택). 드라이버의 모니터 수는 0으로 두어도 하나가 생겨서, 모니터 하나를 두고 쓰는 동안에만 바탕 화면에 붙였다가 떼는 방식으로 켜고 끕니다(붙이고 떼는 데는 관리자 권한이 필요 없음). 설치 때 관리자 권한을 한 번 묻고(설치 승인받음), Windows가 "SignPath Foundation의 장치 소프트웨어를 설치할까요?"를 한 번 더 묻습니다. 드라이버 설정은 드라이버(시스템 서비스)가 데이터 폴더를 읽을 수 없어 `%ProgramData%\JarvisBot\display-driver`에 둡니다. 다른 프로그램이 같은 드라이버를 이미 깔아 두었으면 설치하지 않고 그 모니터도 건드리지 않습니다. 대상은 x64 Windows 10/11(S 모드 제외)입니다. 자세한 동작은 `app/src/admin.spec.md` "Virtual monitor". - 앱이 꺼질 때는 봇용 크롬을 먼저 닫습니다. 가상 모니터가 먼저 사라지면 그 위의 창이 실제 모니터로 옮겨질 수 있기 때문입니다. - M0 `vdisplay` 단계(Parsec 드라이버로 하는 개념 확인)는 돌리지 않기로 했습니다(사용자 결정). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치는 M6에서 함께 넣을 드라이버로 직접 확인합니다. 드라이버 설치 시험은 게임PC가 아니라 서버의 Windows 가상머신에서 먼저 합니다. - 마우스가 가상 모니터로 넘어가지 않도록, 실제 모니터와 구석 한 점만 닿게 배치합니다. - 디스코드에서는 "화면" 탭에서 그 가상 모니터를 고릅니다. - Alt+Tab에서는 그대로 빠지고, 실제 모니터에도 보이지 않습니다. +- 크롬 창을 처음부터 띄우면 사용자가 하던 게임의 포커스를 가져갈 수 있어서, 창 없이 켠 뒤 앱이 CDP로 창을 뒤에서 엽니다. Windows가 가상 모니터에도 작업 표시줄을 두면 페이지 아래를 가리지 않게 창을 작업 영역에 맞춥니다. +- **서버 Windows 가상머신 확인(2026-11-14)**: 드라이버 설치(SignPath 질문 한 번)와 제거(장치·드라이버 패키지·레지스트리·설정 폴더 남지 않음), 설치 직후 모니터 꺼짐, 봇용 크롬을 켜는 동안만 실제 모니터 오른쪽 아래 구석(1024,768)에 1280x720으로 켜짐, 크롬 창 하나가 그 모니터의 작업 영역을 채우고 봇의 탭도 그 창에 열림, 메모장에 입력하는 동안 포커스를 뺏지 않음, 작업 표시줄에 버튼 없음, 정지 뒤 크롬 프로세스 0개와 모니터 꺼짐. 남은 확인: 디스코드 "화면" 탭에 그 모니터가 나오고 공유되는지, 커서, 게임PC(실제 GPU)에서의 동작. ## 다른 사람의 디스코드 화면공유 보기 (창 분리 방식) diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index c628845..e93caaf 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -10,7 +10,7 @@ | M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 3단계 완료(2026-11-11): 앱이 음성 워커에 음성 채널 입장·퇴장, 사람 출입, 등록한 채팅 채널의 글·수정·삭제를 알리고, 워커가 최종 전사를 저장함. 워커는 `--history`로 저장소를, `--brain`으로 두뇌를 켜고, `reply` 요청에 묻는 사람의 범위로 찾은 기록을 넣어 답하고(`reply_text`) 음성이면 바로 말함. 실제 디스코드 시험(봇 두 개)에서 전사 8개가 이름과 함께 저장되고, 채팅 수정은 반영, 삭제한 글은 빠지고, 자비스가 나간 뒤 출입 기록이 모두 닫힘. 워커와 실제 두뇌(이 서버 Ollama `/v1`, qwen2.5:7b, 맥락 8천 토큰)로 다른 사람이 채팅에 남긴 약속을 4번 물어 4번 모두 맞게 답함. Ollama의 `/v1`은 맥락을 2,048토큰으로 고정해 지시문을 자르므로, Ollama로 시험할 때는 `num_ctx`를 넣은 모델 이름을 씀(Strata는 시작할 때 맥락을 정해 해당 없음). v2 두뇌는 한 사람용인 v1 장기 기억(프로필·일기·그래프)을 넣지 않고, 답하는 동안 원문이 로그에 찍히지 않게 함. 언제 `reply`를 보낼지(호출 판정)와 음성 답 재생 연결은 M4. 4단계 완료(2026-11-11): 채팅 채널 도구 `chatChannels`(목록·읽기·검색·보내기·수정·반응·삭제·고정, 스펙 [chat_channels.spec.md](../../src/jarvis/tools/builtin/chat_channels.spec.md)). 읽기·검색은 대화 기록 저장소에서, 나머지는 앱이 채널별 허용 설정을 확인하고 디스코드에서 실행. 삭제는 다음 메시지에서 사용자가 동의해야 실행하고, 채널 글은 명령이 아닌 자료로 표시. 실제 디스코드에서 수정(자기 글만)·반응·삭제·고정을 확인(음성 채널의 채팅은 디스코드가 고정을 막아 오류로 돌아옴). 평가(qwen2.5:7b) 3번에 12번 중 10번 통과, 글 속 명령을 따르지 않기와 같은 턴에 지우지 않기는 12번 모두 지킴. 식단 기록은 사람별로 나눔(v1 데이터는 그대로). 기존 테스트·평가 확인(2026-11-11): 단위 테스트는 2,215개 통과, 10개 실패이고, 실패 10개는 이 서버에 PortAudio가 없어 마이크 코드(음성 듣기·받아쓰기)가 꺼진 탓임. 갱신되지 않았던 테스트 4개(한국어 한 문장 날씨 3, 잡담 빠른 경로를 지나는 캐시 1)와 설치된 PyQt6를 가짜로 바꿔 다른 화면 테스트를 깨뜨리던 테스트 1곳을 고침. 평가(evals, qwen2.5:7b)는 145개 통과, 56개 실패, 60개 건너뜀. 실패 중 54개는 M3 이전 커밋(beaacb3)에서도 실패하거나, 3번씩 다시 돌린 통과 횟수가 양쪽이 같아 M3 때문에 생긴 실패는 없음. 나머지 2개는 새 채팅 도구 평가의 알려진 실패(12번 중 2번). 원래 실패하는 평가는 이 서버에 없는 모델(gpt-oss:20b, nomic-embed-text)을 쓰거나 qwen2.5:7b가 웹 검색·날씨 도구를 부르지 않는 경우가 대부분임. 실제로 쓸 모델로 평가 확인(2026-11-11): 게임PC의 Strata(Qwen3.6-35B-A3B UD-Q4_K_XL, 맥락 32K, 평소 배치)에 SSH 터널로 붙어 이 서버에서 평가 전체를 돌림. 193개 통과, 12개 실패, 60개 건너뜀(의도 판정·도구 선택 평가는 gemma4 단계에서만 돌고, gemma4는 이 서버 Ollama에 없음), 8분 13초. 실패 12개를 3번씩 다시 돌리니 5개는 3번 모두 실패(알려진 위치를 날씨 도구 인자로 넣지 않음 2, 파리·런던 비교에서 날씨 도구를 한 번만 부름 1, 지식 그래프 갈래 분류 1, 맥락에 있는 위치를 기억 검색 질문에 다시 넣음 1)했고, 날씨 한 번 부르기 평가는 엔진의 정해진 날씨 경로(`_maybe_deterministic_weather`)가 평가가 바꿔 둔 도구 실행기를 거치지 않고 실제 날씨를 받아 한국어로 바로 답해 3번 모두 실패함(모델과 상관없음). 나머지 6개는 3번 중 1~3번 통과함. qwen2.5:7b에서 없던 실패는 기억 검색 질문 1개(3번 모두)와 날씨 다시 시도 2개(다시 돌리면 6번 중 4번 통과)임 실패 고침(2026-11-11): 엔진의 정해진 한국어 날씨 경로를 뺌(평가의 도구 실행기를 거치지 않았고, 사용자가 말한 위치를 쓰지 못함, 큰 모델은 도구 결과를 한국어 한 문장으로 그대로 답함). 날씨 도구와 대화 지시문은 사용자가 대화나 기억에서 말한 위치를 넣고, 자동으로 잡힌 위치는 옮겨 적지 않게 함. "구, 시, 나라" 이름이 안 찾아지면 넓은 지역으로 다시 찾음. 계획 단계에 현재 시간·위치 줄을 주어, 위치를 모를 때만 기억에서 사용자 위치를 먼저 찾게 함. 같은 도구 반복 제한이 이전 답변의 호출까지 세어 사용자가 다시 해 달라고 해도 막던 버그를 고침. 기억 검색어 지시문에서 평가와 같은 문장의 예시를 바꾸고 현재 맥락 블록을 예시 뒤로 옮김(위치를 모를 때는 여전히 묻는지 보는 평가 추가, qwen2.5:7b는 바꾸기 전에도 묻지 않음). 평가 전체 202개 통과, 4개 실패, 9분 3초. 이 전체 실행의 날씨 실패 1개는 장소를 말하지 않은 "what's the weather this week"에 자동으로 잡힌 위치(`Hackney, England, UK`)를 인자로 옮겨 적은 것으로, 그 뒤 날씨 도구와 지시문을 사용자가 말한 위치만 넣도록 좁혀 고침. 고친 뒤 날씨 평가 12개를 따로 3번 돌려 36번 중 34번 통과(이 평가는 3번 모두 통과, 실패 2번은 날씨 한 번 부르기 평가가 파리 날씨 답에 도시 이름을 다시 말하지 않은 것). 전체 실행의 나머지 실패는 지식 그래프 갈래 분류 1개(모델이 "사용자가 물었다"를 사용자 사실로 하나 더 남김, 지시문을 두 번 고쳐도 같아 되돌림, v2는 v1 장기 기억을 쓰지 않음)와 다시 돌리면 통과하는 2개(유명인 두 턴 대화, 최근 일기 반영) | | M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트. 1단계 완료(2026-11-11): 앱의 호출 판정 `app/src/calls.rs`와 응답 정책 `app/src/policy.rs`(스펙 [conversation.spec.md](../../app/src/conversation.spec.md)), 설정 `call`·`response`. 비슷한 발음은 유니코드 NFKD로 한글을 자모로 나눠 편집 거리로 판단(기본 0.2: "자비즈"는 호출, "서비스"는 아님). 정책은 말이 끝난 시각 순서, 먼저 끝난 말의 전사 대기(최대 0.8초), 끼어들기, 놓친 요청 사유를 가짜 시각으로 시험함. 2단계 완료(2026-11-11): 대화 루프 `app/src/conversation.rs`가 최종 전사를 호출 판정과 응답 정책에 넣고, 정책의 결정대로 두뇌에 답을 요청해(`reply`, 답은 워커가 같은 id로 읽음) 앱의 재생 대기열에서 재생, 끼어들 때는 그 답만 멈춤, "자비스 멈춰"는 모든 말을 멈춤, 놓친 요청은 글 없이 최근 100개를 남김. 두뇌의 두 판정 `src/voice_worker/judges.py`(봇에게 하는 말인지, 중요도 순위)는 답과 따로 돌아 기다리지 않음. 평가 `evals/test_voice_judges.py` 12개를 qwen2.5:7b에서 모두 통과. 답을 만드는 중에 멈춘 요청은 말하지 않음. 실제 Python 워커(가짜 두뇌)와 앱의 통합 시험 통과. 3단계 완료(2026-11-11): 채팅 채널 호출. 채널마다 `answer`(호출어로 부를 때만 / 모든 메시지에 대답), 채팅 호출어(`call.chatWakeWords`, 없으면 음성과 같음)와 지정한 사람 설정은 음성과 같이 씀. 답은 같은 채널에 원래 메시지의 답글로 올리고 아무도 부르지 않음. 다른 봇의 글과 보내기가 꺼진 채널에는 답하지 않음. 음성 대화 순서와는 따로 감(워커가 음성 답과 채팅 답을 따로 써서 다른 사람의 채팅 답 때문에 음성 답이 기다리지 않음. 한 사람의 답은 물은 순서대로 하나씩 씀. 두 답의 LLM 호출이 동시에 돌려면 Strata를 `--parallel 2`로 띄움, 앱이 Strata를 띄우는 M5 전까지). 5분 넘게 늦은 채팅 답은 올리지 않음. 실제 디스코드 시험과 지연 측정은 4단계. 4단계 첫 측정(2026-11-12): 앱의 실제 서비스(`start_services`: 대화 루프, 응답 정책, 워커, 두뇌)를 게임PC Strata(`--parallel 2`)에 붙이고, 봇 두 개로 질문 5개를 2번씩 말해 잼(`app/tests/live_round_trip.rs`). 10개 모두 소리로 답했고, 말 끝부터 첫 소리까지 중앙값 3.5초(최소 2.8초, 날씨 도구 8.6초). 9명이 동시에 말하는 부하(워커의 두 번째 연결로 녹음 문장 9개를 실시간으로 넣음, 그동안 최종 전사 259개)에서는 중앙값 4.4초, 최종 전사가 0.6~0.9초에서 0.8~1.8초로 늦어졌고 1번은 "기분"을 "딥"으로 잘못 들어 날씨 도구를 불러 18.8초가 걸림. 짧은 답의 시간은 최종 전사 0.65~0.85초, 두뇌 2.0~2.9초(도구 고르기 0.42초, 계획 0.5초, 답 호출의 지시문 약 4,300토큰 읽기 1.1초와 생성), 재생 시작과 전달 약 0.4초. Strata의 Qwen3.6 엔진은 지시문 앞부분 재사용을 하지 않아(`--prompt-cache-every`는 "이 엔진의 옵션이 아님"으로 무시됨, 같은 대화를 그대로 이어 갈 때만 재사용) 매 호출을 처음부터 읽음. 생성은 0.2~0.5초라 문장 단위로 흘려도 짧은 답은 거의 빨라지지 않음. 1.5초 기준은 아직 못 맞춤. 같은 시험에서 찾아 고친 것: v1 TTS 설정(영어 전용 Piper) 때문에 한국어 질문에 영어로 답하던 것(v2 두뇌는 묻는 사람의 언어로 답함), 호출어 뒤에 쉬면 "자비스"만 따로 끊겨 그 이름에만 답하고 이어진 질문은 무시하던 것(이제 같은 사람이 이어서 하는 말과 합침, `call.followUpMs`). 4단계 지연 줄이기(사용자 결정, 2026-11-12): 부름을 받으면 "띠링" 효과음(앱이 만든 0.3초 소리, `call.earcon`, 이름만 부르고 쉬면 그때 바로), 답은 한국어 기본(영어 등은 따로 부탁할 때만), v2 두뇌의 짧은 지시문(성격 설명 7.4천 자를 1.3천 자로, 답은 최대한 짧게, 화면공유 도구는 v2에 없어 뺌: 인사의 답 지시문 4,500토큰이 1,400토큰), 답 전에 판단 한 번(도구 고르기로 도구가 필요한지 정하고, 필요할 때만 계획. 계획 하나로 합치거나 계획을 아예 빼 보니 날씨나 여러 단계 질문이 틀려 이 방식으로 정함), 말하는 중의 중간 전사가 호출로 읽히면 도구 고르기를 미리 해 둠(워커 `prepare`). 평가 전체(v2 설정, 마지막 지시문 수정 전) 219개 통과, 6개 실패: 파리·런던 비교와 지식 그래프 갈래 분류는 전부터 실패, 3개는 v2가 쓰지 않는 v1 개인 기억(그래프·일기) 평가, 1개는 새 답 길이 평가("하늘은 왜 파래"의 답이 72자로 기준 70자를 넘음). 그 뒤 "왜·어떻게" 질문은 핵심 이유만 말하도록 지시문을 고치고 답 길이 평가를 따로 3번 돌려 3번 모두 통과(v2 답 합계 185~205자, 예전 315~356자), 한국어 기본·지난 대화·채팅 채널·건너뛴 도구 평가 22개도 모두 통과(전체 평가는 이 수정 뒤 다시 돌리지 않음). 실제 디스코드 재측정(2026-11-12, `app/tests/live_round_trip.rs`, 질문 5개 2번): 첫 소리(효과음)는 이름 뒤에 쉬면 질문이 끝나기 전에, 쉬지 않으면 0.94~1.10초. 답의 첫 소리는 중앙값 1.9초(1.56~2.30초, 날씨 도구 5.75~5.85초), 9명이 동시에 말할 때 2.8초(2.13~3.41초, "기분"을 "딥"으로 잘못 들은 1번은 웹 검색으로 13.3초). 혼자일 때는 미리 해 둔 판단이 5번 모두 쓰여 말 끝 뒤 두뇌 시간이 0.6~0.74초였고, 9명 부하에서는 중간 전사가 밀려 미리 판단이 한 번도 되지 않음(두뇌 1.4초). 같은 시험에서 찾아 고친 것: 모델이 "10시 37분"을 오후로 읽음(시간 줄에 12시간 표기 추가), 없는 타이머 도구 호출 글자(``)를 답으로 내 TTS가 읽을 뻔함(도구 호출로 읽음) | | M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드). 단계: 1 관리 기능(화면 없음), 2 서비스 제어와 대시보드 자료, 3 Tauri 화면, 4 런타임·모델 자동 설치, 5 Windows 빌드와 확인. 1단계 완료(2026-11-12): `app/src/datadir.rs`(데이터 폴더와 위치 기억 파일, 남은 용량), `settings_edit.rs`(화면 5개의 항목 36개, 기본값과 다른 값만 저장, 모르는 키 보존, 앱 검사를 통과해야만 저장), `secrets.rs`(봇 토큰, Windows는 사용자 계정 DPAPI 암호화), `logs.rs`(서비스별 탭, 날짜별 파일 14일 보관, 최근 오류 복사, 10MB 이하 zip, 비밀값·토큰 모양 가림), 앱 설정에 대화 기억(`memory`) 칸을 넣어 워커에 넘김. 스펙 [admin.spec.md](../../app/src/admin.spec.md). Windows용 코드는 Windows 대상으로 컴파일만 확인(실행 확인은 5단계). 2단계 완료(2026-11-12): `control.rs`(서비스 시작·정지·재시작 규칙, 실패는 비밀값을 가린 오류로 남기고 아무것도 켜 두지 않음, 앱 실행 파일도 같은 제어기를 씀), `dashboard.rs`(디스코드 이벤트만으로 만드는 대시보드 자료: 연결 상태, 음성 채널과 참가자, 실시간 자막 30줄(화면에만, 기록하지 않음, 나가거나 정지하면 지움), 답 20개의 단계별 지연(말 끝→최종 전사, 두뇌, 목소리, 전체)과 중앙값, 놓친 요청 20개(글 없이)), `system.rs`(RAM, `nvidia-smi`로 GPU 사용률·VRAM). 성능 단계(평소/게임 중/일시정지)는 게임 감지와 함께 M7. 3단계 완료(2026-11-12): 화면 `app/ui/`(빌드 도구 없는 HTML/CSS/JS, 어두운 테마, 한국어)와 화면이 부르는 명령 `admin_api.rs`(설정, 대시보드, 시작·정지, 로그 조회·복사·zip, PC 점검, 디스코드 토큰 확인·초대 링크·서버/채널 목록 `discord_setup.rs`). 첫 실행 마법사(데이터 폴더, PC 점검, 모델 안내, 봇 연결, 서버·음성 채널, 호출어, 시작), 대시보드, 설정 5개, 로그. 개발용 서버 `jarvis-admin-dev`로 이 서버의 브라우저에서 실제 테스트 봇과 음성 워커를 켜고 확인: 마법사 각 단계, 시작 뒤 "실행 중 · 테스트봇#9029 · 워커 연결됨", 다시 시작·정지, 설정 저장(바뀐 값만, 모르는 키 보존), 채팅 채널 추가, 로그 실시간 보기와 zip 내보내기. Tauri 창(셸)은 이 서버에서 빌드할 수 없어(webkit2gtk 없음) Windows 빌드 단계에서 붙임. 디스코드 채널 이름·주제 반영은 아직. 4단계 첫 부분 완료(2026-11-12): 설치 `install.rs`·`download.rs`(이어받기, SHA-256 확인), M0 키트와 같은 방식으로 uv 0.11.20 → 워커·두뇌 Python 3.12 환경(v2 전용 패키지 목록 `requirements-brain.txt`) → MeloTTS Python 3.11 환경 → Whisper large-v3-turbo → MeloTTS 한국어 음성 → Strata를 모두 데이터 폴더 안에 설치하고, 끝나면 다운로드 캐시를 비우고 워커 설정을 설치된 Python으로 바꿈. 마법사 "모델" 단계에서 진행·취소·다시 시도. 이 서버(Linux)에서 빈 폴더부터 전부 설치해 보고 그 런타임으로 서비스를 켜 워커 연결, 받아 적기·음성 준비까지 확인했고, 설치 중 데이터 폴더 밖에는 아무것도 쓰지 않음. 대화 모델(약 23GB)은 앱이 Strata를 직접 띄우는 다음 부분에서 받음. 4단계 뒷부분 완료(2026-11-12): 서비스를 켜면 앱이 먼저 데이터 폴더의 Strata를 띄움(`app/src/strata.rs`, M0와 같은 모델과 평소 배치, 처음 켤 때 대화 모델 약 23GB를 받음, 대시보드에 진행률과 Strata의 마지막 줄, 켜는 중에도 정지 가능, 서비스를 끄면 Strata도 끔). 동시 요청은 1개(모든 메시지에 답하는 채팅 채널이 있으면 2개), 그림 읽기는 v2에서 아직 쓰지 않아 끔. 시작할 때마다 두뇌 설정 `config/brain.json`(Strata 주소, Strata가 알려 준 모델 이름, 데이터 폴더 안의 기억 DB)을 써서 워커에 넘김. 이미 떠 있는 서버를 쓰려면 설정 파일의 `llm.url`. 확인: 가짜 Strata로 진행률·준비·정지·다운로드 중 취소·실패를 단위 시험, 게임PC의 Strata 0.1.59가 앱의 실행 옵션을 그대로 받아들임(`--plan`), 앱 서비스를 `llm.url`로 게임PC Strata에 붙여 실제 디스코드 왕복 10개 모두 소리로 답함. 앱이 Strata를 직접 띄워 모델을 받는 실제 확인은 이 서버에서 할 수 없어(메모리) Windows 빌드 단계에서 게임PC로 함. 5단계 완료(2026-11-12): Tauri 2 창 `app/shell`(`jarvis.exe`, 화면의 명령을 같은 `AdminApi`로 넘김, 창을 닫으면 서비스와 Strata를 끄고 끝날 때까지 기다림, 창의 브라우저 자료는 위치 기억 파일 옆)과 Windows 빌드 `app/shell/package.sh`(이 서버에서 `x86_64-pc-windows-gnu`로 빌드, `Jarvis/` 폴더에 실행 파일·WebView2Loader.dll·Python 소스 `python-src`, zip 11MB). 시험용 Windows VM에서: 창과 마법사, PC 점검, uv·워커 환경 설치, 설치 취소 뒤 남은 프로세스 없음, 봇 토큰 DPAPI 암호화 저장, 시작 실패 이유 표시, 로그 화면·오류 복사·zip, 창 닫기로 종료, %APPDATA%·%LOCALAPPDATA%에 아무것도 안 남김, 앱 핵심 단위 테스트(Windows 빌드) 통과. 게임PC(RTX 5070 Ti, C:\JarvisM0 안에서만)에서 같은 관리 명령으로: 전체 설치 7단계 6분 40초, 앱이 직접 띄운 Strata가 엔진과 대화 모델 22.9GB를 약 6분에 받고 준비, 워커(GPU 받아 적기·음성) 연결, 디스코드 음성 채널 입장, 시험 봇이 말한 질문 5개에 모두 소리로 답함(앱이 잰 전체 중앙값 3.36초, 처음 질문 6.4초, 날씨 11.6초), 정지 8초에 GPU 메모리 반환. 같은 시험에서 찾아 고친 것: Windows는 닫힌 로컬 포트의 연결 거부가 약 2초 늦어 정지 확인이 실패로 나오던 것, Strata가 모델 크기(`X of Y GB`)로만 진행을 알려 진행률이 앞 단계의 80%에 멈춰 있던 것, Strata와 NVIDIA 셰이더 캐시가 %APPDATA%에 쓰던 것(데이터 폴더로). 마무리(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가 쓰이고 있어 아직 못 돌림. 남은 것: 실제 모델 평가, 가상 모니터와 "봇용 크롬창 화면공유 선택 표시", 나머지 기능 스위치(PC 제어·화면 보기, 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 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 |