// 追進度 on the brain (followup.rs): each bot's follow-ups are checked when due, on the computer // they name, on threads of their own; what a check says becomes a progress line in the chat (no // model) or wakes the bot. A screen of a brain runs none: the brain's bots are the brain's. use super::*; use crate::followup::{self, Verdict}; impl App { /// Whether registering this follow-up asks the person first: as running its check with /// `shell` there would (Err: refused — never registered). Listing and stopping don't. pub(super) fn followup_ask(&self, bot_id: u64, args: &str) -> Result, String> { let v: serde_json::Value = serde_json::from_str(args).unwrap_or(serde_json::Value::Null); if v.get("list").is_some() || v.get("stop").is_some() { return Ok(None); } let check = v["check"].as_str().unwrap_or("").trim(); if check.is_empty() { return Ok(None); } let Some(b) = self.state.bot(bot_id) else { return Err("找不到這個 Bot".into()) }; let (target, name) = self.followup_target(b, v["computer"].as_str().unwrap_or(""))?; let every = v["every_secs"].as_u64().unwrap_or(followup::DEFAULT_EVERY_SECS).clamp(followup::MIN_EVERY_SECS, followup::MAX_EVERY_SECS); match tools::decide_on("shell", &serde_json::json!({"command": check}).to_string(), &target, &b.allow_rules) { tools::Decision::Allow => Ok(None), tools::Decision::Ask { reason, .. } => Ok(Some(format!("追進度:之後每 {every} 秒會在「{name}」自動執行這個檢查(不再一次次問你),直到好了或停掉。\n{reason}"))), tools::Decision::Deny(why) => Err(format!("這個檢查指令不能用:{why}")), } } /// The computer a follow-up runs on: the one it names, or the bot's chosen one. fn followup_target(&self, b: &Bot, named: &str) -> Result<(tools::Target, String), String> { let targets = self.targets_for(b); let roles = self.roles_for(b, &targets); let name = if named.trim().is_empty() { Self::chosen_computer(b, &targets, &roles).0 } else { named.trim().to_string() }; targets.into_iter().find(|t| t.name == name).map(|t| (t, name.clone())).ok_or_else(|| format!("「{name}」現在連不到")) } pub(super) fn followup_tick(&mut self, ctx: &egui::Context) { if self.mir.on { return; } let now = crate::model::now_ms(); let (mut notes, mut wakes) = (vec![], vec![]); for (bot, id, got) in followup::take_results() { let Some(b) = self.state.bot_mut(bot) else { continue }; let Some(i) = b.follow_ups.iter().position(|f| f.id == id) else { continue }; let mut f = b.follow_ups[i].clone(); let verdict = followup::judge(&mut f, got, now); match &verdict { Verdict::Wait => b.follow_ups[i] = f, Verdict::Progress(line) => { notes.push((bot, followup::progress_text(&f, line, now))); b.follow_ups[i] = f; } ended => { b.follow_ups.remove(i); if let Some(text) = followup::wake_text(&f, ended, now) { wakes.push((bot, text)); } } } self.dirty = true; } for (bot, text) in notes { self.goal_note(bot, &text); } for (bot, text) in wakes { log::info!("AnyBot:追進度叫醒 Bot {bot}:{}", text.lines().next().unwrap_or("")); self.wake(ctx, bot, Message { wake: true, ..Message::user(&text) }); } // The ones due now, each on a thread of its own; the window comes back at the next one. let mut soonest: Option = None; let all: Vec<(u64, followup::FollowUp)> = self.state.bots.iter().flat_map(|b| b.follow_ups.iter().map(move |f| (b.id, f.clone()))).collect(); for (bot, f) in all { if followup::is_running(bot, f.id) { continue; } if f.next_ms > now { soonest = Some(soonest.map_or(f.next_ms, |s: i64| s.min(f.next_ms))); continue; } let Some(b) = self.state.bot(bot) else { continue }; match self.followup_target(b, &f.computer) { Ok((target, _)) => followup::start_check(bot, &f, target, self.repaint_fn()), // (Out of reach now: counted like a failed check, at its own pace.) Err(e) => followup::push_result(bot, f.id, Err(e)), } } if let Some(at) = soonest { ctx.request_repaint_after(std::time::Duration::from_millis((at - now).max(1_000) as u64)); } } } #[cfg(test)] mod tests { use super::*; /// 追進度 end to end on the brain: registered by the tool, a check that moved on is one line /// in the chat (no model), and the one that says done wakes the bot with what to do next. #[test] fn a_follow_up_reports_and_wakes_its_bot_when_done() { let ctx = egui::Context::default(); let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-followup.png"))); let id = app.state.bots[0].id; let r = crate::appctl::apply(&mut app.state, id, crate::followup::TOOL, r#"{"what":"下載 Turbo","check":"du -sh /m","done_when":"DL_DONE","then":"跑第一張驗證圖"}"#); assert!(r.ok && r.text.contains("結束這一輪"), "{}", r.text); let f = app.state.bot(id).unwrap().follow_ups[0].clone(); // The bot is busy: a wake waits for its turn to end (no model in this test). app.streams.insert(id, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Default::default(), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 0 }); // Ten minutes later it moved on: a progress line, still followed. app.state.bot_mut(id).unwrap().follow_ups[0].reported_ms -= crate::followup::REPORT_EVERY_MS; followup::push_result(id, f.id, Ok("5.2G /m".into())); app.followup_tick(&ctx); let b = app.state.bot(id).unwrap(); assert_eq!(b.follow_ups.len(), 1); assert!(b.messages.iter().any(|m| m.note && m.text.contains("還在進行") && m.text.contains("5.2G")), "a progress line in the chat"); // Done: no longer followed, and the bot is woken with what it said it would do next. followup::push_result(id, f.id, Ok("14G /m\nDL_DONE".into())); app.followup_tick(&ctx); assert!(app.state.bot(id).unwrap().follow_ups.is_empty()); let woke = app.waiting_wakes.iter().find(|(b, _)| *b == id).map(|(_, m)| m.text.clone()).unwrap_or_default(); assert!(woke.contains("好了") && woke.contains("跑第一張驗證圖") && woke.contains("DL_DONE"), "{woke}"); // list and stop. let r = crate::appctl::apply(&mut app.state, id, crate::followup::TOOL, r#"{"list":true}"#); assert!(r.text.contains("沒有在追")); } }