feat(conversation): answers wait until the asker is quiet, and going on joins while the answer plays

Live 2026-11-19 (the user's own pieced requests replayed into Discord) the pauses inside
one thought, 2.3-4.7 s, were longer than writing the answer: the answer started in the
pause, and what followed became a new request, so answers were cut off mid-sentence.

- A voice answer is written at once but starts playing only after its asker has been
  quiet for call.answerWaitMs (default 3000, 0 = off, settings "말이 끝나고 답하기 전
  기다림"); while they talk it waits for their final, which joins the request.
- A request stays open (Going on) until its answer ended, not until it is first heard:
  going on within call.continueMs while it plays stops it and answers all of it.

Replayed live: the three pieced requests each get one answer, none cut off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-19 22:10:07 +09:00
parent e716065538
commit 81bd8bd573
9 changed files with 226 additions and 31 deletions

View File

@@ -33,7 +33,10 @@ pub struct Room {
pub trait Voice {
/// Have the brain answer and speak it; the speech request id, or None when it cannot. `heard`:
/// when the request's speech ended and its final arrived (the dashboard times the answer by it).
fn answer(&self, user: u64, text: &str, heard: (Instant, Instant)) -> Option<String>;
/// `hold`: the answer is written but does not start playing until `release`.
fn answer(&self, user: u64, text: &str, heard: (Instant, Instant), hold: bool) -> Option<String>;
/// Let a held answer play.
fn release(&self, id: &str);
/// Stop one speech request.
fn cancel(&self, id: &str);
/// Stop all speech at once.
@@ -57,8 +60,11 @@ pub trait Voice {
}
impl Voice for DiscordCore {
fn answer(&self, user: u64, text: &str, heard: (Instant, Instant)) -> Option<String> {
DiscordCore::answer(self, user, text, heard)
fn answer(&self, user: u64, text: &str, heard: (Instant, Instant), hold: bool) -> Option<String> {
DiscordCore::answer(self, user, text, heard, hold)
}
fn release(&self, id: &str) {
DiscordCore::release(self, id)
}
fn cancel(&self, id: &str) {
DiscordCore::cancel(self, id)
@@ -170,6 +176,8 @@ pub struct Conversation<V: Voice> {
/// Each speaker's latest voice request whose answer has not been heard yet: what they say next
/// may still be part of it ("Going on").
turns: HashMap<u64, Turn>,
/// Held answers (speech id): their asker, and when they will have been quiet for `call.answerWaitMs`.
waiting: HashMap<String, (u64, Instant)>,
}
/// A voice request whose answer is not heard yet.
@@ -202,7 +210,7 @@ impl<V: Voice> Conversation<V> {
Self { voice, calls, policy: Policy::new(policy), next_id: 0, answers: HashMap::new(),
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(), turns: HashMap::new() }
chimed: HashSet::new(), turns: HashMap::new(), waiting: HashMap::new() }
}
/// Answer the registered chat channels too.
@@ -272,6 +280,24 @@ impl<V: Voice> Conversation<V> {
}
pub fn on_event(&mut self, ev: &CoreEvent, now: Instant) {
self.handle(ev, now);
self.release_due(now);
}
/// Held answers whose asker has been quiet for `call.answerWaitMs` start playing; while the asker
/// talks, their answer waits for what they say (it may join the request).
fn release_due(&mut self, now: Instant) {
let due: Vec<String> = self.waiting.iter()
.filter(|(_, (speaker, at))| now >= *at && !self.started.contains_key(speaker))
.map(|(sid, _)| sid.clone()).collect();
for sid in due {
self.waiting.remove(&sid);
debug_log!("conversation", "release speech={sid}");
self.voice.release(&sid);
}
}
fn handle(&mut self, ev: &CoreEvent, now: Instant) {
match ev {
CoreEvent::SpeechStart(h) => {
self.policy.utterance_open(h.speaker_id);
@@ -390,16 +416,16 @@ impl<V: Voice> Conversation<V> {
let a = self.policy.ranked(rank_id, &order, now);
self.apply(a, now);
}
// The answer is heard: what its asker says next is a new request.
// The answer is heard; while it plays, its asker may still go on (within call.continueMs).
CoreEvent::SpeakStart(id) => {
if let Some(pid) = self.by_speech.get(id).copied() {
self.turns.retain(|_, t| t.id != pid || t.held);
for t in self.turns.values_mut().filter(|t| t.id == pid) {
t.heard = true;
}
}
}
CoreEvent::SpeakEnd(e) => {
self.waiting.remove(&e.id);
if let Some(pid) = self.by_speech.remove(&e.id) {
self.answers.remove(&pid);
// A held request waits for its speaker's next final even after its answer ended.
@@ -484,6 +510,7 @@ impl<V: Voice> Conversation<V> {
fn stop_everything(&mut self, now: Instant) {
self.wakes.clear();
self.turns.clear();
self.waiting.clear();
let a = self.policy.stop();
self.apply(a, now);
self.chimed.clear(); // nothing is waiting any more
@@ -516,26 +543,33 @@ impl<V: Voice> Conversation<V> {
}
let a = self.policy.tick(now);
self.apply(a, now);
self.release_due(now);
}
pub fn next_deadline(&self) -> Option<Instant> {
let asks = self.asks.values().map(|(_, at)| *at + ADDRESSED_TIMEOUT);
let wakes = self.wakes.values().filter_map(|(_, d)| *d);
self.policy.next_deadline().into_iter().chain(asks).chain(wakes).min()
// Not while the asker talks: their final decides.
let held = self.waiting.values().filter(|(s, _)| !self.started.contains_key(s)).map(|(_, at)| *at);
self.policy.next_deadline().into_iter().chain(asks).chain(wakes).chain(held).min()
}
fn apply(&mut self, actions: Vec<Action>, now: Instant) {
for action in actions {
match action {
Action::Answer(r) => match {
// The earcon plays first, then the answer as soon as it is written.
// The earcon plays first, then the answer once it is written and its asker has
// been quiet for call.answerWaitMs.
if self.calls.earcon && !self.chimed.remove(&r.id) {
self.voice.earcon();
}
self.voice.answer(r.speaker, &r.text, (r.ended_at, r.arrived_at))
self.voice.answer(r.speaker, &r.text, (r.ended_at, r.arrived_at), !self.calls.answer_wait.is_zero())
} {
Some(sid) => {
debug_log!("conversation", "answer req={} speaker={} speech={sid}", r.id, r.speaker);
if !self.calls.answer_wait.is_zero() {
self.waiting.insert(sid.clone(), (r.speaker, r.ended_at + self.calls.answer_wait));
}
self.by_speech.insert(sid.clone(), r.id);
self.answers.insert(r.id, sid);
}
@@ -547,6 +581,7 @@ impl<V: Voice> Conversation<V> {
Action::StopAnswer(pid) => {
if let Some(sid) = self.answers.remove(&pid) {
self.by_speech.remove(&sid);
self.waiting.remove(&sid);
self.voice.cancel(&sid);
}
}
@@ -601,7 +636,7 @@ mod tests {
/// The tests call Jarvis by one wake word of their own, whatever the default is.
fn test_calls() -> CallSettings {
CallSettings { wake_words: vec!["자비스".into()], ..CallSettings::default() }
CallSettings { wake_words: vec!["자비스".into()], answer_wait: Duration::ZERO, ..CallSettings::default() }
}
use crate::discord::{Heard, HeardFinal};
use crate::playback::PlaybackEnd;
@@ -613,6 +648,9 @@ mod tests {
#[derive(Debug, Clone, PartialEq)]
enum Did {
Answer(u64, String),
/// The answer just asked for is held until released.
Held(String),
Release(String),
Cancel(String),
StopAll,
Earcon,
@@ -637,10 +675,17 @@ mod tests {
people: Rc<RefCell<Vec<u64>>>,
}
impl Voice for Fake {
fn answer(&self, user: u64, text: &str, _heard: (Instant, Instant)) -> Option<String> {
fn answer(&self, user: u64, text: &str, _heard: (Instant, Instant), hold: bool) -> Option<String> {
*self.n.borrow_mut() += 1;
let id = format!("s{}", self.n.borrow());
self.did.borrow_mut().push(Did::Answer(user, text.into()));
Some(format!("s{}", self.n.borrow()))
if hold {
self.did.borrow_mut().push(Did::Held(id.clone()));
}
Some(id)
}
fn release(&self, id: &str) {
self.did.borrow_mut().push(Did::Release(id.into()));
}
fn cancel(&self, id: &str) {
self.did.borrow_mut().push(Did::Cancel(id.into()));
@@ -1163,13 +1208,13 @@ mod tests {
}
#[test]
fn once_the_answer_is_heard_or_the_pause_is_long_the_next_words_are_a_new_request() {
fn once_the_answer_ended_or_the_pause_is_long_the_next_words_are_a_new_request() {
let (mut c, f, t) = alone(PolicyKind::Latest);
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0));
c.on_event(&speak_start("s1"), ms(t, 1500));
c.on_event(&fin(A, "고마워", 100), ms(t, 2500));
assert_eq!(f.take(), vec![Did::Answer(A, "계산기 켜 줘".into()), Did::Cancel("s1".into()),
Did::Answer(A, "고마워".into())]);
c.on_event(&end("s1", false), ms(t, 2000));
c.on_event(&fin(A, "고마워", 100), ms(t, 3500));
assert_eq!(f.take(), vec![Did::Answer(A, "계산기 켜 줘".into()), Did::Answer(A, "고마워".into())]);
// Still thinking, but the speaker paused longer than call.continueMs.
let (mut c, f, t) = alone(PolicyKind::InOrder);
let pause = test_calls().continue_window.as_millis() as u64;
@@ -1216,6 +1261,77 @@ mod tests {
const ALL: [PolicyKind; 4] = [PolicyKind::Latest, PolicyKind::InOrder, PolicyKind::First, PolicyKind::Important];
/// Alone with Jarvis, answers held until the asker has been quiet for `wait_ms`.
fn alone_waiting(kind: PolicyKind, wait_ms: u64) -> (Conversation<Fake>, Fake, Instant) {
let f = Fake::default();
let calls = CallSettings { mode: CallMode::Addressed, earcon: false, answer_wait: Duration::from_millis(wait_ms),
..test_calls() };
let policy = PolicySettings { kind, collect: Duration::ZERO, ..PolicySettings::default() };
*f.people.borrow_mut() = vec![A];
(Conversation::new(f.clone(), calls, policy), f, Instant::now())
}
#[test]
fn an_answer_starts_only_after_its_asker_was_quiet_for_the_wait() {
// Live 2026-11-19: pauses inside one thought were up to 4.7 s, longer than writing an answer.
for kind in ALL {
let (mut c, f, t) = alone_waiting(kind, 3000);
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0)); // ended at -100
assert_eq!(f.take(), vec![Did::Answer(A, "계산기 켜 줘".into()), Did::Held("s1".into())], "{kind:?}");
assert_eq!(c.next_deadline(), Some(ms(t, 2900)), "{kind:?}");
c.tick(ms(t, 2800));
assert!(f.take().is_empty(), "{kind:?}");
c.tick(ms(t, 2900));
assert_eq!(f.take(), vec![Did::Release("s1".into())], "{kind:?}");
assert_eq!(c.next_deadline(), None, "{kind:?}");
}
}
#[test]
fn a_held_answer_waits_while_its_asker_talks_and_their_words_join_it() {
for kind in ALL {
let (mut c, f, t) = alone_waiting(kind, 3000);
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0));
f.take();
c.on_event(&start(A, 2), ms(t, 2000));
c.tick(ms(t, 2900));
assert!(f.take().is_empty(), "still talking ({kind:?})");
c.on_event(&fin_utt(A, 2, "메모장도"), ms(t, 3500));
assert_eq!(f.take(), vec![Did::Cancel("s1".into()), Did::Answer(A, "계산기 켜 줘 메모장도".into()),
Did::Held("s2".into())], "{kind:?}");
c.tick(ms(t, 6400)); // the joined request ended at 3400
assert_eq!(f.take(), vec![Did::Release("s2".into())], "{kind:?}");
}
}
#[test]
fn a_held_answer_is_released_when_what_followed_was_noise() {
let (mut c, f, t) = alone_waiting(PolicyKind::Latest, 3000);
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0));
c.on_event(&start(A, 2), ms(t, 2000));
c.tick(ms(t, 2900));
f.take();
c.on_event(&fin_utt(A, 2, " "), ms(t, 3500));
assert_eq!(f.take(), vec![Did::Release("s1".into())]);
}
#[test]
fn going_on_while_the_answer_plays_stops_it_and_answers_all_of_it() {
// A pause longer than the wait: the answer started, then the speaker went on within
// call.continueMs of their request's end.
for kind in ALL {
let (mut c, f, t) = alone_waiting(kind, 3000);
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0));
c.tick(ms(t, 2900));
c.on_event(&speak_start("s1"), ms(t, 3000));
f.take();
c.on_event(&fin(A, "제일 앞으로", 100), ms(t, 5000)); // started at 3900, 4 s after the end
assert_eq!(f.take(), vec![Did::Cancel("s1".into()), Did::Answer(A, "계산기 켜 줘 제일 앞으로".into()),
Did::Held("s2".into())], "{kind:?}");
assert_eq!(c.missed().count(), 0, "{kind:?}");
}
}
#[test]
fn going_on_is_joined_even_when_the_short_answer_already_ended() {
// Final -> next SpeechStart -> the answer plays and ends -> next Final.