From 0973ad981557435690633ce459d3442d6bca0bfd Mon Sep 17 00:00:00 2001 From: javis-bot Date: Thu, 12 Nov 2026 13:49:51 +0900 Subject: [PATCH] feat(app): M5 step 2, service control and the dashboard data - control: one Controller starts, stops and restarts the services (stopped, starting, running, stopping, failed); a failed start leaves nothing running and keeps its error with secrets masked. The app binary uses it. - dashboard: built from the core's events alone: the bot's tag, the voice channel, live captions (screen only, cleared on leaving or stopping), the last 20 voice answers split into stages with medians (matched by the new AnswerAsked event), and missed requests without text. - system: memory in use and per NVIDIA GPU its use and VRAM (nvidia-smi). - DiscordCore::voice_members, WorkerClient::hello, the conversation's missed requests shared with the dashboard. Co-Authored-By: Claude Opus 5.5 --- app/src/admin.spec.md | 37 +++- app/src/control.rs | 321 +++++++++++++++++++++++++++++++++++ app/src/conversation.rs | 27 ++- app/src/dashboard.rs | 277 ++++++++++++++++++++++++++++++ app/src/discord.rs | 19 +++ app/src/discord_core.spec.md | 5 +- app/src/lib.rs | 3 + app/src/main.rs | 33 ++-- app/src/policy.rs | 3 +- app/src/services.rs | 5 +- app/src/system.rs | 98 +++++++++++ app/src/worker_client.rs | 5 + docs/v2/roadmap.md | 2 +- 13 files changed, 799 insertions(+), 36 deletions(-) create mode 100644 app/src/control.rs create mode 100644 app/src/dashboard.rs create mode 100644 app/src/system.rs diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 19d5972..e62d9d5 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -88,6 +88,39 @@ STT, LLM and TTS lines go to `stt`, `llm`, `tts` by their worker category), `bro - Errors the voice worker reports to the app (`error` messages: code and request id) are always logged, debug logging or not, so the log screen and the error report show them. +## Service control (`app/src/control.rs`) + +The dashboard's start and stop buttons, and the app binary itself, run the services through one +`Controller` for the data folder: states `stopped`, `starting`, `running`, `stopping`, `failed` +(with the error, secrets masked). `start` from stopped or failed only, `stop` from running only; +`restart` is stop then start. A start that fails leaves nothing running. Starting reads the +settings and the stored token again, so saved changes take effect on the next start. + +## Dashboard data (`app/src/dashboard.rs`) + +`Controller::snapshot()` is everything the dashboard shows, as one JSON-ready value: + +- `state` and `error` (above); `discord`: the bot's tag once connected; `worker`: connected, STT + and TTS ready (from the worker's `hello_ok`), restarts of its process. +- `voice`: the voice channel Jarvis is in and the people there (ID and display name), as the core + reports them to the worker. +- `captions`: live captions, the last 30 lines: a speaker's partial transcript is replaced by + their next partial and then by the final. On the screen only: never logged, never written, + cleared when Jarvis leaves the voice channel or the services stop. +- `latency`: the last 20 voice answers, each split into its stages: speech end to final transcript, + the brain (answer asked to answer text), the voice (answer text to the first sound) and the + total; with the median of each. An answer is matched to its question by the core's + `AnswerAsked { id, user }` event (the speech id and the asker) and that user's latest final. +- `missed`: the conversation's missed requests (`conversation.spec.md`), newest first, at most 20: + who, why and how long ago, never the text. +- `system`: memory in use and total, and per NVIDIA GPU its use and VRAM (from `nvidia-smi`, + missing when there is none); sampled when the snapshot is taken, at most once a second. +- `performance`: the performance stage (normal, gaming, paused, and why) comes with game + detection in M7; until then `null`. + +The dashboard's state is built from the core's events alone (`Dashboard::on_event` with the time), +so it is tested with made-up events. + ## Tests `cargo test`: data folder layout, location file and the environment override, a refused relative @@ -95,5 +128,7 @@ path, free space; settings view with defaults, apply writing only non-defaults, back to its default, keeping unknown keys, refusing a bad value or a result `parse_settings` refuses without touching the file; secrets round trip, file permissions on Unix, masking; log tabs from categories, query filters and follow, files per day and retention, error report bounds, zip size -cap, redaction of stored secrets and token-shaped text. Windows-only paths (DPAPI, `%APPDATA%`) are +cap, redaction of stored secrets and token-shaped text; the controller's state rules with a fake +service starter; the dashboard from made-up events (captions replaced and cleared, latency stages +and medians, an answer matched to its asker's final, missed requests without text). Windows-only paths (DPAPI, `%APPDATA%`) are checked on the Windows VM in the Windows build step. diff --git a/app/src/control.rs b/app/src/control.rs new file mode 100644 index 0000000..9358079 --- /dev/null +++ b/app/src/control.rs @@ -0,0 +1,321 @@ +//! Starting and stopping the services, and the dashboard snapshot (`app/src/admin.spec.md`, +//! "Service control" and "Dashboard data"). + +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use async_trait::async_trait; +use serde_json::{json, Value}; +use tokio::sync::mpsc; + +use crate::dashboard::Dashboard; +use crate::discord::CoreEvent; +use crate::system::Usage; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] +pub enum State { + Stopped, + Starting, + Running, + Stopping, + Failed, +} + +/// The running services as the controller sees them. +#[async_trait] +pub trait Running: Send + Sync + 'static { + async fn stop(&self); + /// Worker, voice channel members and missed requests, for the snapshot. + fn status(&self, now: Instant) -> Value; +} + +/// What starts the services (the real ones, or a fake in tests). +#[async_trait] +pub trait Host: Send + Sync + 'static { + async fn start(&self) -> Result<(Arc, mpsc::UnboundedReceiver), String>; + /// Stored secrets, masked in error messages. + fn secrets(&self) -> Vec; +} + +struct Inner { + state: State, + error: Option, + running: Option>, +} + +pub struct Controller { + host: Box, + inner: Mutex, + dashboard: Arc>, + usage: tokio::sync::Mutex>, +} + +impl Controller { + pub fn new(host: impl Host) -> Arc { + Arc::new(Self { host: Box::new(host), inner: Mutex::new(Inner { state: State::Stopped, error: None, running: None }), + dashboard: Arc::default(), usage: tokio::sync::Mutex::new(None) }) + } + + pub fn state(&self) -> State { + self.inner.lock().unwrap().state + } + + /// Start from stopped or failed; a failed start leaves nothing running. + pub async fn start(&self) -> Result<(), String> { + { + let mut i = self.inner.lock().unwrap(); + if !matches!(i.state, State::Stopped | State::Failed) { + return Err(format!("cannot start while {:?}", i.state).to_lowercase()); + } + i.state = State::Starting; + i.error = None; + } + crate::info_log!("app", "starting the services"); + match self.host.start().await { + Ok((running, mut events)) => { + let dash = self.dashboard.clone(); + tokio::spawn(async move { + while let Some(ev) = events.recv().await { + dash.lock().unwrap().on_event(&ev, Instant::now()); + } + }); + let mut i = self.inner.lock().unwrap(); + i.state = State::Running; + i.running = Some(running); + Ok(()) + } + Err(e) => { + let e = crate::logs::redact(&e, &self.host.secrets()); + crate::error_log!("app", "the services did not start: {e}"); + let mut i = self.inner.lock().unwrap(); + i.state = State::Failed; + i.error = Some(e.clone()); + Err(e) + } + } + } + + /// Stop from running; what was said is forgotten. + pub async fn stop(&self) -> Result<(), String> { + let running = { + let mut i = self.inner.lock().unwrap(); + if i.state != State::Running { + return Err(format!("cannot stop while {:?}", i.state).to_lowercase()); + } + i.state = State::Stopping; + i.running.take() + }; + if let Some(r) = running { + r.stop().await; + } + self.dashboard.lock().unwrap().clear(); + self.inner.lock().unwrap().state = State::Stopped; + crate::info_log!("app", "services stopped"); + Ok(()) + } + + pub async fn restart(&self) -> Result<(), String> { + if self.state() == State::Running { + self.stop().await?; + } + self.start().await + } + + /// Everything the dashboard shows. + pub async fn snapshot(&self) -> Value { + let now = Instant::now(); + let (state, error, running) = { + let i = self.inner.lock().unwrap(); + (i.state, i.error.clone(), i.running.clone()) + }; + let status = running.map(|r| r.status(now)).unwrap_or_else(|| json!({"worker": null, "voiceMembers": [], + "missed": []})); + let mut view = self.dashboard.lock().unwrap().view(&[], now); + view["missed"] = status["missed"].clone(); + view["worker"] = status["worker"].clone(); + view["voiceMembers"] = status["voiceMembers"].clone(); + view["state"] = json!(state); + view["error"] = json!(error); + view["system"] = json!(self.system().await); + view["performance"] = Value::Null; // game detection comes in M7 + view + } + + /// Memory and GPU use, sampled at most once a second. + async fn system(&self) -> Usage { + let mut cache = self.usage.lock().await; + if let Some((at, u)) = cache.as_ref() { + if at.elapsed() < Duration::from_secs(1) { + return u.clone(); + } + } + let u = crate::system::usage().await; + *cache = Some((Instant::now(), u.clone())); + u + } +} + +/// The real services from a data folder. +pub struct ServicesHost { + pub data_dir: PathBuf, +} + +#[async_trait] +impl Host for ServicesHost { + async fn start(&self) -> Result<(Arc, mpsc::UnboundedReceiver), String> { + let mut s = crate::services::start_services(&self.data_dir).await.map_err(|e| e.to_string())?; + let (tx, rx) = mpsc::unbounded_channel(); + let mut events = std::mem::replace(&mut s.events, mpsc::unbounded_channel().1); + tokio::spawn(async move { + while let Some(e) = events.recv().await { + if tx.send(e).is_err() { + break; + } + } + }); + Ok((Arc::new(s), rx)) + } + + fn secrets(&self) -> Vec { + crate::secrets::Secrets::new(&self.data_dir.join("config").join("secrets.dat")).values() + } +} + +#[async_trait] +impl Running for crate::services::Services { + async fn stop(&self) { + crate::services::Services::stop(self).await; + } + + fn status(&self, now: Instant) -> Value { + let hello = self.worker.hello(); + let missed: Vec<_> = self.missed.lock().unwrap().iter().cloned().collect(); + json!({ + "worker": {"connected": hello.is_some(), "sttReady": hello.as_ref().map(|h| h.stt_ready), + "ttsReady": hello.as_ref().map(|h| h.tts_ready), "restarts": self.worker_process.restarts()}, + "voiceMembers": self.core.voice_members().into_iter() + .map(|(id, name)| json!({"id": id.to_string(), "name": name})).collect::>(), + "missed": crate::dashboard::missed_view(&missed, now), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU32, Ordering}; + + #[derive(Default)] + struct Counts { + starts: AtomicU32, + stops: AtomicU32, + } + + struct FakeRunning(Arc); + #[async_trait] + impl Running for FakeRunning { + async fn stop(&self) { + self.0.stops.fetch_add(1, Ordering::SeqCst); + } + fn status(&self, _: Instant) -> Value { + json!({"worker": {"connected": true}, "voiceMembers": [{"id": "11", "name": "민수"}], "missed": []}) + } + } + + struct FakeHost { + counts: Arc, + fail_first: AtomicU32, + events: Mutex>>, + } + #[async_trait] + impl Host for FakeHost { + async fn start(&self) -> Result<(Arc, mpsc::UnboundedReceiver), String> { + self.counts.starts.fetch_add(1, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(20)).await; + if self.fail_first.load(Ordering::SeqCst) > 0 { + self.fail_first.fetch_sub(1, Ordering::SeqCst); + return Err("login failed for token Mt0kenSecretValue".into()); + } + let (tx, rx) = mpsc::unbounded_channel(); + *self.events.lock().unwrap() = Some(tx); + Ok((Arc::new(FakeRunning(self.counts.clone())), rx)) + } + fn secrets(&self) -> Vec { + vec!["Mt0kenSecretValue".into()] + } + } + + fn controller(fail_first: u32) -> (Arc, Arc, Arc) { + let counts = Arc::new(Counts::default()); + let host = Arc::new(FakeHost { counts: counts.clone(), fail_first: AtomicU32::new(fail_first), + events: Mutex::new(None) }); + struct Shared(Arc); + #[async_trait] + impl Host for Shared { + async fn start(&self) -> Result<(Arc, mpsc::UnboundedReceiver), String> { + self.0.start().await + } + fn secrets(&self) -> Vec { + self.0.secrets() + } + } + (Controller::new(Shared(host.clone())), counts, host) + } + + #[tokio::test] + async fn start_and_stop_follow_the_state_rules() { + let (c, counts, _) = controller(0); + assert!(c.stop().await.is_err(), "nothing to stop"); + let c2 = c.clone(); + let first = tokio::spawn(async move { c2.start().await }); + tokio::time::sleep(Duration::from_millis(5)).await; + assert_eq!(c.state(), State::Starting); + assert!(c.start().await.unwrap_err().contains("starting"), "one start at a time"); + first.await.unwrap().unwrap(); + assert_eq!(c.state(), State::Running); + assert!(c.start().await.is_err()); + c.restart().await.unwrap(); + assert_eq!((counts.starts.load(Ordering::SeqCst), counts.stops.load(Ordering::SeqCst)), (2, 1)); + c.stop().await.unwrap(); + assert_eq!(c.state(), State::Stopped); + } + + #[tokio::test] + async fn a_failed_start_is_reported_masked_and_can_be_retried() { + let (c, counts, _) = controller(1); + let e = c.start().await.unwrap_err(); + assert_eq!(e, "login failed for token [비밀값]"); + let snap = c.snapshot().await; + assert_eq!((snap["state"].clone(), snap["error"].clone()), (json!("failed"), json!(e))); + c.start().await.unwrap(); + assert_eq!(c.state(), State::Running); + assert_eq!(counts.stops.load(Ordering::SeqCst), 0, "a failed start leaves nothing to stop"); + } + + #[tokio::test] + async fn the_snapshot_carries_the_events_and_stopping_forgets_what_was_said() { + let (c, _, host) = controller(0); + c.start().await.unwrap(); + let tx = host.events.lock().unwrap().clone().unwrap(); + tx.send(CoreEvent::Ready { user_id: 1, tag: "Jarvis#0001".into() }).unwrap(); + tx.send(CoreEvent::Joined { guild_id: 1, channel_id: 77 }).unwrap(); + tx.send(CoreEvent::Partial(crate::discord::Heard { speaker_id: 11, speaker_name: "민수".into(), utt: 1 }, + "자비스 안녕".into())).unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + let s = c.snapshot().await; + assert_eq!(s["state"], json!("running")); + assert_eq!(s["discord"], json!("Jarvis#0001")); + assert_eq!(s["voiceChannel"], json!("77")); + assert_eq!(s["captions"][0]["text"], json!("자비스 안녕")); + assert_eq!(s["voiceMembers"][0]["name"], json!("민수")); + assert_eq!(s["worker"]["connected"], json!(true)); + assert!(s["system"]["ramTotalMb"].is_u64() || !cfg!(any(target_os = "linux", windows))); + assert_eq!(s["performance"], Value::Null); + c.stop().await.unwrap(); + let s = c.snapshot().await; + assert_eq!(s["captions"], json!([])); + assert_eq!(s["worker"], Value::Null); + } +} diff --git a/app/src/conversation.rs b/app/src/conversation.rs index cc0aff5..8b5571b 100644 --- a/app/src/conversation.rs +++ b/app/src/conversation.rs @@ -117,6 +117,9 @@ impl ChatCalls { /// Chat answers waited for longer than this are forgotten (the brain or the worker went away). const CHAT_ANSWER_KEPT: Duration = Duration::from_secs(300); +/// The missed requests, shared between the conversation loop and the dashboard. +pub type MissedLog = std::sync::Arc>>; + /// A request that was not answered, or an answer that was stopped. No text: only who, why and when. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Missed { @@ -136,7 +139,8 @@ pub struct Conversation { by_speech: HashMap, /// Ask id -> the request it becomes on a yes, and when it was asked. asks: HashMap, - missed: VecDeque, + /// Shared with the dashboard (`missed_handle`). + missed: MissedLog, chat: ChatCalls, /// Chat answer id -> the message it answers (channel, message) and when it was asked. chat_answers: HashMap, @@ -152,7 +156,7 @@ pub struct Conversation { impl Conversation { pub fn new(voice: V, calls: CallSettings, policy: PolicySettings) -> Self { Self { voice, calls, policy: Policy::new(policy), next_id: 0, answers: HashMap::new(), - by_speech: HashMap::new(), asks: HashMap::new(), missed: VecDeque::new(), chat: ChatCalls::default(), + by_speech: HashMap::new(), asks: HashMap::new(), missed: MissedLog::default(), chat: ChatCalls::default(), chat_answers: HashMap::new(), started: HashMap::new(), wakes: HashMap::new(), chimed: HashSet::new() } } @@ -206,8 +210,14 @@ impl Conversation { } } - pub fn missed(&self) -> impl Iterator { - self.missed.iter() + /// The missed requests kept, oldest first. + pub fn missed(&self) -> std::vec::IntoIter { + self.missed.lock().unwrap().iter().cloned().collect::>().into_iter() + } + + /// The same records for the dashboard, readable while the loop runs. + pub fn missed_handle(&self) -> MissedLog { + self.missed.clone() } pub fn on_event(&mut self, ev: &CoreEvent, now: Instant) { @@ -413,10 +423,11 @@ impl Conversation { Action::Missed(r, reason) => { self.chimed.remove(&r.id); debug_log!("conversation", "missed req={} speaker={} reason={reason:?}", r.id, r.speaker); - if self.missed.len() == MISSED_KEPT { - self.missed.pop_front(); + let mut missed = self.missed.lock().unwrap(); + if missed.len() == MISSED_KEPT { + missed.pop_front(); } - self.missed.push_back(Missed { speaker: r.speaker, reason, at: now, chars: r.text.chars().count() }); + missed.push_back(Missed { speaker: r.speaker, reason, at: now, chars: r.text.chars().count() }); } Action::Rank { id, candidates } => { let c: Vec<(String, u64, String)> = @@ -724,7 +735,7 @@ mod tests { c.on_event(&fin(A, "자비스 날씨", 100), ms(t, 0)); c.on_event(&fin(B, "자비스 안녕", 100), ms(t, 100)); assert_eq!(f.take().len(), 1); - let m: Vec<_> = c.missed().cloned().collect(); + let m: Vec<_> = c.missed().collect(); assert_eq!(m, vec![Missed { speaker: B, reason: MissReason::Busy, at: ms(t, 100), chars: "자비스 안녕".chars().count() }]); } diff --git a/app/src/dashboard.rs b/app/src/dashboard.rs new file mode 100644 index 0000000..46c83db --- /dev/null +++ b/app/src/dashboard.rs @@ -0,0 +1,277 @@ +//! What the dashboard shows, built from the core's events (`app/src/admin.spec.md`, "Dashboard data"). +//! +//! Pure: `on_event` takes the time, so every rule is tested with made-up events. Captions hold what +//! people said for the screen only; nothing here is logged or written. + +use std::collections::{HashMap, VecDeque}; +use std::time::{Duration, Instant}; + +use serde::Serialize; +use serde_json::{json, Value}; + +use crate::conversation::Missed; +use crate::discord::CoreEvent; + +pub const CAPTIONS_KEPT: usize = 30; +pub const ANSWERS_KEPT: usize = 20; +pub const MISSED_SHOWN: usize = 20; + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Caption { + pub speaker: String, + pub name: String, + pub text: String, + #[serde(rename = "final")] + pub is_final: bool, + #[serde(skip)] + utt: u32, +} + +/// One voice answer's stages in milliseconds (None: that stage could not be seen). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct AnswerTiming { + /// Speech end to its final transcript. + pub final_ms: Option, + /// The answer asked to its text. + pub brain_ms: Option, + /// The text to the first sound of the answer. + pub voice_ms: Option, + /// Speech end to the first sound. + pub total_ms: Option, +} + +struct Pending { + asked: Instant, + /// The asker's latest final: when their speech ended and when the final came. + heard: Option<(Instant, Instant)>, + reply: Option, +} + +#[derive(Default)] +pub struct Dashboard { + bot_tag: Option, + voice_channel: Option, + captions: VecDeque, + last_final: HashMap, + pending: HashMap, + answers: VecDeque, +} + +fn ms(from: Instant, to: Instant) -> u64 { + to.saturating_duration_since(from).as_millis() as u64 +} + +impl Dashboard { + pub fn on_event(&mut self, ev: &CoreEvent, now: Instant) { + match ev { + CoreEvent::Ready { tag, .. } => self.bot_tag = Some(tag.clone()), + CoreEvent::Joined { channel_id, .. } => self.voice_channel = Some(*channel_id), + CoreEvent::Left { .. } => { + self.voice_channel = None; + self.captions.clear(); + self.pending.clear(); + } + CoreEvent::Partial(h, text) => self.caption(h.speaker_id, &h.speaker_name, h.utt, text, false), + CoreEvent::Final(f) => { + let h = &f.heard; + self.caption(h.speaker_id, &h.speaker_name, h.utt, &f.text, true); + if !f.text.trim().is_empty() { + let ended = now.checked_sub(Duration::from_millis(f.wait_ms)).unwrap_or(now); + self.last_final.insert(h.speaker_id, (ended, now)); + } + } + CoreEvent::AnswerAsked { id, user } => { + let heard = self.last_final.get(user).copied(); + self.pending.insert(id.clone(), Pending { asked: now, heard, reply: None }); + } + CoreEvent::ReplyText { id, .. } => { + if let Some(p) = self.pending.get_mut(id) { + p.reply = Some(now); + } + } + CoreEvent::SpeakStart(id) => { + if let Some(p) = self.pending.remove(id) { + let t = AnswerTiming { + final_ms: p.heard.map(|(e, f)| ms(e, f)), + brain_ms: p.reply.map(|r| ms(p.asked, r)), + voice_ms: p.reply.map(|r| ms(r, now)), + total_ms: p.heard.map(|(e, _)| ms(e, now)), + }; + if self.answers.len() == ANSWERS_KEPT { + self.answers.pop_front(); + } + self.answers.push_back(t); + } + } + // An answer that ends without starting (failed, stopped) has nothing to time. + CoreEvent::SpeakEnd(e) => { + self.pending.remove(&e.id); + } + _ => {} + } + } + + /// A partial replaces the same utterance's earlier caption; the final replaces the partial + /// (an empty final removes it). + fn caption(&mut self, speaker: u64, name: &str, utt: u32, text: &str, is_final: bool) { + let id = speaker.to_string(); + let pos = self.captions.iter().position(|c| c.speaker == id && c.utt == utt && !c.is_final); + if let Some(i) = pos { + self.captions.remove(i); + } + if text.trim().is_empty() { + return; + } + if self.captions.len() == CAPTIONS_KEPT { + self.captions.pop_front(); + } + self.captions.push_back(Caption { speaker: id, name: name.into(), text: text.into(), is_final, utt }); + } + + /// Forget what was said (the services stopped). + pub fn clear(&mut self) { + *self = Self::default(); + } + + pub fn captions(&self) -> Vec { + self.captions.iter().cloned().collect() + } + + pub fn answers(&self) -> Vec { + self.answers.iter().copied().collect() + } + + /// The median of each stage over the answers kept. + pub fn medians(&self) -> AnswerTiming { + fn median(mut v: Vec) -> Option { + v.sort_unstable(); + (!v.is_empty()).then(|| v[v.len() / 2]) + } + let pick = |f: fn(&AnswerTiming) -> Option| median(self.answers.iter().filter_map(f).collect()); + AnswerTiming { final_ms: pick(|a| a.final_ms), brain_ms: pick(|a| a.brain_ms), + voice_ms: pick(|a| a.voice_ms), total_ms: pick(|a| a.total_ms) } + } + + pub fn view(&self, missed: &[Missed], now: Instant) -> Value { + json!({ + "discord": self.bot_tag, + "voiceChannel": self.voice_channel.map(|c| c.to_string()), + "captions": self.captions(), + "latency": {"answers": self.answers(), "median": self.medians()}, + "missed": missed_view(missed, now), + }) + } +} + +/// Newest first, at most `MISSED_SHOWN`: who, why, how long ago and how long the request was. +pub fn missed_view(missed: &[Missed], now: Instant) -> Value { + Value::Array(missed.iter().rev().take(MISSED_SHOWN).map(|m| json!({ + "speaker": m.speaker.to_string(), + "reason": m.reason, + "secondsAgo": now.saturating_duration_since(m.at).as_secs(), + "chars": m.chars, + })).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::discord::{Heard, HeardFinal}; + use crate::playback::PlaybackEnd; + use crate::policy::MissReason; + + const A: u64 = 11; + fn heard(utt: u32) -> Heard { + Heard { speaker_id: A, speaker_name: "민수".into(), utt } + } + fn fin(utt: u32, text: &str, wait_ms: u64) -> CoreEvent { + CoreEvent::Final(HeardFinal { heard: heard(utt), text: text.into(), end_reason: "silence".into(), + audio_ms: 900, wait_ms, stt_ms: 200 }) + } + fn at(t: Instant, ms: u64) -> Instant { + t + Duration::from_millis(ms) + } + + #[test] + fn a_partial_is_replaced_by_the_next_and_then_by_the_final() { + let (mut d, t) = (Dashboard::default(), Instant::now()); + d.on_event(&CoreEvent::Partial(heard(1), "자비스 오늘".into()), t); + d.on_event(&CoreEvent::Partial(heard(1), "자비스 오늘 날씨".into()), t); + assert_eq!(d.captions().iter().map(|c| (c.text.as_str(), c.is_final)).collect::>(), + vec![("자비스 오늘 날씨", false)]); + d.on_event(&fin(1, "자비스 오늘 날씨 어때?", 700), t); + d.on_event(&CoreEvent::Partial(heard(2), "그리고".into()), t); + assert_eq!(d.captions().iter().map(|c| (c.text.as_str(), c.is_final)).collect::>(), + vec![("자비스 오늘 날씨 어때?", true), ("그리고", false)]); + // An empty final removes its partial. + d.on_event(&fin(2, "", 300), t); + assert_eq!(d.captions().len(), 1); + assert_eq!(d.captions()[0].name, "민수"); + } + + #[test] + fn captions_are_capped_and_cleared_when_jarvis_leaves() { + let (mut d, t) = (Dashboard::default(), Instant::now()); + d.on_event(&CoreEvent::Joined { guild_id: 1, channel_id: 5 }, t); + for i in 0..(CAPTIONS_KEPT as u32 + 5) { + d.on_event(&fin(i, &format!("말 {i}"), 100), t); + } + let caps = d.captions(); + assert_eq!(caps.len(), CAPTIONS_KEPT); + assert_eq!(caps.last().unwrap().text, format!("말 {}", CAPTIONS_KEPT + 4)); + d.on_event(&CoreEvent::Left { guild_id: 1, channel_id: 5, reason: "command".into() }, t); + assert!(d.captions().is_empty()); + assert_eq!(d.view(&[], t)["voiceChannel"], Value::Null); + } + + #[test] + fn an_answer_is_timed_from_its_askers_speech_end_to_its_first_sound() { + let (mut d, t) = (Dashboard::default(), Instant::now()); + d.on_event(&fin(1, "자비스 몇 시야", 700), at(t, 1000)); // speech ended at 300 + d.on_event(&CoreEvent::AnswerAsked { id: "r1".into(), user: A }, at(t, 1010)); + d.on_event(&CoreEvent::ReplyText { id: "r1".into(), text: "열 시입니다.".into(), failed: false }, at(t, 1700)); + d.on_event(&CoreEvent::SpeakStart("r1".into()), at(t, 1900)); + assert_eq!(d.answers(), vec![AnswerTiming { final_ms: Some(700), brain_ms: Some(690), voice_ms: Some(200), + total_ms: Some(1600) }]); + // An answer stopped before it started is not timed; the earcon (another id) is not either. + d.on_event(&CoreEvent::AnswerAsked { id: "r3".into(), user: A }, at(t, 3000)); + d.on_event(&CoreEvent::SpeakStart("r2".into()), at(t, 3000)); + d.on_event(&CoreEvent::SpeakEnd(PlaybackEnd { id: "r3".into(), played: 0, cancelled: true, failed: false }), + at(t, 3100)); + d.on_event(&CoreEvent::SpeakStart("r3".into()), at(t, 3200)); + assert_eq!(d.answers().len(), 1); + } + + #[test] + fn the_medians_cover_the_last_answers_kept() { + let (mut d, t) = (Dashboard::default(), Instant::now()); + for (i, brain) in [500u64, 900, 700].into_iter().enumerate() { + let base = i as u64 * 10_000; + d.on_event(&fin(i as u32, "자비스", 600), at(t, base + 1000)); + d.on_event(&CoreEvent::AnswerAsked { id: format!("r{i}"), user: A }, at(t, base + 1000)); + d.on_event(&CoreEvent::ReplyText { id: format!("r{i}"), text: "네".into(), failed: false }, + at(t, base + 1000 + brain)); + d.on_event(&CoreEvent::SpeakStart(format!("r{i}")), at(t, base + 1000 + brain + 100)); + } + let m = d.medians(); + assert_eq!((m.final_ms, m.brain_ms, m.voice_ms, m.total_ms), (Some(600), Some(700), Some(100), Some(1400))); + for i in 0..ANSWERS_KEPT as u64 { + d.on_event(&CoreEvent::AnswerAsked { id: format!("x{i}"), user: 99 }, at(t, 100_000 + i)); + d.on_event(&CoreEvent::SpeakStart(format!("x{i}")), at(t, 100_000 + i)); + } + assert_eq!(d.answers().len(), ANSWERS_KEPT); + assert_eq!(d.medians().final_ms, None, "no final seen for the asker of the answers kept"); + } + + #[test] + fn missed_requests_show_newest_first_without_text() { + let t = Instant::now(); + let missed: Vec = (0..25).map(|i| Missed { speaker: i, reason: MissReason::Busy, + at: t, chars: 7 }).collect(); + let v = missed_view(&missed, at(t, 3000)); + let a = v.as_array().unwrap(); + assert_eq!(a.len(), MISSED_SHOWN); + assert_eq!(a[0], json!({"speaker": "24", "reason": "busy", "secondsAgo": 3, "chars": 7})); + } +} diff --git a/app/src/discord.rs b/app/src/discord.rs index 7a2b651..04d7ef7 100644 --- a/app/src/discord.rs +++ b/app/src/discord.rs @@ -76,6 +76,8 @@ pub enum CoreEvent { /// The voice worker connection ended: finals of utterances in progress will not come, and the /// restarted worker numbers utterances afresh. WorkerLost, + /// `answer(user, ..)` queued speech `id` (the dashboard times answers by it). + AnswerAsked { id: String, user: u64 }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -318,6 +320,22 @@ impl DiscordCore { // --- voice ------------------------------------------------------------------------------------ + /// The people in Jarvis's voice channel that it hears (ID and display name), as reported to the + /// worker; empty outside a voice channel. + pub fn voice_members(&self) -> Vec<(u64, String)> { + let inner = &self.inner; + let Some((guild, channel)) = inner.session.lock().unwrap().as_ref().map(|s| (s.guild_id, s.channel_id)) else { + return vec![]; + }; + let users: Vec = inner.cache.get() + .and_then(|c| c.guild(GuildId::new(guild)).map(|g| g.voice_states.values() + .filter(|v| v.channel_id.map(|c| c.get()) == Some(channel)) + .map(|v| v.user_id.get()) + .collect())) + .unwrap_or_default(); + users.into_iter().filter(|u| should_hear(inner, *u)).map(|u| (u, name_of(inner, u))).collect() + } + pub fn voice_channel_id(&self) -> Option { self.inner.session.lock().unwrap().as_ref().map(|s| s.channel_id) } @@ -410,6 +428,7 @@ impl DiscordCore { pub fn answer(&self, user: u64, text: &str) -> Option { self.voice_channel_id()?; let id = with_playback(&self.inner, |p| p.adopt()); + let _ = self.inner.events.send(CoreEvent::AnswerAsked { id: id.clone(), user }); self.inner.worker.reply(&id, user, text, "voice", true); Some(id) } diff --git a/app/src/discord_core.spec.md b/app/src/discord_core.spec.md index 8a9e440..fce770a 100644 --- a/app/src/discord_core.spec.md +++ b/app/src/discord_core.spec.md @@ -145,7 +145,10 @@ and the late "left" update cancelled the new join (seen on real Discord). `SpeakStart` and `SpeakEnd`; `Stopped` when all speech is stopped (`stop()`, the slash command or the session ending), sent before the `SpeakEnd`s it causes; `Joined` and `Left` (with a reason: `command`, `moved`, `disconnected`, `shutdown`); `Addressed` and `Ranked` with the brain's answers to `ask_addressed` and `ask_rank`. `WorkerLost` when the voice worker connection ends: the finals of utterances in progress will not - come, and the restarted worker numbers utterances afresh. + come, and the restarted worker numbers utterances afresh. `AnswerAsked { id, user }` when + `answer(user, ..)` queued speech `id` (the dashboard times answers by it, `admin.spec.md`). + `voice_members()` lists the people in Jarvis's voice channel that it hears (ID and display name), + the same set reported to the worker. - **Speaking**: `say(text, more)` queues a TTS request and returns its id (`None` when not in a voice channel); `continue_text(id, text, more)` adds text to an open request. Each sentence the worker sends becomes one clip (a 48 kHz stereo WAV played through songbird without resampling); clips play diff --git a/app/src/lib.rs b/app/src/lib.rs index 520b3e5..348e663 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -3,7 +3,9 @@ pub mod log; pub mod calls; pub mod chat; +pub mod control; pub mod conversation; +pub mod dashboard; pub mod datadir; pub mod discord; pub mod earcon; @@ -17,5 +19,6 @@ pub mod services; pub mod settings; pub mod settings_edit; pub mod speakers; +pub mod system; pub mod worker_client; pub mod worker_process; diff --git a/app/src/main.rs b/app/src/main.rs index 83d1e37..6b64e14 100644 --- a/app/src/main.rs +++ b/app/src/main.rs @@ -1,9 +1,9 @@ //! Jarvis app (headless until the Tauri GUI arrives in M5): jarvis-app -//! The data folder can also come from JARVIS_DATA_DIR; the bot token from JARVIS_DISCORD_TOKEN. +//! The data folder can also come from JARVIS_DATA_DIR; the bot token from the stored secrets, else +//! JARVIS_DISCORD_TOKEN. The services run through the same controller the dashboard uses. -use jarvis_app::discord::CoreEvent; -use jarvis_app::services::start_services; -use jarvis_app::{debug_log, error_log}; +use jarvis_app::control::{Controller, ServicesHost}; +use jarvis_app::error_log; #[tokio::main] async fn main() { @@ -12,32 +12,19 @@ async fn main() { error_log!("app", "usage: jarvis-app (or set JARVIS_DATA_DIR)"); std::process::exit(2); }; - let data_dir = std::path::Path::new(&data_dir); + let data_dir = std::path::PathBuf::from(data_dir); // The log hub: daily files in /logs, stored secrets masked in exports. let logs_dir = data_dir.join("logs"); let _ = std::fs::create_dir_all(&logs_dir); let hub = jarvis_app::logs::LogHub::new(Some(&logs_dir)); hub.set_secrets(jarvis_app::secrets::Secrets::new(&data_dir.join("config").join("secrets.dat")).values()); jarvis_app::logs::install(hub); - let mut services = match start_services(data_dir).await { - Ok(s) => s, - Err(e) => { - error_log!("app", "could not start: {e}"); - std::process::exit(1); - } - }; - loop { - tokio::select! { - ev = services.events.recv() => match ev { - // The conversation loop answers what is heard; here only the shape is logged, never the text. - Some(CoreEvent::Final(f)) => debug_log!("app", "heard {} utt={} chars={}", f.heard.speaker_id, f.heard.utt, f.text.chars().count()), - Some(_) => {} - None => break, - }, - _ = shutdown_signal() => break, - } + let controller = Controller::new(ServicesHost { data_dir }); + if controller.start().await.is_err() { + std::process::exit(1); } - services.stop().await; + shutdown_signal().await; + let _ = controller.stop().await; } async fn shutdown_signal() { diff --git a/app/src/policy.rs b/app/src/policy.rs index 38346d5..a2fded6 100644 --- a/app/src/policy.rs +++ b/app/src/policy.rs @@ -56,7 +56,8 @@ pub struct Request { pub arrived_at: Instant, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] pub enum MissReason { /// `first`: an answer was running or another caller finished first. Busy, diff --git a/app/src/services.rs b/app/src/services.rs index 36a5e83..6479616 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -17,6 +17,8 @@ pub struct Services { pub events: mpsc::UnboundedReceiver, pub worker: WorkerClient, pub worker_process: WorkerProcess, + /// The conversation's missed requests, for the dashboard. + pub missed: conversation::MissedLog, } impl Services { @@ -66,6 +68,7 @@ pub async fn start_services(data_dir: &Path) -> Result Result, + pub ram_total_mb: Option, + pub gpus: Vec, +} + +/// One line per GPU of `nvidia-smi --query-gpu=name,utilization.gpu,memory.used,memory.total +/// --format=csv,noheader,nounits`; lines that do not parse are skipped. +pub fn parse_nvidia_smi(out: &str) -> Vec { + out.lines().filter_map(|l| { + let f: Vec<&str> = l.split(',').map(str::trim).collect(); + let [name, util, used, total] = f.as_slice() else { return None }; + Some(Gpu { name: (*name).into(), use_percent: util.parse().ok()?, vram_used_mb: used.parse().ok()?, + vram_total_mb: total.parse().ok()? }) + }).collect() +} + +/// The GPUs `nvidia-smi` reports; empty without one (or when it does not answer within 2 s). +pub async fn gpus() -> Vec { + let mut cmd = tokio::process::Command::new("nvidia-smi"); + cmd.args(["--query-gpu=name,utilization.gpu,memory.used,memory.total", "--format=csv,noheader,nounits"]) + .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true); + #[cfg(windows)] + cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + match tokio::time::timeout(Duration::from_secs(2), cmd.output()).await { + Ok(Ok(o)) if o.status.success() => parse_nvidia_smi(&String::from_utf8_lossy(&o.stdout)), + _ => vec![], + } +} + +pub async fn usage() -> Usage { + let (used, total) = memory_mb(); + Usage { ram_used_mb: used, ram_total_mb: total, gpus: gpus().await } +} + +#[cfg(target_os = "linux")] +fn memory_mb() -> (Option, Option) { + let Ok(s) = std::fs::read_to_string("/proc/meminfo") else { return (None, None) }; + let kb = |key: &str| s.lines().find(|l| l.starts_with(key)) + .and_then(|l| l.split_whitespace().nth(1)?.parse::().ok()); + let (total, avail) = (kb("MemTotal:"), kb("MemAvailable:")); + (total.zip(avail).map(|(t, a)| (t - a) / 1024), total.map(|t| t / 1024)) +} +#[cfg(windows)] +fn memory_mb() -> (Option, Option) { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: the struct is sized and zeroed as the API asks. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + if unsafe { GlobalMemoryStatusEx(&mut m) } == 0 { + return (None, None); + } + let mb = 1024 * 1024; + (Some((m.ullTotalPhys - m.ullAvailPhys) / mb), Some(m.ullTotalPhys / mb)) +} +#[cfg(not(any(target_os = "linux", windows)))] +fn memory_mb() -> (Option, Option) { + (None, None) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nvidia_smi_lines_become_gpus_and_junk_is_skipped() { + let out = "NVIDIA GeForce RTX 5050, 37, 5120, 8151\nNVIDIA GeForce RTX 4090, [N/A], 1, 24564\n\n"; + assert_eq!(parse_nvidia_smi(out), vec![Gpu { name: "NVIDIA GeForce RTX 5050".into(), use_percent: 37, + vram_used_mb: 5120, vram_total_mb: 8151 }]); + } + + #[tokio::test] + async fn usage_reads_this_machines_memory() { + let u = usage().await; + if cfg!(any(target_os = "linux", windows)) { + let (used, total) = (u.ram_used_mb.unwrap(), u.ram_total_mb.unwrap()); + assert!(used > 0 && used <= total); + } + } +} diff --git a/app/src/worker_client.rs b/app/src/worker_client.rs index 9334be5..8d60a25 100644 --- a/app/src/worker_client.rs +++ b/app/src/worker_client.rs @@ -184,6 +184,11 @@ impl WorkerClient { tokio::spawn(async move { run(inner).await }); } + /// The worker's `hello_ok` while connected (STT and TTS readiness), else None. + pub fn hello(&self) -> Option { + self.inner.ready.borrow().clone() + } + pub fn is_ready(&self) -> bool { self.inner.ready.borrow().is_some() } diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 0941722..b33e783 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단계) | +| 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 | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 |