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:
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -163,9 +163,12 @@ async fn discord_voice_core_on_real_discord() {
|
||||
}
|
||||
|
||||
// The real voice worker.
|
||||
let mut args = vec![];
|
||||
// A fresh history store: the worker records what this test says and who was there.
|
||||
let history_db = Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("live-history-{}.sqlite", std::process::id()));
|
||||
let _ = std::fs::remove_file(&history_db);
|
||||
let mut args = vec!["--history".to_string(), history_db.to_string_lossy().into_owned()];
|
||||
if let Ok(m) = std::env::var("JARVIS_MELO_PYTHON") {
|
||||
args = vec!["--melo-python".to_string(), m];
|
||||
args.extend(["--melo-python".to_string(), m]);
|
||||
}
|
||||
let wp = WorkerProcess::new(WorkerProcessOptions::new(env("JARVIS_VOICE_PYTHON"), root.join("../src"), args)).unwrap();
|
||||
let mut pev = wp.subscribe();
|
||||
@@ -325,6 +328,14 @@ async fn discord_voice_core_on_real_discord() {
|
||||
let history = core.read_chat(voice, 20).await.unwrap();
|
||||
assert!(history.iter().any(|m| m.content == marker && !m.from_self));
|
||||
assert!(history.iter().any(|m| m.from_self && m.content.contains("받아 적습니다")), "join notice missing");
|
||||
// An edit and a delete reach the history store.
|
||||
let mut marker_msg = ChannelId::new(voice).messages(&s_http, serenity::all::GetMessages::new().limit(5)).await.unwrap()
|
||||
.into_iter().find(|m| m.content == marker).unwrap();
|
||||
let edited = format!("{marker} 수정");
|
||||
marker_msg.edit(&s_http, serenity::all::EditMessage::new().content(&edited)).await.unwrap();
|
||||
let doomed = ChannelId::new(voice).send_message(&s_http, CreateMessage::new().content("곧 지울 메시지")).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(800)).await;
|
||||
doomed.delete(&s_http).await.unwrap();
|
||||
let reply = format!("자비스 답장 @everyone {}", stop_at.elapsed().as_nanos());
|
||||
let ids = core.send_chat(voice, &reply).await.unwrap();
|
||||
let sent = ChannelId::new(voice).message(&s_http, serenity::all::MessageId::new(ids[0])).await.unwrap();
|
||||
@@ -387,6 +398,41 @@ async fn discord_voice_core_on_real_discord() {
|
||||
assert_eq!(core.voice_channel_id(), None);
|
||||
assert!(core.say("아무도 못 듣는 말", false).is_none());
|
||||
|
||||
// 9. The history store: the speaker's finals under its name, its chat with the edit and without
|
||||
// the deleted message, Jarvis's own messages, and presence closed now that Jarvis left.
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
let check = r#"
|
||||
import json, sys
|
||||
from jarvis.memory.history import HistoryStore
|
||||
s = HistoryStore(sys.argv[1]); sp, jv = sys.argv[2], sys.argv[3]
|
||||
own = s.records_of(sp)
|
||||
q = lambda sql, *a: s._conn.execute(sql, a).fetchone()[0]
|
||||
print(json.dumps({"voice": [[r.author_name, r.channel_id, r.text] for r in own if r.kind == "voice"],
|
||||
"chat": [r.text for r in own if r.kind == "chat"], "jarvis_chat": [r.text for r in s.records_of(jv) if r.kind == "chat"],
|
||||
"presence": q("select count(*) from presence where user_id = ?", sp), "open": q("select count(*) from presence where left_at is null")},
|
||||
ensure_ascii=False))
|
||||
"#;
|
||||
let out = std::process::Command::new(env("JARVIS_VOICE_PYTHON")).current_dir(root.join("../src"))
|
||||
.args(["-c", check, &history_db.to_string_lossy(), &speaker_id.to_string(), &jarvis.to_string()])
|
||||
.output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let h: Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
let voice_recs = h["voice"].as_array().unwrap();
|
||||
let speaker_name = s_cache.user(UserId::new(speaker_id)).map(|u| u.display_name().to_owned()).unwrap_or_default();
|
||||
report.insert("history".into(), json!({"voice_records": voice_recs.len(), "presence_intervals": h["presence"],
|
||||
"open_presence": h["open"], "chat": h["chat"], "jarvis_chat": h["jarvis_chat"].as_array().map(|a| a.len())}));
|
||||
assert!(voice_recs.len() >= 8, "finals not stored: {h}");
|
||||
assert!(voice_recs.iter().all(|r| r[0].as_str() != Some(&speaker_id.to_string()) && !r[2].as_str().unwrap().is_empty()),
|
||||
"a final without the speaker's name: {h}");
|
||||
assert!(voice_recs.iter().any(|r| r[0].as_str() == Some(speaker_name.as_str())), "{speaker_name} not in {h}");
|
||||
assert!(voice_recs.iter().any(|r| r[1] == voice.to_string()), "{h}");
|
||||
let chat: Vec<&str> = h["chat"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect();
|
||||
assert_eq!(chat, [edited.as_str()], "speaker chat in the history");
|
||||
let jarvis_chat: Vec<&str> = h["jarvis_chat"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect();
|
||||
assert!(jarvis_chat.contains(&reply.as_str()) && jarvis_chat.iter().any(|t| t.contains("받아 적습니다")), "{h}");
|
||||
assert!(h["presence"].as_u64().unwrap() >= 4, "joins and rejoins open presence: {h}");
|
||||
assert_eq!(h["open"], 0, "presence left open after Jarvis left: {h}");
|
||||
|
||||
println!("live report {}", serde_json::to_string_pretty(&Value::Object(report.clone())).unwrap());
|
||||
})).await;
|
||||
|
||||
|
||||
@@ -228,3 +228,34 @@ async fn tts_while_disconnected_fails_at_once() {
|
||||
let e = next_matching(&mut rx, |_| true).await;
|
||||
assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r1".into(), chunks: 0, cancelled: false, failed: true }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn history_messages_follow_the_worker_protocol() {
|
||||
let w = FakeWorker::start(0).await;
|
||||
let (c, _rx) = client(&w.url(), json!({}));
|
||||
c.start();
|
||||
c.wait_ready(Duration::from_secs(2)).await.expect("ready");
|
||||
c.voice_join(42);
|
||||
c.member_join(7, "Alice");
|
||||
c.member_leave(7);
|
||||
c.chat_message(9, 100, 7, "Alice", "hi there", 1_800_000_000.5, None);
|
||||
c.chat_message(9, 101, 1, "Jarvis", "hello", 1_800_000_001.0, Some(7));
|
||||
c.chat_edit(9, 100, "hi, edited");
|
||||
c.chat_delete(9, 100);
|
||||
c.voice_leave();
|
||||
until(|| w.got().len() >= 9).await;
|
||||
let got: Vec<Value> = w.got()[1..].iter().map(|g| match g { Got::Json(v) => v.clone(), Got::Bin(_) => json!(null) }).collect();
|
||||
assert_eq!(got, vec![
|
||||
json!({"type": "voice_join", "channel": "42"}),
|
||||
json!({"type": "member_join", "user": "7", "name": "Alice"}),
|
||||
json!({"type": "member_leave", "user": "7"}),
|
||||
json!({"type": "chat_message", "channel": "9", "message_id": "100", "author": "7", "name": "Alice",
|
||||
"text": "hi there", "ts": 1_800_000_000.5}),
|
||||
json!({"type": "chat_message", "channel": "9", "message_id": "101", "author": "1", "name": "Jarvis",
|
||||
"text": "hello", "ts": 1_800_000_001.0, "to": "7"}),
|
||||
json!({"type": "chat_edit", "channel": "9", "message_id": "100", "text": "hi, edited"}),
|
||||
json!({"type": "chat_delete", "channel": "9", "message_id": "100"}),
|
||||
json!({"type": "voice_leave"}),
|
||||
]);
|
||||
c.close();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user