feat(chat): chatChannels tool for the registered Discord chat channels

- Tool (chat_channels.spec.md): list, read, search, send, edit, react,
  delete, pin, unpin. Offered only when the v2 brain gives the turn a chat
  backend, and then on every turn. Channel by ID, name, part of a name or a
  name inside the text; a message ID finds its channel; planner forms of the
  action ("send_message") work. Read and search results are fenced as
  untrusted data. delete only reports until called again with confirm=true
  in a later turn of the same person.
- Worker: chat_channels from the app, ChatBridge reads/searches the history
  store and sends chat_action, waiting for chat_action_result (15 s timeout,
  failed on session close); per-person reply turns and pending deletes.
- App: channel switches edit/react (on) and delete/pin (off); chat_channels
  sent on worker ready and after login; chat_action runs send, edit (own
  messages only), react, delete, pin, unpin and answers with ids or the error.
- Engine: chatChannels left out of the catalogue without a backend; the
  "router returned everything" check now tolerates that.
- live_discord: edit own, refuse editing the speaker's, react, pin (Discord
  refuses in a voice channel's chat, reported as an error), delete, refuse an
  unregistered channel; passed in 109.4 s.
- Eval (qwen2.5:7b, 3 runs): 10 of 12; never obeyed the "delete everything"
  message and never deleted in the same turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 14:01:33 +09:00
parent 3dbf1e8c56
commit fe4e296361
25 changed files with 1058 additions and 26 deletions

View File

@@ -187,7 +187,8 @@ async fn discord_voice_core_on_real_discord() {
// The "person" here is a bot, so bots must be heard.
"voice": {"listenToBots": true},
// The voice channel's own chat stands in for a registered chat channel.
"chatChannels": [{"id": voice.to_string(), "name": "테스트", "description": "라이브 테스트"}],
"chatChannels": [{"id": voice.to_string(), "name": "테스트", "description": "라이브 테스트",
"delete": true, "pin": true}],
})).unwrap();
let (core, mut core_rx) = DiscordCore::new(settings, bot_token.clone(), worker.clone(), worker_events);
let events: Arc<Mutex<Vec<CoreEvent>>> = Arc::default();
@@ -344,6 +345,44 @@ async fn discord_voice_core_on_real_discord() {
tokio::time::sleep(Duration::from_millis(500)).await;
assert!(!events.lock().unwrap().iter().any(|e| matches!(e, CoreEvent::Chat(c) if c.content == reply)));
// 5b. The chat tool's actions, as the worker asks for them: edit (own messages only), react, pin,
// unpin, delete; a switch that is off is refused.
let act = |action: &str, id: u64, text: Option<&str>, emoji: Option<&str>| jarvis_app::worker_client::ChatAction {
id: "live".into(), action: action.into(), channel: voice.to_string(), message_id: Some(id.to_string()),
text: text.map(Into::into), emoji: emoji.map(Into::into) };
let tool_msg = format!("자비스 도구 시험 {}", stop_at.elapsed().as_nanos());
let tid = core.send_chat(voice, &tool_msg).await.unwrap()[0];
let edited_tool = format!("{tool_msg} 수정");
core.chat_action(&act("edit", tid, Some(&edited_tool), None)).await.expect("edit own message");
let err = core.chat_action(&act("edit", marker_msg.id.get(), Some("남의 글"), None)).await.unwrap_err();
assert!(err.0.contains("own"), "{err}");
core.chat_action(&act("react", marker_msg.id.get(), None, Some("👍"))).await.expect("react");
// A voice channel's chat cannot pin (Discord answers "cannot be pinned in this channel"); the
// refusal must come back as an error the assistant can say, not a crash.
let pinned = core.chat_action(&act("pin", tid, None, None)).await;
let pin_report = match &pinned {
Ok(_) => "pinned".to_string(),
Err(e) => {
assert!(e.0.contains("pinned"), "unexpected pin error: {e}");
format!("refused by Discord: {}", e.0)
}
};
let fetched = ChannelId::new(voice).message(&s_http, serenity::all::MessageId::new(tid)).await.unwrap();
assert_eq!(fetched.content, edited_tool, "edit");
assert_eq!(fetched.pinned, pinned.is_ok(), "pin state");
let marked = ChannelId::new(voice).message(&s_http, marker_msg.id).await.unwrap();
assert!(marked.reactions.iter().any(|r| r.count >= 1), "no reaction");
if pinned.is_ok() {
core.chat_action(&act("unpin", tid, None, None)).await.expect("unpin");
}
core.chat_action(&act("delete", tid, None, None)).await.expect("delete");
tokio::time::sleep(Duration::from_millis(800)).await;
assert!(ChannelId::new(voice).message(&s_http, serenity::all::MessageId::new(tid)).await.is_err(), "not deleted");
let off = jarvis_app::worker_client::ChatAction { channel: voice2.to_string(), ..act("send", tid, Some("x"), None) };
assert!(core.chat_action(&off).await.unwrap_err().0.contains("not a registered"));
report.insert("chat_tool".into(), json!({"edit": true, "edit_others_refused": true, "react": true,
"pin": pin_report, "delete": true, "unregistered_refused": true}));
// 6. Moving to another channel and back: the old connection's shutdown must not end the new one.
for (to, what) in [(voice2, "the second channel"), (voice, "the first channel")] {
core.join(to).await.expect("move");
@@ -425,11 +464,12 @@ print(json.dumps({"voice": [[r.author_name, r.channel_id, r.text] for r in own i
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}");
assert!(voice_recs.iter().any(|r| r[1].as_str() == Some(voice.to_string().as_str())), "{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!(!jarvis_chat.iter().any(|t| t.contains(&tool_msg)), "the deleted tool message is still stored: {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}");

View File

@@ -6,7 +6,8 @@ use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use jarvis_app::frames::{encode_audio_frame, KIND_TTS};
use jarvis_app::playback::TtsBackend;
use jarvis_app::worker_client::{TtsDone, WorkerClient, WorkerClientOptions, WorkerEvent};
use jarvis_app::settings::ChatChannelSettings;
use jarvis_app::worker_client::{ChatAction, TtsDone, WorkerClient, WorkerClientOptions, WorkerEvent};
use serde_json::{json, Value};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
@@ -259,3 +260,29 @@ async fn history_messages_follow_the_worker_protocol() {
]);
c.close();
}
#[tokio::test]
async fn chat_channels_go_out_and_chat_actions_come_back_with_their_results() {
let w = FakeWorker::start(0).await;
let (c, mut rx) = client(&w.url(), json!({}));
c.start();
c.wait_ready(Duration::from_secs(2)).await.expect("ready");
c.chat_channels(Some(900), &[ChatChannelSettings { id: 5, name: "일정".into(), description: "약속".into(),
read: true, send: true, edit: true, react: true, delete: false, pin: false }]);
w.send(Message::text(json!({"type": "chat_action", "id": "a1", "action": "react", "channel": "5",
"message_id": "77", "emoji": "👍"}).to_string()));
let ev = next_matching(&mut rx, |e| matches!(e, WorkerEvent::ChatAction(_))).await;
assert_eq!(ev, WorkerEvent::ChatAction(ChatAction { id: "a1".into(), action: "react".into(), channel: "5".into(),
message_id: Some("77".into()), text: None, emoji: Some("👍".into()) }));
c.chat_action_result("a1", Ok(vec![77]));
c.chat_action_result("a2", Err("send is turned off".into()));
until(|| w.got().len() >= 4).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": "chat_channels", "bot": "900", "channels": [{"id": "5", "name": "일정", "description": "약속",
"read": true, "send": true, "edit": true, "react": true, "delete": false, "pin": false}]}),
json!({"type": "chat_action_result", "id": "a1", "ok": true, "message_ids": ["77"]}),
json!({"type": "chat_action_result", "id": "a2", "ok": false, "error": "send is turned off"}),
]);
c.close();
}