fix(app): a transcript belongs to the voice session its utterance started in

Each Joined carries a new session number; the core records, when an
utterance's speech_start arrives, the session Jarvis is in, and its Partial
and Final carry that number (Heard.session) even when they arrive after a
leave or a move. The dashboard shows only the current session's captions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-12 14:00:21 +09:00
parent 371e87f553
commit e8ddde5be6
6 changed files with 129 additions and 25 deletions

View File

@@ -39,6 +39,10 @@ pub struct Heard {
pub speaker_id: u64,
pub speaker_name: String,
pub utt: u32,
/// The voice session the utterance started in (the number its `Joined` carried); None when its
/// start was not seen in a session. A transcript belongs to the session its utterance started
/// in, even when it arrives after Jarvis left or moved on.
pub session: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -54,7 +58,8 @@ pub struct HeardFinal {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CoreEvent {
Ready { user_id: u64, tag: String },
Joined { guild_id: u64, channel_id: u64 },
/// Jarvis joined a voice channel; `session` numbers each voice session from 1.
Joined { guild_id: u64, channel_id: u64, session: u64 },
Left { guild_id: u64, channel_id: u64, reason: String },
SpeechStart(Heard),
/// The speaker stopped sending audio (their final is still to come).
@@ -191,6 +196,34 @@ struct Inner {
/// Serialises join and leave.
voice_lock: tokio::sync::Mutex<()>,
names: Mutex<HashMap<u64, String>>,
/// The latest voice session's number, and the session each utterance in progress started in.
voice_session: std::sync::atomic::AtomicU64,
utt_sessions: Mutex<UttSessions>,
}
/// The voice session each utterance in progress started in (`Heard::session`).
#[derive(Default)]
pub struct UttSessions(HashMap<(u64, u32), u64>);
impl UttSessions {
/// Utterance `(speaker, utt)` started; `current` is the session Jarvis is in (None: none).
pub fn started(&mut self, speaker: u64, utt: u32, current: Option<u64>) {
match current {
Some(s) => self.0.insert((speaker, utt), s),
None => self.0.remove(&(speaker, utt)),
};
}
pub fn session_of(&self, speaker: u64, utt: u32) -> Option<u64> {
self.0.get(&(speaker, utt)).copied()
}
/// Its final came: nothing more of it will.
pub fn finished(&mut self, speaker: u64, utt: u32) {
self.0.remove(&(speaker, utt));
}
/// The session ended or the worker restarted: no utterance in progress belongs to a session now.
pub fn clear(&mut self) {
self.0.clear();
}
}
/// Handle to the core; cheap to clone.
@@ -225,6 +258,8 @@ impl DiscordCore {
session: Mutex::new(None),
voice_lock: tokio::sync::Mutex::new(()),
names: Mutex::new(HashMap::new()),
voice_session: std::sync::atomic::AtomicU64::new(0),
utt_sessions: Mutex::new(UttSessions::default()),
});
tokio::spawn(player_task(Arc::downgrade(&inner), player_rx));
tokio::spawn(worker_task(Arc::downgrade(&inner), worker_events));
@@ -391,11 +426,13 @@ impl DiscordCore {
}
let alive = Arc::new(AtomicBool::new(true));
tokio::spawn(speaking_end_timer(Arc::downgrade(&self.inner), rx.clone(), alive.clone()));
// A new session number before any of its utterances can start.
let session = self.inner.voice_session.fetch_add(1, Ordering::SeqCst) + 1;
*self.inner.session.lock().unwrap() = Some(Session { guild_id: gc.guild_id.get(), channel_id, rx, alive });
let _ = self.inner.player.send(PlayerCmd::SetCall(Some(call)));
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 });
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 {
@@ -615,6 +652,8 @@ fn with_playback<T>(inner: &Inner, f: impl FnOnce(&mut Playback<WorkerClient, Pl
/// the connection and points it at the new channel instead).
async fn end_session(inner: &Arc<Inner>, s: Session, reason: &str, disconnect: bool) {
s.alive.store(false, Ordering::Relaxed);
// Utterances still in progress carry no session from here: their late transcripts belong to none.
inner.utt_sessions.lock().unwrap().clear();
let _ = inner.events.send(CoreEvent::Stopped);
with_playback(inner, |p| p.stop());
let _ = inner.player.send(PlayerCmd::SetCall(None));
@@ -693,7 +732,15 @@ fn name_of(inner: &Inner, user: u64) -> String {
fn heard(inner: &Inner, speaker: &str, utt: u32) -> Option<Heard> {
let id: u64 = speaker.parse().ok()?;
Some(Heard { speaker_id: id, speaker_name: name_of(inner, id), utt })
let session = inner.utt_sessions.lock().unwrap().session_of(id, utt);
Some(Heard { speaker_id: id, speaker_name: name_of(inner, id), utt, session })
}
/// An utterance started: it belongs to the session Jarvis is in now (none outside one).
fn utterance_started(inner: &Inner, speaker: &str, utt: u32) {
let Ok(id) = speaker.parse::<u64>() else { return };
let current = inner.session.lock().unwrap().is_some().then(|| inner.voice_session.load(Ordering::SeqCst));
inner.utt_sessions.lock().unwrap().started(id, utt, current);
}
fn to_chat(inner: &Inner, m: &Message) -> ChatMessage {
@@ -716,6 +763,7 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
let Some(inner) = core.upgrade() else { return };
match ev {
WorkerEvent::SpeechStart(m) => {
utterance_started(&inner, &m.speaker, m.utt);
if let Some(h) = heard(&inner, &m.speaker, m.utt) {
let _ = inner.events.send(CoreEvent::SpeechStart(h));
}
@@ -753,6 +801,8 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
});
}
WorkerEvent::Disconnected => {
// The restarted worker numbers utterances afresh: the old ones' sessions are void.
inner.utt_sessions.lock().unwrap().clear();
let _ = inner.events.send(CoreEvent::WorkerLost);
}
WorkerEvent::Error(_) => {}
@@ -763,7 +813,11 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
fn on_final(inner: &Inner, m: Final) {
debug_log!("voice", "final speaker={} utt={} reason={} chars={} audio_ms={} wait_ms={}", m.speaker, m.utt,
m.end_reason, m.text.chars().count(), m.audio_ms, m.wait_ms);
if let Some(h) = heard(inner, &m.speaker, m.utt) {
let h = heard(inner, &m.speaker, m.utt);
if let Ok(id) = m.speaker.parse::<u64>() {
inner.utt_sessions.lock().unwrap().finished(id, m.utt);
}
if let Some(h) = h {
let _ = inner.events.send(CoreEvent::Final(HeardFinal { heard: h, text: m.text, end_reason: m.end_reason,
audio_ms: m.audio_ms, wait_ms: m.wait_ms, stt_ms: m.stt_ms }));
}
@@ -1090,6 +1144,20 @@ impl Handler {
#[cfg(test)]
mod tests {
#[test]
fn an_utterance_keeps_the_session_it_started_in() {
let mut u = super::UttSessions::default();
u.started(11, 7, Some(1)); // in channel A
u.started(22, 1, None); // started outside a session
// Jarvis moves to B (session 2): A's utterance still belongs to session 1.
u.started(11, 8, Some(2));
assert_eq!((u.session_of(11, 7), u.session_of(11, 8), u.session_of(22, 1)), (Some(1), Some(2), None));
u.finished(11, 7);
assert_eq!(u.session_of(11, 7), None);
u.clear();
assert_eq!(u.session_of(11, 8), None);
}
use super::*;
#[tokio::test]