diff --git a/app/src/chat.rs b/app/src/chat.rs index 7b5084f..a3e358b 100644 --- a/app/src/chat.rs +++ b/app/src/chat.rs @@ -178,7 +178,7 @@ mod tests { fn ch(id: u64, read: bool, send: bool) -> ChatChannelSettings { ChatChannelSettings { id, name: String::new(), description: String::new(), read, send, edit: true, - react: true, delete: false, pin: false } + react: true, delete: false, pin: false, answer_all: false } } #[test] diff --git a/app/src/conversation.rs b/app/src/conversation.rs index e4558f0..a696ec7 100644 --- a/app/src/conversation.rs +++ b/app/src/conversation.rs @@ -30,6 +30,10 @@ pub trait Voice { fn stop_all(&self); fn ask_addressed(&self, id: &str, user: u64, text: &str) -> bool; fn ask_rank(&self, id: &str, candidates: &[(String, u64, String)]) -> bool; + /// Have the brain answer a chat message (not spoken); its text comes as `CoreEvent::ReplyText`. + fn chat_answer(&self, id: &str, user: u64, text: &str) -> bool; + /// Post `text` in `channel` as a reply to `message` (never pinging anyone). + fn send_reply(&self, channel: u64, message: u64, text: &str); } impl Voice for DiscordCore { @@ -48,8 +52,53 @@ impl Voice for DiscordCore { fn ask_rank(&self, id: &str, candidates: &[(String, u64, String)]) -> bool { DiscordCore::ask_rank(self, id, candidates) } + fn chat_answer(&self, id: &str, user: u64, text: &str) -> bool { + DiscordCore::chat_answer(self, id, user, text) + } + fn send_reply(&self, channel: u64, message: u64, text: &str) { + let core = self.clone(); + let text = text.to_owned(); + tokio::spawn(async move { + if let Err(e) = core.send_chat_reply(channel, message, &text).await { + crate::error_log!("conversation", "could not post the chat answer in {channel}: {e}"); + } + }); + } } +/// How a registered chat channel is answered (`chatChannels[].answer`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ChatChannelCall { + /// Answer every message, not only those with a wake word. + pub everything: bool, + /// Sending is on; without it no answer could be posted, so none is asked for. + pub send: bool, +} + +/// Call detection for chat: the chat wake words (`call.chatWakeWords`, else the voice ones) with the +/// shared designated-people switches, and each registered channel's answer setting. +#[derive(Debug, Clone, Default)] +pub struct ChatCalls { + pub calls: CallSettings, + pub channels: HashMap, +} + +impl ChatCalls { + pub fn from_settings(s: &crate::settings::Settings) -> Self { + let mut calls = s.call.clone(); + if let Some(w) = &s.chat_wake_words { + calls.wake_words = w.clone(); + } + let channels = s.chat_channels.iter() + .map(|c| (c.id, ChatChannelCall { everything: c.answer_all, send: c.send })) + .collect(); + Self { calls, channels } + } +} + +/// 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); + /// 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 { @@ -70,12 +119,49 @@ pub struct Conversation { /// Ask id -> the request it becomes on a yes, and when it was asked. asks: HashMap, missed: VecDeque, + chat: ChatCalls, + /// Chat answer id -> the message it answers (channel, message) and when it was asked. + chat_answers: HashMap, } 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() } + by_speech: HashMap::new(), asks: HashMap::new(), missed: VecDeque::new(), chat: ChatCalls::default(), + chat_answers: HashMap::new() } + } + + /// Answer the registered chat channels too. + pub fn with_chat(mut self, chat: ChatCalls) -> Self { + self.chat = chat; + self + } + + fn on_chat(&mut self, m: &crate::chat::ChatMessage, now: Instant) { + // Other bots are never answered, so two bots cannot keep answering each other. + if m.author_is_bot || m.from_self { + return; + } + let Some(ch) = self.chat.channels.get(&m.channel_id).copied() else { return }; + if !ch.send { + return; + } + let calls = CallSettings { + mode: if ch.everything { crate::calls::CallMode::Everything } else { crate::calls::CallMode::WakeWord }, + ..self.chat.calls.clone() + }; + let call = calls.judge(m.author_id, &m.content); + debug_log!("conversation", "chat {} in {} from {} call={call:?}", m.message_id, m.channel_id, m.author_id); + // A chat message is answered in chat; a stop there is not a question. + if !matches!(call, Call::Request { .. }) { + return; + } + self.chat_answers.retain(|_, (_, _, at)| now < *at + CHAT_ANSWER_KEPT); + self.next_id += 1; + let id = format!("c{}", self.next_id); + if self.voice.chat_answer(&id, m.author_id, &m.content) { + self.chat_answers.insert(id, (m.channel_id, m.message_id, now)); + } } pub fn missed(&self) -> impl Iterator { @@ -85,6 +171,15 @@ impl Conversation { pub fn on_event(&mut self, ev: &CoreEvent, now: Instant) { match ev { CoreEvent::SpeechStart(h) => self.policy.utterance_open(h.speaker_id), + CoreEvent::Chat(m) => self.on_chat(m, now), + CoreEvent::ReplyText { id, text, failed } => { + if let Some((channel, message, _)) = self.chat_answers.remove(id) { + debug_log!("conversation", "chat answer {id} chars={} failed={failed}", text.chars().count()); + if !failed && !text.trim().is_empty() { + self.voice.send_reply(channel, message, text); + } + } + } CoreEvent::SpeakingStopped(user) => self.policy.speaking_stopped(*user, now), CoreEvent::Final(f) => { let speaker = f.heard.speaker_id; @@ -266,6 +361,8 @@ mod tests { StopAll, Addressed(String, u64), Rank(String, Vec), + ChatAnswer(String, u64, String), + SendReply(u64, u64, String), } #[derive(Clone, Default)] @@ -293,6 +390,13 @@ mod tests { self.did.borrow_mut().push(Did::Rank(id.into(), c.iter().map(|x| x.0.clone()).collect())); true } + fn chat_answer(&self, id: &str, user: u64, text: &str) -> bool { + self.did.borrow_mut().push(Did::ChatAnswer(id.into(), user, text.into())); + true + } + fn send_reply(&self, channel: u64, message: u64, text: &str) { + self.did.borrow_mut().push(Did::SendReply(channel, message, text.into())); + } } impl Fake { fn take(&self) -> Vec { @@ -445,6 +549,82 @@ mod tests { assert!(f.take().is_empty()); } + const CH_WAKE: u64 = 100; + const CH_ALL: u64 = 200; + const CH_MUTE: u64 = 300; + + fn chat_conv(calls: CallSettings) -> (Conversation, Fake, Instant) { + let f = Fake::default(); + let chat = ChatCalls { calls, channels: [ + (CH_WAKE, ChatChannelCall { everything: false, send: true }), + (CH_ALL, ChatChannelCall { everything: true, send: true }), + (CH_MUTE, ChatChannelCall { everything: true, send: false }), + ].into() }; + let c = Conversation::new(f.clone(), CallSettings::default(), PolicySettings::default()).with_chat(chat); + (c, f, Instant::now()) + } + fn chat(channel: u64, message: u64, author: u64, bot: bool, text: &str) -> CoreEvent { + CoreEvent::Chat(crate::chat::ChatMessage { channel_id: channel, message_id: message, author_id: author, + author_name: "x".into(), author_is_bot: bot, from_self: false, content: text.into(), + created_at: String::new() }) + } + + #[test] + fn a_chat_call_is_answered_as_a_reply_to_its_message() { + let (mut c, f, t) = chat_conv(CallSettings::default()); + c.on_event(&chat(CH_WAKE, 5, A, false, "자비스 내일 일정 알려 줘"), t); + let Did::ChatAnswer(id, user, text) = f.take().remove(0) else { panic!() }; + assert_eq!((user, text.as_str()), (A, "자비스 내일 일정 알려 줘")); + c.on_event(&CoreEvent::ReplyText { id: id.clone(), text: "내일은 비어 있어요.".into(), failed: false }, t); + assert_eq!(f.take(), vec![Did::SendReply(CH_WAKE, 5, "내일은 비어 있어요.".into())]); + // A second reply_text for the same id sends nothing. + c.on_event(&CoreEvent::ReplyText { id, text: "x".into(), failed: false }, t); + assert!(f.take().is_empty()); + } + + #[test] + fn chat_answers_follow_each_channels_switch_and_never_answer_bots() { + let (mut c, f, t) = chat_conv(CallSettings::default()); + c.on_event(&chat(CH_WAKE, 1, A, false, "오늘 뭐 먹지"), t); + assert!(f.take().is_empty(), "wake word only"); + c.on_event(&chat(CH_ALL, 2, A, false, "오늘 뭐 먹지"), t); + assert!(matches!(f.take()[..], [Did::ChatAnswer(..)]), "every message"); + c.on_event(&chat(CH_MUTE, 3, A, false, "자비스 안녕"), t); + assert!(f.take().is_empty(), "sending is off: no answer could be posted"); + c.on_event(&chat(CH_ALL, 4, B, true, "자비스 안녕"), t); + assert!(f.take().is_empty(), "other bots are never answered"); + c.on_event(&chat(999, 6, A, false, "자비스 안녕"), t); + assert!(f.take().is_empty(), "not a registered channel"); + c.on_event(&chat(CH_ALL, 7, A, false, "자비스 멈춰"), t); + assert!(f.take().is_empty(), "a stop in chat is not a question"); + } + + #[test] + fn chat_uses_its_own_wake_words_and_the_designated_people() { + let calls = CallSettings { wake_words: vec!["봇".into()], designated: [A].into(), designated_only: true, + ..CallSettings::default() }; + let (mut c, f, t) = chat_conv(calls); + c.on_event(&chat(CH_WAKE, 1, A, false, "봇 안녕"), t); + assert_eq!(f.take().len(), 1); + c.on_event(&chat(CH_WAKE, 2, B, false, "봇 안녕"), t); + assert!(f.take().is_empty(), "only designated people"); + c.on_event(&chat(CH_WAKE, 3, A, false, "자비스 안녕"), t); + assert!(f.take().is_empty(), "the voice wake word is not the chat one here"); + } + + #[test] + fn a_failed_chat_answer_posts_nothing_and_chat_leaves_voice_alone() { + let (mut c, f, t) = chat_conv(CallSettings::default()); + c.on_event(&fin(A, "자비스 날씨", 100), t); + c.on_event(&chat(CH_ALL, 9, B, false, "안녕"), t); + let did = f.take(); + assert!(matches!(did[0], Did::Answer(..)) && matches!(did[1], Did::ChatAnswer(..)), "{did:?}"); + let Did::ChatAnswer(id, ..) = &did[1] else { panic!() }; + c.on_event(&CoreEvent::ReplyText { id: id.clone(), text: String::new(), failed: true }, t); + assert!(f.take().is_empty()); + assert_eq!(c.missed().count(), 0, "a chat message never takes the voice turn"); + } + #[test] fn end_times_come_from_the_finals_wait() { let (mut c, f, t) = conv(PolicyKind::InOrder, CallMode::WakeWord); diff --git a/app/src/conversation.spec.md b/app/src/conversation.spec.md index e33d345..c4ededd 100644 --- a/app/src/conversation.spec.md +++ b/app/src/conversation.spec.md @@ -114,12 +114,36 @@ request first, the answer stops (missed, `interrupted`) and the new request is a running answer first, or does not come in time, the answer goes on and the new request waits. The ranking is dropped when the running answer ends first. +## Chat calls + +Registered chat channels are answered in chat, by text, beside the voice conversation: a chat message +never takes the voice turn and never goes through the response policy. + +| Key | Default | Meaning | +|---|---|---| +| `chatChannels[].answer` | `"wakeWord"` | `wakeWord`: answer messages that call a wake word. `everything`: answer every message. | + +- The wake words are `call.chatWakeWords` (or `voice.wakeWords` when it is `null`), with the same + similarity and the same designated-people switches as voice; `call.mode` is voice only. +- Only messages of a registered channel with reading on reach the loop (the core's rule), and only a + channel with sending on is answered: there an answer could not be posted, so none is asked for. +- Messages from bots (other bots and Jarvis itself) are never answered, so two bots cannot keep + answering each other. +- Only a request is answered: a stop in chat ("자비스 멈춰") is not a question and gets no answer. +- The brain answers through `reply` with `via: "chat"` and `speak: false`; the answer is posted in the + same channel as a Discord reply to the message (so the history records it as an answer to that + person), pinging nobody. A failed or empty answer posts nothing. Answers waited for over 5 minutes + are forgotten. +- Known limit: the worker writes one reply at a time, so a voice answer waits while a chat answer is + being written (the LLM's parallel requests for "answer everything" channels are M5/M6 settings). + ## The conversation loop `app/src/conversation.rs` runs between the core's events and everything else that reads them (every event is passed on unchanged). It talks to the core through a small `Voice` interface (answer, cancel one request, stop all, ask "addressed", ask "rank"), so the glue is tested with a fake. +- `Chat` and `ReplyText`: chat calls, above. - `SpeechStart` opens the speaker's utterance; `SpeakingStopped` marks it ending. - `Final`: a request gets the next id, `ended_at` = arrival minus the final's `wait_ms`, and goes through call detection. Ignore closes the utterance. Stop stops all speech, runs the policy's stop, @@ -149,5 +173,6 @@ modes) and every policy rule above with fake times (settling, ordering by end ti interruption, ranking tie, ranking timeout, stop dropping the queue), and the conversation loop with a fake voice side (answering and queueing, a busy drop recorded without text, voice stop, addressed yes, no and timeout, interruption cancelling the right speech, a ranking deciding, end times from -`wait_ms`). `tests/worker_protocol.rs` checks an answer spoken under its id and both judgements against +`wait_ms`, and chat: an answer posted as a reply once, per-channel switches, no answers to bots or to +a stop, chat wake words and designated people, a failed answer posting nothing). `tests/worker_protocol.rs` checks an answer spoken under its id and both judgements against the real Python worker with a fake brain. diff --git a/app/src/discord.rs b/app/src/discord.rs index 05095ea..b6eec43 100644 --- a/app/src/discord.rs +++ b/app/src/discord.rs @@ -67,6 +67,8 @@ pub enum CoreEvent { /// `SpeakEnd`s of what it stopped. Stopped, Chat(ChatMessage), + /// The brain's answer text for a `reply` (`answer()` or `chat_answer()`). + ReplyText { id: String, text: String, failed: bool }, /// The brain's answer to `addressed()`. Addressed { id: String, addressed: bool }, /// The brain's answer to `rank()`: candidate ids, most important first (empty: failed). @@ -405,10 +407,15 @@ impl DiscordCore { pub fn answer(&self, user: u64, text: &str) -> Option { self.voice_channel_id()?; let id = with_playback(&self.inner, |p| p.adopt()); - self.inner.worker.reply(&id, user, text, true); + self.inner.worker.reply(&id, user, text, "voice", true); Some(id) } + /// Have the brain answer a chat message under `id`; the text comes as `CoreEvent::ReplyText`. + pub fn chat_answer(&self, id: &str, user: u64, text: &str) -> bool { + self.inner.worker.reply(id, user, text, "chat", false) + } + /// Stop one request (an answer or a `say`); the rest of the queue goes on. pub fn cancel(&self, id: &str) { with_playback(&self.inner, |p| p.cancel(id)); @@ -474,6 +481,27 @@ impl DiscordCore { Ok(ids) } + /// Send `text` to a registered channel as a reply to `message` (the first part carries the reply; + /// nobody is pinged, not even the person answered). The message ids. + pub async fn send_chat_reply(&self, channel_id: u64, message: u64, text: &str) -> Result, CoreError> { + self.inner.chat.check_send(channel_id)?; + if text.trim().is_empty() { + return Err(CoreError("nothing to send".into())); + } + let http = self.http()?; + let mut ids = vec![]; + for (i, part) in split_message(text, MESSAGE_LIMIT).into_iter().enumerate() { + let mut m = CreateMessage::new().content(part).allowed_mentions(CreateAllowedMentions::new().replied_user(false)); + if i == 0 { + m = m.reference_message((ChannelId::new(channel_id), MessageId::new(message))); + } + let sent = ChannelId::new(channel_id).send_message(http.as_ref(), m).await.map_err(cerr("could not send"))?; + ids.push(sent.id.get()); + } + debug_log!("chat", "chat answer sent to {channel_id} parts={} chars={}", ids.len(), text.chars().count()); + Ok(ids) + } + /// Do what the brain's chat channel tool asked (chat_channels.spec.md). The message ids made or /// touched. Every action needs its channel switch; edits only the bot's own messages. pub async fn chat_action(&self, a: &ChatAction) -> Result, CoreError> { @@ -660,6 +688,7 @@ async fn worker_task(core: std::sync::Weak, mut rx: mpsc::UnboundedReceiv WorkerEvent::TtsDone(d) => with_playback(&inner, |p| p.done(&d)), WorkerEvent::ReplyText { id, text, failed } => { debug_log!("voice", "reply {id} chars={} failed={failed}", text.chars().count()); + let _ = inner.events.send(CoreEvent::ReplyText { id, text, failed }); } WorkerEvent::Addressed { id, addressed } => { let _ = inner.events.send(CoreEvent::Addressed { id, addressed }); diff --git a/app/src/discord_core.spec.md b/app/src/discord_core.spec.md index 05a9095..ff45766 100644 --- a/app/src/discord_core.spec.md +++ b/app/src/discord_core.spec.md @@ -67,7 +67,7 @@ strings (numbers would lose precision). | `voice.joinNotice` | "자비스가 이 음성 채널에 들어왔습니다. 이 채널의 대화는 자비스가 받아 적습니다." | Posted in the voice channel's chat on every join. Must not be empty. | | `voice.wakeWords` | `["자비스"]` | Sent to the worker as STT `hotwords`, and the voice wake words of call detection. | | `voice.stt` | `{}` | Other worker STT settings (`partials`, `end_silence_ms`, `final_beam`, `language`, ...); the worker validates them. | -| `chatChannels` | `[]` | `{id, name, description, read (true), send (true), edit (true), react (true), delete (false), pin (false)}` per channel. | +| `chatChannels` | `[]` | `{id, name, description, read (true), send (true), edit (true), react (true), delete (false), pin (false), answer ("wakeWord")}` per channel; `answer` is in `conversation.spec.md`. | | `voiceWorker.python` | `python3` (`python.exe` on Windows) | Python of the worker venv. | | `voiceWorker.cwd` | the repo's `src/` (development builds) | Folder holding the `voice_worker` package. | | `voiceWorker.args` | `[]` | Extra worker arguments, e.g. `["--melo-python", ""]`. | @@ -188,6 +188,9 @@ registered until it is removed (M5 setup). - **Send**: `send_chat(channel_id, text)` sends to a registered channel with sending on, split at Discord's 2,000-character limit at the last newline or space (never inside a character), and returns the message ids. +- **Answer** (M4): `send_chat_reply(channel_id, message_id, text)` sends like Send, with the first + part as a Discord reply to the message; nobody is pinged, not even its author. `chat_answer(id, user, + text)` asks the brain for a chat answer (`reply` with `via: "chat"`); its text comes as `ReplyText`. - A channel that is not registered, or has the needed switch off, is refused with an access error. - **Chat tool actions** (M3, `chat_channels.spec.md`): when the worker link is ready and after login, the core sends `chat_channels` (every registered channel with its switches, and the bot's user ID). diff --git a/app/src/services.rs b/app/src/services.rs index 8cd22b0..eb3c068 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -56,10 +56,12 @@ pub async fn start_services(data_dir: &Path) -> Result Result { react: get_bool(Some(m), "react", &path, true)?, delete: get_bool(Some(m), "delete", &path, false)?, pin: get_bool(Some(m), "pin", &path, false)?, + answer_all: match get_str(Some(m), "answer", &path, "wakeWord")?.as_str() { + "wakeWord" => false, + "everything" => true, + _ => return err(format!("{path}.answer must be wakeWord or everything")), + }, }); } @@ -435,7 +443,7 @@ mod tests { assert_eq!(s.voice.stt.get("end_silence_ms"), Some(&json!(250))); assert_eq!(s.chat_channels, vec![ChatChannelSettings { id: IDN, name: "일정".into(), description: "일정 올리는 곳".into(), read: true, send: false, edit: true, react: true, delete: false, - pin: false }]); + pin: false, answer_all: false }]); assert_eq!(s.voice_worker.args, vec!["--melo-python", "/m/python"]); assert_eq!(s.voice_worker.cwd, PathBuf::from("/repo/src")); } @@ -453,6 +461,7 @@ mod tests { (json!({"chatChannels": [{"id": ID}, {"id": ID}]}), "twice"), (json!({"chatChannels": [{"id": "1"}]}), "chatChannels[0].id"), (json!({"chatChannels": {}}), "chatChannels"), + (json!({"chatChannels": [{"id": ID, "answer": "sometimes"}]}), "chatChannels[0].answer"), (json!({"voice": []}), "voice"), (json!([]), "object"), ]; @@ -483,6 +492,8 @@ mod tests { assert_eq!(s.response.collect, Duration::from_millis(500)); assert_eq!(s.response.settle, Duration::ZERO); assert_eq!(s.response.priorities.get(&IDN), Some(&2)); + let s = parse_settings(&json!({"chatChannels": [{"id": ID, "answer": "everything"}]})).unwrap(); + assert!(s.chat_channels[0].answer_all); let cases = [ (json!({"call": {"similarity": 0.9}}), "call.similarity"), diff --git a/app/src/worker_client.rs b/app/src/worker_client.rs index db246ab..bc9e07c 100644 --- a/app/src/worker_client.rs +++ b/app/src/worker_client.rs @@ -312,12 +312,13 @@ impl WorkerClient { /// Ask the brain to answer `user`. With `speak` the answer is spoken under `id` (its audio and /// `tts_done` come like a TTS request's); it ends as failed when it cannot be sent, the brain gives /// no answer, or the worker refuses it. - pub fn reply(&self, id: &str, user: u64, text: &str, speak: bool) -> bool { + /// `via`: `voice` or `chat` (the brain's history scope and where the answer is stored). + pub fn reply(&self, id: &str, user: u64, text: &str, via: &str, speak: bool) -> bool { if speak { self.inner.state.lock().unwrap().open_tts.insert(id.to_owned()); } let sent = self.send_json(json!({"type": "reply", "id": id, "user": user.to_string(), "text": text, - "via": "voice", "speak": speak})); + "via": via, "speak": speak})); if !sent && speak { self.end_failed(id); } diff --git a/app/tests/worker_client.rs b/app/tests/worker_client.rs index 455df6d..4f59d62 100644 --- a/app/tests/worker_client.rs +++ b/app/tests/worker_client.rs @@ -268,7 +268,7 @@ async fn chat_channels_go_out_and_chat_actions_come_back_with_their_results() { c.start(); c.wait_ready(Duration::from_secs(2)).await.expect("ready"); c.chat_channels(Some(900), &[ChatChannelSettings { id: 5, name: "일정".into(), description: "약속".into(), - read: true, send: true, edit: true, react: true, delete: false, pin: false }]); + read: true, send: true, edit: true, react: true, delete: false, pin: false, answer_all: false }]); w.send(Message::text(json!({"type": "chat_action", "id": "a1", "action": "react", "channel": "5", "message_id": "77", "emoji": "👍"}).to_string())); let ev = next_matching(&mut rx, |e| matches!(e, WorkerEvent::ChatAction(_))).await; @@ -293,8 +293,8 @@ async fn a_spoken_reply_takes_its_audio_and_a_failed_one_ends_its_speech() { let (c, mut rx) = client(&w.url(), json!({})); c.start(); c.wait_ready(Duration::from_secs(2)).await.expect("ready"); - assert!(c.reply("r1", 42, "자비스 날씨 어때", true)); - assert!(c.reply("r2", 43, "자비스 안녕", true)); + assert!(c.reply("r1", 42, "자비스 날씨 어때", "voice", true)); + assert!(c.reply("r2", 43, "자비스 안녕", "voice", true)); until(|| w.got().len() >= 3).await; assert_eq!(w.got()[1], Got::Json(json!({"type": "reply", "id": "r1", "user": "42", "text": "자비스 날씨 어때", "via": "voice", "speak": true}))); @@ -317,14 +317,14 @@ async fn a_reply_the_worker_cannot_answer_or_send_ends_as_failed() { let (c, mut rx) = client(&w.url(), json!({})); c.start(); c.wait_ready(Duration::from_secs(2)).await.expect("ready"); - c.reply("r3", 42, "x", true); + c.reply("r3", 42, "x", "voice", true); w.send(Message::text(json!({"type": "error", "code": "brain_unavailable", "message": "no", "id": "r3"}).to_string())); let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::TtsDone(_))).await; assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r3".into(), chunks: 0, cancelled: false, failed: true })); c.close(); let (c, mut rx) = client("ws://127.0.0.1:1", json!({})); - assert!(!c.reply("r4", 42, "x", true)); + assert!(!c.reply("r4", 42, "x", "voice", true)); let e = next_matching(&mut rx, |_| true).await; assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r4".into(), chunks: 0, cancelled: false, failed: true })); } @@ -359,3 +359,20 @@ async fn addressed_and_rank_questions_go_out_and_their_answers_come_back() { assert_eq!(e, WorkerEvent::Ranked { id: "k4".into(), order: vec![] }); c.close(); } + +#[tokio::test] +async fn a_chat_reply_is_not_spoken_and_its_text_comes_back() { + let w = FakeWorker::start(0).await; + let (c, mut rx) = client(&w.url(), json!({})); + c.start(); + c.wait_ready(Duration::from_secs(2)).await.expect("ready"); + assert!(c.reply("c1", 42, "자비스 일정", "chat", false)); + until(|| w.got().len() >= 2).await; + assert_eq!(w.got()[1], Got::Json(json!({"type": "reply", "id": "c1", "user": "42", "text": "자비스 일정", + "via": "chat", "speak": false}))); + w.send(tts_frame("c1", 0)); // not a speech the app asked for + w.send(Message::text(json!({"type": "reply_text", "id": "c1", "text": "", "failed": true}).to_string())); + let e = next_matching(&mut rx, |e| !matches!(e, WorkerEvent::Ready(_))).await; + assert_eq!(e, WorkerEvent::ReplyText { id: "c1".into(), text: String::new(), failed: true }); + c.close(); +} diff --git a/app/tests/worker_protocol.rs b/app/tests/worker_protocol.rs index 4248de5..e86efa5 100644 --- a/app/tests/worker_protocol.rs +++ b/app/tests/worker_protocol.rs @@ -108,7 +108,7 @@ async fn audio_and_tts_round_trip_through_the_python_server() { // A spoken brain answer plays under the adopted id, like a TTS request. let id = p.adopt(); - assert!(c.reply(&id, 42, "자비스 안녕", true)); + assert!(c.reply(&id, 42, "자비스 안녕", "voice", true)); let end = tokio::time::timeout(Duration::from_secs(5), async { loop { match rx.recv().await.unwrap() { diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 957746c..99b817e 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -8,7 +8,7 @@ | M1 | 음성 워커 | 화자별 스트리밍 STT(공용 모델, 배치), 문장 단위 TTS를 WebSocket으로 제공. 녹음 파일 10개 동시 입력 테스트 통과. 구현과 테스트 완료(2026-11-11): `src/voice_worker/`, 스펙은 [voice_worker.spec.md](../../src/voice_worker/voice_worker.spec.md). 이 서버의 RTX 5050에서 10명이 겹쳐 말하는 실시간 입력(48kHz 스테레오, M0 한국어 샘플 8개를 10명에게 나눠 줌, 절반은 디스코드 speaking 종료, 절반은 무음으로 끝남)을 넣어 10명 모두 최종 전사를 받았고 문자 오류율은 평균 4%, 최대 19%("일곱 시"를 "7시"로 적은 것), 말 끝 판정부터 최종 전사 전송까지 중앙값 0.64초, 최대 1.56초였습니다. TTS는 첫 문장 소리가 0.2초에 나왔고, 그 소리를 다시 넣으면 같은 문장으로 받아 적혔습니다. 샘플이 MeloTTS 합성 음성이라 실제 사람 녹음과 게임PC 수치는 아직 없습니다 | | 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 워커(가짜 두뇌)와 앱의 통합 시험 통과. 실제 디스코드 시험과 지연 측정은 4단계 | +| 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`, 없으면 음성과 같음)와 지정한 사람 설정은 음성과 같이 씀. 답은 같은 채널에 원래 메시지의 답글로 올리고 아무도 부르지 않음. 다른 봇의 글과 보내기가 꺼진 채널에는 답하지 않음. 음성 대화 순서와는 따로 감(워커가 답을 한 번에 하나씩 쓰므로 채팅 답을 쓰는 동안 음성 답은 기다림). 실제 디스코드 시험과 지연 측정은 4단계 | | M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드) | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. |