AnyBot/src/app/followup_ui.rs

129 lines
7.1 KiB
Rust
Raw Normal View History

feat: 追進度、送 token 減量、首字等待依請求大小、摘要分段必成、換模型不掉東西 追進度(follow_up,src/followup.rs、src/app/followup_ui.rs) - Bot 啟動要等的事後登記檢查指令與 done_when(可選 fail_when、then),就結束這一輪;大腦定期在那台電腦上跑檢查(不叫模型) - 有進展時聊天記一行(最多每 10 分鐘);好了、失敗、15 分鐘沒變、超時、檢查連續失敗就叫醒 Bot 接著做 - 登記時檢查指令照 shell 規則審批一次(被擋的不登記);存在 Bot 身上,重開照樣追;只有大腦跑 - 系統指示:要等的事不要 sleep、不要說「我去盯」就結束;主動回報。說了就做的提醒也指向 follow_up 送 token 減量 - 收起的步驟,它的長參數(例如三千字 SSH 腳本)送給模型時也只留開頭(fold_called_args);估算同步 - 滾動收起:舊結果累積到可讀長度 15% 就整批收起,一批一次,快取只斷一次 模型怪怪的 - 第一個字的等待依請求大小(120 秒起,每多 1,000 token 多 2 秒,最多 10 分鐘),看門狗同步 - 等不到任何回應時不再原樣重送:先收小對話(收起結果、寫摘要)再問一次 壓縮 - 摘要分段寫(每段 40,000 字內,結果只帶 600 字),模型寫不出來時 AnyBot 本地整理一份,收縮一定成功 換模型 - 換過去的第一輪先收起舊結果;別的模型的思考區塊不送(會被拒);可讀長度改成每個模型各記(model_limits) feature-map:goal.md 新增 goal-followup(含步驟);chat.md 改寫 chat-compact、chat-stall;models.md 新增 models-switch。FEATURES.md 同步。 已驗證: cargo test 753 通過(新增 followup 5 項、a_follow_up_reports_and_wakes_its_bot_when_done、calls_of_set_aside_steps_go_shortened、old_results_are_set_aside_before_the_chat_is_full、a_long_stretch_is_summarized_in_pieces、a_summary_the_model_cant_write_is_written_here、a_switched_model_starts_from_a_lean_request、首字等待兩項),clippy 無新警告;verify-anybot:goal.md「追進度」(登記後同一輪結束,背景檢查看到 DL_DONE 把 Bot 叫回來,follow_ups 歸零)、chat.md「說了就做」「/ 指令」,ctl down 無殘留 未驗證: 手機頁面畫面(這台沒有 Google Chrome);真的自架模型的首字等待與收小重試(要真的慢模型);跨機器(SSH、帳號裡別台電腦)的檢查實跑;models.md「從手機換回來」步驟(要無頭 Chrome);新增 App 工具 follow_up 與其審批需實機測試+人類簽名,本輪不發佈 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:28:52 +00:00
// 追進度 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<Option<String>, 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<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::*;
/// 追進度 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("沒有在追"));
}
}