From 24d0798bae2f678e73b0ab52ea1715c707c389e5 Mon Sep 17 00:00:00 2001 From: javis-bot Date: Fri, 13 Nov 2026 22:01:04 +0900 Subject: [PATCH] feat(app): the bot's own Chrome in the data folder, reaching only public addresses - install step browser: Chrome for Testing 157 (pinned SHA-256) into runtime/chrome - services start it headless with its own profile when features.browser is on; CDP on a free loopback port passed to the worker as JARVIS_BROWSER_CDP; a failure leaves the services running - every Chrome connection goes through the app's loopback egress proxy: one lookup, public addresses only (403 otherwise, no host logged), QUIC off, WebRTC only through the proxy - stop: Browser.close, then kill after 5 s; dashboard shows the browser's state - the worker's runtime environment follows the settings step, not every step being installed Co-Authored-By: Claude Opus 5.5 --- app/src/admin.spec.md | 40 +++- app/src/browser.rs | 425 +++++++++++++++++++++++++++++++++++++++ app/src/control.rs | 2 + app/src/features.rs | 4 +- app/src/install.rs | 95 ++++++++- app/src/lib.rs | 1 + app/src/services.rs | 69 ++++++- app/src/settings.rs | 9 +- app/src/settings_edit.rs | 1 + app/tests/bot_browser.rs | 87 ++++++++ app/ui/app.js | 5 +- docs/v2/roadmap.md | 2 +- 12 files changed, 724 insertions(+), 16 deletions(-) create mode 100644 app/src/browser.rs create mode 100644 app/tests/bot_browser.rs diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index a55dca2..03c9aee 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -60,10 +60,11 @@ 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), also on by default. The tools of a feature that + collection, below; no brain tool) and `browser` (the bot browser, below "Bot browser"; its brain + tool comes with it), also on 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 (browser control, PC - control, screen viewing) come with their milestones (M6, M7). + (`voice_worker.spec.md`, "Tools"). The other features of the 기능 screen (PC control, screen + viewing) come with their milestone (M7). - `mcpServers` (new list): each `{name, command, args, env, enabled}`. `name` is 1-32 letters, digits, `-` or `_` without `__` (the brain names a server's tools `__`), not listed twice; `command` is not empty; `args` a list of strings; `env` the names of the environment @@ -183,6 +184,7 @@ reaches the screen. who, why and how long ago, never the text. - `system`: memory in use and total, and per NVIDIA GPU its use and VRAM (from `nvidia-smi`, missing when there is none); sampled when the snapshot is taken, at most once a second. +- `browser`: the bot browser's `{state, note}` ("Bot browser"). - `llm`: the LLM's state (`off`, `starting`, `ready`, `failed`), whether the app runs it (`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 @@ -206,6 +208,7 @@ on the game PC (`scripts/m0`). The steps, in order: | `stt_model` | Whisper `large-v3-turbo` (faster-whisper) | | `tts_model` | the NLTK data MeloTTS's English g2p reads, then the worker's own `melo_child.py` loads the Korean voice once (downloading it) and must say its warm-up sentence | | `strata` | Strata's own installer (`install.ps1`, `install.sh` elsewhere) with Strata's state, engine and components under `runtime/strata` and no PATH change | +| `browser` | the bot's Chrome: Chrome for Testing 157.0.8103.78 (win64, linux64), downloaded with resume and checked against its pinned SHA-256, unpacked into `runtime/chrome` (below, "Bot browser") | | `settings` | `voiceWorker` in the settings pointed at the worker venv's Python with `--melo-python --history memory/history.sqlite --brain` (other settings kept); the install is done only once this is written | The LLM itself (Qwen3.6-35B-A3B, about 23 GB) is downloaded by Strata on its first start (below). @@ -230,6 +233,37 @@ 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). + +- `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 + worker. Without it (off, or not installed) nothing starts. A browser that does not start is a + warning on the dashboard and in the `browser` log tab; the services run on without it. +- Chrome runs with its own profile `browser/profile` (`--user-data-dir`), headless, no first-run, + sync, component updates, translation or background networking, and CDP on a free loopback port + (`--remote-debugging-port=0`; the port is read from the profile's `DevToolsActivePort`, which is + removed before each start, and `/json/version` must answer within 30 s). The worker gets + `JARVIS_BROWSER_CDP` = `http://127.0.0.1:`. +- **Egress proxy**: every Chrome connection goes through the app's proxy on a free loopback port + (`--proxy-server`, and `--proxy-bypass-list=<-loopback>` so not even loopback is direct; QUIC off, + WebRTC only through the proxy). The proxy takes `CONNECT host:port` (HTTPS, WebSocket) and plain + HTTP requests with an absolute `http://` address. It resolves the name once (at most 10 s), refuses + with 403 unless every address is public (not loopback, private, link-local, CGNAT, documentation, + benchmarking, multicast, reserved or unspecified, also inside IPv4-mapped IPv6), and connects + only to those addresses, so Chrome can never reach the PC or the local network. Plain HTTP goes + on with `Connection: close` and without proxy headers. A request it cannot read is a 400. It logs + no host or address, only that it refused one. +- Stop: CDP `Browser.close`, then up to 5 s for the process to end, else it and the processes it + started are killed. The services' stop ends the proxy too. +- 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. + ## LLM (`app/src/strata.rs`) The brain answers with one model, Qwen3.6-35B-A3B UD-Q4_K_XL through Strata (M0). The services diff --git a/app/src/browser.rs b/app/src/browser.rs new file mode 100644 index 0000000..fe4f931 --- /dev/null +++ b/app/src/browser.rs @@ -0,0 +1,425 @@ +//! The bot browser (`app/src/admin.spec.md`, "Bot browser"): the bot's own Chrome in the data +//! folder, driven over CDP, and the egress proxy every Chrome connection goes through so it can +//! only reach public addresses. + +use std::net::{IpAddr, SocketAddr}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::Duration; + +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +const RESOLVE_TIMEOUT: Duration = Duration::from_secs(10); +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +const HEAD_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_HEAD: usize = 64 * 1024; +const READY_TIMEOUT: Duration = Duration::from_secs(30); +const CLOSE_WAIT: Duration = Duration::from_secs(5); + +/// Whether an address is on the public internet: not this PC, the local network or a special range. +pub fn is_public(ip: &IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => { + let o = v4.octets(); + !(v4.is_private() || v4.is_loopback() || v4.is_link_local() || v4.is_broadcast() + || v4.is_documentation() || v4.is_unspecified() || v4.is_multicast() + || o[0] == 0 // "this network" + || (o[0] == 100 && (64..128).contains(&o[1])) // CGNAT 100.64/10 + || (o[0] == 192 && o[1] == 0 && o[2] == 0) // IETF 192.0.0/24 + || (o[0] == 198 && (18..20).contains(&o[1])) // benchmarking 198.18/15 + || o[0] >= 240) // reserved + } + IpAddr::V6(v6) => { + if let Some(v4) = v6.to_ipv4_mapped() { + return is_public(&IpAddr::V4(v4)); + } + let s = v6.segments(); + !(v6.is_loopback() || v6.is_unspecified() || v6.is_multicast() + || (s[0] & 0xfe00) == 0xfc00 // unique local fc00::/7 + || (s[0] & 0xffc0) == 0xfe80 // link local fe80::/10 + || (s[0] == 0x2001 && s[1] == 0x0db8) // documentation + || (s[0] == 0x0064 && s[1] == 0xff9b) // NAT64 (could reach IPv4 private) + || s[0] == 0x2002 // 6to4 (embeds any IPv4) + || (s[0] == 0x2001 && s[1] == 0)) // Teredo + } + } +} + +// ---- egress proxy --------------------------------------------------------------------------------- + +/// A loopback HTTP proxy that connects only to addresses `allow` accepts (`is_public` for Chrome). +pub struct EgressProxy { + pub port: u16, + task: tokio::task::JoinHandle<()>, +} + +impl EgressProxy { + pub async fn start(allow: fn(&IpAddr) -> bool) -> std::io::Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let port = listener.local_addr()?.port(); + let task = tokio::spawn(async move { + while let Ok((client, _)) = listener.accept().await { + tokio::spawn(async move { + let _ = serve(client, allow).await; + }); + } + }); + Ok(Self { port, task }) + } + + pub fn stop(&self) { + self.task.abort(); + } +} + +impl Drop for EgressProxy { + fn drop(&mut self) { + self.task.abort(); + } +} + +/// The request head (up to the blank line) and whatever came after it. +async fn read_head(s: &mut TcpStream) -> std::io::Result)>> { + let mut buf = Vec::new(); + let mut chunk = [0u8; 8192]; + loop { + if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let rest = buf.split_off(end + 4); + return Ok(String::from_utf8(buf).ok().map(|h| (h, rest))); + } + if buf.len() > MAX_HEAD { + return Ok(None); + } + let n = s.read(&mut chunk).await?; + if n == 0 { + return Ok(None); + } + buf.extend_from_slice(&chunk[..n]); + } +} + +/// `host:port` with an optional `[..]` around an IPv6 address. +fn split_host_port(s: &str) -> Option<(String, u16)> { + let (host, port) = s.rsplit_once(':')?; + let host = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host); + if host.is_empty() { + return None; + } + Some((host.to_owned(), port.parse().ok()?)) +} + +/// Resolve once, require every address to be allowed, and connect only to those. +async fn connect_allowed(host: &str, port: u16, allow: fn(&IpAddr) -> bool) -> Result { + let addrs: Vec = match host.parse::() { + Ok(ip) => vec![SocketAddr::new(ip, port)], + Err(_) => match tokio::time::timeout(RESOLVE_TIMEOUT, tokio::net::lookup_host((host, port))).await { + Ok(Ok(a)) => a.collect(), + _ => return Err("name not resolved"), + }, + }; + if addrs.is_empty() || !addrs.iter().all(|a| allow(&a.ip())) { + return Err("not a public address"); + } + for a in &addrs { + if let Ok(Ok(s)) = tokio::time::timeout(CONNECT_TIMEOUT, TcpStream::connect(a)).await { + return Ok(s); + } + } + Err("could not connect") +} + +async fn reply(client: &mut TcpStream, status: &str) -> std::io::Result<()> { + client.write_all(format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").as_bytes()).await +} + +async fn serve(mut client: TcpStream, allow: fn(&IpAddr) -> bool) -> std::io::Result<()> { + let Ok(Ok(Some((head, rest)))) = tokio::time::timeout(HEAD_TIMEOUT, read_head(&mut client)).await else { + return reply(&mut client, "400 Bad Request").await; + }; + let mut lines = head.split("\r\n"); + let mut first = lines.next().unwrap_or("").split(' '); + let (method, target, version) = (first.next().unwrap_or(""), first.next().unwrap_or(""), first.next().unwrap_or("")); + if method.eq_ignore_ascii_case("CONNECT") { + let Some((host, port)) = split_host_port(target) else { return reply(&mut client, "400 Bad Request").await }; + let mut up = match connect_allowed(&host, port, allow).await { + Ok(s) => s, + Err(why) => return refused(&mut client, why).await, + }; + client.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await?; + up.write_all(&rest).await?; + tokio::io::copy_bidirectional(&mut client, &mut up).await?; + return Ok(()); + } + let Ok(url) = reqwest::Url::parse(target) else { return reply(&mut client, "400 Bad Request").await }; + let (Some(host), Some(port)) = (url.host_str(), url.port_or_known_default()) else { + return reply(&mut client, "400 Bad Request").await; + }; + if url.scheme() != "http" || !version.starts_with("HTTP/") { + return reply(&mut client, "400 Bad Request").await; + } + let host = host.trim_start_matches('[').trim_end_matches(']').to_owned(); + let mut up = match connect_allowed(&host, port, allow).await { + Ok(s) => s, + Err(why) => return refused(&mut client, why).await, + }; + // Origin form, no proxy headers, one request per connection (the next may be for another host). + let path = match url.query() { + Some(q) => format!("{}?{q}", url.path()), + None => url.path().to_owned(), + }; + let mut out = format!("{method} {path} {version}\r\n"); + for l in lines.filter(|l| !l.is_empty()) { + let name = l.split(':').next().unwrap_or("").trim().to_ascii_lowercase(); + if !matches!(name.as_str(), "proxy-connection" | "proxy-authorization" | "connection" | "keep-alive") { + out.push_str(l); + out.push_str("\r\n"); + } + } + out.push_str("Connection: close\r\n\r\n"); + up.write_all(out.as_bytes()).await?; + up.write_all(&rest).await?; + tokio::io::copy_bidirectional(&mut client, &mut up).await?; + Ok(()) +} + +async fn refused(client: &mut TcpStream, why: &str) -> std::io::Result<()> { + // Never the host or the address: they are what the bot was asked to open. + crate::debug_log!("browser", "proxy refused a connection: {why}"); + reply(client, "403 Forbidden").await +} + +// ---- 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 { + 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}"), + "--proxy-bypass-list=<-loopback>".into(), + "--disable-quic".into(), + "--force-webrtc-ip-handling-policy=disable_non_proxied_udp".into(), + "--no-first-run".into(), + "--no-default-browser-check".into(), + "--disable-sync".into(), + "--disable-background-networking".into(), + "--disable-component-update".into(), + "--disable-default-apps".into(), + "--disable-features=Translate,MediaRouter,OptimizationHints".into(), + "--window-size=1280,800".into(), + ]; + if no_sandbox { + a.push("--no-sandbox".into()); + } + a.push("about:blank".into()); + a +} + +pub struct BotBrowser { + child: Mutex>, + proxy: EgressProxy, + pub cdp_port: u16, +} + +impl BotBrowser { + /// Start Chrome `exe` with profile folder `profile` and wait until CDP answers. + pub async fn start(exe: &Path, profile: &Path) -> 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()) + .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true); + #[cfg(unix)] + cmd.process_group(0); + #[cfg(windows)] + cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + let mut child = cmd.spawn().map_err(|e| format!("Chrome을 실행하지 못했습니다: {e}"))?; + let until = tokio::time::Instant::now() + READY_TIMEOUT; + let cdp_port = loop { + if let Some(p) = std::fs::read_to_string(&port_file).ok() + .and_then(|t| t.lines().next().and_then(|l| l.trim().parse::().ok())) { + if version(p).await.is_some() { + break p; + } + } + if let Ok(Some(status)) = child.try_wait() { + return Err(format!("Chrome이 바로 끝났습니다 ({status})")); + } + if tokio::time::Instant::now() > until { + kill_tree(&mut child).await; + return Err("Chrome이 30초 안에 준비되지 않았습니다".into()); + } + 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 }) + } + + pub fn cdp_url(&self) -> String { + format!("http://127.0.0.1:{}", self.cdp_port) + } + + /// Whether Chrome still runs. + pub fn running(&self) -> bool { + self.child.lock().unwrap().as_mut().is_some_and(|c| matches!(c.try_wait(), Ok(None))) + } + + /// `Browser.close`, then up to 5 s for Chrome to end, else it is killed; the proxy ends too. + pub async fn stop(&self) { + let child = self.child.lock().unwrap().take(); + if let Some(mut child) = child { + if let Some(ws) = version(self.cdp_port).await.and_then(|v| v["webSocketDebuggerUrl"].as_str().map(str::to_owned)) { + let _ = close_over_cdp(&ws).await; + } + if !matches!(tokio::time::timeout(CLOSE_WAIT, child.wait()).await, Ok(Ok(_))) { + crate::warn_log!("browser", "Chrome did not close in {} s; killing it", CLOSE_WAIT.as_secs()); + kill_tree(&mut child).await; + } + crate::info_log!("browser", "bot browser stopped"); + } + self.proxy.stop(); + } +} + +/// CDP's `/json/version`, if it answers. +async fn version(port: u16) -> Option { + let client = reqwest::Client::builder().no_proxy().timeout(Duration::from_secs(2)).build().ok()?; + let text = client.get(format!("http://127.0.0.1:{port}/json/version")).send().await.ok()?.text().await.ok()?; + serde_json::from_str(&text).ok() +} + +async fn close_over_cdp(ws: &str) -> Result<(), String> { + use futures_util::SinkExt; + let (mut s, _) = tokio::time::timeout(Duration::from_secs(2), tokio_tungstenite::connect_async(ws)).await + .map_err(|_| "timeout".to_string())?.map_err(|e| e.to_string())?; + s.send(tokio_tungstenite::tungstenite::Message::text(r#"{"id":1,"method":"Browser.close"}"#)).await + .map_err(|e| e.to_string()) +} + +async fn kill_tree(child: &mut tokio::process::Child) { + if let Some(pid) = child.id() { + #[cfg(unix)] + // SAFETY: a plain signal to Chrome's own process group (made with process_group(0)). + unsafe { + libc::kill(-(pid as i32), libc::SIGKILL); + } + #[cfg(windows)] + { + let mut tk = tokio::process::Command::new("taskkill"); + tk.args(["/T", "/F", "/PID", &pid.to_string()]).stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).creation_flags(0x0800_0000); + let _ = tk.status().await; + } + } + let _ = child.kill().await; +} + +/// Where the bot browser's profile lives in the data folder. +pub fn profile_dir(data: &Path) -> PathBuf { + data.join("browser").join("profile") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[test] + fn only_public_addresses_are_public() { + let public = ["8.8.8.8", "1.1.1.1", "142.250.1.1", "2606:4700:4700::1111", "2a00:1450:4001::1"]; + let not = ["127.0.0.1", "10.0.0.1", "172.16.5.4", "192.168.10.9", "169.254.169.254", "100.64.0.1", + "0.0.0.0", "0.1.2.3", "192.0.0.8", "192.0.2.1", "198.18.0.1", "203.0.113.5", "224.0.0.1", "240.0.0.1", + "255.255.255.255", "::1", "::", "fc00::1", "fd12::1", "fe80::1", "ff02::1", "2001:db8::1", + "::ffff:127.0.0.1", "::ffff:192.168.0.1", "64:ff9b::a00:1", "2002:c0a8:1::1", "2001:0:4136:e378::1"]; + for a in public { + assert!(is_public(&a.parse().unwrap()), "{a} should be public"); + } + for a in not { + assert!(!is_public(&a.parse().unwrap()), "{a} should not be public"); + } + } + + /// A local server recording each connection's first bytes and answering `answer`. + async fn server(answer: &'static [u8]) -> (u16, Arc>>) { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = l.local_addr().unwrap().port(); + let seen = Arc::new(Mutex::new(Vec::new())); + let s2 = seen.clone(); + tokio::spawn(async move { + while let Ok((mut c, _)) = l.accept().await { + let seen = s2.clone(); + tokio::spawn(async move { + let mut buf = vec![0u8; 4096]; + let n = c.read(&mut buf).await.unwrap_or(0); + seen.lock().unwrap().push(String::from_utf8_lossy(&buf[..n]).into_owned()); + let _ = c.write_all(answer).await; + }); + } + }); + (port, seen) + } + + async fn ask(proxy: u16, req: String) -> String { + let mut c = TcpStream::connect(("127.0.0.1", proxy)).await.unwrap(); + c.write_all(req.as_bytes()).await.unwrap(); + let mut out = Vec::new(); + let _ = tokio::time::timeout(Duration::from_secs(5), c.read_to_end(&mut out)).await; + String::from_utf8_lossy(&out).into_owned() + } + + fn loopback(ip: &IpAddr) -> bool { + ip.is_loopback() + } + + #[tokio::test] + async fn the_proxy_refuses_this_pc_and_the_local_network() { + let (port, seen) = server(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi").await; + let p = EgressProxy::start(is_public).await.unwrap(); + for req in [format!("CONNECT 127.0.0.1:{port} HTTP/1.1\r\nHost: x\r\n\r\n"), + format!("CONNECT localhost:{port} HTTP/1.1\r\n\r\n"), + format!("CONNECT [::1]:{port} HTTP/1.1\r\n\r\n"), + format!("GET http://127.0.0.1:{port}/a HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"), + format!("GET http://localhost:{port}/a HTTP/1.1\r\n\r\n"), + "CONNECT 192.168.10.1:443 HTTP/1.1\r\n\r\n".to_string(), + "GET http://10.0.0.1/ HTTP/1.1\r\n\r\n".to_string()] { + let r = ask(p.port, req.clone()).await; + assert!(r.starts_with("HTTP/1.1 403"), "{req:?} -> {r:?}"); + } + assert!(seen.lock().unwrap().is_empty()); + for bad in ["nonsense\r\n\r\n", "GET /relative HTTP/1.1\r\n\r\n", "GET ftp://a.example/ HTTP/1.1\r\n\r\n", + "CONNECT nohost HTTP/1.1\r\n\r\n"] { + assert!(ask(p.port, bad.into()).await.starts_with("HTTP/1.1 400"), "{bad:?}"); + } + } + + #[tokio::test] + async fn the_proxy_tunnels_and_forwards_to_allowed_addresses() { + let (port, seen) = server(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi").await; + let p = EgressProxy::start(loopback).await.unwrap(); + let r = ask(p.port, format!("CONNECT 127.0.0.1:{port} HTTP/1.1\r\n\r\nping")).await; + assert!(r.starts_with("HTTP/1.1 200 Connection Established\r\n\r\nHTTP/1.1 200 OK"), "{r:?}"); + let r = ask(p.port, format!("GET http://127.0.0.1:{port}/a/b?c=1 HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\ + Proxy-Connection: keep-alive\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")).await; + assert!(r.ends_with("hi"), "{r:?}"); + let seen = seen.lock().unwrap().clone(); + assert_eq!(seen[0], "ping"); + assert_eq!(seen[1], format!("GET /a/b?c=1 HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nAccept: */*\r\nConnection: close\r\n\r\n")); + } + + #[test] + fn chrome_goes_through_the_proxy_with_its_own_profile() { + let a = chrome_args(Path::new("/d/browser/profile"), 4321, 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")); + } +} diff --git a/app/src/control.rs b/app/src/control.rs index b58a527..a00d3d4 100644 --- a/app/src/control.rs +++ b/app/src/control.rs @@ -269,6 +269,7 @@ impl Controller { view["missed"] = status["missed"].clone(); view["worker"] = status["worker"].clone(); view["voiceMembers"] = status["voiceMembers"].clone(); + view["browser"] = status.get("browser").cloned().unwrap_or_else(|| json!({"state": "off", "note": null})); view["state"] = json!(state); view["error"] = json!(error); view["system"] = json!(self.system().await); @@ -360,6 +361,7 @@ impl Running for crate::services::Services { "voiceMembers": self.core.voice_members().into_iter() .map(|(id, name)| json!({"id": id.to_string(), "name": name})).collect::>(), "missed": crate::dashboard::missed_view(&missed, now), + "browser": self.browser.view(), }) } } diff --git a/app/src/features.rs b/app/src/features.rs index 5d61406..ada74da 100644 --- a/app/src/features.rs +++ b/app/src/features.rs @@ -100,9 +100,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 }; + let all_on = FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true }; assert!(disabled_tools(&all_on).is_empty()); - let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false, collect: false }); + let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false, collect: false, browser: false }); assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal"]); } diff --git a/app/src/install.rs b/app/src/install.rs index 39d16ba..f9caa82 100644 --- a/app/src/install.rs +++ b/app/src/install.rs @@ -32,6 +32,15 @@ const TORCH: [&str; 2] = ["torch==2.11.0", "torchaudio==2.11.0"]; const TORCH_PIN: &str = "torch==2.11.0+cu128\ntorchaudio==2.11.0+cu128\n"; const MELO_URL: &str = "https://github.com/myshell-ai/MeloTTS/archive/209145371cff8fc3bd60d7be902ea69cbdb7965a.tar.gz"; pub const STT_MODEL: &str = "large-v3-turbo"; +/// The bot browser (admin.spec.md, "Bot browser"): Chrome for Testing, per platform the archive +/// and its SHA-256 (computed from the downloads; Google publishes none). +pub const CHROME_VERSION: &str = "157.0.8103.78"; +#[cfg(windows)] +const CHROME_ARCHIVE: (&str, &str) = ("win64/chrome-win64.zip", + "5f6ec40206407112702e163bf694d07f9fdc8ccbd346c70ce61fa62f716493f9"); +#[cfg(not(windows))] +const CHROME_ARCHIVE: (&str, &str) = ("linux64/chrome-linux64.zip", + "9223832977a13db3646201b1341c1f9cf08afa3ceae92540116d7b0c062364fb"); /// Where everything goes, from the data folder and the app's Python sources (`voice_worker`, `jarvis`). #[derive(Debug, Clone)] @@ -61,6 +70,10 @@ impl Layout { self.strata_home().join("terminal").join("current").join("bin") .join(if cfg!(windows) { "strata.cmd" } else { "strata" }) } + pub fn chrome_exe(&self) -> PathBuf { + let dir = self.runtime().join("chrome"); + if cfg!(windows) { dir.join("chrome-win64").join("chrome.exe") } else { dir.join("chrome-linux64").join("chrome") } + } /// Hugging Face models (Whisper, MeloTTS and its BERT); the worker gets the same `HF_HOME`. pub fn hf_home(&self) -> PathBuf { self.data.join("models").join("hf") @@ -346,6 +359,11 @@ impl Installer { serde_json::json!({"running": self.running.load(Ordering::SeqCst), "done": all_done, "steps": steps}) } + /// Whether the step `id` is installed at its current version. + pub fn done(&self, id: &str) -> bool { + self.steps.iter().any(|s| s.id() == id && self.is_done(s.as_ref())) + } + pub fn all_done(&self) -> bool { self.steps.iter().all(|s| self.is_done(s.as_ref())) } @@ -600,6 +618,55 @@ impl Step for StrataStep { } } +struct BrowserStep; +#[async_trait] +impl Step for BrowserStep { + fn id(&self) -> &'static str { "browser" } + fn label(&self) -> &'static str { "봇용 크롬" } + fn size_hint(&self) -> &'static str { "약 200MB" } + fn version(&self, _: &Layout) -> String { CHROME_VERSION.into() } + async fn run(&self, ctx: &Ctx) -> Result<(), String> { + let (path, sum) = CHROME_ARCHIVE; + let url = format!("https://storage.googleapis.com/chrome-for-testing-public/{CHROME_VERSION}/{path}"); + let archive = ctx.layout.data.join("cache").join("downloads").join(path.rsplit('/').next().unwrap()); + crate::download::download(&url, &archive, sum, &|d, t| ctx.bytes(d, t), &ctx.cancel).await.map_err(|e| e.0)?; + let dir = ctx.layout.runtime().join("chrome"); + let _ = std::fs::remove_dir_all(&dir); + unzip(&archive, &dir)?; + let _ = std::fs::remove_file(&archive); + if !ctx.layout.chrome_exe().exists() { + return Err("크롬 압축을 풀었지만 실행 파일이 없습니다".into()); + } + Ok(()) + } +} + +/// Unpack a zip into `dir`, keeping its folders and (on Unix) its executable bits. +fn unzip(archive: &Path, dir: &Path) -> Result<(), String> { + let f = std::fs::File::open(archive).map_err(|e| e.to_string())?; + let mut z = zip::ZipArchive::new(f).map_err(|e| e.to_string())?; + for i in 0..z.len() { + let mut entry = z.by_index(i).map_err(|e| e.to_string())?; + let Some(rel) = entry.enclosed_name() else { continue }; + let out = dir.join(rel); + if entry.is_dir() { + std::fs::create_dir_all(&out).map_err(|e| e.to_string())?; + continue; + } + if let Some(parent) = out.parent() { + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let mut w = std::fs::File::create(&out).map_err(|e| e.to_string())?; + std::io::copy(&mut entry, &mut w).map_err(|e| e.to_string())?; + #[cfg(unix)] + if let Some(mode) = entry.unix_mode() { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&out, std::fs::Permissions::from_mode(mode & 0o777)).map_err(|e| e.to_string())?; + } + } + Ok(()) +} + /// Point the services at what was installed: the worker venv's Python and the arguments for the /// MeloTTS venv, the history store and the brain (`voiceWorker` in `config/settings.json`; other /// keys are kept). @@ -638,7 +705,7 @@ impl Step for SettingsStep { /// The install steps, in order. pub fn steps() -> Vec> { vec![Box::new(UvStep), Box::new(WorkerEnvStep), Box::new(MeloEnvStep), Box::new(SttModelStep), - Box::new(TtsModelStep), Box::new(StrataStep), Box::new(SettingsStep)] + Box::new(TtsModelStep), Box::new(StrataStep), Box::new(BrowserStep), Box::new(SettingsStep)] } #[cfg(test)] @@ -823,4 +890,30 @@ mod tests { } assert!(l.uv().starts_with(&l.data) && l.venv_python("worker").starts_with(&l.data)); } + + #[test] + fn a_zip_unpacks_with_its_folders_and_executable_bits() { + use std::io::Write; + let d = temp_dir("unzip"); + let archive = d.join("a.zip"); + let mut w = zip::ZipWriter::new(std::fs::File::create(&archive).unwrap()); + let exe = zip::write::SimpleFileOptions::default().unix_permissions(0o755); + w.add_directory("top/sub/", zip::write::SimpleFileOptions::default()).unwrap(); + w.start_file("top/chrome", exe).unwrap(); + w.write_all(b"#!/bin/sh\n").unwrap(); + w.start_file("top/sub/data.pak", zip::write::SimpleFileOptions::default().unix_permissions(0o644)).unwrap(); + w.write_all(b"data").unwrap(); + w.start_file("../escape", zip::write::SimpleFileOptions::default()).unwrap(); + w.write_all(b"no").unwrap(); + w.finish().unwrap(); + let out = d.join("out"); + unzip(&archive, &out).unwrap(); + assert_eq!(std::fs::read(out.join("top/sub/data.pak")).unwrap(), b"data"); + assert!(!d.join("escape").exists()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(out.join("top/chrome")).unwrap().permissions().mode() & 0o777, 0o755); + } + } } diff --git a/app/src/lib.rs b/app/src/lib.rs index b341fcb..9799a12 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -2,6 +2,7 @@ pub mod log; pub mod admin_api; +pub mod browser; pub mod calls; pub mod channel_sync; pub mod chat; diff --git a/app/src/services.rs b/app/src/services.rs index d774436..2d0d36e 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -22,6 +22,34 @@ pub struct Services { /// The conversation's missed requests, for the dashboard. pub missed: conversation::MissedLog, pub llm: Arc, + pub browser: BrowserRun, +} + +/// The bot browser of a run (admin.spec.md, "Bot browser"). +pub enum BrowserRun { + /// Not started: the feature is off, or (with a note) it is not installed. + Off(Option), + Failed(String), + Running(Arc), +} + +impl BrowserRun { + /// `{state, note}` for the dashboard. + pub fn view(&self) -> Value { + 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), + }; + serde_json::json!({"state": state, "note": note}) + } + + pub async fn stop(&self) { + if let BrowserRun::Running(b) = self { + b.stop().await; + } + } } impl Services { @@ -30,10 +58,31 @@ impl Services { self.core.close().await; self.worker.close(); self.worker_process.stop().await; + self.browser.stop().await; self.llm.stop().await } } +/// Start the bot browser when its feature is on and it is installed; a failure leaves the services +/// running without it. +async fn start_browser(data_dir: &Path, settings: &crate::settings::Settings) -> BrowserRun { + if !settings.features.browser { + return BrowserRun::Off(None); + } + let layout = crate::install::Layout { data: data_dir.to_path_buf(), src: std::path::PathBuf::new() }; + if !crate::install::Installer::new(layout.clone(), crate::install::steps()).done("browser") { + 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)), + Err(e) => { + crate::warn_log!("browser", "Warning: the bot browser did not start: {e}"); + BrowserRun::Failed(e) + } + } +} + /// Start the services; the LLM first (its first start downloads the model), so nothing answers /// before the brain can. A failure stops what already started. pub async fn start_services(data_dir: &Path, llm: Arc) -> Result> { @@ -60,24 +109,28 @@ pub async fn start_services(data_dir: &Path, llm: Arc) -> Result f, Err(e) => return Err(after_llm_stop(&llm, format!("could not write the brain settings: {e}")).await.into()), }; + let browser = start_browser(data_dir, &settings).await; let w = &settings.voice_worker; let mut wopts = WorkerProcessOptions::new(&w.python, &w.cwd, settings.worker_args()); // With the installed runtime, the worker's models, caches and temp files stay in the data folder. let layout = crate::install::Layout { data: data_dir.to_path_buf(), src: w.cwd.clone() }; - if crate::install::Installer::new(layout.clone(), crate::install::steps()).all_done() { + if crate::install::Installer::new(layout.clone(), crate::install::steps()).done("settings") { wopts.env.extend(layout.env()); } wopts.env.insert("JARVIS_CONFIG_PATH".into(), brain_config.to_string_lossy().into_owned()); wopts.env.insert(crate::features::MCP_ENV_VAR.into(), mcp_env.to_string()); + if let BrowserRun::Running(b) = &browser { + wopts.env.insert("JARVIS_BROWSER_CDP".into(), b.cdp_url()); + } // Background collection (admin.spec.md): the enabled targets, and the keep days in any case. match crate::collect::write_config(data_dir, &settings) { Ok(f) => { wopts.env.insert(crate::collect::COLLECT_ENV_VAR.into(), f.to_string_lossy().into_owned()); } - Err(e) => return Err(after_llm_stop(&llm, format!("could not write the collection settings: {e}")).await.into()), + Err(e) => return Err(after_stop(&llm, &browser, format!("could not write the collection settings: {e}")).await.into()), } let worker_process = match WorkerProcess::new(wopts) { Ok(p) => p, - Err(e) => return Err(after_llm_stop(&llm, e.to_string()).await.into()), + Err(e) => return Err(after_stop(&llm, &browser, e.to_string()).await.into()), }; let mut process_events = worker_process.subscribe(); worker_process.start(); @@ -111,10 +164,10 @@ pub async fn start_services(data_dir: &Path, llm: Arc) -> Result Vec { v } +/// Stop the bot browser and the LLM after a failed start. +async fn after_stop(llm: &Llm, browser: &BrowserRun, error: String) -> String { + browser.stop().await; + after_llm_stop(llm, error).await +} + /// Stop the LLM after a failed start; the error also says if its server may still run. async fn after_llm_stop(llm: &Llm, error: String) -> String { match llm.stop().await { diff --git a/app/src/settings.rs b/app/src/settings.rs index 037924e..f0939c0 100644 --- a/app/src/settings.rs +++ b/app/src/settings.rs @@ -93,6 +93,8 @@ pub struct FeatureSettings { pub meals: bool, /// Background collection (admin.spec.md, "Background collection"). pub collect: bool, + /// The bot browser (admin.spec.md, "Bot browser"). + pub browser: bool, } /// Background collection (admin.spec.md, "Background collection"); no targets by default. @@ -184,7 +186,7 @@ impl Default for Settings { response: PolicySettings::default(), memory: Map::new(), llm: LlmSettings { url: None, port: 8080, context: 32768 }, - features: FeatureSettings { weather: true, web_search: true, meals: true, collect: true }, + features: FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true }, mcp_servers: vec![], collect: CollectSettings { keep_days: 30, targets: vec![] }, } @@ -505,6 +507,7 @@ pub fn parse_settings(raw: &Value) -> Result { web_search: get_bool(f, "webSearch", "features", d.features.web_search)?, 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)?, } }, mcp_servers: parse_mcp_servers(raw)?, @@ -804,13 +807,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 }); + assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true }); let s = parse_settings(&json!({ "features": {"weather": false, "meals": false}, "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 }); + assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false, collect: true, browser: 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 d5d3d48..5979097 100644 --- a/app/src/settings_edit.rs +++ b/app/src/settings_edit.rs @@ -123,6 +123,7 @@ pub fn fields() -> Vec { f("features.webSearch", Features, Bool, json!(true), "웹 검색"), f("features.meals", Features, Bool, json!(true), "식단 기록"), f("features.collect", Features, Bool, json!(true), "백그라운드 수집"), + f("features.browser", Features, Bool, json!(true), "브라우저 제어(봇용 크롬)"), 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/tests/bot_browser.rs b/app/tests/bot_browser.rs new file mode 100644 index 0000000..421c9eb --- /dev/null +++ b/app/tests/bot_browser.rs @@ -0,0 +1,87 @@ +//! The bot browser with a real Chrome (admin.spec.md, "Bot browser"). Runs only with +//! `JARVIS_TEST_CHROME=`; needs the internet for the public page. On Ubuntu also +//! set `JARVIS_CHROME_NO_SANDBOX=1`. + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use jarvis_app::browser::BotBrowser; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +async fn titles(client: &reqwest::Client, port: u16) -> Vec<(String, String)> { + let text = client.get(format!("http://127.0.0.1:{port}/json/list")).send().await.unwrap().text().await.unwrap(); + let list: serde_json::Value = serde_json::from_str(&text).unwrap(); + list.as_array().unwrap().iter() + .map(|t| (t["url"].as_str().unwrap_or("").to_owned(), t["title"].as_str().unwrap_or("").to_owned())).collect() +} + +#[tokio::test] +async fn the_bot_browser_reaches_public_pages_never_this_pc_and_stops() { + let Ok(exe) = std::env::var("JARVIS_TEST_CHROME") else { + eprintln!("skipped: set JARVIS_TEST_CHROME"); + return; + }; + // A page on this PC the browser must never reach. + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let local = l.local_addr().unwrap().port(); + let hits = Arc::new(Mutex::new(0)); + let h2 = hits.clone(); + tokio::spawn(async move { + while let Ok((mut c, _)) = l.accept().await { + *h2.lock().unwrap() += 1; + let mut b = [0u8; 1024]; + let _ = c.read(&mut b).await; + let _ = c.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\nsecret localxx").await; + } + }); + + 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"); + 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()] { + client.put(format!("http://127.0.0.1:{}/json/new?{url}", b.cdp_port)).send().await.unwrap(); + } + let mut got = vec![]; + for _ in 0..40 { + got = titles(&client, b.cdp_port).await; + if got.iter().any(|(_, t)| t == "Example Domain") { + break; + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + eprintln!("tabs: {got:?}"); + assert!(got.iter().any(|(_, t)| t == "Example Domain"), "the public page loads through the proxy"); + assert!(!got.iter().any(|(_, t)| t.contains("secret local"))); + assert_eq!(*hits.lock().unwrap(), 0, "nothing reached this PC"); + + let port = b.cdp_port; + let t0 = std::time::Instant::now(); + b.stop().await; + eprintln!("stopped in {:?}", t0.elapsed()); + assert!(!b.running()); + assert!(client.get(format!("http://127.0.0.1:{port}/json/version")).send().await.is_err(), "CDP is closed"); + let _ = std::fs::remove_dir_all(&profile); +} + +/// The install step downloads the pinned Chrome (about 200 MB) and unpacks a runnable browser. +/// Runs only with `JARVIS_TEST_CHROME_INSTALL=1`. +#[tokio::test] +async fn the_browser_step_installs_a_chrome_that_starts() { + if std::env::var("JARVIS_TEST_CHROME_INSTALL").as_deref() != Ok("1") { + eprintln!("skipped: set JARVIS_TEST_CHROME_INSTALL=1"); + return; + } + let data = std::env::temp_dir().join(format!("jarvis-chrome-install-{}", std::process::id())); + let layout = jarvis_app::install::Layout { data: data.clone(), src: std::path::PathBuf::new() }; + let steps = jarvis_app::install::steps().into_iter().filter(|s| s.id() == "browser").collect(); + let installer = jarvis_app::install::Installer::new(layout.clone(), steps); + assert!(installer.run_all().await, "{}", installer.status()); + 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"); + assert!(b.running()); + b.stop().await; + let _ = std::fs::remove_dir_all(&data); +} diff --git a/app/ui/app.js b/app/ui/app.js index 3e2e769..560433b 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -42,6 +42,7 @@ const CHOICE = { }; const REASON = { busy: "다른 답을 하는 중", queue_full: "대기열이 가득 참", replaced: "더 새 요청이 대신함", interrupted: "끼어들어 멈춤", lower_score: "다른 요청이 더 중요함", stopped: "정지 명령" }; +const BROWSER = { off: "꺼짐", ready: "준비", failed: "실패", exited: "꺼짐(스스로 끝남)" }; const STATE = { stopped: ["꺼짐", ""], starting: ["켜는 중", "warn"], running: ["실행 중", "ok"], stopping: ["끄는 중", "warn"], failed: ["실패", "bad"] }; @@ -426,7 +427,9 @@ function dashboardBody(d) { h("span", { class: "k" }, "음성 워커"), h("span", {}, w ? (w.connected ? "연결됨" : "연결 안 됨") : "–"), h("span", { class: "k" }, "STT / TTS"), h("span", {}, w ? `${w.sttReady ? "준비" : "–"} / ${w.ttsReady ? "준비" : "–"}` : "–"), h("span", { class: "k" }, "워커 재시작"), h("span", {}, w?.restarts ?? "–"), - h("span", { class: "k" }, "대화 모델"), h("span", {}, llm ? (LLM[llm.state] ?? llm.state) : "–"))), + h("span", { class: "k" }, "대화 모델"), h("span", {}, llm ? (LLM[llm.state] ?? llm.state) : "–"), + h("span", { class: "k" }, "봇용 크롬"), h("span", { title: d.browser?.note ?? "" }, + (BROWSER[d.browser?.state] ?? "–") + (d.browser?.note ? ` (${d.browser.note})` : "")))), h("div", { class: "card" }, h("h2", {}, "음성 채널"), h("div", {}, d.voiceChannel ? `채널 ${d.voiceChannel}` : "들어가 있지 않음"), h("div", { class: "small muted", style: "margin-top:6px" }, diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 190b530..1936890 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개) 수집, 내부 주소는 거절, 개발용 서버 화면에서 대상 저장·잘못된 이름 거절·결과 보기, 실제 서비스 시작으로 켠 대상만 워커에 넘어가 수집되고 정지 때 워커도 꺼짐. 남은 것: 봇용 크롬과 가상 모니터, 나머지 기능 스위치(브라우저 제어·PC 제어·화면 보기, 각 기능과 함께) | +| 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 대상 컴파일. 남은 것: 두뇌가 봇용 크롬을 쓰는 브라우저 제어 도구(평가 포함), 가상 모니터와 "봇용 크롬창 화면공유 선택 표시", 나머지 기능 스위치(PC 제어·화면 보기, M7) | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 |