From 511791f39b854a40f2e0efb84321916c67f7c5a7 Mon Sep 17 00:00:00 2001 From: javis-bot Date: Sat, 14 Nov 2026 11:52:49 +0900 Subject: [PATCH] feat(app): update the app from the project's Gitea releases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - update.rs finds the newest app-v release above the running version (v1 tags, drafts, prereleases, incomplete releases and files on another server are skipped), downloads Jarvis-Setup-.exe into cache/updates checked against its .sha256, and hands it over. - update_install hashes the file again, stops what runs, starts the installer with /S /RUN as administrator and the window quits; a declined administrator prompt keeps the app with the services stopped. - New 업데이트 screen; the app checks once when the main screens open. - tauri.conf.json no longer sets its own version, so the program file carries the Cargo.toml version the update compares. Co-Authored-By: Claude Opus 5.5 --- app/shell/src/main.rs | 10 +- app/shell/tauri.conf.json | 1 - app/src/admin.spec.md | 39 +++- app/src/admin_api.rs | 68 +++++- app/src/lib.rs | 1 + app/src/update.rs | 438 ++++++++++++++++++++++++++++++++++++++ app/ui/app.js | 46 ++++ app/ui/index.html | 1 + docs/v2/roadmap.md | 2 +- 9 files changed, 599 insertions(+), 7 deletions(-) create mode 100644 app/src/update.rs diff --git a/app/shell/src/main.rs b/app/shell/src/main.rs index af663f6..1af0197 100644 --- a/app/shell/src/main.rs +++ b/app/shell/src/main.rs @@ -27,8 +27,14 @@ struct Api { } #[tauri::command] -async fn admin(state: tauri::State<'_, Api>, command: String, args: Option) -> Result { - state.api.call(&command, args.unwrap_or(Value::Null)).await +async fn admin(app: tauri::AppHandle, state: tauri::State<'_, Api>, command: String, args: Option) -> Result { + let out = state.api.call(&command, args.unwrap_or(Value::Null)).await?; + // An update's installer was started (what ran is stopped): quit so it can replace the app. + if out["exit"] == Value::Bool(true) { + state.phase.store(CLOSING, Ordering::SeqCst); + app.exit(0); + } + Ok(out) } fn arg(name: &str) -> Option { diff --git a/app/shell/tauri.conf.json b/app/shell/tauri.conf.json index c2478fc..acccc21 100644 --- a/app/shell/tauri.conf.json +++ b/app/shell/tauri.conf.json @@ -1,7 +1,6 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Jarvis", - "version": "0.1.0", "identifier": "kr.jarvis.manager", "build": { "frontendDist": "../ui" diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index a229985..07aa2c3 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -501,6 +501,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | `display_driver_status` / `display_driver_install` / `display_driver_uninstall` | the virtual monitor's driver: `{supported, installed, leftover, other, action}` (Windows only, above) / install or remove it elevated (above), then its status; refused unless the services are stopped or failed, and `service_start` / `service_restart` are refused meanwhile | | `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 | +| `update_status` / `update_check` / `update_download` / `update_install` | updates (below): `{current, phase, latest, error, done, total}` / look for a newer release / download it in the background / stop what runs, start the installer and answer `{exit: true}`, on which the window quits without asking | The invite link asks for: view channels, send messages, read history, add reactions, manage messages, manage channels, connect, speak, voice activity, and the slash command scope; never @@ -534,6 +535,9 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A 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). +- **업데이트**: the version here, the state, "다시 확인", "받기" (with its percentage) and "설치하고 + 다시 시작", and the release's notes as plain text. The app checks once when the main screens open; + a newer release renames the button "업데이트 (새 버전)" and says so once. - **Logs**: tab, level and text filters, pause, live follow (lines after the last seen), "최근 오류 복사" (to the clipboard; over 2,000 characters it suggests the zip), and the zip export by days. @@ -541,6 +545,30 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A the commands on 127.0.0.1; every command needs the random token it prints (`#token=` in the page URL), so other local programs cannot drive it. +## Updates (`app/src/update.rs`) + +The app updates itself from the project's Gitea releases +(`https://git.tkrmagid.kr/api/v1/repos/tkrmagid/javis_bot/releases`; `JARVIS_UPDATE_SOURCE` points a +test at another server). A release of this app is tagged `app-v` and carries the two files +`installer.sh` writes, `Jarvis-Setup-.exe` and its `.sha256`; publishing one is uploading +both to a release with that tag. The repository's other releases (v1's `v1.x`) are skipped. + +- **Check**: the release list (50 newest); drafts, prereleases, other tags, releases without both + files, and files on another server than the list are skipped; the newest version above the + app's own (dotted numbers, "0.2" equals "0.2.0") is offered. HTTPS only (plain HTTP only to + 127.0.0.1 or localhost). A failure keeps its reason for the screen and the `app` log tab. +- **Download**: the `.sha256` first (64 hex digits, for that file name), then the installer into the + data folder's `cache/updates` through the install's resumable, checked download; a mismatch + deletes it and fails. Once it is there, earlier installers in that folder are removed. Checking + again keeps a downloaded release ready. +- **Install**: the file is hashed again, then what runs is stopped as when the window closes (a + failure stops here), then the installer starts with `/S /RUN` as administrator (Windows asks) + without waiting, and the app quits. The installer waits for it to close, replaces it and starts + it again (above, "Installer"). Declining the administrator question keeps the app open with the + services stopped and says so. +- The app's version is the one in `app/Cargo.toml` and `app/shell/Cargo.toml` (kept equal; the + program file's version comes from the latter, `tauri.conf.json` sets none). + ## Window and Windows build (`app/shell/`) - `jarvis.exe` (crate `jarvis-shell`, Tauri 2 on the WebView2 Windows already has) opens one window @@ -618,6 +646,13 @@ a stop right after a background start running no launch at all, and the next sta closing the app (the controller's shutdown after a failed stop: clean-up failing keeps it failed, succeeding stops it; an install in progress cancelled and waited for); command output that is not UTF-8 read on to the end; the window data folder (data folder, or a scratch folder removed later); +updates (the newest release of this app picked past v1's, prerelease, incomplete and other-server +releases; the checksum file read for its own file only; a fake Gitea on 127.0.0.1 found, downloaded, +checked and handed over with earlier installers removed, a ready download kept by a new check, a +file changed after the download refused, a wrong checksum never offered, an unreachable or plain +HTTP server failing with a reason; the install command refused before a download, keeping the app +when the administrator question is declined, and starting the installer after stopping what runs; +one version in both Cargo.toml files and none in tauri.conf.json); the TTS speed reaching the worker's arguments; features and MCP servers (read and refused with the key, the feature tools named as the brain names them, only enabled servers in the brain's settings without values, stored values passed for enabled servers only, values of removed servers @@ -674,7 +709,9 @@ second task) refused while one runs, also after it failed; removing a driver tha there is nothing to remove. The installer (by hand on a Windows VM): installing into a folder that holds other files and uninstalling keeps them; a driver removal that fails stops the uninstall with the files and entry kept, and nothing to remove lets it finish; with no WebView2 and its installer -failing nothing is installed or started; with the lock held the app shows its message and exits +failing nothing is installed or started; an update end to end (0.1.0 installed, a release server +on 127.0.0.1 offering `app-v0.2.0`: the screen finds it at the start, downloads it, and "설치하고 +다시 시작" leaves 0.2.0 installed and running); with the lock held the app shows its message and exits after OK, and starts normally once released; `/S /RUN` (fresh, and over a running app that closes) and the finish page's "Jarvis 실행" start the app's window; a silent install while the uninstaller's window is open, and a silent uninstall while the installer's is, stop with code 5 and change diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index c30f20a..08e9e15 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -25,6 +25,9 @@ pub struct AdminApi { hub: Arc, /// The virtual monitor's driver is being installed or removed: no service start meanwhile. driver_busy: Mutex, + updater: Mutex>>, + /// Starts a downloaded installer (`update::launch_installer`; a fake in tests). + launcher: fn(&Path) -> Result<(), String>, } fn arg<'a>(args: &'a Value, key: &str) -> Result<&'a Value, String> { @@ -53,7 +56,8 @@ impl AdminApi { hub.set_secrets(Secrets::new(&d.secrets_file()).values()); } Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None), - syncer: Mutex::new(None), hub, driver_busy: Mutex::new(false) } + syncer: Mutex::new(None), hub, driver_busy: Mutex::new(false), updater: Mutex::new(None), + launcher: crate::update::launch_installer } } fn dir(&self) -> Result { @@ -129,6 +133,24 @@ impl AdminApi { Ok(()) } + /// Updates for this data folder (installers go to its `cache/updates`). + fn updater(&self) -> Result, String> { + let dir = self.dir()?; + let mut u = self.updater.lock().unwrap(); + Ok(u.get_or_insert_with(|| crate::update::Updater::new(crate::update::source(), APP_VERSION, + dir.path().join("cache").join("updates"))).clone()) + } + + /// Install the downloaded update: stop what runs (as when the window closes), then start the + /// installer, which waits for this app to close. `{"exit": true}`: the shell quits now. + async fn install_update(&self) -> Result { + let path = self.updater()?.ready_installer()?; + self.shutdown().await.map_err(|e| format!("실행 중인 것을 멈추지 못해 업데이트를 설치하지 않았습니다: {e}"))?; + (self.launcher)(&path).map_err(|e| format!("{e}. 서비스는 정지된 상태입니다"))?; + crate::info_log!("app", "update installer started: the app closes"); + Ok(json!({"exit": true})) + } + fn controller(&self) -> Result, String> { let dir = self.dir()?; let mut c = self.controller.lock().unwrap(); @@ -208,6 +230,7 @@ impl AdminApi { *self.dir.lock().unwrap() = Some(dir); *self.controller.lock().unwrap() = None; *self.installer.lock().unwrap() = None; + *self.updater.lock().unwrap() = None; crate::info_log!("admin", "data folder chosen"); Ok(json!({"dataDir": path.to_string_lossy()})) } @@ -351,6 +374,14 @@ impl AdminApi { } "service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})), "dashboard" => Ok(self.controller()?.snapshot().await), + "update_status" => Ok(self.updater()?.status()), + "update_check" => self.updater()?.check().await, + "update_download" => { + let u = self.updater()?; + u.download()?; + Ok(u.status()) + } + "update_install" => self.install_update().await, "logs_query" => { let tab = args.get("tab").and_then(Value::as_str).filter(|t| !t.is_empty() && *t != "all"); let level = level_of(args.get("level").and_then(Value::as_str).unwrap_or("debug")); @@ -387,7 +418,7 @@ mod tests { let base = temp_dir(tag); let loc = base.join("cfg").join("location.json"); (AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), installer: Mutex::new(None), syncer: Mutex::new(None), - hub: LogHub::new(None), driver_busy: Mutex::new(false) }, + hub: LogHub::new(None), driver_busy: Mutex::new(false), updater: Mutex::new(None), launcher: refused_launch }, base) } @@ -524,6 +555,39 @@ mod tests { assert!(a.call("service_stop", json!({})).await.is_err()); } + static LAUNCHED: Mutex> = Mutex::new(None); + fn fake_launch(p: &Path) -> Result<(), String> { + *LAUNCHED.lock().unwrap() = Some(p.to_path_buf()); + Ok(()) + } + fn refused_launch(_: &Path) -> Result<(), String> { + Err("관리자 권한을 받지 못해 업데이트를 설치하지 않았습니다".into()) + } + + #[tokio::test] + async fn an_update_is_installed_only_once_downloaded_and_checked_after_stopping_what_runs() { + let (mut a, base) = api("apiupd"); + a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); + a.call("dashboard", json!({})).await.unwrap(); + assert!(a.call("update_install", json!({})).await.unwrap_err().contains("먼저 받아")); + let installer = b"setup".to_vec(); + let sum = format!("{:x}", ::digest(&installer)); + let src = format!("{}/releases", crate::update::tests::gitea("9.0.0", installer, sum).await); + *a.updater.lock().unwrap() = Some(crate::update::Updater::new(src, APP_VERSION, base.join("d/cache/updates"))); + assert_eq!(a.call("update_check", json!({})).await.unwrap()["latest"]["version"], json!("9.0.0")); + a.call("update_download", json!({})).await.unwrap(); + for _ in 0..200 { + if a.call("update_status", json!({})).await.unwrap()["phase"] != json!("downloading") { break } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + a.launcher = refused_launch; + assert!(a.call("update_install", json!({})).await.unwrap_err().contains("서비스는 정지된 상태")); + a.launcher = fake_launch; + assert_eq!(a.call("update_install", json!({})).await.unwrap(), json!({"exit": true})); + assert_eq!(LAUNCHED.lock().unwrap().clone(), Some(base.join("d/cache/updates/Jarvis-Setup-9.0.0.exe"))); + assert_eq!(a.call("dashboard", json!({})).await.unwrap()["state"], json!("stopped")); + } + #[tokio::test] async fn closing_the_app_while_starting_waits_until_everything_is_stopped() { let (a, base) = api("api5"); diff --git a/app/src/lib.rs b/app/src/lib.rs index a89515a..2f7026d 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -33,6 +33,7 @@ pub mod setup_lock; pub mod speakers; pub mod strata; pub mod system; +pub mod update; pub mod vdisplay; pub mod worker_client; pub mod worker_process; diff --git a/app/src/update.rs b/app/src/update.rs new file mode 100644 index 0000000..ca4b2ca --- /dev/null +++ b/app/src/update.rs @@ -0,0 +1,438 @@ +//! App updates (admin.spec.md, "Updates"): the app looks for a newer release on the project's +//! Gitea, downloads its installer into the data folder checked against the release's SHA-256, and +//! on request stops what runs and starts the installer silently (`/S /RUN`), which waits for the +//! app to close, replaces it and starts it again. +//! +//! A release of this app is tagged `app-v` and carries `Jarvis-Setup-.exe` and +//! `Jarvis-Setup-.exe.sha256` (what `app/shell/installer.sh` writes). Other releases of the +//! repository (v1's `v1.x` tags) are not this app's and are skipped. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Mutex}; + +use serde::Serialize; +use serde_json::{json, Value}; + +/// The project's releases (Gitea API, newest first). +pub const SOURCE: &str = "https://git.tkrmagid.kr/api/v1/repos/tkrmagid/javis_bot/releases"; +pub const TAG_PREFIX: &str = "app-v"; + +/// Where to look: `JARVIS_UPDATE_SOURCE` when set (a test server), else `SOURCE`. +pub fn source() -> String { + std::env::var("JARVIS_UPDATE_SOURCE").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| SOURCE.into()) +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Release { + pub version: String, + pub notes: String, + pub file: String, + pub size: u64, + #[serde(skip)] + pub installer_url: String, + #[serde(skip)] + pub checksum_url: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Phase { + Idle, + Checking, + UpToDate, + Available, + Downloading, + Ready, + Failed, +} + +/// Dotted numbers ("0.2.0"), padded to four parts so "1.0" equals "1.0.0"; anything else is `None`. +fn version(s: &str) -> Option<[u64; 4]> { + let parts: Vec = s.split('.').map(|p| p.parse().ok()).collect::>()?; + if parts.is_empty() || parts.len() > 4 { + return None; + } + let mut v = [0; 4]; + v[..parts.len()].copy_from_slice(&parts); + Some(v) +} + +/// "https://host[:port]" of a URL: downloads come only from where the release list came from. +fn origin(url: &str) -> Option<&str> { + let rest = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://"))?; + Some(&url[..url.len() - rest.len() + rest.find('/').unwrap_or(rest.len())]) +} + +/// HTTPS only; plain HTTP only to this PC (a test server). +fn allowed(url: &str) -> bool { + url.starts_with("https://") || url.starts_with("http://127.0.0.1:") || url.starts_with("http://localhost:") +} + +/// The newest release of this app above `current` in a Gitea release list, if any. Drafts, +/// prereleases, other tags and releases without both assets on `source`'s origin are skipped. +pub fn pick(list: &Value, current: &str, source: &str) -> Result, String> { + let list = list.as_array().ok_or("릴리스 목록을 읽지 못했습니다")?; + let current = version(current).ok_or("현재 버전을 읽지 못했습니다")?; + let home = origin(source); + let mut best: Option<([u64; 4], Release)> = None; + for r in list { + if r["draft"] == json!(true) || r["prerelease"] == json!(true) { + continue; + } + let Some(v) = r["tag_name"].as_str().and_then(|t| t.strip_prefix(TAG_PREFIX)) else { continue }; + let Some(parsed) = version(v) else { continue }; + if parsed <= current || best.as_ref().is_some_and(|(b, _)| parsed <= *b) { + continue; + } + let file = format!("Jarvis-Setup-{v}.exe"); + let asset = |name: &str| r["assets"].as_array()?.iter().find(|a| a["name"].as_str() == Some(name)).cloned(); + let (Some(exe), Some(sum)) = (asset(&file), asset(&format!("{file}.sha256"))) else { continue }; + let url = |a: &Value| a["browser_download_url"].as_str().map(str::to_owned) + .filter(|u| allowed(u) && origin(u).is_some() && origin(u) == home); + let (Some(installer_url), Some(checksum_url)) = (url(&exe), url(&sum)) else { continue }; + best = Some((parsed, Release { version: v.into(), notes: r["body"].as_str().unwrap_or("").into(), file, + size: exe["size"].as_u64().unwrap_or(0), installer_url, checksum_url })); + } + Ok(best.map(|(_, r)| r)) +} + +/// The SHA-256 in a `.sha256` file (" "): 64 hex digits, for `file` when it names one. +pub fn checksum(text: &str, file: &str) -> Result { + let mut words = text.split_whitespace(); + let hex = words.next().unwrap_or("").to_ascii_lowercase(); + let named = words.next().map(|n| n.trim_start_matches('*')); + if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) || named.is_some_and(|n| n != file) { + return Err("릴리스의 SHA-256 파일이 올바르지 않습니다".into()); + } + Ok(hex) +} + +struct State { + phase: Phase, + latest: Option, + error: Option, + done: u64, + total: Option, + sha256: Option, +} + +/// The update state for the screens: checks, the download in the background, and the ready file. +pub struct Updater { + source: String, + current: String, + dir: PathBuf, + state: Mutex, +} + +impl Updater { + /// `dir`: where installers are downloaded (the data folder's `cache/updates`). + pub fn new(source: String, current: &str, dir: PathBuf) -> Arc { + Arc::new(Self { source, current: current.into(), dir, state: Mutex::new(State { + phase: Phase::Idle, latest: None, error: None, done: 0, total: None, sha256: None }) }) + } + + pub fn status(&self) -> Value { + let s = self.state.lock().unwrap(); + json!({"current": self.current, "phase": s.phase, "latest": s.latest, "error": s.error, + "done": s.done, "total": s.total}) + } + + fn client() -> Result { + reqwest::Client::builder().timeout(std::time::Duration::from_secs(30)).build().map_err(|e| e.to_string()) + } + + async fn get_text(url: &str) -> Result { + let r = Self::client()?.get(url).header("accept", "application/json").send().await + .map_err(|e| format!("업데이트 서버에 연결하지 못했습니다: {e}"))?; + if !r.status().is_success() { + return Err(format!("업데이트 서버가 HTTP {}로 답했습니다", r.status())); + } + r.text().await.map_err(|e| format!("업데이트 정보를 받지 못했습니다: {e}")) + } + + fn fail(&self, e: String) -> String { + let mut s = self.state.lock().unwrap(); + (s.phase, s.error) = (Phase::Failed, Some(e.clone())); + crate::warn_log!("app", "update: {e}"); + e + } + + /// Look for a newer release; not while downloading. + pub async fn check(&self) -> Result { + let was = { + let mut s = self.state.lock().unwrap(); + if matches!(s.phase, Phase::Checking | Phase::Downloading) { + return Ok(json!({"current": self.current, "phase": s.phase, "latest": s.latest})); + } + std::mem::replace(&mut s.phase, Phase::Checking) + }; + self.state.lock().unwrap().error = None; + if !allowed(&self.source) { + return Err(self.fail(format!("업데이트 주소는 https여야 합니다: {}", self.source))); + } + let url = format!("{}?limit=50", self.source); + let found = match Self::get_text(&url).await + .and_then(|t| serde_json::from_str::(&t).map_err(|_| "릴리스 목록을 읽지 못했습니다".into())) + .and_then(|v| pick(&v, &self.current, &self.source)) { + Ok(f) => f, + Err(e) => return Err(self.fail(e)), + }; + let mut s = self.state.lock().unwrap(); + // The release already downloaded stays ready. + if was == Phase::Ready && found.is_some() && s.latest == found { + s.phase = Phase::Ready; + } else { + s.phase = if found.is_some() { Phase::Available } else { Phase::UpToDate }; + (s.done, s.total, s.sha256) = (0, None, None); + } + crate::info_log!("app", "update check: {}", found.as_ref().map_or("up to date".into(), |r| format!("{} available", r.version))); + s.latest = found; + Ok(json!({"current": self.current, "phase": s.phase, "latest": s.latest})) + } + + /// Download the release found by `check` in the background (resumed where an earlier try stopped). + pub fn download(self: &Arc) -> Result<(), String> { + let release = { + let mut s = self.state.lock().unwrap(); + let release = match (s.phase, &s.latest) { + (Phase::Available | Phase::Failed, Some(r)) => r.clone(), + (Phase::Downloading | Phase::Ready, Some(_)) => return Ok(()), + _ => return Err("먼저 새 버전을 확인해 주세요".into()), + }; + (s.phase, s.error, s.done, s.total) = (Phase::Downloading, None, 0, Some(release.size)); + release + }; + let me = self.clone(); + tokio::spawn(async move { + let dest = me.dir.join(&release.file); + let got = async { + let sha = checksum(&Self::get_text(&release.checksum_url).await?, &release.file)?; + std::fs::create_dir_all(&me.dir).map_err(|e| format!("업데이트 폴더를 만들지 못했습니다: {e}"))?; + let never = AtomicBool::new(false); + let progress = |done: u64, total: Option| { + let mut s = me.state.lock().unwrap(); + (s.done, s.total) = (done, total.or(s.total)); + }; + crate::download::download(&release.installer_url, &dest, &sha, &progress, &never).await + .map_err(|e| format!("설치 파일을 받지 못했습니다: {e}"))?; + Ok::<_, String>(sha) + }.await; + match got { + Ok(sha) => { + // Earlier installers and broken parts go; this one stays until it is installed. + let keep = [release.file.clone(), format!("{}.part", release.file)]; + for e in std::fs::read_dir(&me.dir).into_iter().flatten().flatten() { + if !keep.iter().any(|k| e.file_name() == k.as_str()) { + let _ = std::fs::remove_file(e.path()); + } + } + let mut s = me.state.lock().unwrap(); + (s.phase, s.sha256) = (Phase::Ready, Some(sha)); + crate::info_log!("app", "update {} downloaded", release.version); + } + Err(e) => { me.fail(e); } + } + }); + Ok(()) + } + + /// The downloaded installer, checked again right before it is started. + pub fn ready_installer(&self) -> Result { + let s = self.state.lock().unwrap(); + let (Phase::Ready, Some(r), Some(sha)) = (s.phase, &s.latest, &s.sha256) else { + return Err("설치할 업데이트를 먼저 받아 주세요".into()); + }; + let path = self.dir.join(&r.file); + if crate::download::sha256_file(&path).ok().as_deref() != Some(sha.as_str()) { + return Err("받은 설치 파일이 바뀌었습니다. 다시 받아 주세요".into()); + } + Ok(path) + } +} + +/// Start the installer silently, as administrator (Windows asks), without waiting: it waits for +/// this app to close, installs, and starts the app again. +#[cfg(windows)] +pub fn launch_installer(path: &Path) -> Result<(), String> { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Foundation::{GetLastError, ERROR_CANCELLED}; + use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SHELLEXECUTEINFOW}; + use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; + let wide = |s: &std::ffi::OsStr| s.encode_wide().chain(Some(0)).collect::>(); + let (verb, file, params) = (wide("runas".as_ref()), wide(path.as_os_str()), wide("/S /RUN".as_ref())); + // 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.lpVerb = verb.as_ptr(); + info.lpFile = file.as_ptr(); + info.lpParameters = params.as_ptr(); + info.nShow = SW_SHOWNORMAL; + // SAFETY: `info` is filled as documented and its strings live through the call; no process + // handle is asked for. + if unsafe { ShellExecuteExW(&mut info) } == 0 { + let e = unsafe { GetLastError() }; + return Err(if e == ERROR_CANCELLED { "관리자 권한을 받지 못해 업데이트를 설치하지 않았습니다".into() } + else { format!("설치 파일을 실행하지 못했습니다 ({e})") }); + } + Ok(()) +} + +#[cfg(not(windows))] +pub fn launch_installer(_path: &Path) -> Result<(), String> { + Err("업데이트 설치는 Windows에서만 됩니다".into()) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::datadir::temp_dir; + use sha2::{Digest, Sha256}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + fn both(v: &str) -> Vec { + vec![format!("Jarvis-Setup-{v}.exe"), format!("Jarvis-Setup-{v}.exe.sha256")] + } + + fn rel(tag: &str, base: &str, files: &[String]) -> Value { + json!({"tag_name": tag, "draft": false, "prerelease": false, "body": format!("notes {tag}"), + "assets": files.iter().map(|f| json!({"name": f, "size": 10, + "browser_download_url": format!("{base}/download/{tag}/{f}")})).collect::>()}) + } + + #[test] + fn the_newest_release_of_this_app_above_the_current_version_is_picked() { + let src = "https://git.example/api/v1/repos/o/r/releases"; + let base = "https://git.example/o/r/releases"; + let mut pre = rel("app-v0.4.0", base, &both("0.4.0")); + pre["prerelease"] = json!(true); + let list = json!([ + rel("v1.10.0", base, &[]), // v1's release + rel("app-v0.3.0", base, &both("0.3.0")[..1]), // no checksum + pre, + rel("app-v0.2.1", "https://elsewhere.example/o/r", &both("0.2.1")), // another server + rel("app-v0.2.0", base, &both("0.2.0")), + rel("app-v0.1.5", base, &both("0.1.5")), + ]); + let r = pick(&list, "0.1.0", src).unwrap().unwrap(); + assert_eq!((r.version.as_str(), r.file.as_str(), r.notes.as_str()), ("0.2.0", "Jarvis-Setup-0.2.0.exe", "notes app-v0.2.0")); + assert_eq!(r.installer_url, format!("{base}/download/app-v0.2.0/Jarvis-Setup-0.2.0.exe")); + assert_eq!(pick(&list, "0.2.0", src).unwrap(), None, "nothing newer"); + assert_eq!(pick(&list, "0.2", src).unwrap(), None, "0.2 is 0.2.0"); + assert_eq!(pick(&json!([]), "0.1.0", src).unwrap(), None); + assert!(pick(&json!({"message": "not found"}), "0.1.0", src).is_err()); + // Plain http only to this PC. + let http = rel("app-v0.2.0", "http://git.example/o/r", &both("0.2.0")); + assert_eq!(pick(&json!([http]), "0.1.0", "http://git.example/api").unwrap(), None); + } + + #[test] + fn a_checksum_file_gives_its_hash_for_the_right_file_only() { + let h = "AB".repeat(32); + assert_eq!(checksum(&format!("{h} Jarvis-Setup-0.2.0.exe\n"), "Jarvis-Setup-0.2.0.exe").unwrap(), h.to_lowercase()); + assert_eq!(checksum(&format!("{h} *Jarvis-Setup-0.2.0.exe"), "Jarvis-Setup-0.2.0.exe").unwrap(), h.to_lowercase()); + assert_eq!(checksum(&h, "x.exe").unwrap(), h.to_lowercase()); + assert!(checksum(&format!("{h} other.exe"), "Jarvis-Setup-0.2.0.exe").is_err()); + assert!(checksum("abc Jarvis-Setup-0.2.0.exe", "Jarvis-Setup-0.2.0.exe").is_err()); + assert!(checksum("", "x").is_err()); + } + + /// A fake Gitea on this PC: the release list and the two assets of `app-v`. + pub(crate) async fn gitea(version: &str, installer: Vec, sum: String) -> String { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", l.local_addr().unwrap()); + let file = format!("Jarvis-Setup-{version}.exe"); + let list = json!([rel("v1.10.0", &base, &[]), rel(&format!("app-v{version}"), &base, &both(version))]).to_string(); + let sum_text = format!("{sum} {file}\n"); + tokio::spawn(async move { + while let Ok((mut s, _)) = l.accept().await { + let mut buf = vec![0u8; 4096]; + let n = s.read(&mut buf).await.unwrap_or(0); + let path = String::from_utf8_lossy(&buf[..n]).split_whitespace().nth(1).unwrap_or("").to_owned(); + let body: Vec = if path.starts_with("/releases") { list.clone().into_bytes() } + else if path.ends_with(".sha256") { sum_text.clone().into_bytes() } + else if path.ends_with(".exe") { installer.clone() } else { vec![] }; + let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()); + let _ = s.write_all(head.as_bytes()).await; + let _ = s.write_all(&body).await; + } + }); + base + } + + async fn settle(u: &Updater) -> Value { + for _ in 0..200 { + let s = u.status(); + if s["phase"] != json!("downloading") { + return s; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + panic!("the download did not end"); + } + + #[tokio::test] + async fn a_newer_release_is_found_downloaded_checked_and_handed_over() { + let installer: Vec = (0..50_000u32).map(|i| (i % 253) as u8).collect(); + let sum = format!("{:x}", Sha256::digest(&installer)); + let base = gitea("0.2.0", installer.clone(), sum).await; + let dir = temp_dir("upd1").join("cache/updates"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Jarvis-Setup-0.1.5.exe"), b"old").unwrap(); + let u = Updater::new(format!("{base}/releases"), "0.1.0", dir.clone()); + assert!(u.ready_installer().is_err(), "nothing to install yet"); + assert!(u.download().is_err(), "check first"); + let c = u.check().await.unwrap(); + assert_eq!((c["phase"].clone(), c["latest"]["version"].clone()), (json!("available"), json!("0.2.0"))); + u.download().unwrap(); + let s = settle(&u).await; + assert_eq!((s["phase"].clone(), s["done"].clone()), (json!("ready"), json!(installer.len()))); + let path = u.ready_installer().unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), installer); + assert!(!dir.join("Jarvis-Setup-0.1.5.exe").exists(), "the earlier installer is gone"); + // Checking again keeps the ready file; a file changed after the download is refused. + assert_eq!(u.check().await.unwrap()["phase"], json!("ready")); + std::fs::write(&path, b"changed").unwrap(); + assert!(u.ready_installer().unwrap_err().contains("바뀌었")); + // The same version as the release: up to date. + let same = Updater::new(format!("{base}/releases"), "0.2.0", temp_dir("upd1b")); + assert_eq!(same.check().await.unwrap()["phase"], json!("upToDate")); + } + + #[tokio::test] + async fn a_download_that_does_not_match_its_checksum_is_not_offered_for_install() { + let base = gitea("0.2.0", b"tampered".to_vec(), "0".repeat(64)).await; + let dir = temp_dir("upd2"); + let u = Updater::new(format!("{base}/releases"), "0.1.0", dir.clone()); + u.check().await.unwrap(); + u.download().unwrap(); + let s = settle(&u).await; + assert_eq!(s["phase"], json!("failed")); + assert!(s["error"].as_str().unwrap().contains("damaged")); + assert!(u.ready_installer().is_err()); + assert!(!dir.join("Jarvis-Setup-0.2.0.exe").exists()); + } + + #[tokio::test] + async fn a_server_that_cannot_be_reached_or_is_not_https_fails_with_a_reason() { + let u = Updater::new("http://127.0.0.1:9/releases".into(), "0.1.0", temp_dir("upd3")); + assert!(u.check().await.unwrap_err().contains("연결하지 못했습니다")); + assert_eq!(u.status()["phase"], json!("failed")); + let plain = Updater::new("http://git.example/releases".into(), "0.1.0", temp_dir("upd4")); + assert!(plain.check().await.unwrap_err().contains("https")); + } + + #[test] + fn the_app_and_its_installer_carry_the_same_version() { + // installer.sh names the setup after the shell's version; the app compares its own; the + // program file's version comes from the shell's Cargo.toml when tauri.conf.json sets none. + let shell = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/shell/Cargo.toml")).unwrap(); + let v = shell.lines().find_map(|l| l.strip_prefix("version = \"")).unwrap().trim_end_matches('"'); + assert_eq!(v, env!("CARGO_PKG_VERSION")); + let conf: Value = serde_json::from_str(&std::fs::read_to_string( + concat!(env!("CARGO_MANIFEST_DIR"), "/shell/tauri.conf.json")).unwrap()).unwrap(); + assert_eq!(conf.get("version"), None, "one version, in the Cargo.toml files"); + } +} diff --git a/app/ui/app.js b/app/ui/app.js index d868a6e..bf6bcf0 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -545,6 +545,50 @@ function logsScreen() { return { view, tick: poll }; } +// ---- update ------------------------------------------------------------------------------------- + +/** The update screen: the version here, the newest release, its download and install. */ +function updateScreen() { + const body = h("div"); + let key = null; + async function tick() { + let u; + try { u = await api("update_status"); } catch (e) { return; } + const k = JSON.stringify([u.phase, u.latest?.version, u.error, u.phase === "downloading" ? u.done : 0]); + if (k === key) return; + key = k; + const act = (cmd, text, primary) => h("button", { class: "btn" + (primary ? " primary" : ""), onclick: async (e) => { + e.target.disabled = true; + try { await api(cmd); } catch (err) { fail(err); } + key = null; tick(); + } }, text); + const pct = u.total ? Math.floor((u.done / u.total) * 100) : null; + const line = { idle: "아직 확인하지 않았습니다", checking: "확인하는 중…", upToDate: "최신 버전입니다", + available: `새 버전 ${u.latest?.version}이 있습니다`, downloading: `받는 중${pct != null ? ` ${pct}%` : ""}`, + ready: `${u.latest?.version}을 설치할 준비가 됐습니다`, failed: u.error ?? "실패했습니다" }[u.phase] ?? u.phase; + body.replaceChildren(h("div", { class: "card" }, + h("div", { class: "kv" }, h("span", { class: "k" }, "현재 버전"), h("span", {}, u.current), + h("span", { class: "k" }, "상태"), h("span", { style: u.phase === "failed" ? "color:var(--bad)" : "" }, line)), + h("div", { class: "row", style: "margin-top:12px" }, + u.phase !== "checking" && u.phase !== "downloading" ? act("update_check", "다시 확인") : null, + (u.phase === "available" || (u.phase === "failed" && u.latest)) ? act("update_download", "받기", true) : null, + u.phase === "ready" ? act("update_install", "설치하고 다시 시작", true) : null), + u.phase === "ready" ? h("p", { class: "small muted" }, "설치하면 봇과 서비스를 멈추고 Jarvis를 닫은 뒤 새 버전을 설치하고 다시 켭니다. Windows가 관리자 권한을 한 번 묻습니다.") : null), + u.latest?.notes ? h("div", { class: "card" }, h("h2", {}, `${u.latest.version} 바뀐 점`), + h("pre", { class: "small", style: "white-space:pre-wrap" }, u.latest.notes)) : null); + } + tick(); + return { view: h("div", {}, h("h1", {}, "업데이트"), body), tick }; +} + +/** Look for a new version once when the app opens; the nav button says so when there is one. */ +async function checkUpdate() { + try { + const u = await api("update_check"); + if (u.latest) { $("#nav-update").textContent = "업데이트 (새 버전)"; toast(`새 버전 ${u.latest.version}이 있습니다. 업데이트 화면에서 설치할 수 있습니다.`); } + } catch (e) { /* offline: the update screen shows why */ } +} + // ---- navigation --------------------------------------------------------------------------------- let current = null, ticker = null; @@ -578,6 +622,7 @@ async function show(name) { try { if (name === "dashboard") { screen.replaceChildren(); await refresh(); ticker = setInterval(refresh, 1000); return; } if (name === "logs") { const l = logsScreen(); screen.replaceChildren(l.view); ticker = setInterval(l.tick, 1000); return; } + if (name === "update") { const u = updateScreen(); screen.replaceChildren(u.view); ticker = setInterval(u.tick, 1000); return; } const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능", collect: "백그라운드 수집", game: "게임 모드" }; const extra = name === "bot" ? await tokenCard() : name === "features" ? await displayDriverCard() : null; @@ -755,6 +800,7 @@ async function start() { $("#main").hidden = false; for (const b of document.querySelectorAll(".nav")) b.onclick = () => show(b.dataset.screen); show("dashboard"); + checkUpdate(); } // The window tells what closing does: stopping what runs first, or that it could not. if (window.__TAURI__?.event) { diff --git a/app/ui/index.html b/app/ui/index.html index 27aec31..d46e9ad 100644 --- a/app/ui/index.html +++ b/app/ui/index.html @@ -21,6 +21,7 @@ +
diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 438a758..d7564e2 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -12,7 +12,7 @@ | M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드). 단계: 1 관리 기능(화면 없음), 2 서비스 제어와 대시보드 자료, 3 Tauri 화면, 4 런타임·모델 자동 설치, 5 Windows 빌드와 확인. 1단계 완료(2026-11-12): `app/src/datadir.rs`(데이터 폴더와 위치 기억 파일, 남은 용량), `settings_edit.rs`(화면 5개의 항목 36개, 기본값과 다른 값만 저장, 모르는 키 보존, 앱 검사를 통과해야만 저장), `secrets.rs`(봇 토큰, Windows는 사용자 계정 DPAPI 암호화), `logs.rs`(서비스별 탭, 날짜별 파일 14일 보관, 최근 오류 복사, 10MB 이하 zip, 비밀값·토큰 모양 가림), 앱 설정에 대화 기억(`memory`) 칸을 넣어 워커에 넘김. 스펙 [admin.spec.md](../../app/src/admin.spec.md). Windows용 코드는 Windows 대상으로 컴파일만 확인(실행 확인은 5단계). 2단계 완료(2026-11-12): `control.rs`(서비스 시작·정지·재시작 규칙, 실패는 비밀값을 가린 오류로 남기고 아무것도 켜 두지 않음, 앱 실행 파일도 같은 제어기를 씀), `dashboard.rs`(디스코드 이벤트만으로 만드는 대시보드 자료: 연결 상태, 음성 채널과 참가자, 실시간 자막 30줄(화면에만, 기록하지 않음, 나가거나 정지하면 지움), 답 20개의 단계별 지연(말 끝→최종 전사, 두뇌, 목소리, 전체)과 중앙값, 놓친 요청 20개(글 없이)), `system.rs`(RAM, `nvidia-smi`로 GPU 사용률·VRAM). 성능 단계(평소/게임 중/일시정지)는 게임 감지와 함께 M7. 3단계 완료(2026-11-12): 화면 `app/ui/`(빌드 도구 없는 HTML/CSS/JS, 어두운 테마, 한국어)와 화면이 부르는 명령 `admin_api.rs`(설정, 대시보드, 시작·정지, 로그 조회·복사·zip, PC 점검, 디스코드 토큰 확인·초대 링크·서버/채널 목록 `discord_setup.rs`). 첫 실행 마법사(데이터 폴더, PC 점검, 모델 안내, 봇 연결, 서버·음성 채널, 호출어, 시작), 대시보드, 설정 5개, 로그. 개발용 서버 `jarvis-admin-dev`로 이 서버의 브라우저에서 실제 테스트 봇과 음성 워커를 켜고 확인: 마법사 각 단계, 시작 뒤 "실행 중 · 테스트봇#9029 · 워커 연결됨", 다시 시작·정지, 설정 저장(바뀐 값만, 모르는 키 보존), 채팅 채널 추가, 로그 실시간 보기와 zip 내보내기. Tauri 창(셸)은 이 서버에서 빌드할 수 없어(webkit2gtk 없음) Windows 빌드 단계에서 붙임. 디스코드 채널 이름·주제 반영은 아직. 4단계 첫 부분 완료(2026-11-12): 설치 `install.rs`·`download.rs`(이어받기, SHA-256 확인), M0 키트와 같은 방식으로 uv 0.11.20 → 워커·두뇌 Python 3.12 환경(v2 전용 패키지 목록 `requirements-brain.txt`) → MeloTTS Python 3.11 환경 → Whisper large-v3-turbo → MeloTTS 한국어 음성 → Strata를 모두 데이터 폴더 안에 설치하고, 끝나면 다운로드 캐시를 비우고 워커 설정을 설치된 Python으로 바꿈. 마법사 "모델" 단계에서 진행·취소·다시 시도. 이 서버(Linux)에서 빈 폴더부터 전부 설치해 보고 그 런타임으로 서비스를 켜 워커 연결, 받아 적기·음성 준비까지 확인했고, 설치 중 데이터 폴더 밖에는 아무것도 쓰지 않음. 대화 모델(약 23GB)은 앱이 Strata를 직접 띄우는 다음 부분에서 받음. 4단계 뒷부분 완료(2026-11-12): 서비스를 켜면 앱이 먼저 데이터 폴더의 Strata를 띄움(`app/src/strata.rs`, M0와 같은 모델과 평소 배치, 처음 켤 때 대화 모델 약 23GB를 받음, 대시보드에 진행률과 Strata의 마지막 줄, 켜는 중에도 정지 가능, 서비스를 끄면 Strata도 끔). 동시 요청은 1개(모든 메시지에 답하는 채팅 채널이 있으면 2개), 그림 읽기는 v2에서 아직 쓰지 않아 끔. 시작할 때마다 두뇌 설정 `config/brain.json`(Strata 주소, Strata가 알려 준 모델 이름, 데이터 폴더 안의 기억 DB)을 써서 워커에 넘김. 이미 떠 있는 서버를 쓰려면 설정 파일의 `llm.url`. 확인: 가짜 Strata로 진행률·준비·정지·다운로드 중 취소·실패를 단위 시험, 게임PC의 Strata 0.1.59가 앱의 실행 옵션을 그대로 받아들임(`--plan`), 앱 서비스를 `llm.url`로 게임PC Strata에 붙여 실제 디스코드 왕복 10개 모두 소리로 답함. 앱이 Strata를 직접 띄워 모델을 받는 실제 확인은 이 서버에서 할 수 없어(메모리) Windows 빌드 단계에서 게임PC로 함. 5단계 완료(2026-11-12): Tauri 2 창 `app/shell`(`jarvis.exe`, 화면의 명령을 같은 `AdminApi`로 넘김, 창을 닫으면 서비스와 Strata를 끄고 끝날 때까지 기다림, 창의 브라우저 자료는 위치 기억 파일 옆)과 Windows 빌드 `app/shell/package.sh`(이 서버에서 `x86_64-pc-windows-gnu`로 빌드, `Jarvis/` 폴더에 실행 파일·WebView2Loader.dll·Python 소스 `python-src`, zip 11MB). 시험용 Windows VM에서: 창과 마법사, PC 점검, uv·워커 환경 설치, 설치 취소 뒤 남은 프로세스 없음, 봇 토큰 DPAPI 암호화 저장, 시작 실패 이유 표시, 로그 화면·오류 복사·zip, 창 닫기로 종료, %APPDATA%·%LOCALAPPDATA%에 아무것도 안 남김, 앱 핵심 단위 테스트(Windows 빌드) 통과. 게임PC(RTX 5070 Ti, C:\JarvisM0 안에서만)에서 같은 관리 명령으로: 전체 설치 7단계 6분 40초, 앱이 직접 띄운 Strata가 엔진과 대화 모델 22.9GB를 약 6분에 받고 준비, 워커(GPU 받아 적기·음성) 연결, 디스코드 음성 채널 입장, 시험 봇이 말한 질문 5개에 모두 소리로 답함(앱이 잰 전체 중앙값 3.36초, 처음 질문 6.4초, 날씨 11.6초), 정지 8초에 GPU 메모리 반환. 같은 시험에서 찾아 고친 것: Windows는 닫힌 로컬 포트의 연결 거부가 약 2초 늦어 정지 확인이 실패로 나오던 것, Strata가 모델 크기(`X of Y GB`)로만 진행을 알려 진행률이 앞 단계의 80%에 멈춰 있던 것, Strata와 NVIDIA 셰이더 캐시가 %APPDATA%에 쓰던 것(데이터 폴더로). 마무리(2026-11-12): 채팅 채널 이름·주제 반영 `app/src/channel_sync.rs`(채널마다 "디스코드에도 반영", 기본 켜짐; 등록하면 디스코드의 이름·주제로 채움, 저장하면 바뀐 채널만 디스코드에 반영하고 디스코드가 바꾼 이름(공백은 `-`)을 화면에 다시 보여 줌, 주제 1,024자 초과는 저장 전에 거절, 10분에 2번 제한에 걸리면 "잠시 뒤 반영" 후 디스코드가 알려 준 시간 뒤 마지막 저장값으로 저절로 다시 시도, 권한이 없으면 이유를 보여 주고 앱에만 저장). 실제 디스코드 시험 채널에서 채움·반영·제한(587초 대기)·자동 재시도까지 확인 후 채널 삭제. 모델 화면에 TTS 말하기 속도(MeloTTS, 0.5~2.0, 기본 1.5; 한국어 모델은 목소리가 KR 하나뿐이라 목소리 선택은 없음). 창을 닫을 때 설치 중이면 취소하고 끝날 때까지 기다림, 정리를 확인하지 못하면 창을 닫지 않고 이유를 보여 줌(한 번 더 닫으면 종료), 실패한 실행이 남긴 Strata도 정리. 창의 WebView 자료는 데이터 폴더(`cache/webview`), 폴더를 고르기 전에는 임시 폴더에 두었다가 다음 시작 때 지움(`%APPDATA%\JarvisBot`에는 위치 파일 하나만). Windows의 UTF-8 옵션이 꺼진 PC의 CP949 출력도 끝까지 읽음. VM에서 다시 확인: 설치 중 창 닫기 뒤 남은 프로세스 없음, `--location` 없이 실행 시 위치 파일 하나만, Windows용 단위 테스트 168개 통과. 게임PC에서 UTF-8 옵션을 끈 상태(코드 페이지 949)로 다시 확인: 전체 설치 7단계, Strata의 대화 모델 22.9GB 다운로드(진행률 10.9%→90%로 표시)와 준비, 워커·디스코드 연결, 시험 봇 질문 5개 모두 소리로 답함(앱이 잰 전체 중앙값 4.0초), 정지 7초에 GPU 메모리 반환, 로그 485줄에 깨진 글자 없음. 남은 것: 설치 파일(NSIS), Strata가 VRAM을 거의 다 써서(15.8/16.3GB) 받아 적기와 GPU를 나누는 문제(M0의 STT 자리 남기기 배치, M7 성능 단계와 함께) | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인. 1단계 완료(2026-11-13): 관리 앱 "기능" 화면(`app/src/features.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Features and MCP servers"). 날씨·웹 검색·식단 기록 켜기/끄기(끄면 그 도구는 두뇌가 제안하지도 실행하지도 않음, 모델이 이름을 대도, 도구 찾기 도구로도 안 나옴), MCP 서버 추가·삭제·켜기/끄기(이름, 명령, 인자, 환경 변수 이름). API 키 같은 환경 변수 값은 암호화 저장소에만 두고 화면에는 저장 여부만, 로그에서는 가림, 서버를 지우면 값도 지움. 앱이 켤 때 값을 워커 환경으로만 넘기고 두뇌는 그 변수를 자기 환경에서 빼서 각 서버에 자기 값만 줌. 서버마다 연결 결과(도구 수, 실패 이유)는 디버그 없이도 LLM 로그 탭에 남음. 같은 작업에서 v2 두뇌가 v1의 PC 파일 도구(홈 폴더 읽기·쓰기·지우기)와 화면 캡처 도구를 쓰던 것을 뺌(음성·채팅 채널의 누구든 요청할 수 있었음, 화면 보기는 M7에서 권한과 함께). 이 서버에서 확인: 개발용 서버의 브라우저로 날씨를 끄고 MCP 서버(시험용 서버)와 키를 저장, 실제 서비스를 켜니 `brain.json`에 끈 도구와 서버만 있고 키는 없음, 워커가 "MCP server fake: 1 tool(s)"를 남기고 MCP 서버 프로세스만 키를 받음, 로그·설정 파일에 키 없음, 정지 때 MCP 서버도 꺼짐. 2단계 완료(2026-11-13): 예약 수집 틀(`app/src/collect.rs`, 워커 `src/voice_worker/collect.py`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Background collection"). 관리 앱 "백그라운드 수집" 화면에서 대상(사이트·검색어·RSS, 주기 15분~7일, 켜기/끄기)과 보관 기간(기본 30일)을 정하고 결과를 봄. 기본 대상은 없음. 기능 화면의 "백그라운드 수집" 스위치를 끄거나 켠 대상이 없으면 수집은 하지 않고 보관 기간이 지난 결과만 지움. 대소문자만 다른 대상 이름은 Windows에서 같은 폴더라 거절. 워커가 음성·두뇌와 따로 돌며, 사이트는 바뀌었을 때만, RSS·검색은 새 항목만 남김. 모든 요청은 공개 주소만 허용하고 검사한 그 주소로만 연결(DNS를 다시 물어 내부망으로 새는 것 막음, 리디렉트마다 다시 검사, 1MB, 전체 15초, 주소는 로그에 남기지 않음)하고, 모은 내용은 데이터 폴더 `collect/`에만 쓰며 두뇌나 로그로 가지 않음(로그에는 대상 이름과 개수만). 덕덕고가 봇 확인 화면을 주면 "결과 없음"이 아니라 실패로 남김. 이 서버에서 확인: 실제 인터넷의 RSS(hnrss 20개), Atom(cpython 10개), 검색어(10개), 사이트(1개) 수집, 내부 주소는 거절, 개발용 서버 화면에서 대상 저장·잘못된 이름 거절·결과 보기, 실제 서비스 시작으로 켠 대상만 워커에 넘어가 수집되고 정지 때 워커도 꺼짐. 3단계 첫 부분 완료(2026-11-13): 봇용 크롬(`app/src/browser.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Bot browser"). 설치 단계 `browser`가 Chrome for Testing 157(약 200MB, SHA-256 고정)을 데이터 폴더 `runtime/chrome`에 받고, 기능 화면의 "브라우저 제어(봇용 크롬)"가 켜져 있으면 서비스가 화면 없이(headless) 띄움(프로필 `browser/profile`, CDP는 빈 루프백 포트, 워커에 `JARVIS_BROWSER_CDP`). 크롬의 모든 연결은 앱의 중계기(루프백 프록시)를 거쳐 이름을 한 번만 풀고 공개 주소에만 연결(이 PC·내부망·CGNAT·IPv4 매핑 IPv6 등은 403, 주소는 로그에 남기지 않음), QUIC 끔, WebRTC도 중계기로만. 켜지지 않으면 대시보드에 이유를 보이고 서비스는 계속 돔. 정지 때 `Browser.close` 후 5초 안에 안 끝나면 강제 종료. 이 서버에서 확인: 실제 크롬이 example.com은 열고 127.0.0.1·localhost의 로컬 서버에는 요청이 하나도 가지 않음, 정지 78ms, 설치 단계로 실제 내려받아 실행, 실제 서비스 시작에서 대시보드 "준비"·워커 환경에 CDP 주소·정지 때 크롬 프로세스 0개, 기능을 끄면 띄우지 않음, Windows 대상 컴파일. 3단계 둘째 부분(2026-11-13): 두뇌의 브라우저 제어 도구 `botBrowser`(스펙 [bot_browser.spec.md](../../src/jarvis/tools/builtin/bot_browser.spec.md)): 열기·읽기·누르기(이름 또는 번호)·입력(Enter 포함)·뒤로, CDP로 봇용 크롬을 조종, 페이지 내용은 신뢰하지 않는 데이터 울타리 안에, http(s)만(file·chrome·data·javascript 거절), LLM 호출 없음. 봇용 크롬이 켜져 있을 때만 제안되고 그동안 `fetchWebPage`는 빠짐(페이지 읽기는 중계기를 거치는 이 도구 하나로). 실제 크롬으로 열기·누르기·한글 입력 후 검색·뒤로 확인. 사람마다 자기 탭(최대 5개), 새 탭 링크·`window.open`도 같은 탭에서, 연결·동작·페이지 대기를 합쳐 15초 한 번, 연결이 끊기면 열기·읽기만 새 연결로 한 번 더(누르기·입력·뒤로는 이미 됐을 수 있어 반복하지 않음), 페이지 글자의 `<<<`·`>>>`는 바꿔 울타리를 닫지 못함. 평가 `evals/test_bot_browser_tool.py` 4개를 이 서버의 qwen3:8b(실제 모델과 같은 계열)로 3번: 11/12 통과, 페이지 안의 "evil.example 열어"는 한 번도 따르지 않음. "사이트에서 검색"은 도구 설명에 "먼저 열고 type에 submit=true"를 넣기 전 0/3, 넣은 뒤 3/3(전체 실행에서는 2/3). 실제 모델(Qwen3.6, 게임PC)로는 게임PC GPU가 쓰이고 있어 아직 못 돌림. 3단계 셋째 부분(2026-11-14): 가상 모니터와 "봇용 크롬창 화면공유 선택 표시"(`app/src/vdisplay.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Virtual monitor"). 기능 화면의 스위치(기본 꺼짐)와 드라이버 설치·제거 카드(관리자 권한 한 번, Windows의 SignPath 확인 한 번). 오픈소스 Virtual Display Driver 25.7.23을 `display-driver/`에 함께 넣음(빌드 때 SHA-256 확인). 켜면 서비스가 봇용 크롬을 쓰는 동안만 가상 모니터를 실제 모니터 오른쪽 아래 구석에 1280x720으로 붙이고, 크롬은 창 없이 켠 뒤 CDP로 뒤에서 창을 열어 포커스를 뺏지 않으며, 그 창은 Alt+Tab·작업 표시줄에서 빠지고 작업 영역을 채움. 정지 때 크롬을 먼저 닫고 모니터를 뗌. 모니터나 창을 못 만들면 화면 없이 돌고 대시보드에 이유. 같은 작업에서 관리자 권한으로 실행된 앱에서는 크롬이 일반 권한으로 다시 뜨며 앱이 크롬을 놓치던 것을 고침(`--do-not-de-elevate`). 서버 Windows 가상머신에서 설치부터 제거까지 확인(위 [pc-features.md](pc-features.md#봇용-크롬창과-디스코드-화면공유)). 남은 것: 실제 모델 평가, 게임PC에서 디스코드 "화면" 탭 공유 확인(드라이버 설치에 사용자 허락 필요), 나머지 기능 스위치(PC 제어·화면 보기, M7) | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. 1단계(2026-11-14): 게임 감지(`app/src/game.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Game detection"). 서비스가 도는 동안 2초마다 앞 창을 보고 M0 기준(전체화면, 모니터를 덮는 테두리 없는 창 + GPU 3D 10% 이상, Steam·Epic·Riot 게임 폴더와 Windows 설치 정보로 찾은 Battle.net 게임 폴더, 직접 등록한 게임, "게임 아님" 목록 우선, 브라우저·영상 플레이어·디스코드·런처 창 제외)으로 판단, 게임이 끝날 때까지 유지. 관리 앱 "게임 모드" 화면(감지 켜기/끄기, 두 목록)과 대시보드 "게임 모드: 켜짐 (이름, 이유)". 서버 Windows 가상머신에서 Steam 게임 폴더의 프로그램을 켜면 1.4초 뒤 켜짐, 끄면 2.0초 뒤 꺼짐. 한글 등이 섞인 경로의 Steam 게임과 Battle.net 게임(시험용 제거 항목)도 같은 시험으로 확인. GPU 사용률 기준(테두리 없는 창)은 GPU가 있는 게임PC에서 확인할 것. 2단계 첫 부분(2026-11-14): 평소 배치(`app/src/placement.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "LLM"). NVIDIA 카드가 있으면 M0 키트의 식대로 `--expert-vram`을 정해 STT 몫(2740MiB)·엔진 여유(768MiB)·다른 프로그램 여유(기본 1GB)를 남김(Strata 자동 배치가 STT 자리를 남기지 않던 M5의 문제). 전문가 없는 모델 VRAM은 맥락·동시 요청 수·카드(UUID)마다 처음 한 번 재서(`config/llm-probe.json`) 다시 씀. 측정이 실패하면 저장하지 않고 전문가 0으로 켜며, 이전 실행에서 남은 서버는 응답 상태와 상관없이 늘 먼저 끄고 포트가 닫힌 것을 확인한 뒤 잼(확인이 안 되면 재지 않고 전문가 0). 게임PC M0 측정값으로 계산하면 M0와 같은 1.5GB. 게임 중 배치 계산(게임 몫 8GB를 못 비우면 최소 전문가 2GB와 남는 게임 몫, 그것도 안 되면 전문가 0GB, 그것도 안 되면 일시정지)도 넣음. 실제 게임PC 확인은 아직. 2단계 둘째 부분(2026-11-14): 성능 단계 전환(`app/src/perf.rs`, `services.rs`, 워커 "LLM switches"). 게임이 감지되면 워커에 전환을 알리고, 하던 답이 끝나면 맥락 16K·동시 1개·CPU 작업자 절반·게임 배치로 LLM을 다시 켬. 그동안 들어온 요청은 기다리고, 처음 음성 요청에 "잠깐만요, 게임 모드로 바꾸는 중이에요"를 한 번 말함. 게임이 끝나고 30초 뒤(설정) 평소 배치로 되돌림. 게임 몫을 비울 수 없거나 "게임 중 일시정지"를 켜면 LLM을 멈추고 답하지 않음. 대시보드에 "성능 단계: 게임 중 · 게임에 X GB". 설정: 게임용 VRAM(8GB), 되돌리기 대기(30초), 게임 중 일시정지(끔). 실제 게임PC 확인은 아직. 같은 단계에서 실패 경로도 다룸: 재시작 실패 시 이전 배치로 되돌리고 60초 뒤 최대 3번 다시 시도, 워커 재연결 시 마지막 LLM 상태 다시 보냄, 전환 번호로 늦은 신호 무시, 다른 프로그램 VRAM은 게임이 없을 때 잰 값만 기준으로 저장(시작 시 뒤에 있는 게임 폴더·등록 게임 프로세스도 확인; 그 밖의 숨은 게임은 못 찾음). 2단계 셋째 부분(2026-11-14): 게임 중 답하는 동안 부분 전사 멈추기(워커 `game` 표시, 최종 전사는 그대로, 답이 끝나면 밀린 부분 전사 이어서; M0 `gamemode_tune` 결정). 실제 게임PC 확인은 아직. 다음: 화면 보기·PC 제어(누가 시킬 수 있는지 사용자 결정 필요). | -| M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인. 1단계(2026-11-14): 설치 파일(`app/shell/installer.nsi`, `installer.sh`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Installer"). NSIS로 약 10MB, Program Files에 관리자 권한 한 번, 한국어 화면, 구성 요소(시작 메뉴·바탕 화면 바로 가기, 가상 모니터 드라이버 기본 꺼짐), WebView2가 없으면 함께 설치, 실행 중이면 닫힐 때까지 기다림, `/S`·`/S /RUN`(업데이트용), 제거 때 이 앱이 설치한 드라이버도 지우고 데이터 폴더는 남김. 서버 Windows 가상머신에서 조용한 설치(4초)·실행·실행 중 업데이트 뒤 다시 실행·제거, 화면으로 드라이버까지 설치하고 제거하면 장치·패키지·레지스트리가 모두 지워짐 확인. 다음: 자동 업데이트(Gitea 릴리스). | +| M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인. 1단계(2026-11-14): 설치 파일(`app/shell/installer.nsi`, `installer.sh`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Installer"). NSIS로 약 10MB, Program Files에 관리자 권한 한 번, 한국어 화면, 구성 요소(시작 메뉴·바탕 화면 바로 가기, 가상 모니터 드라이버 기본 꺼짐), WebView2가 없으면 함께 설치, 실행 중이면 닫힐 때까지 기다림, `/S`·`/S /RUN`(업데이트용), 제거 때 이 앱이 설치한 드라이버도 지우고 데이터 폴더는 남김. 서버 Windows 가상머신에서 조용한 설치(4초)·실행·실행 중 업데이트 뒤 다시 실행·제거, 화면으로 드라이버까지 설치하고 제거하면 장치·패키지·레지스트리가 모두 지워짐 확인. 실패 경로 보강: 고른 폴더의 다른 파일은 남기고, 드라이버 제거 실패 시 제거 중단, WebView2 실패 시 아무것도 설치하지 않음, 설치 잠금(설치 중 앱 실행·설치 프로그램 동시 실행 거절, 끝나면 풀고 다시 실행). 2단계(2026-11-14): 자동 업데이트(`app/src/update.rs`, 스펙 admin.spec.md "Updates"). `app-v<버전>` 태그 릴리스의 설치 파일과 `.sha256`을 찾아 받고 해시를 확인한 뒤, 서비스를 멈추고 `/S /RUN`으로 설치하고 다시 켬. 앱을 열 때 한 번 확인하고 업데이트 화면에서 받기·설치. VM에서 0.1.0 → 0.2.0 끝까지 확인. 남은 것: 실제 릴리스 게시(공개 저장소 사용 여부 결정 대기), 깨끗한 Windows에서 설치부터 첫 대화까지. | M0에서 확인할 항목: