196 lines
12 KiB
Rust
196 lines
12 KiB
Rust
// 追進度 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), String> {
|
||
// (Someone else's turn may not look at or stop the person's follow-ups either.)
|
||
if self.strangers.contains(&bot_id) {
|
||
return Err("這則訊息是別人傳來的(訊息管道或團隊成員):不能用追進度。".into());
|
||
}
|
||
let mut v: serde_json::Value = serde_json::from_str(args).unwrap_or(serde_json::Value::Null);
|
||
if !v.is_object() {
|
||
return Err("follow_up 的參數要是一個 JSON 物件".into());
|
||
}
|
||
if followup::action_of(&v) != followup::Action::Register {
|
||
return Ok((None, args.to_string()));
|
||
}
|
||
let Some(b) = self.state.bot(bot_id) else { return Err("找不到這個 Bot".into()) };
|
||
let named = v["computer"].as_str().unwrap_or("").trim().to_string();
|
||
let (target, name) = self.followup_target(b, &named)?;
|
||
let ssh = matches!(target.place, tools::Place::Ssh { .. });
|
||
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}"));
|
||
}
|
||
}
|
||
// Written in: an SSH machine by its name; the bot's own computer as empty (「its own」,
|
||
// whatever the bot is called later).
|
||
v["computer"] = serde_json::json!(if ssh { name.clone() } else { String::new() });
|
||
let args = v.to_string();
|
||
let card = |reason: &str| format!("追進度:之後每 {every} 秒會在「{name}」自動執行這個檢查(不再一次次問你),直到好了或停掉。{reason}");
|
||
match tools::decide_on("shell", &shell_args, &target, &b.allow_rules) {
|
||
// (Another machine is the person's: asked every time it is registered.)
|
||
tools::Decision::Allow if ssh => Ok((Some(card("")), args)),
|
||
tools::Decision::Allow => Ok((None, args)),
|
||
tools::Decision::Ask { reason, .. } => Ok((Some(card(&format!("\n{reason}"))), args)),
|
||
tools::Decision::Deny(why) => Err(format!("這個檢查指令不能用:{why}")),
|
||
}
|
||
}
|
||
|
||
/// The computer a follow-up runs on: the bot's own (empty, or its name), or an SSH machine
|
||
/// it names — never the person's computers (this one, the account's others), where `shell`
|
||
/// has more doors than one decision (在這台電腦上執行, its admin lock, the steps asked every
|
||
/// time) and the check would run again and again with nobody watching.
|
||
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 own = roles.own.clone();
|
||
let name = if named.trim().is_empty() { own.clone() } else { named.trim().to_string() };
|
||
let Some(t) = targets.into_iter().find(|t| t.name == name) else {
|
||
return Err(format!("「{name}」現在連不到"));
|
||
};
|
||
if name != own && !matches!(t.place, tools::Place::Ssh { .. }) {
|
||
return Err(format!("追進度的檢查只在你自己的電腦「{own}」或 SSH 主機上跑(它會無人看著一再執行),「{name}」是使用者的電腦。要看那裡的進度,從「{own}」用 SSH 或 curl 看,computer 留空。"));
|
||
}
|
||
Ok((t, 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<i64> = 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 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::<serde_json::Value>(&args).unwrap()["computer"], "", "its own computer, as 「its own」"),
|
||
Err(e) => assert!(e.contains("連不到"), "{e}"),
|
||
}
|
||
let this = crate::model::THIS_COMPUTER_NAME;
|
||
let other = app.followup_ask(id, &call(&format!(r#","computer":"{this}""#))).unwrap_err();
|
||
assert!(other.contains("使用者的電腦") || other.contains("連不到"), "{other}");
|
||
// Not an object (a model that sent its arguments as a string): refused, never a panic.
|
||
assert!(app.followup_ask(id, r#""{\"check\":\"ls\"}""#).unwrap_err().contains("JSON 物件"));
|
||
// Listing and stopping ask nothing (and change nothing to ask about).
|
||
assert!(app.followup_ask(id, r#"{"list":true}"#).unwrap().0.is_none());
|
||
app.strangers.insert(id);
|
||
assert!(app.followup_ask(id, &call("")).unwrap_err().contains("別人傳來的"));
|
||
assert!(app.followup_ask(id, r#"{"list":true}"#).is_err(), "someone else can't look at them either");
|
||
}
|
||
|
||
/// 追進度 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("沒有在追"));
|
||
}
|
||
}
|