// 問同事 (ask_bot): one bot asks another and waits for the answer. The question goes into the // other bot's own chat (the person sees it, and that bot remembers it); that bot works on it with // its own model, soul, tools, memories and computers; when its turn ends, its last words go back // as the asking step's result and the asking bot goes on. Neither reads the other's chat: the // question carries what is needed, the answer carries only the final words (tokens stay small). // // What keeps it from going wrong: a request goes through at most MAX_HOPS bots from the person; // no one waits on a bot that (through others) waits on it (A asks B while B waits on A would hang // both forever); a busy bot answers when it's free, but not after ASK_WAIT; stopping the asker // stops the ones working for it. use std::sync::mpsc::Sender; use std::time::{Duration, Instant}; use eframe::egui; use super::App; use crate::appctl; use crate::model::{Message, Role, TurnOutcome}; use crate::providers::AppCall; /// How long a question waits for a busy bot to be free. pub(super) const ASK_WAIT: Duration = Duration::from_secs(10 * 60); /// The most of an answer handed back (the whole answer stays in the other bot's chat). const ANSWER_MAX_CHARS: usize = 12_000; /// A question one bot put to another, waiting for the answer. pub(super) struct Ask { /// The asking chat (a bot, or the group whose member asked) and the bot asked. pub from: u64, pub to: u64, pub reply: Sender<(String, bool)>, /// The question, as it goes into the other bot's chat. pub msg: Message, /// It went in, and that bot's turn is answering it. pub started: bool, pub since: Instant, } impl App { /// ask_bot from `conv`'s turn: refused at once when it can't be asked, otherwise kept until /// the other bot's turn ends (the step waits on `call.reply`). pub(super) fn ask_bot(&mut self, ctx: &egui::Context, conv: u64, call: AppCall) { match self.ask_of(conv, &call.args) { Err(e) => { let _ = call.reply.send((e, false)); } Ok((to, msg)) => { self.asks.push(Ask { from: conv, to, reply: call.reply, msg, started: false, since: Instant::now() }); self.tick_asks(ctx); } } } /// The question for the bot asked, or why it can't be asked. pub(super) fn ask_of(&self, conv: u64, args: &str) -> Result<(u64, Message), String> { let v: serde_json::Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).map_err(|_| "問題的格式看不懂".to_string())?; let who = v["bot"].as_str().map(str::trim).unwrap_or(""); let question = v["question"].as_str().or(v["text"].as_str()).map(str::trim).unwrap_or(""); if who.is_empty() { return Err("要指定問哪個 Bot".into()); } if question.is_empty() { return Err("要寫出問題".into()); } let me = self.speaking_bot(conv); let to = appctl::find_bot(&self.state, who).ok_or_else(|| format!("找不到叫「{who}」的 Bot(同事名冊裡有誰就問誰)"))?; if to.id == me || to.id == conv { return Err("不能問自己".into()); } if !to.members.is_empty() { return Err(format!("「{}」是群組,不能問:問裡面的成員", to.name)); } let hops = appctl::hops_of(&self.state, conv) + 1; if hops > appctl::MAX_HOPS { return Err(appctl::too_many_hops()); } if self.waits_on(to.id, conv) { return Err(format!("「{}」正在等你(它在等你回答,或在等別人、而那邊在等你)。互相等會兩邊都卡住:先用你手上有的做完,或把需要它的部分告訴使用者。", to.name)); } let name = self.state.bot(me).map(|b| b.name.clone()).unwrap_or_default(); let msg = Message { wake: true, asked: true, from_bot: me, hops, ..Message::user(&format!("[來自 Bot]「{name}」問你:{question}")) }; Ok((to.id, msg)) } /// Whether `who` waits, directly or through others, on `on` (who asked whom, started or not). fn waits_on(&self, who: u64, on: u64) -> bool { let mut seen = vec![who]; let mut i = 0; while i < seen.len() { let x = seen[i]; if x == on { return true; } for a in self.asks.iter().filter(|a| a.from == x) { if !seen.contains(&a.to) { seen.push(a.to); } } i += 1; } false } /// Questions to bots that are free now go in; ones that waited too long for a busy bot are /// answered as such. pub(super) fn tick_asks(&mut self, ctx: &egui::Context) { let mut i = 0; while i < self.asks.len() { let a = &self.asks[i]; if a.started { i += 1; continue; } let to = a.to; let name = self.state.bot(to).map(|b| b.name.clone()).unwrap_or_default(); if self.state.bot(to).is_none() { let a = self.asks.remove(i); let _ = a.reply.send(("沒問到:那個 Bot 已經不在了。".into(), false)); continue; } // One question at a time for each bot, and only when it isn't working on something. let busy = self.streams.contains_key(&to) || self.asks.iter().any(|x| x.started && x.to == to); if busy { if a.since.elapsed() > ASK_WAIT { let a = self.asks.remove(i); let _ = a.reply.send((format!("沒問到:「{name}」一直在忙({} 分鐘還沒空)。等一下再問,或用 message_bot 交給它、不等回覆。", ASK_WAIT.as_secs() / 60), false)); } else { i += 1; } continue; } let msg = self.asks[i].msg.clone(); self.asks[i].started = true; self.wake(ctx, to, msg); self.dirty = true; // It couldn't start (no key, no model…): what it said goes back. if !self.streams.contains_key(&to) { let a = self.asks.remove(i); let said = self.state.bot(to).and_then(|b| b.messages.last()).filter(|m| m.role == Role::Assistant).map(|m| m.text.clone()).unwrap_or_default(); let _ = a.reply.send((format!("沒問到:「{name}」沒辦法開始。{said}").trim().to_string(), false)); continue; } i += 1; } self.deliver_reports(); } /// The bot's turn ended: the question it was answering gets its answer. pub(super) fn ask_answered(&mut self, to: u64, outcome: TurnOutcome) { let Some(i) = self.asks.iter().position(|a| a.started && a.to == to) else { return }; let a = self.asks.remove(i); let _ = a.reply.send(self.answer_of(to, a.msg.at, outcome)); } /// What goes back: the last words of the turn that answered (the question at `at`), or why /// there aren't any. pub(super) fn answer_of(&self, to: u64, at: i64, outcome: TurnOutcome) -> (String, bool) { let Some(b) = self.state.bot(to) else { return ("沒問到:那個 Bot 已經不在了。".into(), false) }; let name = &b.name; let from = b.messages.iter().rposition(|m| (m.from_bot != 0 || m.asked) && m.role == Role::User && m.at == at).map(|i| i + 1).unwrap_or(b.messages.len()); let after = &b.messages[from..]; let last = after.iter().rev().find(|m| m.role == Role::Assistant && !m.note && !m.text.trim().is_empty()); let files: Vec<&str> = after.iter().flat_map(|m| m.attachments.iter()).map(|f| f.name.as_str()).collect(); match outcome { TurnOutcome::Success => { let Some(m) = last else { return (format!("「{name}」做完了,但沒有寫回答。"), true) }; let mut text: String = m.text.trim().chars().take(ANSWER_MAX_CHARS).collect(); if m.text.trim().chars().count() > ANSWER_MAX_CHARS { text.push_str(&format!("\n…(後面省略,完整的在「{name}」的聊天裡)")); } let mut out = format!("「{name}」的回答:\n{text}"); if !files.is_empty() { out.push_str(&format!("\n(它也在自己的聊天裡附了檔案:{})", files.join("、"))); } (out, true) } TurnOutcome::Cancelled => (format!("「{name}」被停止了,沒有答完。"), false), _ => { let why = last.map(|m| m.text.trim().chars().take(300).collect::()).unwrap_or_default(); (format!("「{name}」沒有答完:出錯了。{why}").trim().to_string(), false) } } } /// 交辦 (message_bot): a bot's turn that did work another chat handed it has ended. Its last /// words go back to that chat as its report — the person reads the result where they asked, /// instead of being told to go and look. (Once per hand-off; held while that chat works, so /// its running turn isn't cut into.) pub(super) fn report_handoff(&mut self, to: u64, outcome: TurnOutcome) { let Some(b) = self.state.bot(to) else { return }; let Some(q) = b.messages.iter().rev().find(|m| m.role == Role::User && !m.steer && !m.interrupted) else { return }; if q.from_bot == 0 || q.asked || !b.members.is_empty() || !self.reported.insert((to, q.at)) { return; } let (from, at) = (q.from_bot, q.at); let (said, ok) = self.answer_of(to, at, outcome); // (Its words as they are: the card says who it is.) let body = said.split_once('\n').filter(|_| ok).map(|(_, rest)| rest.to_string()).unwrap_or(said); let text = if ok { format!("交辦的事做完了:\n{body}") } else { format!("交辦的事沒有做完:{body}") }; let via = self.state.bot(to).map(|b| format!("{} · {}", b.provider.label(), b.model)).unwrap_or_default(); self.reports.push((from, Message { author: to, error: !ok, ..Message::assistant(&text, &via) })); } /// Reports for chats that are free now go in. pub(super) fn deliver_reports(&mut self) { let selected = self.state.selected; for (chat, m) in std::mem::take(&mut self.reports) { if self.streams.contains_key(&chat) { self.reports.push((chat, m)); continue; } if let Some(b) = self.state.bot_mut(chat) { b.messages.push(m); if chat != selected { b.unread = true; } self.dirty = true; } } } /// The asking chat stopped (or its turn ended): its questions are dropped, and the bots /// working on them stop too (and the ones working for those). pub(super) fn drop_asks_from(&mut self, conv: u64) -> Vec { let working: Vec = self.asks.iter().filter(|a| a.from == conv && a.started).map(|a| a.to).collect(); self.asks.retain(|a| a.from != conv); working } } #[cfg(test)] mod tests { use super::*; fn app() -> (egui::Context, App) { let ctx = egui::Context::default(); let app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-asks.png"))); (ctx, app) } #[test] fn a_question_says_why_it_cant_be_asked() { let (_ctx, mut app) = app(); let (a, b) = (app.state.bots[0].id, app.state.bots[1].id); let bname = app.state.bots[1].name.clone(); let err = |app: &App, args: serde_json::Value| app.ask_of(a, &args.to_string()).err().unwrap_or_default(); assert!(err(&app, serde_json::json!({"question": "?"})).contains("指定")); assert!(err(&app, serde_json::json!({"bot": bname})).contains("問題")); assert!(err(&app, serde_json::json!({"bot": "沒有這個", "question": "?"})).contains("找不到")); let me = app.state.bots[0].name.clone(); assert!(err(&app, serde_json::json!({"bot": me, "question": "?"})).contains("自己")); // A good one: into its chat as a question from the asker, one hop from the person. let (to, msg) = app.ask_of(a, &serde_json::json!({"bot": bname, "question": "FSD 最新進度?"}).to_string()).unwrap(); assert_eq!(to, b); assert!(msg.asked && msg.wake && msg.from_bot == a && msg.hops == 1, "{msg:?}"); assert!(msg.text.contains("問你:FSD 最新進度?") && msg.text.contains(&me)); // A request that already went through MAX_HOPS bots goes back to the person. app.state.bot_mut(a).unwrap().messages.push(Message { hops: appctl::MAX_HOPS, from_bot: b, wake: true, ..Message::user("轉了好幾手") }); assert!(err(&app, serde_json::json!({"bot": bname, "question": "?"})).contains("轉了")); } #[test] fn bots_never_wait_on_each_other_in_a_circle() { let (_ctx, mut app) = app(); let (a, b, c) = (app.state.bots[0].id, app.state.bots[1].id, app.state.bots[2].id); let (an, cn) = (app.state.bots[0].name.clone(), app.state.bots[2].name.clone()); let pending = |from: u64, to: u64, started: bool| Ask { from, to, reply: std::sync::mpsc::channel().0, msg: Message::user("?"), started, since: Instant::now() }; // A waits on B, B waits on C (not yet started: C is busy). app.asks.push(pending(a, b, true)); app.asks.push(pending(b, c, false)); // C can't ask A (A → B → C → A), nor B ask A back. assert!(app.ask_of(c, &serde_json::json!({"bot": an, "question": "?"}).to_string()).unwrap_err().contains("正在等你")); assert!(app.ask_of(b, &serde_json::json!({"bot": an, "question": "?"}).to_string()).unwrap_err().contains("正在等你")); // A can still ask C (it waits on B, not the other way round). assert!(app.ask_of(a, &serde_json::json!({"bot": cn, "question": "?"}).to_string()).is_ok()); // A stops: what it waited on goes, and B (working on its question) is to stop too. assert_eq!(app.drop_asks_from(a), vec![b]); assert!(app.asks.iter().all(|x| x.from != a)); } #[test] fn the_answer_is_the_last_words_after_the_question() { let (_ctx, mut app) = app(); let b = app.state.bots[1].id; let name = app.state.bots[1].name.clone(); let q = Message { asked: true, wake: true, from_bot: 1, at: 42, ..Message::user("[來自 Bot]「A」問你:幾點?") }; { let bot = app.state.bot_mut(b).unwrap(); bot.messages.push(Message::assistant("舊的回答", "")); bot.messages.push(q); bot.messages.push(Message::assistant("我查一下", "")); bot.messages.push(Message::tool_result("t1", "web_fetch", "…")); bot.messages.push(Message::assistant("三點", "")); } let (text, ok) = app.answer_of(b, 42, TurnOutcome::Success); assert!(ok && text == format!("「{name}」的回答:\n三點"), "{text}"); assert!(!app.answer_of(b, 42, TurnOutcome::Cancelled).1); assert!(app.answer_of(b, 42, TurnOutcome::Error).0.contains("出錯")); // Nothing said after the question: says so. app.state.bot_mut(b).unwrap().messages.push(Message { asked: true, at: 43, ..Message::user("再問") }); assert!(app.answer_of(b, 43, TurnOutcome::Success).0.contains("沒有寫回答")); // A long answer comes back cut, saying where the rest is. app.state.bot_mut(b).unwrap().messages.push(Message::assistant(&"長".repeat(ANSWER_MAX_CHARS + 10), "")); let (long, _) = app.answer_of(b, 43, TurnOutcome::Success); assert!(long.contains("後面省略") && long.chars().count() < ANSWER_MAX_CHARS + 100); } }