feat(app): answer registered chat channels in chat
- chatChannels[].answer: wakeWord (default) or everything. Chat uses call.chatWakeWords (else the voice wake words) with the shared designated-people switches. - The brain's answer (reply via chat, not spoken) is posted as a Discord reply to the message, pinging nobody; failed or empty answers post nothing. Bots, channels with sending off and stops are not answered. - Chat runs beside the voice conversation and never takes its turn. - Core: send_chat_reply, chat_answer and the ReplyText event; the worker client's reply takes via. - Specs (conversation, discord core) and the roadmap updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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<u64, ChatChannelCall>,
|
||||
}
|
||||
|
||||
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<V: Voice> {
|
||||
/// Ask id -> the request it becomes on a yes, and when it was asked.
|
||||
asks: HashMap<String, (Request, Instant)>,
|
||||
missed: VecDeque<Missed>,
|
||||
chat: ChatCalls,
|
||||
/// Chat answer id -> the message it answers (channel, message) and when it was asked.
|
||||
chat_answers: HashMap<String, (u64, u64, Instant)>,
|
||||
}
|
||||
|
||||
impl<V: Voice> Conversation<V> {
|
||||
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<Item = &Missed> {
|
||||
@@ -85,6 +171,15 @@ impl<V: Voice> Conversation<V> {
|
||||
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<String>),
|
||||
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<Did> {
|
||||
@@ -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>, 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);
|
||||
|
||||
Reference in New Issue
Block a user