diff --git a/app/Cargo.lock b/app/Cargo.lock index 0f4cc67..d432fbf 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -1493,9 +1493,11 @@ dependencies = [ "futures-util", "opus2", "rand 0.9.5", + "reqwest", "serde", "serde_json", "serenity", + "sha2", "songbird", "symphonia", "tokio", diff --git a/app/Cargo.toml b/app/Cargo.toml index 6214ab5..8ab14ac 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -29,6 +29,8 @@ base64 = "0.22" async-trait = "0.1" opus2 = "0.4" fs4 = "1.1" +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream"] } +sha2 = "0.10" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } zip = { version = "9", default-features = false, features = ["deflate"] } unicode-normalization = "0.1" diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 8f393fe..06856f8 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -26,7 +26,7 @@ never deletes anything. `DataDir::choose(path)` creates it and writes the locati ``` config/ runtime/ models/llm models/stt models/tts models/vad memory/ browser/ collect/ -cache/ logs/ +cache/ logs/ models/hf models/nltk ``` `free_bytes(path)` reports the free space of the disk holding the folder (or its nearest existing @@ -127,7 +127,39 @@ reaches the screen. The dashboard's state is built from the core's events alone (`Dashboard::on_event` with the time), so it is tested with made-up events. -## Admin commands (`app/src/admin_api.rs`) +## Install (`app/src/install.rs`, `app/src/download.rs`) + +The wizard's model step installs the runtime into the data folder with the recipe the M0 kit used +on the game PC (`scripts/m0`). The steps, in order: + +| Step | What | +|---|---| +| `uv` | `uv` 0.11.20, downloaded with resume and checked against the release's SHA-256, into `runtime/uv` | +| `worker_env` | Python 3.12 venv `runtime/venvs/worker` with `src/voice_worker/requirements.txt` and `requirements-brain.txt` (the v2 brain only; the repository's `requirements.txt` is v1's desktop app) | +| `melo_env` | Python 3.11 venv `runtime/venvs/melo`: PyTorch 2.11 cu128 (pinned so later installs keep it), MeloTTS at a pinned commit, `python-mecab-ko` instead of the Japanese MeCab | +| `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 | + +The LLM itself (Qwen3.6-35B-A3B, about 23 GB) is downloaded by Strata on its first start, which the +app runs next (M5, later step). + +- A finished step leaves `runtime/.done/` holding its version (the pin; for `worker_env` a hash + of its requirement files), so later runs skip it and a new pin runs it again. Steps run one at a + time; a failure stops the run and the next run starts at that step; cancel stops the running + command or download (a download's part file stays, so the next try continues it). +- Every command runs with the layout's environment: `uv`'s cache and Pythons, `HF_HOME` + (`models/hf`), `NLTK_DATA` (`models/nltk`), temp files (`cache/tmp`) and Strata's folders, all + inside the data folder. Python comes from `uv` only. Output lines go to the `install` log tab. +- Downloads go to `.part`, continue with an HTTP range after a break (a server without ranges + starts over), and are checked against the pinned SHA-256; a wrong checksum deletes the part. +- When every step is done, `uv`'s download cache is cleaned (the venvs hold copies), and + `voiceWorker` in the settings is pointed at the worker venv's Python with + `--melo-python --history memory/history.sqlite --brain` (other settings kept). +- With the install complete, the services start the worker with the same environment (models, + caches and temp files in the data folder; on Linux also the CUDA wheels' library folders). + + `AdminApi::call(command, args)` is the one entry point of the screens, JSON in and out; errors come back as Korean messages for the screen. The Tauri shell passes the screens' `invoke("admin", @@ -144,6 +176,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | `discord_guilds` / `discord_channels` `{guildId}` | the bot's servers / a server's voice and text channels, for the pickers | | `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run | | `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot | +| `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 | The invite link asks for: view channels, send messages, read history, add reactions, manage @@ -158,7 +191,8 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A - **First-run wizard** (while `firstRun`): data folder (free space, warning under 200 GB), PC check, the model to download (the download itself is step 4 of M5), Discord bot (token check with the Message Content state and the invite link, then save), server and auto-join voice channel - pickers, wake words, then start. Each step reached is saved, so a reload or a restart resumes at + pickers, wake words, then start. The model step shows the install (each step's state, download + bytes and last line; start, cancel, retry) and goes on only once everything is installed. Each step reached is saved, so a reload or a restart resumes at that step; only the last step's start finishes it. A stored token lets the bot step go on without entering it again. - **Dashboard**: the snapshot every second; the header with start, restart and stop is rebuilt diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index 322c69c..543fb94 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -20,6 +20,7 @@ pub struct AdminApi { location_file: PathBuf, dir: Mutex>, controller: Mutex>>, + installer: Mutex>>, hub: Arc, } @@ -44,7 +45,7 @@ impl AdminApi { /// `location_file`: where the data folder is remembered; `hub`: the app's log hub. pub fn new(location_file: &Path, hub: Arc) -> Self { let dir = DataDir::locate(location_file); - Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), hub } + Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None), hub } } fn dir(&self) -> Result { @@ -73,6 +74,18 @@ impl AdminApi { .map_err(|e| format!("설정 진행 상황을 저장하지 못했습니다: {e}")) } + /// The installer for the data folder; the Python sources come from the settings' worker folder. + fn installer(&self) -> Result, String> { + let dir = self.dir()?; + let mut i = self.installer.lock().unwrap(); + if i.is_none() { + let src = crate::settings::load_settings(&dir.settings_file()).map_err(|e| e.0)?.voice_worker.cwd; + let layout = crate::install::Layout { data: dir.path().to_path_buf(), src }; + *i = Some(crate::install::Installer::new(layout, crate::install::steps())); + } + Ok(i.clone().unwrap()) + } + fn controller(&self) -> Result, String> { let dir = self.dir()?; let mut c = self.controller.lock().unwrap(); @@ -127,9 +140,27 @@ impl AdminApi { self.hub.set_dir(&dir.logs()); *self.dir.lock().unwrap() = Some(dir); *self.controller.lock().unwrap() = None; + *self.installer.lock().unwrap() = None; crate::info_log!("admin", "data folder chosen"); Ok(json!({"dataDir": path.to_string_lossy()})) } + "install_status" => Ok(self.installer()?.status()), + "install_start" => { + let inst = self.installer()?; + let settings = self.dir()?.settings_file(); + if !inst.start_then(move |layout| { + if let Err(e) = crate::install::apply_runtime_settings(&settings, layout) { + crate::error_log!("install", "could not point the settings at the runtime: {e}"); + } + }) { + return Err("설치가 이미 진행 중입니다".into()); + } + Ok(json!({"started": true})) + } + "install_cancel" => { + self.installer()?.cancel(); + Ok(json!({"cancelling": true})) + } "pc_check" => { let usage = crate::system::usage().await; let driver = crate::system::driver_version().await; @@ -207,7 +238,7 @@ mod tests { fn api(tag: &str) -> (AdminApi, PathBuf) { 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), hub: LogHub::new(None) }, + (AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), installer: Mutex::new(None), hub: LogHub::new(None) }, base) } diff --git a/app/src/datadir.rs b/app/src/datadir.rs index 8bf9902..d0e55d9 100644 --- a/app/src/datadir.rs +++ b/app/src/datadir.rs @@ -10,7 +10,7 @@ pub const RECOMMENDED_FREE_BYTES: u64 = 200 * 1_000_000_000; /// Folders inside the data folder (desktop-app.md, "데이터 폴더 구조"). pub const LAYOUT: &[&str] = &[ "config", "runtime", "models/llm", "models/stt", "models/tts", "models/vad", "memory", "browser", - "collect", "cache", "logs", + "collect", "cache", "logs", "models/hf", "models/nltk", ]; #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/app/src/download.rs b/app/src/download.rs new file mode 100644 index 0000000..bed4d6b --- /dev/null +++ b/app/src/download.rs @@ -0,0 +1,187 @@ +//! Downloads for the installer (`app/src/admin.spec.md`, "Install"): resumed where they stopped, and +//! checked against a pinned SHA-256 before they are used. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; + +use futures_util::StreamExt; +use sha2::{Digest, Sha256}; +use tokio::io::AsyncWriteExt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DownloadError(pub String); + +impl std::fmt::Display for DownloadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for DownloadError {} + +fn e(what: &str) -> impl FnOnce(std::io::Error) -> DownloadError + '_ { + move |err| DownloadError(format!("{what}: {err}")) +} + +pub fn sha256_file(path: &Path) -> std::io::Result { + let mut f = std::fs::File::open(path)?; + let mut h = Sha256::new(); + std::io::copy(&mut f, &mut h)?; + Ok(format!("{:x}", h.finalize())) +} + +/// Download `url` to `dest`, checked against `sha256` (lowercase hex). The bytes go to +/// `dest.part` first; an interrupted download continues from there (HTTP Range), a server that +/// ignores the range starts it over. A wrong checksum deletes the part file, so the next try starts +/// clean. `progress(done, total)` is called as bytes arrive; `cancel` stops it between chunks (the +/// part file stays for the next try). An existing `dest` with the right checksum is kept as it is. +pub async fn download(url: &str, dest: &Path, sha256: &str, progress: &(dyn Fn(u64, Option) + Sync), + cancel: &AtomicBool) -> Result<(), DownloadError> { + if dest.exists() && sha256_file(dest).map_err(e("could not read the download"))? == sha256 { + return Ok(()); + } + if let Some(dir) = dest.parent() { + tokio::fs::create_dir_all(dir).await.map_err(e("could not create the download folder"))?; + } + let part = PathBuf::from(format!("{}.part", dest.display())); + let have = tokio::fs::metadata(&part).await.map(|m| m.len()).unwrap_or(0); + let client = reqwest::Client::builder().build().map_err(|x| DownloadError(x.to_string()))?; + let mut req = client.get(url); + if have > 0 { + req = req.header(reqwest::header::RANGE, format!("bytes={have}-")); + } + let resp = req.send().await.map_err(|x| DownloadError(format!("could not download {url}: {x}")))?; + let status = resp.status(); + if status.as_u16() == 416 && have > 0 { + // The part file already holds every byte: check it below. + } else if !status.is_success() { + return Err(DownloadError(format!("download of {url} failed: HTTP {status}"))); + } + let resumed = status.as_u16() == 206; + let total = resp.content_length().map(|n| if resumed { n + have } else { n }); + let mut file = tokio::fs::OpenOptions::new().create(true).write(true).append(resumed).truncate(!resumed && status.as_u16() != 416) + .open(&part).await.map_err(e("could not write the download"))?; + let mut done = if resumed || status.as_u16() == 416 { have } else { 0 }; + progress(done, total); + if status.as_u16() != 416 { + let mut stream = resp.bytes_stream(); + while let Some(chunk) = stream.next().await { + if cancel.load(Ordering::Relaxed) { + file.flush().await.ok(); + return Err(DownloadError("cancelled".into())); + } + let chunk = chunk.map_err(|x| DownloadError(format!("download of {url} broke off: {x}")))?; + file.write_all(&chunk).await.map_err(e("could not write the download"))?; + done += chunk.len() as u64; + progress(done, total); + } + } + file.flush().await.map_err(e("could not write the download"))?; + drop(file); + let got = sha256_file(&part).map_err(e("could not read the download"))?; + if got != sha256 { + let _ = tokio::fs::remove_file(&part).await; + return Err(DownloadError(format!("the download of {url} is damaged (checksum {got}, expected {sha256})"))); + } + tokio::fs::rename(&part, dest).await.map_err(e("could not move the download into place"))?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::datadir::temp_dir; + use std::sync::{Arc, Mutex}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + /// A file server that honours `Range: bytes=N-` (unless `ranges` is off) and can stop after + /// `cut` bytes of a response, like a broken connection. Records the ranges asked for. + async fn serve(body: Vec, ranges: bool, cut: Option) -> (String, Arc>>) { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/f.bin", l.local_addr().unwrap()); + let asked = Arc::new(Mutex::new(vec![])); + let a2 = asked.clone(); + let cut = Arc::new(Mutex::new(cut)); + tokio::spawn(async move { + loop { + let Ok((mut s, _)) = l.accept().await else { return }; + let mut buf = vec![0u8; 4096]; + let n = s.read(&mut buf).await.unwrap_or(0); + let head = String::from_utf8_lossy(&buf[..n]).to_string(); + let from = head.lines().find_map(|l| l.strip_prefix("range: bytes=").or(l.strip_prefix("Range: bytes="))) + .and_then(|r| r.trim_end_matches('-').parse::().ok()); + a2.lock().unwrap().push(from.map(|f| f.to_string()).unwrap_or_default()); + let (status, slice) = match from { + Some(f) if ranges && f >= body.len() => ("416 Range Not Satisfiable", &body[0..0]), + Some(f) if ranges => ("206 Partial Content", &body[f..]), + _ => ("200 OK", &body[..]), + }; + let head = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", slice.len()); + let _ = s.write_all(head.as_bytes()).await; + let send = cut.lock().unwrap().take().map_or(slice.len(), |c| c.min(slice.len())); + let _ = s.write_all(&slice[..send]).await; + } + }); + (url, asked) + } + + fn data() -> (Vec, String) { + let b: Vec = (0..200_000u32).map(|i| (i * 31 % 251) as u8).collect(); + let h = format!("{:x}", Sha256::digest(&b)); + (b, h) + } + + #[tokio::test] + async fn a_broken_download_resumes_where_it_stopped() { + let (body, sum) = data(); + let (url, asked) = serve(body.clone(), true, Some(70_000)).await; + let dest = temp_dir("dl1").join("f.bin"); + let never = AtomicBool::new(false); + assert!(download(&url, &dest, &sum, &|_, _| {}, &never).await.is_err(), "the first try breaks off"); + assert!(!dest.exists()); + let seen = Mutex::new(vec![]); + download(&url, &dest, &sum, &|d, t| seen.lock().unwrap().push((d, t)), &never).await.unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), body); + assert_eq!(asked.lock().unwrap().as_slice(), ["", "70000"]); + let seen = seen.lock().unwrap(); + assert_eq!(seen.first(), Some(&(70_000, Some(200_000)))); + assert_eq!(seen.last(), Some(&(200_000, Some(200_000)))); + // Present and right: nothing is fetched again. + download(&url, &dest, &sum, &|_, _| {}, &never).await.unwrap(); + assert_eq!(asked.lock().unwrap().len(), 2); + } + + #[tokio::test] + async fn a_server_without_ranges_starts_over_and_a_bad_checksum_is_thrown_away() { + let (body, sum) = data(); + let (url, _) = serve(body.clone(), false, Some(50_000)).await; + let dest = temp_dir("dl2").join("f.bin"); + let never = AtomicBool::new(false); + let _ = download(&url, &dest, &sum, &|_, _| {}, &never).await; + download(&url, &dest, &sum, &|_, _| {}, &never).await.unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), body); + + let wrong = "0".repeat(64); + let dest2 = temp_dir("dl3").join("f.bin"); + let err = download(&url, &dest2, &wrong, &|_, _| {}, &never).await.unwrap_err(); + assert!(err.0.contains("damaged")); + assert!(!dest2.exists() && !PathBuf::from(format!("{}.part", dest2.display())).exists()); + } + + #[tokio::test] + async fn cancelling_keeps_the_part_for_the_next_try() { + let (body, sum) = data(); + let (url, asked) = serve(body.clone(), true, None).await; + let dest = temp_dir("dl4").join("f.bin"); + let cancel = AtomicBool::new(false); + let err = download(&url, &dest, &sum, &|d, _| if d > 0 { cancel.store(true, Ordering::Relaxed) }, &cancel) + .await.unwrap_err(); + assert_eq!(err.0, "cancelled"); + let part = std::fs::metadata(format!("{}.part", dest.display())).unwrap().len(); + assert!(part > 0 && part < body.len() as u64); + cancel.store(false, Ordering::Relaxed); + download(&url, &dest, &sum, &|_, _| {}, &cancel).await.unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), body); + assert_eq!(asked.lock().unwrap()[1], part.to_string()); + } +} diff --git a/app/src/install.rs b/app/src/install.rs new file mode 100644 index 0000000..8fb8c3b --- /dev/null +++ b/app/src/install.rs @@ -0,0 +1,653 @@ +//! Runtime and model install into the data folder (`app/src/admin.spec.md`, "Install"). +//! +//! The steps run one after another and each leaves a marker (`runtime/.done/` holding its +//! version) once it finished, so a later run skips what is done and redoes a step whose pinned +//! version changed. The same recipe the M0 kit used on the game PC (`scripts/m0`): a pinned `uv` +//! installs Python and the venvs, Strata's own installer puts it in the folder. Every cache, temp +//! file and model goes inside the data folder. + +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; +use serde::Serialize; +use tokio::io::{AsyncBufReadExt, BufReader}; + +/// Pinned `uv` (the version the M0 kit used), per platform: archive URL and SHA-256 from the +/// release's `.sha256` files. +pub const UV_VERSION: &str = "0.11.20"; +#[cfg(windows)] +const UV_ARCHIVE: (&str, &str) = ("uv-x86_64-pc-windows-msvc.zip", + "4c281f1b6b9ccb14d9567ebde9a218a7cabfb35e5ffe8c1d4ef5e2821a655474"); +#[cfg(not(windows))] +const UV_ARCHIVE: (&str, &str) = ("uv-x86_64-unknown-linux-gnu.tar.gz", + "5de211d9278af365497d387e25316907b3b4a9f25b4476dd6dbf238d6f85cff3"); + +pub const STRATA_INSTALL: &str = "https://github.com/Niko1221/Strata/releases/latest/download/install"; +/// MeloTTS and the PyTorch it runs on (scripts/m0/m0lib/envs.py, "melo"). +const CU128_INDEX: &str = "https://download.pytorch.org/whl/cu128"; +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"; + +/// Where everything goes, from the data folder and the app's Python sources (`voice_worker`, `jarvis`). +#[derive(Debug, Clone)] +pub struct Layout { + pub data: PathBuf, + pub src: PathBuf, +} + +impl Layout { + pub fn runtime(&self) -> PathBuf { + self.data.join("runtime") + } + pub fn uv(&self) -> PathBuf { + self.runtime().join("uv").join(if cfg!(windows) { "uv.exe" } else { "uv" }) + } + pub fn venv(&self, name: &str) -> PathBuf { + self.runtime().join("venvs").join(name) + } + pub fn venv_python(&self, name: &str) -> PathBuf { + let v = self.venv(name); + if cfg!(windows) { v.join("Scripts").join("python.exe") } else { v.join("bin").join("python") } + } + pub fn strata_home(&self) -> PathBuf { + self.runtime().join("strata") + } + pub fn strata_exe(&self) -> PathBuf { + self.strata_home().join("terminal").join("current").join("bin") + .join(if cfg!(windows) { "strata.cmd" } else { "strata" }) + } + /// 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") + } + fn done_marker(&self, id: &str) -> PathBuf { + self.runtime().join(".done").join(id) + } + /// The environment every install command and the voice worker run with: caches, temp files and + /// models inside the data folder, Python from uv only. + pub fn env(&self) -> Vec<(String, String)> { + let s = |p: PathBuf| p.to_string_lossy().into_owned(); + let tmp = s(self.data.join("cache").join("tmp")); + let mut env = vec![ + ("UV_CACHE_DIR".into(), s(self.data.join("cache").join("uv"))), + ("UV_PYTHON_INSTALL_DIR".into(), s(self.runtime().join("python"))), + ("UV_PYTHON_PREFERENCE".into(), "only-managed".into()), + ("UV_LINK_MODE".into(), "copy".into()), + ("PYTHONUTF8".into(), "1".into()), + ("PYTHONIOENCODING".into(), "utf-8".into()), + ("HF_HOME".into(), s(self.hf_home())), + ("NLTK_DATA".into(), s(self.data.join("models").join("nltk"))), + ("TMP".into(), tmp.clone()), + ("TEMP".into(), tmp.clone()), + ("TMPDIR".into(), tmp), + ("STRATA_DATA_DIR".into(), s(self.strata_home())), + ("STRATA_NO_PATH".into(), "1".into()), + ("STRATA_HOME".into(), s(self.strata_home().join("home"))), + ("STRATA_COMPONENTS_DIR".into(), s(self.strata_home().join("components"))), + ]; + if cfg!(windows) { + env.push(("LOCALAPPDATA".into(), s(self.strata_home().join("localappdata")))); + } else { + // On Windows the worker adds the pip CUDA wheels' DLL folders itself; on Linux the loader + // needs them in LD_LIBRARY_PATH before the process starts. + let libs = self.cuda_lib_dirs(); + if !libs.is_empty() { + let mut path = libs.iter().map(|p| s(p.clone())).collect::>().join(":"); + if let Ok(old) = std::env::var("LD_LIBRARY_PATH") { + path = format!("{path}:{old}"); + } + env.push(("LD_LIBRARY_PATH".into(), path)); + } + } + env + } + + /// `nvidia/*/lib` folders of the worker venv's CUDA wheels (cuBLAS, cuDNN). + fn cuda_lib_dirs(&self) -> Vec { + let mut out = vec![]; + let Ok(libs) = std::fs::read_dir(self.venv("worker").join("lib")) else { return out }; + for py in libs.flatten() { + let nvidia = py.path().join("site-packages").join("nvidia"); + if let Ok(rd) = std::fs::read_dir(&nvidia) { + out.extend(rd.flatten().map(|e| e.path().join("lib")).filter(|p| p.is_dir())); + } + } + out.sort(); + out + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum StepState { + Pending, + Running, + Done, + Failed, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StepStatus { + pub id: String, + pub label: String, + pub size_hint: String, + pub state: StepState, + /// Bytes done and total of a download, when the step has one. + pub bytes: Option<(u64, Option)>, + /// The step's last output line or its error (no secrets: install output holds none). + pub note: Option, +} + +/// What a step gets: the layout, a way to report, and the cancel flag. +pub struct Ctx { + pub layout: Layout, + status: Arc>>, + index: usize, + pub cancel: Arc, +} + +impl Ctx { + pub fn note(&self, line: &str) { + let line: String = line.chars().take(300).collect(); + self.status.lock().unwrap()[self.index].note = Some(line); + } + pub fn bytes(&self, done: u64, total: Option) { + self.status.lock().unwrap()[self.index].bytes = Some((done, total)); + } + + /// Run a program with the layout's environment; each output line becomes the step's note and an + /// `install` log line. Fails on a non-zero exit, with the last line. + pub async fn run(&self, program: &Path, args: &[&str]) -> Result<(), String> { + let mut cmd = tokio::process::Command::new(program); + cmd.args(args).envs(self.layout.env()).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()) + .kill_on_drop(true); + #[cfg(windows)] + cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + let _ = std::fs::create_dir_all(self.layout.data.join("cache").join("tmp")); + let name = program.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + crate::info_log!("install", "run {name} {}", args.first().copied().unwrap_or("")); + let mut child = cmd.spawn().map_err(|e| format!("{name}을(를) 실행하지 못했습니다: {e}"))?; + let (out, err) = (child.stdout.take().unwrap(), child.stderr.take().unwrap()); + let last = Arc::new(Mutex::new(String::new())); + let pump = |r: Box| { + let (last, status, index) = (last.clone(), self.status.clone(), self.index); + tokio::spawn(async move { + let mut lines = BufReader::new(r).lines(); + while let Ok(Some(l)) = lines.next_line().await { + let l = l.trim().to_owned(); + if l.is_empty() { + continue; + } + if let Some(hub) = crate::logs::installed() { + hub.push(crate::logs::Level::Info, "install", &l); + } + status.lock().unwrap()[index].note = Some(l.chars().take(300).collect()); + *last.lock().unwrap() = l; + } + }) + }; + let (a, b) = (pump(Box::new(out)), pump(Box::new(err))); + let status = loop { + tokio::select! { + s = child.wait() => break s.map_err(|e| e.to_string())?, + _ = tokio::time::sleep(std::time::Duration::from_millis(200)) => { + if self.cancel.load(Ordering::Relaxed) { + let _ = child.kill().await; + return Err("cancelled".into()); + } + } + } + }; + let _ = (a.await, b.await); + if status.success() { + Ok(()) + } else { + Err(format!("{name}이(가) 실패했습니다 ({status}): {}", last.lock().unwrap())) + } + } +} + +#[async_trait] +pub trait Step: Send + Sync { + fn id(&self) -> &'static str; + fn label(&self) -> &'static str; + fn size_hint(&self) -> &'static str; + /// Changing it (a new pin, new requirement files) makes the step run again. + fn version(&self, layout: &Layout) -> String; + async fn run(&self, ctx: &Ctx) -> Result<(), String>; +} + +pub struct Installer { + layout: Layout, + steps: Vec>, + status: Arc>>, + running: AtomicBool, + cancel: Arc, +} + +impl Installer { + pub fn new(layout: Layout, steps: Vec>) -> Arc { + let status = steps.iter().map(|s| StepStatus { id: s.id().into(), label: s.label().into(), + size_hint: s.size_hint().into(), state: StepState::Pending, bytes: None, note: None }).collect(); + let me = Arc::new(Self { layout, steps, status: Arc::new(Mutex::new(status)), running: AtomicBool::new(false), + cancel: Arc::new(AtomicBool::new(false)) }); + me.mark_done(); + me + } + + fn is_done(&self, s: &dyn Step) -> bool { + std::fs::read_to_string(self.layout.done_marker(s.id())).is_ok_and(|v| v == s.version(&self.layout)) + } + + fn mark_done(&self) { + let mut st = self.status.lock().unwrap(); + for (i, s) in self.steps.iter().enumerate() { + if st[i].state != StepState::Running { + st[i].state = if self.is_done(s.as_ref()) { StepState::Done } else if st[i].state == StepState::Failed { + StepState::Failed } else { StepState::Pending }; + } + } + } + + pub fn status(&self) -> serde_json::Value { + self.mark_done(); + let steps = self.status.lock().unwrap().clone(); + let all_done = steps.iter().all(|s| s.state == StepState::Done); + serde_json::json!({"running": self.running.load(Ordering::SeqCst), "done": all_done, "steps": steps}) + } + + pub fn all_done(&self) -> bool { + self.steps.iter().all(|s| self.is_done(s.as_ref())) + } + + /// Run the steps not done yet, in order, in the background, then `finished` once all are done; + /// false if already running. + pub fn start_then(self: &Arc, finished: impl FnOnce(&Layout) + Send + 'static) -> bool { + if self.running.swap(true, Ordering::SeqCst) { + return false; + } + self.cancel.store(false, Ordering::SeqCst); + let me = self.clone(); + tokio::spawn(async move { + if me.run_all().await { + finished(&me.layout); + } + me.running.store(false, Ordering::SeqCst); + }); + true + } + + /// The same, awaited (tests and the command line). + pub async fn run_all(self: &Arc) -> bool { + let mut ran = false; + for (i, step) in self.steps.iter().enumerate() { + if self.is_done(step.as_ref()) { + continue; + } + ran = true; + { + let mut st = self.status.lock().unwrap(); + st[i].state = StepState::Running; + st[i].note = None; + st[i].bytes = None; + } + crate::info_log!("install", "step {} started", step.id()); + let ctx = Ctx { layout: self.layout.clone(), status: self.status.clone(), index: i, cancel: self.cancel.clone() }; + let result = step.run(&ctx).await; + let mut st = self.status.lock().unwrap(); + match result { + Ok(()) => { + let marker = self.layout.done_marker(step.id()); + let _ = crate::datadir::write_atomic(&marker, step.version(&self.layout).as_bytes()); + st[i].state = StepState::Done; + crate::info_log!("install", "step {} done", step.id()); + } + Err(e) => { + st[i].state = StepState::Failed; + st[i].note = Some(if e == "cancelled" { "취소했습니다. 다시 시도하면 이어서 받습니다.".into() } else { e.clone() }); + crate::error_log!("install", "step {} failed: {e}", step.id()); + return false; + } + } + } + // The venvs hold copies (UV_LINK_MODE=copy): the download cache (about 12 GB after the + // MeloTTS venv) is no longer needed once everything is in. + let uv = self.layout.uv(); + if ran && uv.exists() { + let mut cmd = tokio::process::Command::new(&uv); + cmd.args(["cache", "clean"]).envs(self.layout.env()).stdin(Stdio::null()).stdout(Stdio::null()) + .stderr(Stdio::null()); + #[cfg(windows)] + cmd.creation_flags(0x0800_0000); + let ok = cmd.status().await.is_ok_and(|s| s.success()); + crate::info_log!("install", "download cache cleaned: {ok}"); + } + true + } + + pub fn cancel(&self) { + self.cancel.store(true, Ordering::SeqCst); + } +} + +// ---- the real steps ------------------------------------------------------------------------------- + +struct UvStep; +#[async_trait] +impl Step for UvStep { + fn id(&self) -> &'static str { "uv" } + fn label(&self) -> &'static str { "설치 도구(uv)" } + fn size_hint(&self) -> &'static str { "약 25MB" } + fn version(&self, _: &Layout) -> String { UV_VERSION.into() } + async fn run(&self, ctx: &Ctx) -> Result<(), String> { + let (file, sum) = UV_ARCHIVE; + let url = format!("https://github.com/astral-sh/uv/releases/download/{UV_VERSION}/{file}"); + let archive = ctx.layout.data.join("cache").join("downloads").join(file); + crate::download::download(&url, &archive, sum, &|d, t| ctx.bytes(d, t), &ctx.cancel).await.map_err(|e| e.0)?; + let dir = ctx.layout.uv().parent().unwrap().to_path_buf(); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + if file.ends_with(".zip") { + 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(name) = entry.enclosed_name().and_then(|p| p.file_name().map(PathBuf::from)) else { continue }; + if entry.is_file() { + let mut out = std::fs::File::create(dir.join(name)).map_err(|e| e.to_string())?; + std::io::copy(&mut entry, &mut out).map_err(|e| e.to_string())?; + } + } + } else { + ctx.run(Path::new("tar"), &["-xzf", &archive.to_string_lossy(), "-C", &dir.to_string_lossy(), + "--strip-components=1"]).await?; + } + ctx.run(&ctx.layout.uv(), &["--version"]).await + } +} + +/// `uv venv` then `uv pip install` steps for one venv. +async fn venv(ctx: &Ctx, name: &str, python: &str) -> Result { + let uv = ctx.layout.uv(); + ctx.run(&uv, &["venv", "--clear", "--python", python, &ctx.layout.venv(name).to_string_lossy()]).await?; + Ok(ctx.layout.venv_python(name)) +} + +struct WorkerEnvStep; +#[async_trait] +impl Step for WorkerEnvStep { + fn id(&self) -> &'static str { "worker_env" } + fn label(&self) -> &'static str { "음성 워커·두뇌 Python 환경" } + fn size_hint(&self) -> &'static str { "약 1.5GB" } + fn version(&self, layout: &Layout) -> String { + // The requirement files ship with the app: new pins in them install again. + let read = |f: &str| std::fs::read(layout.src.join("voice_worker").join(f)).unwrap_or_default(); + let mut h = ::new(); + sha2::Digest::update(&mut h, read("requirements.txt")); + sha2::Digest::update(&mut h, read("requirements-brain.txt")); + format!("3.12|{:x}", sha2::Digest::finalize(h)) + } + async fn run(&self, ctx: &Ctx) -> Result<(), String> { + let py = venv(ctx, "worker", "3.12").await?; + let reqs = |f: &str| ctx.layout.src.join("voice_worker").join(f).to_string_lossy().into_owned(); + ctx.run(&ctx.layout.uv(), &["pip", "install", "--python", &py.to_string_lossy(), + "-r", &reqs("requirements.txt"), "-r", &reqs("requirements-brain.txt")]).await + } +} + +struct MeloEnvStep; +#[async_trait] +impl Step for MeloEnvStep { + fn id(&self) -> &'static str { "melo_env" } + fn label(&self) -> &'static str { "음성(MeloTTS) Python 환경" } + fn size_hint(&self) -> &'static str { "약 4GB" } + fn version(&self, _: &Layout) -> String { format!("3.11|{}|{MELO_URL}", TORCH.join(",")) } + async fn run(&self, ctx: &Ctx) -> Result<(), String> { + let uv = ctx.layout.uv(); + let py = venv(ctx, "melo", "3.11").await?; + let p = py.to_string_lossy().into_owned(); + ctx.run(&uv, &["pip", "install", "--python", &p, TORCH[0], TORCH[1], "--index-url", CU128_INDEX]).await?; + // Later installs must not swap the CUDA build of torch for another. + let pin = ctx.layout.venv("melo").join("torch-pin.txt"); + std::fs::write(&pin, TORCH_PIN).map_err(|e| e.to_string())?; + let pin = pin.to_string_lossy().into_owned(); + let keep = ["-c", pin.as_str(), "--extra-index-url", CU128_INDEX, "--index-strategy", "unsafe-best-match"]; + let mut args = vec!["pip", "install", "--python", &p, MELO_URL]; + args.extend(keep); + ctx.run(&uv, &args).await?; + // mecab-python3 (Japanese, folder "MeCab") and python-mecab-ko (folder "mecab") are the same + // folder on Windows: remove the Japanese one first (melo_child stubs its tagger). + ctx.run(&uv, &["pip", "uninstall", "--python", &p, "mecab-python3"]).await?; + remove_package_dir(&ctx.layout.venv("melo"), "mecab"); + let mut args = vec!["pip", "install", "--python", &p, "python-mecab-ko==1.3.7", "python-mecab-ko-dic==2.1.1.post2"]; + args.extend(keep); + ctx.run(&uv, &args).await?; + // The full `unidic` ships without its dictionary; removed, the fallback unidic_lite is used. + ctx.run(&uv, &["pip", "uninstall", "--python", &p, "unidic"]).await + } +} + +fn remove_package_dir(venv: &Path, name: &str) { + let mut sites = vec![venv.join("Lib").join("site-packages")]; + if let Ok(rd) = std::fs::read_dir(venv.join("lib")) { + sites.extend(rd.flatten().map(|e| e.path().join("site-packages"))); + } + for site in sites { + if let Ok(rd) = std::fs::read_dir(&site) { + for e in rd.flatten() { + if e.file_name().to_string_lossy().eq_ignore_ascii_case(name) && e.path().is_dir() { + let _ = std::fs::remove_dir_all(e.path()); + } + } + } + } +} + +struct SttModelStep; +#[async_trait] +impl Step for SttModelStep { + fn id(&self) -> &'static str { "stt_model" } + fn label(&self) -> &'static str { "받아 적기 모델(Whisper)" } + fn size_hint(&self) -> &'static str { "약 1.6GB" } + fn version(&self, _: &Layout) -> String { STT_MODEL.into() } + async fn run(&self, ctx: &Ctx) -> Result<(), String> { + let code = format!("from faster_whisper.utils import download_model; print(download_model({STT_MODEL:?}))"); + ctx.run(&ctx.layout.venv_python("worker"), &["-c", &code]).await + } +} + +struct TtsModelStep; +#[async_trait] +impl Step for TtsModelStep { + fn id(&self) -> &'static str { "tts_model" } + fn label(&self) -> &'static str { "한국어 음성 모델(MeloTTS)" } + fn size_hint(&self) -> &'static str { "약 1GB" } + fn version(&self, _: &Layout) -> String { "KR".into() } + async fn run(&self, ctx: &Ctx) -> Result<(), String> { + // The worker's own MeloTTS child loads the Korean voice (downloading it) and says one + // warm-up sentence, then exits with no input: exit 0 means the voice works. + // MeloTTS's English g2p (g2p_en) fetches NLTK data into the user's home folder on first use; + // fetched here into the data folder's NLTK_DATA instead, where it then finds them. + let nltk = ctx.layout.data.join("models").join("nltk"); + std::fs::create_dir_all(&nltk).map_err(|e| e.to_string())?; + // NLTK refuses a data folder other accounts may write (a group-writable umask on Linux). + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&nltk, std::fs::Permissions::from_mode(0o755)); + } + let code = format!("import nltk\nfor p in ('averaged_perceptron_tagger_eng', 'averaged_perceptron_tagger', 'cmudict'):\n \ + assert nltk.download(p, download_dir={:?}, quiet=True), p", nltk.to_string_lossy()); + ctx.run(&ctx.layout.venv_python("melo"), &["-c", &code]).await?; + let child = ctx.layout.src.join("voice_worker").join("melo_child.py"); + ctx.run(&ctx.layout.venv_python("melo"), &[&child.to_string_lossy(), "--device", "cpu", "--language", "KR"]).await + } +} + +struct StrataStep; +#[async_trait] +impl Step for StrataStep { + fn id(&self) -> &'static str { "strata" } + fn label(&self) -> &'static str { "LLM 엔진(Strata)" } + fn size_hint(&self) -> &'static str { "약 1GB" } + fn version(&self, _: &Layout) -> String { "latest".into() } + async fn run(&self, ctx: &Ctx) -> Result<(), String> { + let home = ctx.layout.strata_home(); + std::fs::create_dir_all(&home).map_err(|e| e.to_string())?; + if cfg!(windows) { + let script = format!("Set-Location -LiteralPath '{}'; irm {STRATA_INSTALL}.ps1 | iex", home.display()); + ctx.run(Path::new("powershell"), &["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &script]).await?; + } else { + let script = format!("cd '{}' && curl -fsSL {STRATA_INSTALL}.sh -o install.sh && sh install.sh", home.display()); + ctx.run(Path::new("sh"), &["-c", &script]).await?; + } + if !ctx.layout.strata_exe().exists() { + return Err("Strata 설치가 끝났지만 실행 파일이 없습니다".into()); + } + 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). +pub fn apply_runtime_settings(settings_file: &Path, layout: &Layout) -> Result<(), String> { + let mut raw: serde_json::Map = match std::fs::read_to_string(settings_file) { + Ok(t) => serde_json::from_str(t.trim_start_matches('\u{feff}')).map_err(|e| format!("설정 파일을 읽지 못했습니다: {e}"))?, + Err(_) => serde_json::Map::new(), + }; + let s = |p: PathBuf| p.to_string_lossy().into_owned(); + let worker = raw.entry("voiceWorker").or_insert_with(|| serde_json::json!({})); + let w = worker.as_object_mut().ok_or("voiceWorker가 객체가 아닙니다")?; + w.insert("python".into(), serde_json::json!(s(layout.venv_python("worker")))); + w.insert("cwd".into(), serde_json::json!(s(layout.src.clone()))); + w.insert("args".into(), serde_json::json!(["--melo-python", s(layout.venv_python("melo")), + "--history", s(layout.data.join("memory").join("history.sqlite")), "--brain"])); + let mut text = serde_json::to_string_pretty(&serde_json::Value::Object(raw)).unwrap(); + text.push('\n'); + crate::datadir::write_atomic(settings_file, text.as_bytes()).map_err(|e| e.to_string()) +} + +/// 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)] +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::datadir::temp_dir; + use std::sync::atomic::AtomicU32; + + struct Fake { + id: &'static str, + version: String, + runs: Arc, + fail: bool, + } + #[async_trait] + impl Step for Fake { + fn id(&self) -> &'static str { self.id } + fn label(&self) -> &'static str { "fake" } + fn size_hint(&self) -> &'static str { "" } + fn version(&self, _: &Layout) -> String { self.version.clone() } + async fn run(&self, ctx: &Ctx) -> Result<(), String> { + self.runs.fetch_add(1, Ordering::SeqCst); + ctx.note("working"); + if self.fail { Err("broke".into()) } else { Ok(()) } + } + } + + fn layout(tag: &str) -> Layout { + Layout { data: temp_dir(tag), src: PathBuf::from("src") } + } + + fn fakes(runs: &[Arc], versions: [&str; 3], fail_second: bool) -> Vec> { + let ids = ["a", "b", "c"]; + (0..3).map(|i| Box::new(Fake { id: ids[i], version: versions[i].into(), runs: runs[i].clone(), + fail: fail_second && i == 1 }) as Box).collect() + } + + #[tokio::test] + async fn steps_run_in_order_stop_at_a_failure_and_resume_after_it() { + let l = layout("inst1"); + let runs: Vec> = (0..3).map(|_| Arc::new(AtomicU32::new(0))).collect(); + let i = Installer::new(l.clone(), fakes(&runs, ["1", "1", "1"], true)); + assert!(!i.run_all().await); + let s = i.status(); + let states: Vec<_> = s["steps"].as_array().unwrap().iter().map(|x| x["state"].as_str().unwrap().to_owned()).collect(); + assert_eq!(states, ["done", "failed", "pending"]); + assert_eq!(s["steps"][1]["note"], "broke"); + assert_eq!(runs.iter().map(|r| r.load(Ordering::SeqCst)).collect::>(), [1, 1, 0]); + // A new run (a fresh app start) skips the finished step and carries on. + let i = Installer::new(l, fakes(&runs, ["1", "1", "1"], false)); + assert!(i.run_all().await); + assert_eq!(runs.iter().map(|r| r.load(Ordering::SeqCst)).collect::>(), [1, 2, 1]); + assert!(i.all_done() && i.status()["done"] == true); + } + + #[tokio::test] + async fn a_new_pinned_version_runs_its_step_again() { + let l = layout("inst2"); + let runs: Vec> = (0..3).map(|_| Arc::new(AtomicU32::new(0))).collect(); + assert!(Installer::new(l.clone(), fakes(&runs, ["1", "1", "1"], false)).run_all().await); + let i = Installer::new(l, fakes(&runs, ["1", "2", "1"], false)); + assert!(!i.all_done()); + assert!(i.run_all().await); + assert_eq!(runs.iter().map(|r| r.load(Ordering::SeqCst)).collect::>(), [1, 2, 1]); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_command_reports_its_lines_fails_on_exit_codes_and_stops_on_cancel() { + let l = layout("inst3"); + let i = Installer::new(l.clone(), vec![]); + let status = Arc::new(Mutex::new(vec![StepStatus { id: "x".into(), label: "".into(), size_hint: "".into(), + state: StepState::Running, bytes: None, note: None }])); + let ctx = Ctx { layout: l.clone(), status: status.clone(), index: 0, cancel: i.cancel.clone() }; + ctx.run(Path::new("sh"), &["-c", "echo one; echo two; echo $UV_CACHE_DIR"]).await.unwrap(); + let note = status.lock().unwrap()[0].note.clone().unwrap(); + assert!(note.ends_with("cache/uv") && note.starts_with(&l.data.to_string_lossy().to_string()), "{note}"); + let err = ctx.run(Path::new("sh"), &["-c", "echo nope; exit 3"]).await.unwrap_err(); + assert!(err.contains("nope"), "{err}"); + let cancel = ctx.cancel.clone(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + cancel.store(true, Ordering::SeqCst); + }); + let t = std::time::Instant::now(); + assert_eq!(ctx.run(Path::new("sh"), &["-c", "sleep 30"]).await.unwrap_err(), "cancelled"); + assert!(t.elapsed() < std::time::Duration::from_secs(5)); + } + + #[test] + fn the_settings_point_at_the_installed_runtime_and_keep_the_rest() { + let l = layout("inst5"); + let f = l.data.join("config").join("settings.json"); + std::fs::create_dir_all(f.parent().unwrap()).unwrap(); + std::fs::write(&f, r#"{"call": {"earcon": false}, "voiceWorker": {"python": "old"}}"#).unwrap(); + apply_runtime_settings(&f, &l).unwrap(); + let s = crate::settings::load_settings(&f).unwrap(); + assert_eq!(std::path::Path::new(&s.voice_worker.python), l.venv_python("worker")); + assert_eq!(s.voice_worker.args[0..2], ["--melo-python".to_string(), l.venv_python("melo").to_string_lossy().into_owned()]); + assert!(s.voice_worker.args.contains(&"--brain".to_string())); + assert!(!s.call.earcon, "other settings are kept"); + } + + #[test] + fn everything_goes_inside_the_data_folder() { + let l = layout("inst4"); + for (k, v) in l.env() { + if v.contains('/') || v.contains('\\') { + assert!(v.starts_with(&l.data.to_string_lossy().to_string()), "{k}={v}"); + } + } + assert!(l.uv().starts_with(&l.data) && l.venv_python("worker").starts_with(&l.data)); + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index f122976..bc3fbe2 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -10,8 +10,10 @@ pub mod dashboard; pub mod datadir; pub mod discord; pub mod discord_setup; +pub mod download; pub mod earcon; pub mod frames; +pub mod install; pub mod logs; pub mod playback; pub mod policy; diff --git a/app/src/logs.rs b/app/src/logs.rs index f4e6ac7..5d98b6e 100644 --- a/app/src/logs.rs +++ b/app/src/logs.rs @@ -52,6 +52,7 @@ pub fn tab_of(category: &str) -> &'static str { "browser" => "browser", "capture" => "capture", "game" => "game", + "install" => "install", _ => "app", } } diff --git a/app/src/services.rs b/app/src/services.rs index 6479616..bd2c51b 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -40,7 +40,13 @@ pub async fn start_services(data_dir: &Path) -> Result go(2))]; }, - async () => [h("h2", {}, "받을 모델"), - h("p", {}, "대화 모델 Qwen3.6-35B-A3B(약 23GB)와 받아 적기(Whisper)·음성(MeloTTS) 모델을 받습니다. 고를 것은 없고, 설치가 끝나면 이 PC에 맞는 설정을 스스로 정합니다."), - h("p", { class: "muted small" }, "자동 설치는 다음 업데이트에서 이 단계에 들어옵니다."), nav(true, () => go(3))], + async () => { + // The install runs in the app; this step shows it and polls while it is on screen. + const list = h("table"); + const btn = h("button", { class: "btn" }); + const next = nav(true, () => go(3)); + const nextBtn = next.lastChild; + const SIZE = (b) => (b >= 1e9 ? (b / 1e9).toFixed(1) + " GB" : (b / 1e6).toFixed(0) + " MB"); + const STEP = { pending: ["대기", ""], running: ["설치 중", "warn"], done: ["완료", "ok"], failed: ["실패", "bad"] }; + const my = wgen; + async function poll() { + if (my !== wgen) return; + let st; + try { st = await api("install_status"); } catch (e) { return fail(e); } + if (my !== wgen) return; + list.replaceChildren(h("tbody", {}, st.steps.map((x) => { + const [label, cls] = STEP[x.state] ?? [x.state, ""]; + const bytes = x.bytes && x.state === "running" ? ` ${SIZE(x.bytes[0])}${x.bytes[1] ? " / " + SIZE(x.bytes[1]) : ""}` : ""; + return h("tr", {}, h("td", {}, x.label, h("div", { class: "small muted" }, x.sizeHint)), + h("td", {}, h("span", { class: "badge " + cls }, label + bytes)), + h("td", { class: "small muted", style: "max-width:320px;word-break:break-all" }, x.state === "done" ? "" : (x.note ?? ""))); + }))); + btn.textContent = st.running ? "취소" : st.done ? "설치됨" : st.steps.some((x) => x.state === "failed") ? "다시 시도" : "설치 시작"; + btn.disabled = st.done && !st.running; + btn.onclick = async () => { + try { await api(st.running ? "install_cancel" : "install_start"); } catch (e) { fail(e); } + poll(); + }; + nextBtn.disabled = !st.done; + if (st.running) setTimeout(poll, 1000); + } + poll(); + return [h("h2", {}, "런타임과 모델 설치"), + h("p", {}, "음성 워커와 두뇌를 돌릴 Python 환경, 받아 적기(Whisper)·음성(MeloTTS) 모델, LLM 엔진(Strata)을 데이터 폴더 안에 받습니다. 끊겨도 다음에 이어서 받습니다. 대화 모델 Qwen3.6-35B-A3B(약 23GB)는 Strata를 처음 켤 때 받습니다."), + list, h("div", { class: "row", style: "margin-top:12px" }, btn), next]; + }, async () => { const input = h("input", { type: "password", placeholder: "디스코드 봇 토큰", autocomplete: "off" }); const out = h("div"); diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index f364697..ba5b65a 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -9,7 +9,7 @@ | M2 | 디스코드 음성 코어 이전 | v1 봇 기능을 새 앱 안으로 이전. 입장/퇴장, 화자별 수신, 재생, 정지 명령 동작. 채팅 채널 연결(읽기·보내기). 구현과 테스트 완료(2026-11-11): `app/`(Rust, serenity + songbird), 스펙은 [discord_core.spec.md](../../app/src/discord_core.spec.md). 처음 Electron + TypeScript로 만든 것을 사용자 요청으로 Rust로 다시 씀. 앱이 음성 워커를 띄우고(실행마다 새 토큰, 죽으면 다시 시작) 연결이 끊기면 다시 붙습니다. 음성 채널에 들어갈 때마다 전사 고지를 채널 채팅에 올립니다. songbird 0.6.1의 DAVE 수신 해독이 조각 3분의 1가량을 깨뜨려서(20ms마다 음이 바뀌는 시험 신호로 확인, 보내기는 정상) 받은 패킷의 순서 맞추기와 Opus 해독은 앱이 직접 합니다. 실제 디스코드에서 봇 두 개로 확인(이 서버의 RTX 5050): 다른 봇이 채널에 튼 녹음 문장 5개를 모두 받아 적었고(문자 오류율 3개 0%, "기록해"를 "비록해"로 적은 1개 5%, "일곱 시"를 "7시"로 적은 1개 12.5%), 말이 끝난 뒤 최종 전사까지 0.71~0.90초였습니다. 자비스가 말한 문장을 상대 봇이 받아 다시 전사하니 오류율 3.4%였고, 정지 명령 뒤 0.08초 만에 소리가 끊겼습니다. 채팅 채널은 새 글 받기, 최근 글 읽기, 보내기(2,000자 넘으면 나눔, 아무도 호출하지 않음)가 됩니다. 사람이 직접 말한 소리와 게임PC(Windows) 빌드는 아직 확인하지 않았고, 음성으로 "자비스, 멈춰"는 호출 판정이 필요해 M4에서 합니다 | | 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 빌드 단계에서 붙임. 디스코드 채널 이름·주제 반영과 모델 자동 설치는 아직 | +| 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를 직접 띄우는 다음 부분에서 받음 | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 | diff --git a/src/voice_worker/requirements-brain.txt b/src/voice_worker/requirements-brain.txt new file mode 100644 index 0000000..86be4bb --- /dev/null +++ b/src/voice_worker/requirements-brain.txt @@ -0,0 +1,9 @@ +# The v2 brain (--brain): the jarvis reply engine, its tools and the MCP client, on top of +# requirements.txt in this folder. Checked in a fresh Python 3.12 venv (2026-11-12): the worker, +# brain, engine and tool tests pass with exactly these two files. The repository's requirements.txt +# is v1's desktop app (PyQt, chatterbox, ...) and is not needed here. +requests==2.32.3 +beautifulsoup4==4.12.3 +html2text==2024.2.26 +mcp==1.28.0 +rapidfuzz==3.6.1