feat(voice_worker): record history from the app and answer reply requests with the brain

Worker (voice_worker.spec.md "History and brain"):
- --history <file> keeps the conversation history store; --brain hosts the
  jarvis reply engine (JarvisBrain, settings point ollama_base_url at /v1).
- voice_join / voice_leave / member_join / member_leave keep presence; the
  session end closes it. Non-empty finals are stored under the speaker's name
  in the current voice channel.
- chat_message / chat_edit / chat_delete keep registered chat channels.
- reply builds the asker's scoped history context, runs the brain on a thread
  (one at a time), answers reply_text, stores a voice answer, and with
  speak=true says it under the same id. memory settings in hello and
  memory_config. brain_unavailable without --brain.

App (discord_core.spec.md "History reporting"):
- WorkerClient sends the new messages; the core reports the voice channel
  and its heard members after a join, a move and every worker reconnect,
  member joins and leaves, voice_leave when a session ends, and every message
  of a readable registered channel (its own too, with `to` on replies), edits
  and deletes.
- live_discord runs the worker with --history and checks the store at the
  end: 8 finals under the speaker's name, the edited chat message only,
  Jarvis's own messages, 5 presence intervals, none left open (passed, 107.8 s).

Eval: history recall gains a chat-record case and fails a reply that reads a
record stamp out (field run with qwen2.5:7b did once in four).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 13:16:24 +09:00
parent 7a288129de
commit 864b2e7fdb
13 changed files with 775 additions and 18 deletions

View File

@@ -14,8 +14,8 @@ use serenity::all::{
Cache, ChannelId, ChannelType, Client, CommandDataOptionValue, CommandInteraction, CommandOptionType, Context,
CreateAllowedMentions, CreateCommand, CreateCommandOption, CreateInteractionResponse,
CreateInteractionResponseMessage, CreateMessage, EditInteractionResponse, EventHandler, GatewayIntents, GetMessages,
GuildId, Http, InstallationContext, Interaction, InteractionContext, Message, Ready, ShardManager, UserId,
VoiceState,
GuildId, Http, InstallationContext, Interaction, InteractionContext, Message, MessageId, MessageUpdateEvent, Ready,
ShardManager, UserId, VoiceState,
};
use songbird::driver::DecodeMode;
use songbird::input::Input;
@@ -359,6 +359,7 @@ impl DiscordCore {
tokio::spawn(speaking_end_timer(Arc::downgrade(&self.inner), rx.clone(), alive.clone()));
*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 notice = CreateMessage::new().content(&self.inner.settings.voice.join_notice)
@@ -477,6 +478,7 @@ async fn end_session(inner: &Arc<Inner>, s: Session, reason: &str, disconnect: b
inner.worker.speaker_leave(&user.to_string());
}
inner.gate.lock().unwrap().clear();
inner.worker.voice_leave();
if disconnect {
let _ = inner.songbird.remove(GuildId::new(s.guild_id)).await;
}
@@ -484,6 +486,27 @@ async fn end_session(inner: &Arc<Inner>, s: Session, reason: &str, disconnect: b
let _ = inner.events.send(CoreEvent::Left { guild_id: s.guild_id, channel_id: s.channel_id, reason: reason.into() });
}
/// Tell the worker which voice channel Jarvis is in and who is there, so the history store knows
/// who heard what. After a join, a move, and every (re)connection of the worker.
fn report_voice_state(inner: &Inner) {
let Some((guild, channel)) = inner.session.lock().unwrap().as_ref().map(|s| (s.guild_id, s.channel_id)) else {
return;
};
inner.worker.voice_join(channel);
let users: Vec<u64> = inner.cache.get()
.and_then(|c| c.guild(GuildId::new(guild)).map(|g| g.voice_states.values()
.filter(|v| v.channel_id.map(|c| c.get()) == Some(channel))
.map(|v| v.user_id.get())
.collect()))
.unwrap_or_default();
let mut n = 0;
for user in users.into_iter().filter(|u| should_hear(inner, *u)) {
inner.worker.member_join(user, &name_of(inner, user));
n += 1;
}
debug_log!("voice", "reported voice {channel} with {n} members to the worker");
}
fn should_hear(inner: &Inner, user: u64) -> bool {
if Some(user) == inner.bot_id.get().copied() {
return false;
@@ -551,7 +574,8 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
WorkerEvent::Final(m) => on_final(&inner, m),
WorkerEvent::TtsAudio { id, seq, pcm } => with_playback(&inner, |p| p.audio(&id, seq, pcm)),
WorkerEvent::TtsDone(d) => with_playback(&inner, |p| p.done(&d)),
WorkerEvent::Ready(_) | WorkerEvent::Disconnected | WorkerEvent::Error(_) => {}
WorkerEvent::Ready(_) => report_voice_state(&inner),
WorkerEvent::Disconnected | WorkerEvent::Error(_) => {}
}
}
}
@@ -756,23 +780,65 @@ impl EventHandler for Handler {
if let Some(s) = inner.session.lock().unwrap().as_mut() {
s.channel_id = c;
}
report_voice_state(inner);
}
return;
}
let was_here = old.and_then(|o| o.channel_id).map(|c| c.get()) == Some(session_channel);
if was_here && new_channel != Some(session_channel) {
let is_here = new_channel == Some(session_channel);
if was_here && !is_here {
Receiver { core: Arc::downgrade(inner), rx }.left(inner, user);
inner.worker.member_leave(user);
} else if is_here && !was_here && should_hear(inner, user) {
// Also fires for a mute or deafen when the old state was not cached; the worker keeps
// one open presence per person, so that is harmless.
inner.worker.member_join(user, &name_of(inner, user));
}
}
async fn message(&self, _: Context, m: Message) {
let inner = &self.core.inner;
let ch = m.channel_id.get();
if !self.core.chat_content() || !inner.chat.can_read(ch) || Some(m.author.id.get()) == self.core.bot_id() {
if !self.core.chat_content() || !inner.chat.can_read(ch) {
return;
}
let c = to_chat(inner, &m);
// The history keeps Jarvis's own messages too; a reply to someone's message is an answer to them.
let to = c.from_self.then(|| m.referenced_message.as_ref().map(|r| r.author.id.get())).flatten();
inner.worker.chat_message(c.channel_id, c.message_id, c.author_id, &c.author_name, &c.content,
m.timestamp.unix_timestamp() as f64, to);
if c.from_self {
return;
}
debug_log!("chat", "chat message in {ch} from {} chars={}", m.author.id, m.content.chars().count());
let _ = inner.events.send(CoreEvent::Chat(to_chat(inner, &m)));
let _ = inner.events.send(CoreEvent::Chat(c));
}
async fn message_update(&self, _: Context, _: Option<Message>, _: Option<Message>, e: MessageUpdateEvent) {
let ch = e.channel_id.get();
if !self.core.chat_content() || !self.core.inner.chat.can_read(ch) {
return;
}
if let Some(text) = &e.content {
debug_log!("chat", "chat message {} edited in {ch}", e.id);
self.core.inner.worker.chat_edit(ch, e.id.get(), text);
}
}
async fn message_delete(&self, _: Context, channel: ChannelId, id: MessageId, _: Option<GuildId>) {
if self.core.inner.chat.can_read(channel.get()) {
debug_log!("chat", "chat message {id} deleted in {channel}");
self.core.inner.worker.chat_delete(channel.get(), id.get());
}
}
async fn message_delete_bulk(&self, _: Context, channel: ChannelId, ids: Vec<MessageId>, _: Option<GuildId>) {
if self.core.inner.chat.can_read(channel.get()) {
debug_log!("chat", "{} chat messages deleted in {channel}", ids.len());
for id in ids {
self.core.inner.worker.chat_delete(channel.get(), id.get());
}
}
}
async fn interaction_create(&self, _: Context, interaction: Interaction) {

View File

@@ -91,6 +91,22 @@ are dropped (not queued), and every TTS request in flight ends as failed, so pla
request the worker refuses (`tts_unavailable`) also ends as failed. TTS audio for request ids the client
did not open is ignored.
### History reporting (M3)
The core tells the worker what its history store needs (`voice_worker.spec.md`, "History and brain"):
- `voice_join` with the channel after every join or move (also when someone else moves the bot), and
`member_join` with the display name for everyone already in the channel that the bot hears (people;
bots only with `voice.listenToBots`). Again whenever the worker link becomes ready, because messages
sent while disconnected are dropped.
- `member_join` / `member_leave` as heard people enter and leave the channel.
- `voice_leave` whenever a session ends (leave, move, disconnect).
- For every message in a readable registered channel, the bot's own included: `chat_message` with
Discord's time; on the bot's own message that replies to someone, `to` is that person. Edits
(`chat_edit`), deletes and bulk deletes (`chat_delete`) follow. Chat sent while the worker is
disconnected is not recorded.
- Finals are recorded by the worker itself; the core does not echo them.
## Voice
One voice session at a time, in the configured server. Joining another channel ends the current
@@ -175,14 +191,18 @@ registered until it is removed (M5 setup).
voice channel with the real worker on the GPU. It refuses to run if a person is in the channel or
either bot is already in a voice channel, and cleans up even when a step fails. It checks command
registration, transcription of recorded sentences played into the channel, speech the other bot
hears and the STT reads back, stop, chat events, history, sending without pings, moving to a second
hears and the STT reads back, stop, chat events, history, an edit and a delete, sending without pings, moving to a second
voice channel and back (the session survives each move and only the two moves end one), the speaker
leaving and coming back three times (each a DAVE group change), and leaving. It needs a second voice
leaving and coming back three times (each a DAVE group change), and leaving. The worker runs with
`--history`; at the end the store must hold the speaker's finals under its display name and channel,
its chat message with the edit and without the deleted one, Jarvis's own messages, a presence
interval per join, and no presence left open. It needs a second voice
channel of the server (`JARVIS_LIVE_VOICE_CHANNEL_2`) and refuses if a person is in either.
Measured on this server's RTX 5050 (2026-11-11): five sentences all heard (character error rate 0%
for three, 5% and 12.5% for two), 0.71-0.90 s from the end of speech to the final, Jarvis's speech
read back at 3.4-6.9%, sound gone 0.03-0.08 s after stop, and the sentence heard exactly after each
of three rejoins.
of three rejoins. With history (2026-11-11): 8 voice records under the speaker's name, the edited
chat message only, 3 of Jarvis's own messages, 5 presence intervals, none open.
## Known risks

View File

@@ -221,6 +221,48 @@ impl WorkerClient {
self.send_json(json!({"type": "speaker_leave", "speaker": speaker}));
}
// --- history (voice_worker.spec.md "History and brain"). Dropped while disconnected; the
// discord core sends the voice state again when the worker is ready. ----------------------
/// Jarvis is in (or moved to) this voice channel.
pub fn voice_join(&self, channel: u64) {
self.send_json(json!({"type": "voice_join", "channel": channel.to_string()}));
}
pub fn voice_leave(&self) {
self.send_json(json!({"type": "voice_leave"}));
}
pub fn member_join(&self, user: u64, name: &str) {
self.send_json(json!({"type": "member_join", "user": user.to_string(), "name": name}));
}
pub fn member_leave(&self, user: u64) {
self.send_json(json!({"type": "member_leave", "user": user.to_string()}));
}
/// A message of a registered chat channel. `to`: the user Jarvis answered, on its own messages.
#[allow(clippy::too_many_arguments)]
pub fn chat_message(&self, channel: u64, message: u64, author: u64, name: &str, text: &str, ts: f64,
to: Option<u64>) {
let mut v = json!({"type": "chat_message", "channel": channel.to_string(), "message_id": message.to_string(),
"author": author.to_string(), "name": name, "text": text, "ts": ts});
if let Some(to) = to {
v["to"] = Value::String(to.to_string());
}
self.send_json(v);
}
pub fn chat_edit(&self, channel: u64, message: u64, text: &str) {
self.send_json(json!({"type": "chat_edit", "channel": channel.to_string(), "message_id": message.to_string(),
"text": text}));
}
pub fn chat_delete(&self, channel: u64, message: u64) {
self.send_json(json!({"type": "chat_delete", "channel": channel.to_string(),
"message_id": message.to_string()}));
}
/// Change STT settings now and for every later connection.
pub fn configure(&self, changes: Map<String, Value>) {
self.inner.state.lock().unwrap().stt.extend(changes.clone());