// 追進度 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, and the call as it will be /// done (its computer written in). Err: refused — never registered. /// /// The check runs again and again with nobody watching, so it runs only on the bot's own /// computer (another machine is reached from there, by SSH or curl): never on the person's /// computers, where `shell` has more doors than one decision (在這台電腦上執行, its admin /// lock, the steps asked every time). The computer is decided now and kept — the bot's /// chosen computer changing later doesn't move it. Then: as `shell` there would decide it, /// and the person's PreToolUse hooks; a turn from someone other than the person can't. pub(super) fn followup_ask(&self, bot_id: u64, args: &str) -> Result<(Option, String), String> { let mut v: serde_json::Value = serde_json::from_str(args).unwrap_or(serde_json::Value::Null); if followup::action_of(&v) != followup::Action::Register { return Ok((None, args.to_string())); } if self.strangers.contains(&bot_id) { return Err("這則訊息是別人傳來的(訊息管道或團隊成員):不能登記追進度。".into()); } let Some(b) = self.state.bot(bot_id) else { return Err("找不到這個 Bot".into()) }; let targets = self.targets_for(b); let roles = self.roles_for(b, &targets); let own = roles.own.clone(); let named = v["computer"].as_str().unwrap_or("").trim().to_string(); if !named.is_empty() && named != own { return Err(format!("追進度的檢查只在你自己的電腦「{own}」上跑(它會無人看著一再執行)。要看別台的進度,從「{own}」用 SSH 或 curl 看,computer 留空。")); } let Some(target) = targets.into_iter().find(|t| t.name == own) else { return Err(format!("你自己的電腦「{own}」現在不能用,沒辦法登記追進度。")); }; let check = v["check"].as_str().unwrap_or("").trim().to_string(); let every = v["every_secs"].as_u64().unwrap_or(followup::DEFAULT_EVERY_SECS).clamp(followup::MIN_EVERY_SECS, followup::MAX_EVERY_SECS); let shell_args = serde_json::json!({"command": check}).to_string(); // The person's own PreToolUse hooks, as for a shell step (a block refuses it). let hooks = crate::hooks::Hooks::load_for(bot_id); if !hooks.is_empty() { let mut input = crate::hooks::base(bot_id, &b.name); input["tool_name"] = serde_json::json!("shell"); input["tool_input"] = crate::hooks::tool_input(&shell_args); let said = hooks.fire("PreToolUse", Some("shell"), input); if let Some(why) = said.block.or_else(|| said.permission.filter(|(p, _)| p == "deny").map(|(_, w)| w)) { return Err(format!("被 hook 擋下:{why}")); } } v["computer"] = serde_json::json!(own); let args = v.to_string(); match tools::decide_on("shell", &shell_args, &target, &b.allow_rules) { tools::Decision::Allow => Ok((None, args)), tools::Decision::Ask { reason, .. } => Ok((Some(format!("追進度:之後每 {every} 秒會在「{own}」自動執行這個檢查(不再一次次問你),直到好了或停掉。\n{reason}")), args)), tools::Decision::Deny(why) => Err(format!("這個檢查指令不能用:{why}")), } } /// The computer a follow-up runs on (the one written in when it was registered). 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); // (One registered before the computer was written in: the bot's own.) let name = if named.trim().is_empty() { roles.own.clone() } else { named.trim().to_string() }; if name != roles.own { return Err(format!("追進度只在 Bot 自己的電腦上跑,「{name}」不是")); } 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::*; /// Registering is asked the way the call will be done, and only for the bot's own computer: /// a stranger's turn can't, another computer is refused, a null `stop` is a registration /// (asked like one), and the computer is written in now. #[test] fn registering_is_decided_as_it_will_be_done() { let ctx = egui::Context::default(); let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-followup-ask.png"))); let id = app.state.bots[0].id; let b = app.state.bot(id).unwrap().clone(); let own = app.roles_for(&b, &app.targets_for(&b)).own.clone(); let call = |extra: &str| format!(r#"{{"check":"ls","done_when":"x"{extra}}}"#); match app.followup_ask(id, &call(r#","stop":null"#)) { Ok((_, args)) => assert_eq!(serde_json::from_str::(&args).unwrap()["computer"], own.as_str(), "written in"), Err(e) => assert!(e.contains("不能用") || e.contains("現在不能用"), "{e}"), } let other = app.followup_ask(id, &call(r#","computer":"王性驊的Mac mini""#)).unwrap_err(); assert!(other.contains("只在你自己的電腦"), "{other}"); app.strangers.insert(id); assert!(app.followup_ask(id, &call("")).unwrap_err().contains("別人傳來的")); // Listing and stopping ask nothing (and change nothing to ask about). assert!(app.followup_ask(id, r#"{"list":true}"#).unwrap().0.is_none()); } /// 追進度 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("沒有在追")); } }