feat(app): speak the transcription notice on joining a voice channel instead of posting it in chat

The notice (voice.joinNotice) is now a speech request in the voice channel.
It is owed from each join until some of it was played or someone stopped
it; when the worker cannot speak yet (auto-join while it still starts) it is
spoken as soon as the worker is ready. Version 0.1.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-15 23:13:31 +09:00
parent f991981776
commit d17a3bbb61
8 changed files with 119 additions and 20 deletions

View File

@@ -209,6 +209,8 @@ struct Inner {
activity: OnceLock<Arc<crate::activity::Activity>>,
/// Speech requests whose end someone waits for (`say_to_end`), by request id.
speech_waits: Mutex<HashMap<String, tokio::sync::oneshot::Sender<PlaybackEnd>>>,
/// The spoken transcription notice of the current voice session.
notice: Mutex<JoinNotice>,
}
/// How long `say_to_end` waits for a reminder's speech (behind what is queued before it).
@@ -243,6 +245,55 @@ impl UttSessions {
}
}
/// The transcription notice (`voice.joinNotice`) is spoken in the voice channel: it is owed from each
/// join until some of it was played or someone stopped it. Speech that could not be made (the worker
/// not connected yet) leaves it owed, and it is spoken when the worker is next ready.
#[derive(Default)]
pub struct JoinNotice {
owed: bool,
speaking: Option<String>,
}
impl JoinNotice {
pub fn joined(&mut self) {
*self = Self { owed: true, speaking: None };
}
pub fn left(&mut self) {
*self = Self::default();
}
/// It should be spoken now (owed and not already in the queue).
pub fn due(&self) -> bool {
self.owed && self.speaking.is_none()
}
/// It was queued as speech request `id`.
pub fn queued(&mut self, id: String) {
self.speaking = Some(id);
}
/// A speech request ended. Some(heard) when it was the notice: false means it is still owed.
pub fn ended(&mut self, e: &PlaybackEnd) -> Option<bool> {
if self.speaking.as_deref() != Some(e.id.as_str()) {
return None;
}
self.speaking = None;
let heard = e.played > 0 || e.cancelled;
self.owed = !heard;
Some(heard)
}
}
/// Queue the transcription notice when it is owed and the worker can make speech.
fn speak_notice(inner: &Inner) {
if inner.session.lock().unwrap().is_none() || !inner.worker.is_ready() {
return;
}
with_playback(inner, |p| {
let mut n = inner.notice.lock().unwrap();
if n.due() {
n.queued(p.say(&inner.settings.voice.join_notice, false));
}
});
}
/// Handle to the core; cheap to clone.
#[derive(Clone)]
pub struct DiscordCore {
@@ -280,6 +331,7 @@ impl DiscordCore {
schedules: OnceLock::new(),
tasks: Mutex::new(HashMap::new()),
speech_waits: Mutex::new(HashMap::new()),
notice: Mutex::new(JoinNotice::default()),
activity: OnceLock::new(),
notes: OnceLock::new(),
});
@@ -398,7 +450,7 @@ impl DiscordCore {
self.inner.session.lock().unwrap().as_ref().map(|s| s.channel_id)
}
/// Join a voice channel of the configured server (leaving the current one) and post the notice.
/// Join a voice channel of the configured server (leaving the current one) and speak the notice.
pub async fn join(&self, channel_id: u64) -> Result<(), CoreError> {
let _guard = self.inner.voice_lock.lock().await;
let http = self.http()?.clone();
@@ -455,11 +507,8 @@ impl DiscordCore {
report_voice_state(&self.inner);
debug_log!("voice", "joined voice {channel_id}");
let _ = self.inner.events.send(CoreEvent::Joined { guild_id: gc.guild_id.get(), channel_id, session });
let notice = CreateMessage::new().content(&self.inner.settings.voice.join_notice)
.allowed_mentions(CreateAllowedMentions::new());
if let Err(e) = gc.id.send_message(&http, notice).await {
error_log!("voice", "could not post the transcription notice in {channel_id}: {e}");
}
self.inner.notice.lock().unwrap().joined();
speak_notice(&self.inner);
Ok(())
}
@@ -736,6 +785,12 @@ fn with_playback<T>(inner: &Inner, f: impl FnOnce(&mut Playback<WorkerClient, Pl
if let Some(tx) = inner.speech_waits.lock().unwrap().remove(&end.id) {
let _ = tx.send(end.clone());
}
match inner.notice.lock().unwrap().ended(end) {
Some(true) => { debug_log!("voice", "transcription notice spoken id={} played={}", end.id, end.played); }
Some(false) => { error_log!("voice", "could not speak the transcription notice; it is spoken when \
the voice worker is next ready"); }
None => {}
}
}
let _ = inner.events.send(match e {
PlaybackEvent::Start(id) => CoreEvent::SpeakStart(id),
@@ -753,6 +808,7 @@ async fn end_session(inner: &Arc<Inner>, s: Session, reason: &str, disconnect: b
inner.utt_sessions.lock().unwrap().clear();
let _ = inner.events.send(CoreEvent::Stopped);
with_playback(inner, |p| p.stop());
inner.notice.lock().unwrap().left();
let _ = inner.player.send(PlayerCmd::SetCall(None));
let (heard, lost, late, bad) = {
let mut rx = s.rx.lock().unwrap();
@@ -898,6 +954,7 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
WorkerEvent::Ready(_) => {
report_chat_channels(&inner);
report_voice_state(&inner);
speak_notice(&inner);
}
WorkerEvent::ChatAction(a) => {
let core = DiscordCore { inner: inner.clone() };
@@ -1350,6 +1407,41 @@ mod tests {
assert!(!with_playback(&core.inner, |p| p.busy()), "nothing is left in the queue");
}
fn end(id: &str, played: u32, cancelled: bool, failed: bool) -> PlaybackEnd {
PlaybackEnd { id: id.into(), played, cancelled, failed }
}
#[test]
fn the_notice_is_owed_from_each_join_until_it_was_heard() {
let mut n = super::JoinNotice::default();
assert!(!n.due(), "nothing is owed outside a voice channel");
n.joined();
assert!(n.due());
n.queued("r1".into());
assert!(!n.due(), "queued once, not twice");
assert_eq!(n.ended(&end("r2", 1, false, false)), None, "other speech does not settle it");
assert_eq!(n.ended(&end("r1", 2, false, false)), Some(true));
assert!(!n.due(), "heard: not spoken again, also after a worker restart");
n.joined();
assert!(n.due(), "every join owes it again");
}
#[test]
fn a_notice_the_worker_could_not_speak_stays_owed() {
let mut n = super::JoinNotice::default();
n.joined();
n.queued("r1".into());
assert_eq!(n.ended(&end("r1", 0, false, true)), Some(false));
assert!(n.due(), "spoken when the worker is next ready");
// Someone stopped it: they were in the channel when it started, it is not forced on them again.
n.queued("r2".into());
assert_eq!(n.ended(&end("r2", 0, true, false)), Some(true));
assert!(!n.due());
n.joined();
n.left();
assert!(!n.due(), "leaving drops it");
}
#[test]
fn an_utterance_keeps_the_session_it_started_in() {
let mut u = super::UttSessions::default();