diff --git a/mobile/index.html b/mobile/index.html index cb2e60c..ceee003 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1948,7 +1948,7 @@ async function editInstructions(b, d) { // ---------- 例行任務 ---------- function routineSheet(b, r) { if (!r) return; - const html = `
${esc(r.title)}
${esc(r.trigger ? "事件觸發:" + r.trigger : r.repeat)} · ${esc(r.when)}${r.last ? " · 上次 " + esc(r.last) : ""}
${r.status ? `
${esc(r.status)}
` : ""}
${esc(r.prompt)}
`; + const html = `
${esc(r.title)}
${esc(r.trigger ? "事件觸發:" + r.trigger : r.repeat)} · ${esc(r.when)}${r.last ? " · 上次 " + esc(r.last) : ""}
${r.status ? `
${esc(r.status)}
` : ""}${r.paused_why ? `
${esc(r.paused_why)}
` : ""}${(r.runs || []).length ? `${r.runs.map((x) => `
${esc(x.line)}
`).join("")}` : ""}
${esc(r.prompt)}
`; sheet("", !isOwner() ? [] : [ {icon: "play", label: "立即執行", on: () => app("run_routine_now", {id: r.id}, b.id, "已開始執行")}, {icon: r.paused ? "play" : "pause", label: r.paused ? "繼續" : "暫停", on: async () => { if (await app("update_routine", {id: r.id, paused: !r.paused}, b.id, r.paused ? "已繼續" : "已暫停")) refreshAfter(b); }}, diff --git a/src/agent.rs b/src/agent.rs index fde59b6..84b743e 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -296,6 +296,11 @@ fn learn(job: &Job, history: &[Message], cancel: &AtomicBool, send: &dyn Fn(Stre return; } }; + let issues = crate::memory::learned_issues(&out.text); + if !issues.is_empty() { + eprintln!("AnyBot:Bot 回報了 {} 個 AnyBot 自己的問題", issues.len()); + send(StreamEvent::Issues(issues)); + } match (crate::memory::learned_skill(&out.text), turn.last()) { (Some(mut k), Some(reply)) => { k.steps = crate::memory::replay_steps(turn, &crate::memory::learned_replay(&out.text)); @@ -985,6 +990,24 @@ fn maybe_compact(job: &Job, history: &mut Vec, percent: u64, cancel: &A Some(cut) } +/// Longest browser_wait after_send (a spacing of up to a quarter of an hour). +const AFTER_SEND_MAX_SECS: f64 = 900.0; + +/// browser_wait after_send: wait until `want` seconds have passed since `last` (this turn's last +/// send). What to tell the bot; None when it was stopped while waiting. +fn wait_after_send(last: Option, want: f64, cancel: &AtomicBool) -> Option { + let Some(t) = last else { return Some("這一輪還沒有送出過東西,不用等。".into()) }; + let left = want.clamp(0.0, AFTER_SEND_MAX_SECS) - t.elapsed().as_secs_f64(); + let until = Instant::now() + Duration::from_secs_f64(left.max(0.0)); + while Instant::now() < until { + if cancel.load(Ordering::Relaxed) { + return None; + } + std::thread::sleep(Duration::from_millis(50)); + } + Some(format!("距離上次送出已經 {} 秒{}。", t.elapsed().as_secs(), if left > 0.0 { format!("(等了 {} 秒)", left.ceil() as u64) } else { ",不用再等".to_string() })) +} + /// What the tools' descriptions take of every request (estimated like the rest). fn tools_tokens(tools: &[serde_json::Value]) -> u64 { tools.iter().map(|t| estimate_tokens(&t.to_string())).sum() @@ -1388,6 +1411,9 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< // Every step's (tool, failed, what it said) this turn: a tool that keeps failing the same // way, whatever it is given, is stopped (see same_failures). let runs: std::cell::RefCell> = Default::default(); + // When this turn last sent something out (evidence::sends): what browser_wait's + // after_send counts from, so posts keep the person's spacing without idle waiting. + let last_sent: std::cell::Cell> = std::cell::Cell::new(None); let mut local_on = job.local_execution; // 「允許一次」at a computer's own gates (電腦工具、在這台電腦上) holds for the rest of // this turn: a task that takes eight steps on the person's computer asks once, not eight @@ -1705,6 +1731,9 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< // (A safety rule's no counts as failing too: the same block again and again.) let failed = status == ToolStatus::Failed || (status == ToolStatus::Denied && output.starts_with("被安全規則擋下")); runs.borrow_mut().push((call.name.clone(), failed, output.chars().take(400).collect())); + if status == ToolStatus::Done && crate::evidence::sends(&call) { + last_sent.set(Some(Instant::now())); + } job.note(crate::oplog::Record::ToolFinished { op: job.op.clone(), call_id: call.id.clone(), status: format!("{status:?}").to_lowercase(), at: crate::model::now_ms() }); send(StreamEvent::ToolStatus(call.id.clone(), status)); let body = noted(&moved, &call.id, output); @@ -1804,6 +1833,16 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< finish(&mut history, &output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img); continue; } + // 間隔從送出算起: wait until `seconds` have passed since the last send — the next + // post is opened and typed first, then sent on time (instead of sleeping the whole + // interval after each send, then preparing). Stopping ends the wait. + if call.name == "browser_wait" && tools::args_of(&call.args)["after_send"].as_bool() == Some(true) { + started(); + let want = tools::args_of(&call.args)["seconds"].as_f64().unwrap_or(120.0); + let Some(said) = wait_after_send(last_sent.get(), want, &cancel) else { return }; + finish(&mut history, &said, ToolStatus::Done, None); + continue; + } // Public web pages need no computer and no permission. // …and neither does AnyBot's own browser (like the reference assistant's own browser). let at = web::is_web_tool(&call.name).then(|| browser_place(&job, &call.name, &call.args)); @@ -4306,6 +4345,26 @@ echo 'done送出了' > done.html; (setsid pyt assert_eq!(same_failures(&blocked(3), "browser"), SAME_FAILURES_STOP); } + #[test] + fn spacing_counts_from_the_last_send() { + let never = AtomicBool::new(false); + assert_eq!(wait_after_send(None, 120.0, &never).unwrap(), "這一輪還沒有送出過東西,不用等。"); + // Sent a while ago: no wait at all. + let long_ago = Instant::now() - Duration::from_secs(200); + let t0 = Instant::now(); + assert!(wait_after_send(Some(long_ago), 120.0, &never).unwrap().contains("不用再等")); + assert!(t0.elapsed() < Duration::from_millis(100)); + // Sent just now: only what is left of the spacing. + let just = Instant::now() - Duration::from_millis(700); + let t0 = Instant::now(); + let said = wait_after_send(Some(just), 1.0, &never).unwrap(); + assert!(t0.elapsed() >= Duration::from_millis(250) && t0.elapsed() < Duration::from_millis(700), "{:?}", t0.elapsed()); + assert!(said.contains("等了 1 秒"), "{said}"); + // Stopped while waiting. + let stop = AtomicBool::new(true); + assert!(wait_after_send(Some(Instant::now()), 60.0, &stop).is_none()); + } + #[test] fn a_desktop_that_cannot_name_the_app_still_offers_always() { // GNOME / KDE on Wayland: no app name, so the grant is the screen's (it used to be none, diff --git a/src/app.rs b/src/app.rs index acd77fc..425e7a7 100644 --- a/src/app.rs +++ b/src/app.rs @@ -389,7 +389,16 @@ impl App { vec![] } else { let found = crate::oplog::recover(&mut state); - if found.changed { + // 例行任務: a run AnyBot was closed during is kept as interrupted (the next run is + // told to check what was already done). + let mut cut = false; + for r in state.bots.iter_mut().flat_map(|b| b.routines.iter_mut()) { + if r.runs.iter().any(|x| x.outcome == crate::routines::RunOutcome::Running) { + r.mark_interrupted(); + cut = true; + } + } + if found.changed || cut { state.save(); } found.close() @@ -1865,6 +1874,7 @@ impl App { /// Record how a turn ended (success / cancelled / error) and clear its live state. fn settle(&mut self, bot_id: u64, outcome: TurnOutcome) { + self.note_routine_run(bot_id, outcome); // 問同事: the question this turn answered gets its answer; the ones it put to others are // over (it can't wait any more). self.ask_answered(bot_id, outcome); @@ -1946,14 +1956,43 @@ impl App { } let selected = self.state.selected; if let Some(b) = self.state.bot_mut(bot_id) { + let routine = msg.routine; b.messages.push(msg); if bot_id != selected { b.unread = true; } + // 例行任務: this run is on its record from now (its end is noted in settle). + if let Some(r) = b.routines.iter_mut().find(|r| routine != 0 && r.id == routine) { + r.run_started(crate::routines::now()); + } } self.start_reply(ctx, bot_id); } + /// 例行任務: the turn that just ended was a routine's run → its record; PAUSE_AFTER_FAILURES + /// failures in a row pause it, said in the chat and, when the person is away, as a notice. + fn note_routine_run(&mut self, bot_id: u64, outcome: TurnOutcome) { + let now = crate::routines::now(); + let paused = { + let Some(b) = self.state.bot_mut(bot_id) else { return }; + let Some(t) = crate::routines::turn_result(&b.messages, outcome) else { return }; + let Some(r) = b.routines.iter_mut().find(|r| r.id == t.routine) else { return }; + let paused = r.run_ended(now, t.outcome, &t.note, t.tally.steps, t.tally.failed, t.tally.sent).then(|| (r.title.clone(), r.paused_why.clone())); + if let Some((title, why)) = &paused { + b.messages.push(Message { note: true, at: crate::model::now_ms(), ..Message::assistant(&format!("例行任務「{title}」{why}。確認原因後,到例行任務設定按繼續。"), "") }); + b.unread = true; + } + paused.map(|(title, why)| (b.name.clone(), title, why)) + }; + self.dirty = true; + if let Some((name, title, why)) = paused { + if !self.headless && !self.demo { + notify::banner_with(&format!("{name} 的例行任務暫停了"), &format!("「{title}」{why}"), false); + } + crate::remote::notify(&format!("{name} 的例行任務暫停了"), &format!("「{title}」{why}"), bot_id); + } + } + /// Turns cut off by AnyBot stopping (found at start, chats already put right by /// oplog::recover): what happens to them next. The policy: nothing goes on by itself, not /// even a turn that was only looking. Each chat got a 「繼續」 card, and the turn goes on only @@ -1991,12 +2030,51 @@ impl App { } } + /// 園丁報告: the day's and the week's look at what went wrong and what costs too much, as a + /// line in the primary bot's chat — only when there is something to say (garden.rs). + fn tend_garden(&mut self) { + if !self.state.garden_reports || self.demo { + return; + } + let (now, tz) = (crate::routines::now(), crate::routines::person_tz()); + let daily = crate::garden::due(now, tz, crate::garden::DAILY_AT, false, self.state.garden_daily); + let weekly = crate::garden::due(now, tz, crate::garden::WEEKLY_AT, true, self.state.garden_weekly); + if daily.is_none() && weekly.is_none() { + return; + } + let mut said = vec![]; + { + let fleet: crate::garden::Fleet = self.state.bots.iter().map(|b| (b.name.as_str(), b.routines.as_slice())).collect(); + if daily.is_some() { + said.extend(crate::garden::daily_report(&fleet, &self.state.improvements, now - 86_400)); + } + if weekly.is_some() { + said.extend(crate::garden::weekly_report(&fleet, now - 7 * 86_400)); + } + } + if let Some(d) = daily { + self.state.garden_daily = d; + } + if let Some(w) = weekly { + self.state.garden_weekly = w; + } + self.dirty = true; + let primary = self.state.primary_bot; + if let Some(b) = self.state.bot_mut(primary) { + for text in said { + b.messages.push(Message { note: true, at: crate::model::now_ms(), ..Message::assistant(&text, "") }); + b.unread = true; + } + } + } + /// Run due routines (a routine firing is a "wake" turn). fn tick_routines(&mut self, ctx: &egui::Context) { if self.demo || self.last_tick.elapsed() < std::time::Duration::from_secs(1) { return; } self.last_tick = Instant::now(); + self.tend_garden(); self.resume_interrupted(ctx); let now = crate::routines::now(); let mut fire = vec![]; @@ -2479,6 +2557,14 @@ impl App { m.images.clear(); } } + // 待改進: AnyBot's own problems this bot ran into, queued for whoever fixes AnyBot. + StreamEvent::Issues(list) => { + let name = b.name.clone(); + let now = crate::routines::now(); + for i in &list { + crate::garden::note_issue(&mut self.state.improvements, i, &name, now); + } + } // The model said how much it reads: this bot summarizes in time from now on. StreamEvent::ContextLimit(n) => { b.context_tokens = n; @@ -3976,6 +4062,30 @@ impl App { } } + /// Settings → 更新: 待改進 — AnyBot's own problems the bots ran into (garden.rs), the ones + /// that keep coming back first. For whoever fixes AnyBot; the bots' skills stay clean of them. + fn improvements_section(&mut self, ui: &mut egui::Ui, p: Palette) { + if self.state.improvements.is_empty() { + return; + } + section(ui, "待改進", p); + hint(ui, "Bot 做事時遇到的 AnyBot 自身問題(工具出錯、要繞路才做得到)。重複出現的優先修;修好後可以清除。", p); + let mut items: Vec<&crate::garden::Improvement> = self.state.improvements.iter().collect(); + items.sort_by(|a, b| b.count.cmp(&a.count).then(b.last.cmp(&a.last))); + let tz = self.state.timezone.clone(); + for i in items { + let when = crate::routines::describe_when(i.last, &tz); + let color = if i.count >= crate::garden::RECURRING { p.attention } else { p.text2 }; + ui.label(RichText::new(format!("×{} {}", i.count, i.text)).size(12.5).color(color)); + ui.label(RichText::new(format!("{when} · {}", i.bots.join("、"))).size(11.0).color(p.text3)); + ui.add_space(4.0); + } + if ui.add(secondary_button("全部清除")).clicked() { + self.state.improvements.clear(); + self.dirty = true; + } + } + /// Settings → 電腦: AnyBot browser profiles (each with its own logins), switch / open / add. fn browser_profiles_section(&mut self, ui: &mut egui::Ui, p: Palette) { setting_title(ui, "AnyBot 瀏覽器設定檔", "每個設定檔是一個獨立的瀏覽器視窗,有自己的登入(例如工作和私人帳號)。Bot 會用「使用中」的那個,你也可以在聊天裡叫它換。", p); @@ -4113,6 +4223,24 @@ impl App { } } hint(ui, r.prompt.clone(), p); + // Why AnyBot paused it, and how its latest runs went (the newest first). + if r.paused && !r.paused_why.is_empty() { + ui.label(RichText::new(&r.paused_why).size(12.0).color(p.attention)); + } + if let Some(last) = r.runs.last() { + let color = match last.outcome { + crate::routines::RunOutcome::Failed | crate::routines::RunOutcome::Interrupted => p.attention, + _ => p.text3, + }; + ui.label(RichText::new(format!("{}{}", t("最近:"), crate::routines::describe_run(last, &r.schedule.timezone))).size(11.5).color(color)); + if r.runs.len() > 1 { + egui::CollapsingHeader::new(RichText::new(format!("{}({})", t("執行紀錄"), r.runs.len())).size(11.5).color(p.text3)).id_salt(("routine-runs", bot.id, r.id)).show(ui, |ui| { + for run in r.runs.iter().rev() { + ui.label(RichText::new(crate::routines::describe_run(run, &r.schedule.timezone)).size(11.5).color(p.text2)); + } + }); + } + } ui.add_space(4.0); ui.horizontal(|ui| { if ui.add(secondary_button(if r.paused { "繼續" } else { "暫停" })).clicked() { @@ -4141,6 +4269,8 @@ impl App { "toggle" => { if let Some(r) = b.routines.iter_mut().find(|r| r.id == id) { r.paused = !r.paused; + // (Going on: why AnyBot paused it is history now.) + r.paused_why.clear(); r.next_run = if r.trigger.is_some() { None } else { crate::routines::next_run(&r.schedule, r.created_at, now) }; } } @@ -4779,6 +4909,12 @@ impl App { } }); hint(ui, "螢幕鎖定或螢幕保護程式開著、10 分鐘沒動作、而且沒有 Bot 在工作時,才會自己換成新版本。", p); + setting_row(ui, p, "園丁報告", "平日早上有例行任務失敗或走冤枉路、週一有例行任務太耗時,就在主要 Bot 的聊天裡說一聲;沒事不說", |ui| { + if ui.add(egui::Checkbox::without_text(&mut self.state.garden_reports)).changed() { + self.dirty = true; + } + }); + self.improvements_section(ui, p); setting_row(ui, p, "重新啟動", "App 不太對勁時用:進行中的工作會停下,聊天記錄都會保留", |ui| { let label = if self.relaunching { "正在重新啟動…" } else { "重新啟動 AnyBot" }; if ui.add_enabled(!self.relaunching, secondary_button(label)).clicked() { @@ -6577,6 +6713,39 @@ fn dialog_footer(ui: &mut egui::Ui, p: Palette, body: impl FnOnce(&mut egui::Ui) #[cfg(test)] mod tests { + /// A routine's runs reach its record when its turns end, and two failures in a row pause it + /// with a line in the chat (the demo app: nothing read from or written to disk). + #[test] + fn a_routines_runs_are_kept_and_two_failures_pause_it() { + use super::*; + let ctx = egui::Context::default(); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-routine-runs-test.png"))); + let bot = app.state.bots.iter().find(|b| !b.routines.is_empty()).map(|b| b.id).expect("a sample routine"); + let run = |app: &mut App, ends: Message, outcome: TurnOutcome| { + let b = app.state.bot_mut(bot).unwrap(); + let r = b.routines[0].clone(); + b.messages.push(appctl::wake_message(&r)); + b.routines[0].run_started(crate::routines::now()); + b.messages.push(Message { tool_calls: vec![crate::model::ToolCall { id: "c".into(), name: "browser_click".into(), args: "{}".into(), status: crate::model::ToolStatus::Failed }], ..Message::assistant("", "") }); + b.messages.push(ends); + app.note_routine_run(bot, outcome); + }; + run(&mut app, Message::assistant("送出 15 則。", ""), TurnOutcome::Success); + run(&mut app, Message { error: true, ..Message::assistant("登入過期了", "") }, TurnOutcome::Error); + let r = &app.state.bot(bot).unwrap().routines[0]; + assert_eq!(r.runs.iter().map(|x| x.outcome).collect::>(), vec![crate::routines::RunOutcome::Succeeded, crate::routines::RunOutcome::Failed]); + assert_eq!((r.runs[1].steps, r.runs[1].failed_steps), (1, 1)); + assert!(!r.paused); + // The next run is told, fails again, and the routine pauses with a line saying why. + let next = appctl::wake_message(r); + assert!(next.text.contains("登入過期了")); + run(&mut app, Message { error: true, ..Message::assistant("登入過期了", "") }, TurnOutcome::Error); + let b = app.state.bot(bot).unwrap(); + assert!(b.routines[0].paused && b.routines[0].paused_why.contains("連續 2 次失敗")); + let said = b.messages.last().unwrap(); + assert!(said.note && said.text.contains("暫停") && said.text.contains("繼續"), "{}", said.text); + } + /// The model's cache holds only when what was sent last turn comes back word for word: the /// instructions don't change with the clock or the message, and each message of the person's /// reads the same (its time and memories come from what it keeps). diff --git a/src/app/goal_ui.rs b/src/app/goal_ui.rs index 5e6a4c2..bf6a0bb 100644 --- a/src/app/goal_ui.rs +++ b/src/app/goal_ui.rs @@ -172,7 +172,7 @@ impl App { "" => b.provider.quick_model(&b.model).map(String::from).unwrap_or_else(|| b.model.clone()), m => m.to_string(), }; - let req = ChatRequest { + let own = ChatRequest { kind: b.provider, base_url: providers::resolve_base(b.provider, &ps.base_url), api_key: providers::resolve_key_for(b.provider, &ps.api_key, &ps.base_url), @@ -183,20 +183,48 @@ impl App { session: format!("anybot-goal-{bot_id}"), effort: String::new(), }; + // A model of another family when the person has one: a bot's own model grades its own + // work too kindly (pstack's judges are from a different family). Its own, if that fails. + let mut tries: Vec = self.judge_elsewhere(b.provider).map(|(kind, base_url, api_key, model)| ChatRequest { kind, base_url, api_key, model, ..own.clone() }).into_iter().collect(); + tries.push(own); self.goal_checking.insert(bot_id); let (tx, ctx) = (self.tx.clone(), ctx.clone()); std::thread::spawn(move || { let cancel = AtomicBool::new(false); - let judged = match providers::run_step(&req, &cancel, &|_| {}) { - Ok(o) => goal::read_verdict(&o.text), - Err(e) => Judged::Failed(e), - }; + let mut judged = Judged::Failed("沒有可以檢查的模型".into()); + for req in &tries { + match providers::run_step(req, &cancel, &|_| {}) { + Ok(o) => { + judged = goal::read_verdict(&o.text); + break; + } + Err(e) => { + eprintln!("AnyBot:用 {} 檢查目標沒有回應:{e}", req.model); + judged = Judged::Failed(e); + } + } + } eprintln!("AnyBot:Bot {bot_id} 的目標檢查:{judged:?}"); let _ = tx.send((bot_id, 0, StreamEvent::Goal(g.since, judged))); ctx.request_repaint(); }); } + /// Another provider the person has set up, for judging a bot's goal: (kind, base url, key, + /// model). Not a local Ollama model (small ones judge poorly), not the bot's own provider. + fn judge_elsewhere(&self, own: ProviderKind) -> Option<(ProviderKind, String, String, String)> { + providers::ALL_PROVIDERS.into_iter().filter(|k| *k != own && *k != ProviderKind::Ollama).find_map(|kind| { + let ps = self.state.provider(kind); + let key = providers::resolve_key_for(kind, &ps.api_key, &ps.base_url); + let usable = if kind == ProviderKind::Custom { !ps.base_url.trim().is_empty() } else { !kind.needs_key() || !key.is_empty() }; + if !usable || (kind.needs_key() && key.is_empty()) { + return None; + } + let model = if ps.default_model.trim().is_empty() { kind.suggested_model().to_string() } else { ps.default_model.trim().to_string() }; + Some((kind, providers::resolve_base(kind, &ps.base_url), key, model)) + }) + } + /// The check has spoken: another turn, or a line saying it is over or paused. pub(super) fn goal_verdict(&mut self, ctx: &egui::Context, bot_id: u64, since: i64, judged: Judged) { self.goal_checking.remove(&bot_id); diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 01e0494..8c5ab2e 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -1670,6 +1670,8 @@ impl App { "schedule": serde_json::to_value(&r.schedule).unwrap_or_default(), "repeat": crate::routines::describe(&r.schedule), "trigger": r.trigger.as_ref().map(|t| t.describe()), "status": trig.get(&r.id).cloned(), "last": r.last_run.map(|t| crate::routines::describe_when(t, &r.schedule.timezone)), "computer": r.computer, + "paused_why": if r.paused { r.paused_why.clone() } else { String::new() }, + "runs": r.runs.iter().rev().take(5).map(|x| json!({"line": crate::routines::describe_run(x, &r.schedule.timezone), "bad": matches!(x.outcome, crate::routines::RunOutcome::Failed | crate::routines::RunOutcome::Interrupted)})).collect::>(), })).collect::>(), "threads": b.threads.iter().enumerate().rev().map(|(i, (title, msgs))| json!({"index": i, "title": title, "count": msgs.len(), "at": msgs.last().map(|m| m.at).unwrap_or(0)})).collect::>(), "files": files, diff --git a/src/appctl.rs b/src/appctl.rs index 5e19e14..5842866 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -287,6 +287,27 @@ pub fn routine_line(r: &Routine) -> String { format!("#{} 「{}」:{} · {}", r.id, r.title, routines::describe(&r.schedule), next) } +/// Runs shown by list_routines (newest first). +const RUNS_LISTED: usize = 5; + +/// A routine as list_routines tells it: its line, why AnyBot paused it, its latest runs. With no +/// record it says there is none to read — not that it never ran (runs before records were kept). +pub fn routine_report(r: &Routine) -> String { + let mut out = routine_line(r); + if r.paused && !r.paused_why.is_empty() { + out.push_str(&format!("\n 暫停原因:{}", r.paused_why)); + } + if r.runs.is_empty() { + out.push_str("\n 查不到執行紀錄(開始記錄之前的執行不會有)"); + } else { + out.push_str("\n 最近執行:"); + for run in r.runs.iter().rev().take(RUNS_LISTED) { + out.push_str(&format!("\n · {}", routines::describe_run(run, &r.schedule.timezone))); + } + } + out +} + /// A skill this bot just learned is one of its own; the others learn it when the person ticks /// it for them (Bot 設定 › 技能). Says who can use it now. fn learned(state: &mut State, bot_id: u64, name: &str) -> String { @@ -305,8 +326,17 @@ fn learned(state: &mut State, bot_id: u64, name: &str) -> String { /// A routine firing, as the message that wakes the bot. pub fn wake_message(r: &Routine) -> Message { // A new run starts fresh for the model (Message::fresh): what earlier runs found is in its - // pages and memories, not in re-reading every run before it. - Message { wake: true, fresh: true, ..Message::user(&format!("[例行任務]「{}」時間到了:{}", r.title, r.prompt)) } + // pages and memories, not in re-reading every run before it — except how the last one went + // wrong, so the same mistake isn't made again tomorrow (noodle's extra_prompt). + let mut text = format!("[例行任務]「{}」時間到了:{}", r.title, r.prompt); + match r.last_trouble() { + Some(t) if t.outcome == crate::routines::RunOutcome::Interrupted => { + text.push_str("\n\n(上一次執行做到一半就中斷了:AnyBot 被關掉。先確認哪些已經做過,不要重做一次。)"); + } + Some(t) => text.push_str(&format!("\n\n(上一次執行沒有成功:{}。這次先想好怎麼避開,再開始。)", t.note)), + None => {} + } + Message { wake: true, fresh: true, routine: r.id, ..Message::user(&text) } } pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome { @@ -341,7 +371,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome if b.routines.is_empty() { return ok("還沒有例行任務。".into()); } - ok(b.routines.iter().map(routine_line).collect::>().join("\n")) + ok(b.routines.iter().map(routine_report).collect::>().join("\n")) } "create_routine" => { let trigger = match v.get("trigger").filter(|t| !t.is_null()) { @@ -378,6 +408,8 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome last_run: None, computer: s("computer").unwrap_or_default(), trigger, + runs: vec![], + paused_why: String::new(), }; let line = routine_line(&r); match state.bot_mut(bot_id) { @@ -430,6 +462,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome } if let Some(p) = v.get("paused").and_then(Value::as_bool) { r.paused = p; + r.paused_why.clear(); } if let Some(t) = v.get("trigger") { if t.is_null() { @@ -845,6 +878,31 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome mod tests { use super::*; + #[test] + fn the_next_run_hears_how_the_last_one_went_and_the_bot_can_read_the_runs() { + use crate::routines::RunOutcome; + let mut st = State::samples(); + st.bots[0].routines.clear(); + let bot = st.bots[0].id; + let made = apply(&mut st, bot, "create_routine", r#"{"title":"貓咪海巡","prompt":"找 15 篇貼文","schedule":{"frequency":"daily","time":"17:00"}}"#); + assert!(made.ok, "{}", made.text); + let listed = apply(&mut st, bot, "list_routines", "{}").text; + assert!(listed.contains("查不到執行紀錄"), "never 「從未執行」: {listed}"); + let r = st.bot_mut(bot).unwrap().routines.last_mut().unwrap(); + let first = wake_message(r); + assert_eq!(first.routine, r.id); + assert!(!first.text.contains("上一次")); + r.run_started(100); + r.run_ended(200, RunOutcome::Failed, "找不到回覆框", 9, 4, 0); + let next = wake_message(r); + assert!(next.text.contains("上一次執行沒有成功:找不到回覆框"), "{}", next.text); + r.run_started(300); + r.mark_interrupted(); + assert!(wake_message(r).text.contains("先確認哪些已經做過")); + let listed = apply(&mut st, bot, "list_routines", "{}").text; + assert!(listed.contains("最近執行") && listed.contains("失敗") && listed.contains("中斷"), "{listed}"); + } + #[test] fn a_bot_reads_only_its_own_skills_and_keeps_what_it_learns() { let mut st = State::demo(); diff --git a/src/browser.rs b/src/browser.rs index 30a35e1..da29188 100644 --- a/src/browser.rs +++ b/src/browser.rs @@ -147,7 +147,11 @@ const ELEMENTS_JS: &str = r#"(() => { if (!el.matches('div,span,li,td,th,p,img,svg,i,label')) continue; if (getComputedStyle(el).cursor === 'pointer' && !(el.parentElement && getComputedStyle(el.parentElement).cursor === 'pointer')) set.add(el); } - all.forEach(e => e.hasAttribute('data-anybot-ref') && e.removeAttribute('data-anybot-ref')); + // Numbers stay with their control from one read to the next (a [17] read a minute ago is still + // the same reply box); new controls get the next numbers; ones not listed now lose theirs. + const prev = new Map(); for (const e of all) if (e.hasAttribute('data-anybot-ref')) prev.set(e, +e.getAttribute('data-anybot-ref')); + let next = Math.max(window.__anybotRefNext || 1, 1); for (const v of prev.values()) if (v + 1 > next) next = v + 1; + const used = new Set(); const listed = new Set(); const inView = el => { const r = el.getBoundingClientRect(); return r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth; }; const ordered = [...set].filter(el => vis(el) && !el.closest('[aria-hidden=true]')).sort((a, b) => order.get(a) - order.get(b)); const out = []; const seen = new Set(); let n = 0; @@ -185,10 +189,14 @@ const ELEMENTS_JS: &str = r#"(() => { const key = kind + '|' + text + '|' + extra; if (seen.has(key)) continue; seen.add(key); - n += 1; el.setAttribute('data-anybot-ref', String(n)); - out.push('[' + n + '] ' + kind + '「' + text + '」' + (extra ? ' ' + extra : '') + (inView(el) ? '' : ' (要捲動)')); + n += 1; + let num = prev.get(el); if (!num || used.has(num)) num = next++; + used.add(num); listed.add(el); el.setAttribute('data-anybot-ref', String(num)); + out.push('[' + num + '] ' + kind + '「' + text + '」' + (extra ? ' ' + extra : '') + (inView(el) ? '' : ' (要捲動)')); if (n >= %MAX%) break; } + for (const e of prev.keys()) if (!listed.has(e)) e.removeAttribute('data-anybot-ref'); + window.__anybotRefNext = next; return JSON.stringify({t: document.title, u: location.href, list: out, more: ordered.length > n}); })()"#; @@ -238,6 +246,53 @@ fn snapshot(tab: &mut Tab) -> (String, String, Vec) { (p["t"].as_str().unwrap_or("").into(), p["u"].as_str().unwrap_or("").into(), lines) } +/// The most of a field's text a typing step reports back. +const FIELD_SHOWN_CHARS: usize = 400; + +/// The focused field (through shadow roots), as `el`, for the scripts below. +const FOCUSED_JS: &str = "let el = document.activeElement; while (el && el.shadowRoot && el.shadowRoot.activeElement) el = el.shadowRoot.activeElement;"; + +/// What the focused field holds (an editor's lines too). +fn field_text(tab: &mut Tab) -> String { + let js = format!("(() => {{ {FOCUSED_JS} if (!el) return ''; return (el.isContentEditable ? el.innerText : (el.value !== undefined ? el.value : '')) || ''; }})()"); + tab.eval(&js).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default() +} + +/// Put text into the focused field in one go. Lines, or long text in Firefox (whose typing is a +/// key at a time), go in like a paste (an editor such as Threads' takes a paste event whole, line +/// breaks and all), else by the browser's own insertText — each checked by what the field holds +/// after it (Firefox hands an editor a paste event without its text). A post used to take four +/// steps for this (a file, the clipboard, a click, ctrl+v). Typed keys only when neither took. +fn insert_text(tab: &mut Tab, text: &str) -> Result<(), String> { + if text.contains('\n') || (tab.is_firefox() && text.chars().count() > 30) { + let t = serde_json::to_string(text).unwrap_or_default(); + let before = field_text(tab); + let paste = format!("(() => {{ {FOCUSED_JS} if (!el) return false; try {{ const dt = new DataTransfer(); dt.setData('text/plain', {t}); const ev = new ClipboardEvent('paste', {{clipboardData: dt, bubbles: true, cancelable: true, composed: true}}); return !el.dispatchEvent(ev); }} catch (e) {{ return false; }} }})()"); + if tab.eval(&paste)?.as_bool() == Some(true) { + // (An editor may put the text in a moment later.) + settle(150); + if field_text(tab) != before { + return Ok(()); + } + } + let exec = format!("(() => {{ {FOCUSED_JS} if (!el) return false; return document.execCommand('insertText', false, {t}); }})()"); + if tab.eval(&exec)?.as_bool() == Some(true) && field_text(tab) != before { + return Ok(()); + } + } + tab.call("Input.insertText", json!({"text": text})).map(|_| ()) +} + +/// How a step that changed nothing on the page is told. +const NO_CHANGE: &str = "頁面看起來沒有變化"; + +/// The text box the cursor is in now (its label, placeholder or first words), or "" when it isn't +/// in one. +fn focused_field(tab: &mut Tab) -> String { + const JS: &str = "(() => { let e = document.activeElement; while (e && e.shadowRoot && e.shadowRoot.activeElement) e = e.shadowRoot.activeElement; if (!e) return ''; const t = (e.type || '').toLowerCase(); const box = e.isContentEditable || e.tagName === 'TEXTAREA' || (e.tagName === 'INPUT' && !['button','submit','checkbox','radio','file','reset','image','hidden'].includes(t)); if (!box) return ''; const c = s => (s || '').replace(/\\s+/g, ' ').trim(); return (c(e.getAttribute('aria-label')) || c(e.getAttribute('placeholder')) || c(e.getAttribute('aria-placeholder')) || c(e.innerText) || '輸入框').slice(0, 40); })()"; + tab.eval(JS).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default() +} + /// What an action changed: the address, and the lines of text that are new. fn changes(before: &(String, String, Vec), after: &(String, String, Vec)) -> String { let mut out = vec![]; @@ -251,7 +306,7 @@ fn changes(before: &(String, String, Vec), after: &(String, String, Vec< let new: Vec<&String> = after.2.iter().filter(|l| !old.contains(l)).collect(); let gone = before.2.iter().filter(|l| !after.2.contains(l)).count(); if new.is_empty() && gone == 0 && before.1 == after.1 { - out.push("頁面看起來沒有變化(可能要等一下、換一個元素,或用 browser_screenshot 看看)。".into()); + out.push(format!("{NO_CHANGE}(可能要等一下、換一個元素,或用 browser_screenshot 看看)。")); } else if !new.is_empty() { let shown: Vec = new.iter().take(40).map(|l| l.chars().take(160).collect()).collect(); out.push(format!("新出現的文字:\n{}{}", shown.join("\n"), if new.len() > 40 { format!("\n…還有 {} 行(用 browser_read 看全部)", new.len() - 40) } else { String::new() })); @@ -312,7 +367,7 @@ fn locate(tab: &mut Tab, r#ref: &str, text: &str) -> Result<(f64, f64, String), ); let v = tab.eval(&js)?; let what = if !r#ref.trim().is_empty() { format!("[{}]", r#ref.trim().trim_matches(['[', ']'])) } else { format!("「{}」", text.trim()) }; - let p: Value = v.as_str().and_then(|s| serde_json::from_str(s).ok()).ok_or_else(|| format!("這一頁找不到 {what}。用 browser_read 或 browser_elements 看最新的清單(編號每次讀取會重排)。"))?; + let p: Value = v.as_str().and_then(|s| serde_json::from_str(s).ok()).ok_or_else(|| format!("這一頁找不到 {what}(可能已經不在頁面上,或換了一頁)。用 browser_read 或 browser_elements 看最新的清單。"))?; Ok((p["x"].as_f64().unwrap_or(0.0), p["y"].as_f64().unwrap_or(0.0), format!("{what}{}", if p["tag"] == "INPUT" && p["ro"] == true { "(唯讀欄位)" } else { "" }))) } @@ -552,11 +607,11 @@ actions: - screenshot {full, marks}: the page as a picture with numbered boxes on every control; needs no screen permission - click {ref|text, double, button}: real mouse click (menus, date pickers, dropdowns, calendar days); buying/paying/sending/deleting needs the person's OK first - hover {ref|text}: move over a control (opens hover menus) and report what appeared -- type {ref|text, value, append, submit}: real keystrokes into a field (clears first unless append). Never type passwords here: use fill +- type {ref|text, value, append, submit}: puts the text into a field (clears first unless append); line breaks in value go in whole, like a paste — no clipboard or ctrl+v needed. The result says what the field holds now: check it before sending. Never type passwords here: use fill - press {key}: Enter, Tab, Escape, ctrl+a, … (optionally on ref/text first) - select {ref|text, option}: choose a dropdown option (custom dropdowns included) - scroll {direction: down|up|top|bottom} (on ref/text brings it into view; loads endless lists) -- wait {text | seconds}: until text appears (≤20 s) or a few seconds +- wait {text | seconds, after_send}: until text appears (≤20 s) or a few seconds; with after_send: true, until `seconds` (up to 900) have passed since you last sent something — to space posts, open and type the next one first, then wait, then send - tabs {action: list|switch|new|close, index, url}: the tab strip - back {direction: back|forward|reload} - upload {ref|text, path}: put a file from this computer into a file chooser @@ -585,6 +640,7 @@ actions: "option": {"type": "string", "description": "select: the option's visible text"}, "direction": {"type": "string", "enum": ["down", "up", "top", "bottom", "back", "forward", "reload"], "description": "scroll: down/up/top/bottom; back: back/forward/reload"}, "seconds": {"type": "number"}, + "after_send": {"type": "boolean", "description": "wait: count `seconds` from the last thing you sent (spacing posts)"}, "path": {"type": "string", "description": "upload: a file on this computer"}, "accept": {"type": "boolean", "description": "dialog"}, "script": {"type": "string", "description": "eval: read-only JavaScript"}, @@ -717,7 +773,12 @@ pub fn run(name: &str, args: &Value) -> Result<(String, Option), String> } settle_after(&mut tab, &sig, 900, 4000); let after = snapshot(&mut tab); - Ok((format!("已{} {what}。\n{}", if name == "browser_hover" { "停在" } else { "點" }, changes(&before, &after)), None)) + let changed = changes(&before, &after); + // A click into a text box changes no words on the page: that is the cursor in the + // box, not a miss (it read 「看起來沒有變化」 and the bot clicked again and again). + let focus = if name == "browser_click" { focused_field(&mut tab) } else { String::new() }; + let changed = if !focus.is_empty() && changed.starts_with(NO_CHANGE) { format!("游標已在「{focus}」裡,可以直接打字或貼上。") } else { changed }; + Ok((format!("已{} {what}。\n{changed}", if name == "browser_hover" { "停在" } else { "點" }), None)) } "browser_type" => { let sig = page_sig(&mut tab); @@ -730,14 +791,16 @@ pub fn run(name: &str, args: &Value) -> Result<(String, Option), String> tab.eval("(() => { const e = document.activeElement; if (e && 'select' in e && typeof e.select === 'function') e.select(); else document.execCommand('selectAll'); return 1; })()")?; press(&mut tab, "Backspace")?; } - tab.call("Input.insertText", json!({"text": s(args, "value")}))?; + insert_text(&mut tab, &s(args, "value"))?; if args["submit"].as_bool().unwrap_or(false) { settle(150); press(&mut tab, "Enter")?; } settle_after(&mut tab, &sig, 700, 4000); let after = snapshot(&mut tab); - let now: String = tab.eval("(() => { const e = document.activeElement; return e && 'value' in e ? (e.type === 'password' ? '' : String(e.value)) : ''; })()")?.as_str().unwrap_or("").chars().take(80).collect(); + // What the field holds now (an editor's lines too): the bot checks the whole text + // went in before it sends, in this same step. + let now: String = tab.eval("(() => { let e = document.activeElement; while (e && e.shadowRoot && e.shadowRoot.activeElement) e = e.shadowRoot.activeElement; if (!e) return ''; if (e.isContentEditable) return e.innerText; return 'value' in e ? (e.type === 'password' ? '' : String(e.value)) : ''; })()")?.as_str().unwrap_or("").trim().replace('\n', " ⏎ ").chars().take(FIELD_SHOWN_CHARS).collect(); Ok((format!("已在 {what} 輸入。{}\n{}", if now.is_empty() { String::new() } else { format!("欄位現在是「{now}」。") }, changes(&before, &after)), None)) } "browser_press" => { @@ -1231,6 +1294,57 @@ mod tests { } } + /// 少一點步驟, live: a click into a box says the cursor is there; lines go in whole (an + /// editor that takes pastes, and a plain textarea); numbers stay put when the page grows. + /// Headless, in a scratch data folder, on a port of its own: + /// ANYBOT_DATA_DIR=$T ANYBOT_BROWSER_PORT=9398 ANYBOT_BROWSER_FLAGS=--headless=new --ignored lines_go_in_whole + /// (Firefox: ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1 and HOME=$T as well) + #[test] + #[ignore] + fn lines_go_in_whole_and_numbers_stay_put() { + use std::io::{Read, Write}; + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + std::thread::spawn(move || { + for mut c in l.incoming().flatten() { + let mut buf = [0u8; 2048]; + let _ = c.read(&mut buf); + let body = r#"回覆測試 +
+ + + +"#; + let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + } + }); + let url = format!("http://127.0.0.1:{port}/"); + let r = (|| -> Result<(), String> { + botbrowser::as_job("lines", || -> Result<(), String> { + botbrowser::open(&url, None)?; + let refs = || -> Result { run("browser_elements", &json!({})).map(|r| r.0) }; + let num = |list: &str, name: &str| -> String { list.lines().find(|l| l.contains(name)).and_then(|l| l.split(']').next()).map(|s| s.trim_start_matches('[').to_string()).unwrap_or_default() }; + let first = refs()?; + let ed = num(&first, "「回覆」"); + assert!(!ed.is_empty(), "{first}"); + let (clicked, _) = run("browser_click", &json!({"ref": ed}))?; + assert!(clicked.contains("游標已在「回覆」裡"), "{clicked}"); + let (typed, _) = run("browser_type", &json!({"ref": ed, "value": "第一行\n第二行\nhttps://s.shopee.tw/x"}))?; + assert!(typed.contains("第一行 ⏎ 第二行 ⏎ https://s.shopee.tw/x"), "{typed}"); + // The page grows: the box keeps its number. + run("browser_click", &json!({"text": "加一個"}))?; + let second = refs()?; + assert_eq!(num(&second, "「回覆」"), ed, "{first}\n---\n{second}"); + let ta = num(&second, "「備註」"); + let (typed, _) = run("browser_type", &json!({"ref": ta, "value": "甲\n乙"}))?; + assert!(typed.contains("甲 ⏎ 乙"), "{typed}"); + Ok(()) + }) + })(); + let _ = botbrowser::quit(None); + r.unwrap(); + } + #[test] fn a_finished_job_closes_its_browser_unless_another_job_is_on_it() { let tabs = |ids: &[&str]| ids.iter().map(|i| json!({"id": i})).collect::>(); diff --git a/src/evidence.rs b/src/evidence.rs new file mode 100644 index 0000000..6adf964 --- /dev/null +++ b/src/evidence.rs @@ -0,0 +1,84 @@ +// 證據: what a stretch of the chat really did, counted from its steps — never from what the bot +// says about them. A bot once reported "2 sent" when one was; the /goal judge read its words and +// a routine's record only knew the turn ended. These counts go to both. + +use crate::model::{Message, Role, ToolCall, ToolStatus}; + +/// What the steps of a stretch of chat did. +#[derive(Debug, Default, PartialEq)] +pub struct Tally { + pub steps: u32, + /// Steps that failed or were refused. + pub failed: u32, + /// Steps that sent something out and went through (a post, a reply, a message, a submit). + pub sent: u32, + /// Those sends, a line each (the tool and what it acted on). + pub sends: Vec, +} + +/// Words on a control that mean it sends something out (a reply box's 「回覆」 only opens it). +fn sends_words(label: &str) -> bool { + let low = label.to_lowercase(); + ["送出", "發佈", "發布", "發文", "傳送", "發送", "貼文", "張貼", "提交"].iter().any(|w| label.contains(w)) || ["send", "post", "publish", "submit", "tweet"].iter().any(|w| low.contains(w)) +} + +/// Whether a step sends something out of the computer: Enter or ctrl+Enter in a page, typing +/// with submit, a click on a 送出/發佈 control, a message or post tool. +pub fn sends(call: &ToolCall) -> bool { + let v = crate::tools::args_of(&call.args); + let text = |k: &str| v[k].as_str().unwrap_or("").to_string(); + match call.name.as_str() { + "browser_press" | "computer_use_press_key" => { + let k = text("key").to_lowercase(); + k.contains("enter") || k.contains("return") + } + "browser_type" | "computer_use_typing" => v["submit"].as_bool() == Some(true), + "browser_click" | "computer_use_click" => sends_words(&format!("{} {}", text("text"), text("name"))), + "send_sms" | "post_to_x" | "message_bot" | "send_to_device" => true, + n => crate::macapps::is_mac_tool(n) && n == crate::macapps::SEND_MESSAGE, + } +} + +/// Count the steps of `msgs`. +pub fn tally(msgs: &[Message]) -> Tally { + let mut t = Tally::default(); + for c in msgs.iter().filter(|m| m.role == Role::Assistant).flat_map(|m| m.tool_calls.iter()) { + t.steps += 1; + match c.status { + ToolStatus::Failed | ToolStatus::Denied => t.failed += 1, + ToolStatus::Done if sends(c) => { + t.sent += 1; + t.sends.push(format!("{} {}", c.name, crate::tools::describe(&c.name, &c.args)).trim().to_string()); + } + _ => {} + } + } + t +} + +#[cfg(test)] +mod tests { + use super::*; + + fn call(name: &str, args: &str, status: ToolStatus) -> ToolCall { + ToolCall { id: "x".into(), name: name.into(), args: args.into(), status } + } + + #[test] + fn only_steps_that_sent_and_went_through_count_as_sent() { + let steps = vec![ + call("browser_click", r#"{"text":"回覆 with._.22"}"#, ToolStatus::Done), + call("browser_press", r#"{"key":"ctrl+v"}"#, ToolStatus::Done), + call("browser_press", r#"{"key":"ctrl+Return"}"#, ToolStatus::Done), + call("browser_press", r#"{"key":"ctrl+Return"}"#, ToolStatus::Failed), + call("browser_click", r#"{"text":"發佈"}"#, ToolStatus::Done), + call("browser_fill_contact", r#"{"contact_id":"x"}"#, ToolStatus::Denied), + call("browser_type", r#"{"ref":"3","value":"貓抓板","submit":true}"#, ToolStatus::Done), + ]; + let msgs = vec![Message::user("發吧"), Message { tool_calls: steps, ..Message::assistant("", "") }, Message::assistant("送出 2 則了", "")]; + let t = tally(&msgs); + assert_eq!((t.steps, t.failed, t.sent), (7, 2, 3)); + assert_eq!(t.sends.len(), 3); + assert!(t.sends[0].starts_with("browser_press")); + } +} diff --git a/src/garden.rs b/src/garden.rs new file mode 100644 index 0000000..cd6c89c --- /dev/null +++ b/src/garden.rs @@ -0,0 +1,225 @@ +// 園丁: watching what goes wrong across every bot, so a mistake that keeps coming back is fixed +// once in AnyBot (or its settings) instead of being written into one more skill. Lauren Tan's +// gardener: watch → queue without fixing → group by cause → fix what repeats; one-offs need +// nothing. Two parts here: the queue of AnyBot's own problems the bots report (待改進), and the +// report a day and a week that reads the routines' runs and that queue. + +use serde::{Deserialize, Serialize}; + +/// One of AnyBot's own problems a bot ran into (a tool that failed, a workaround it needed). +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +pub struct Improvement { + pub text: String, + /// Times it was reported (the same tool, or the same words). + pub count: u32, + /// Seconds since 1970, first and latest report. + pub first: i64, + pub last: i64, + /// Which bots reported it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub bots: Vec, +} + +/// Items kept in the queue (the oldest go first). +pub const MAX_IMPROVEMENTS: usize = 50; +/// Reports after which a problem counts as recurring (worth fixing, said in the report). +pub const RECURRING: u32 = 2; + +/// The tool names a report mentions (words like browser_fill_contact): two reports about the +/// same tool are the same problem, however differently they were worded. +fn tools_named(text: &str) -> Vec { + let mut v: Vec = text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).filter(|w| w.contains('_') && w.len() > 3).map(|w| w.to_ascii_lowercase()).collect(); + v.sort(); + v.dedup(); + v +} + +fn plain(text: &str) -> String { + text.chars().filter(|c| c.is_alphanumeric()).collect::().to_lowercase() +} + +/// Queue a problem a bot reported: counted on an item about the same tool (or with the same +/// words), else added. +pub fn note_issue(list: &mut Vec, text: &str, bot: &str, now: i64) { + let text = text.trim(); + if text.is_empty() { + return; + } + let tools = tools_named(text); + let same = |i: &Improvement| { + let theirs = tools_named(&i.text); + if !tools.is_empty() && !theirs.is_empty() { + tools.iter().any(|t| theirs.contains(t)) + } else { + plain(&i.text) == plain(text) + } + }; + match list.iter_mut().find(|i| same(i)) { + Some(i) => { + i.count += 1; + i.last = now; + if !bot.is_empty() && !i.bots.iter().any(|b| b == bot) { + i.bots.push(bot.to_string()); + } + } + None => { + list.push(Improvement { text: text.to_string(), count: 1, first: now, last: now, bots: if bot.is_empty() { vec![] } else { vec![bot.to_string()] } }); + let extra = list.len().saturating_sub(MAX_IMPROVEMENTS); + list.drain(..extra); + } + } +} + +// ---------- the reports ---------- + +/// A run that took this many steps or more, with this share of them failing, went the long way. +const LONG_WAY_STEPS: u32 = 10; +const LONG_WAY_FAILED_PERCENT: u32 = 30; +/// Weekly: a routine worth a look — failing this share of its runs, or this heavy on average. +const WEEK_FAILED_PERCENT: u32 = 20; +const WEEK_AVG_STEPS: u32 = 60; +const WEEK_AVG_MINUTES: i64 = 30; +/// When the reports come (the person's time): the daily one on weekdays from 8:44, the weekly one +/// on Mondays from 8:49 — dr eggbot's transcript-healthcheck and routine-healthcheck. +pub const DAILY_AT: (u32, u32) = (8, 44); +pub const WEEKLY_AT: (u32, u32) = (8, 49); + +/// One bot's routines, for the reports: (bot name, its routines). +pub type Fleet<'a> = Vec<(&'a str, &'a [crate::routines::Routine])>; + +/// The day's look at what went wrong (since `since`): failed or cut-off runs, runs that went the +/// long way, routines AnyBot paused, problems that keep coming back. None when there is nothing +/// to say — a report with nothing in it trains people to skip it. +pub fn daily_report(fleet: &Fleet, issues: &[Improvement], since: i64) -> Option { + use crate::routines::{describe_run, RunOutcome}; + let mut lines = vec![]; + for (bot, routines) in fleet { + for r in routines.iter() { + if r.paused && !r.paused_why.is_empty() { + lines.push(format!("· {bot}「{}」已暫停:{}", r.title, r.paused_why)); + continue; + } + for run in r.runs.iter().filter(|x| x.started >= since) { + let bad = matches!(run.outcome, RunOutcome::Failed | RunOutcome::Interrupted); + let long_way = run.steps >= LONG_WAY_STEPS && run.failed_steps * 100 >= run.steps * LONG_WAY_FAILED_PERCENT; + if bad || long_way { + let why = if bad { "" } else { "(很多步沒成功)" }; + lines.push(format!("· {bot}「{}」{}{why}", r.title, describe_run(run, &r.schedule.timezone))); + } + } + } + } + for i in issues.iter().filter(|i| i.count >= RECURRING && i.last >= since) { + lines.push(format!("· AnyBot 待改進(×{}):{}", i.count, i.text)); + } + (!lines.is_empty()).then(|| format!("園丁:過去一天有 {} 件事值得看一下。\n{}", lines.len(), lines.join("\n"))) +} + +/// The week's look at what the routines cost (since `since`): the ones failing often or heavy +/// on average, with their runs, steps and minutes. None when every routine is fine. +pub fn weekly_report(fleet: &Fleet, since: i64) -> Option { + use crate::routines::RunOutcome; + let mut lines = vec![]; + for (bot, routines) in fleet { + for r in routines.iter() { + let runs: Vec<_> = r.runs.iter().filter(|x| x.started >= since && x.outcome != RunOutcome::Running).collect(); + if runs.is_empty() { + continue; + } + let n = runs.len() as u32; + let failed = runs.iter().filter(|x| matches!(x.outcome, RunOutcome::Failed | RunOutcome::Interrupted)).count() as u32; + let steps: u32 = runs.iter().map(|x| x.steps).sum(); + let minutes: i64 = runs.iter().map(|x| ((x.ended - x.started).max(0) + 59) / 60).sum(); + let heavy = steps / n >= WEEK_AVG_STEPS || minutes / n as i64 >= WEEK_AVG_MINUTES; + if failed * 100 >= n * WEEK_FAILED_PERCENT || heavy { + lines.push(format!("· {bot}「{}」跑了 {n} 次,{failed} 次沒成功;共 {steps} 步、{minutes} 分鐘(平均每次 {} 步、{} 分鐘)", r.title, steps / n, minutes / n as i64)); + } + } + } + (!lines.is_empty()).then(|| format!("園丁:這週有 {} 條例行任務值得調整(失敗多或很耗時)。\n{}", lines.len(), lines.join("\n"))) +} + +/// Whether a report is due now: its time of day has come in the person's zone, on its day, and +/// it hasn't been made today (`last` = the day it was last made, as yyyymmdd). +pub fn due(now: i64, tz: chrono_tz::Tz, at: (u32, u32), mondays_only: bool, last: u32) -> Option { + use chrono::{Datelike, TimeZone, Timelike}; + let t = chrono::Utc.timestamp_opt(now, 0).single()?.with_timezone(&tz); + let day = t.year() as u32 * 10_000 + t.month() * 100 + t.day(); + let weekday_ok = if mondays_only { t.weekday() == chrono::Weekday::Mon } else { t.weekday().num_days_from_monday() < 5 }; + (weekday_ok && (t.hour(), t.minute()) >= at && day != last).then_some(day) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn routine(title: &str, runs: Vec) -> crate::routines::Routine { + let s = crate::routines::Schedule { frequency: crate::routines::Frequency::Daily, interval: 1, days_of_week: vec![], month_day: None, weekday_of_month: None, month: None, time: "17:00".into(), timezone: "Asia/Taipei".into(), once: false, flexible: false }; + crate::routines::Routine { id: 1, title: title.into(), prompt: String::new(), schedule: s, paused: false, created_at: 0, last_run: None, next_run: None, computer: String::new(), trigger: None, runs, paused_why: String::new() } + } + + fn run(started: i64, outcome: crate::routines::RunOutcome, steps: u32, failed: u32) -> crate::routines::RoutineRun { + crate::routines::RoutineRun { started, ended: started + 600, outcome, note: "原因".into(), steps, failed_steps: failed, sent: 0 } + } + + #[test] + fn the_daily_report_says_only_what_went_wrong_and_nothing_on_a_good_day() { + use crate::routines::RunOutcome::*; + let fine = [routine("貓咪海巡", vec![run(1_000, Succeeded, 40, 1)])]; + let fleet: Fleet = vec![("賴桑", &fine)]; + assert_eq!(daily_report(&fleet, &[], 0), None, "nothing to say, nothing said"); + let rough = [routine("主婦海巡", vec![run(500, Failed, 9, 9), run(1_000, Succeeded, 170, 160), run(2_000, Succeeded, 30, 2)])]; + let fleet: Fleet = vec![("賴桑", &rough)]; + let issues = vec![Improvement { text: "browser_fill_contact 被誤用".into(), count: 3, first: 0, last: 1_500, bots: vec![] }]; + let r = daily_report(&fleet, &issues, 800).unwrap(); + assert!(r.contains("2 件事"), "{r}"); + assert!(r.contains("170 步,160 步沒成功") && r.contains("很多步沒成功"), "{r}"); + assert!(!r.contains("9 步"), "before the window: {r}"); + assert!(r.contains("待改進(×3)")); + } + + #[test] + fn the_weekly_report_names_the_costly_routines_only() { + use crate::routines::RunOutcome::*; + let a = [routine("拾日海巡", vec![run(100, Succeeded, 120, 10), run(200, Succeeded, 100, 5)])]; + let b = [routine("早報", vec![run(100, Succeeded, 8, 0)])]; + let fleet: Fleet = vec![("賴桑", &a), ("小幫手", &b)]; + let w = weekly_report(&fleet, 0).unwrap(); + assert!(w.contains("拾日海巡") && w.contains("跑了 2 次") && w.contains("平均每次 110 步") && !w.contains("早報"), "{w}"); + let quiet: Fleet = vec![("小幫手", &b)]; + assert_eq!(weekly_report(&quiet, 0), None); + } + + #[test] + fn reports_come_once_a_day_after_their_time() { + let tz = chrono_tz::Asia::Taipei; + let at = |d: u32, h: u32, m: u32| tz.with_ymd_and_hms(2026, 11, d, h, m, 0).unwrap().timestamp(); + use chrono::TimeZone; + // Mon 2026-11-16 08:43: not yet; 08:44: due; made today: not again. Saturday: no. + assert_eq!(due(at(16, 8, 43), tz, DAILY_AT, false, 0), None); + assert_eq!(due(at(16, 8, 44), tz, DAILY_AT, false, 0), Some(20261116)); + assert_eq!(due(at(16, 15, 0), tz, DAILY_AT, false, 20261116), None); + assert_eq!(due(at(14, 9, 0), tz, DAILY_AT, false, 0), None); + // The weekly one: Mondays only. + assert_eq!(due(at(16, 8, 50), tz, WEEKLY_AT, true, 0), Some(20261116)); + assert_eq!(due(at(17, 8, 50), tz, WEEKLY_AT, true, 0), None); + } + + #[test] + fn the_same_tool_problem_is_counted_not_repeated() { + let mut q = vec![]; + note_issue(&mut q, "Bot 一直誤用 browser_fill_contact 來打字", "賴桑", 10); + note_issue(&mut q, "browser_fill_contact 回「沒有開著的分頁」,其實分頁開著", "拾日", 20); + note_issue(&mut q, "多行留言只能用剪貼簿貼上", "賴桑", 30); + note_issue(&mut q, "多行留言只能用剪貼簿貼上。", "賴桑", 40); + note_issue(&mut q, " ", "x", 50); + assert_eq!(q.len(), 2); + assert_eq!((q[0].count, q[0].first, q[0].last), (2, 10, 20)); + assert_eq!(q[0].bots, vec!["賴桑", "拾日"]); + assert_eq!(q[1].count, 2, "the same words, punctuation aside"); + for i in 0..60 { + note_issue(&mut q, &format!("問題 {i}"), "", 100 + i); + } + assert_eq!(q.len(), MAX_IMPROVEMENTS); + } +} diff --git a/src/goal.rs b/src/goal.rs index 2c5ee20..a3eaf1b 100644 --- a/src/goal.rs +++ b/src/goal.rs @@ -130,6 +130,7 @@ pub enum Judged { pub const JUDGE_SYSTEM: &str = "你是驗收員。使用者給一個 bot 設了目標,bot 剛做完一輪。你只能看下面的對話紀錄(bot 說的話、它用了哪些工具、工具回了什麼),判斷目標現在是不是已經成立。 - 只認對話裡看得到的證據:指令的輸出、測試結果、檔案內容、畫面、網頁內容。bot 自己說「做完了」「應該可以了」不算證據。 +- 最後的「系統統計」是 AnyBot 從工具紀錄算出來的,不是 bot 說的:bot 說的數字(送出幾則、做了幾個)和它對不上時,以系統統計為準,不能判 met。 - 目標裡有輪數或時間的限制(例如「最多 10 輪」),照紀錄開頭寫的輪數和時間判斷。 - bot 在問使用者問題、等使用者決定,或要使用者做只有他能做的事(登入、付款、給密碼)才能繼續:判 waiting。 - 確定永遠做不到才判 impossible(要的東西不存在、被明確拒絕而且沒有別的路);只是還沒做完、遇到能修的錯誤,都是 not_met。 @@ -156,6 +157,9 @@ pub fn read_verdict(text: &str) -> Judged { /// What the judge reads: the goal, how long and how many turns, and the chat since it was set /// (the newest part when it is long). +/// Sends listed under the judge's 系統統計 (the newest). +const SENDS_LISTED: usize = 20; + pub fn brief(g: &Goal, msgs: &[Message], now: i64) -> String { let start = msgs.iter().position(|m| m.at >= g.since).unwrap_or(0); let mut parts: Vec = vec![]; @@ -169,7 +173,7 @@ pub fn brief(g: &Goal, msgs: &[Message], now: i64) -> String { Role::User => parts.push(format!("【使用者】{}", clip(&m.text, TEXT_CHARS))), Role::Assistant => { if !m.text.trim().is_empty() { - parts.push(format!("【bot】{}", clip(&m.text, TEXT_CHARS))); + parts.push(format!("【bot 的說法(不是證據)】{}", clip(&m.text, TEXT_CHARS))); } for c in &m.tool_calls { parts.push(format!("【bot 用了 {}】{}", c.name, clip(&one_line(&c.args), ARGS_CHARS))); @@ -183,8 +187,14 @@ pub fn brief(g: &Goal, msgs: &[Message], now: i64) -> String { if n > BRIEF_CHARS { chat = format!("(前面較早的部分省略)\n…{}", chat.chars().skip(n - BRIEF_CHARS).collect::()); } + // What the steps really did, counted from them (evidence.rs): never cut, it is the check. + let t = crate::evidence::tally(&msgs[start..]); + let mut stats = format!("共 {} 步,{} 步失敗或被拒絕;成功送出 {} 次", t.steps, t.failed, t.sent); + for s in t.sends.iter().rev().take(SENDS_LISTED).rev() { + stats.push_str(&format!("\n· {}", clip(s, ARGS_CHARS))); + } format!( - "目標:{}\n\n目標設定了 {},現在是第 {} 輪剛結束。\n\n對話紀錄:\n\n{chat}\n\n目標現在成立了嗎?只回 JSON。", + "目標:{}\n\n目標設定了 {},現在是第 {} 輪剛結束。\n\n對話紀錄:\n\n{chat}\n\n【系統統計(AnyBot 從工具紀錄算出,不是 bot 說的)】\n{stats}\n\n目標現在成立了嗎?只回 JSON。", g.condition, elapsed(now - g.since), g.turns + 1 @@ -328,6 +338,23 @@ fn head_tail(s: &str, head: usize, tail: usize) -> String { #[cfg(test)] mod tests { use super::*; + + /// The judge reads the bot's words as words, and the system's own count of what was sent. + #[test] + fn the_judge_gets_the_systems_count_not_only_the_bots_word() { + use crate::model::{ToolCall, ToolStatus}; + let g = Goal::new("拾日 2 則留言送出", 0); + let call = |key: &str, st: ToolStatus| ToolCall { id: "c".into(), name: "browser_press".into(), args: format!(r#"{{"key":"{key}"}}"#), status: st }; + let msgs = vec![ + Message { at: 1, ..Message::user("發") }, + Message { at: 2, tool_calls: vec![call("ctrl+Return", ToolStatus::Done), call("ctrl+Return", ToolStatus::Failed)], ..Message::assistant("", "") }, + Message { at: 3, ..Message::assistant("拾日:2 則已送出", "") }, + ]; + let b = brief(&g, &msgs, 10); + assert!(b.contains("【bot 的說法(不是證據)】拾日:2 則已送出"), "{b}"); + assert!(b.contains("成功送出 1 次") && b.contains("1 步失敗"), "{b}"); + assert!(JUDGE_SYSTEM.contains("以系統統計為準")); + } use crate::model::ToolCall; #[test] diff --git a/src/main.rs b/src/main.rs index 7698043..673ddb0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -65,6 +65,8 @@ mod theme; mod tools; mod triggers; mod embed; +mod evidence; +mod garden; mod goal; mod store; mod docindex; diff --git a/src/memory.rs b/src/memory.rs index 3168d89..d23695a 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -318,9 +318,13 @@ pub const LEARN_SYSTEM: &str = "你在幫一個會操作電腦的 Bot 整理經 - 寫通用的做法,不要寫這次的內容(這篇文的文字、這張圖的檔名);使用者表達過的偏好(語氣、格式、一定要附圖、用哪台電腦)要寫進去。 - 已經有做同一件事的技能,就用同一個名稱,把舊的和這次學到的合併成更好的一版:舊的對的保留,錯的改掉。這次照著技能做而且很順,就不用再存。 +同一個網站的操作知識(有什麼功能、使用者怎麼點到、用哪個工具怎麼操作、陷阱)放在「<網站名> 網站地圖」這份技能,固定四段:## 功能、## 怎麼到、## 怎麼操作、## 陷阱;做事的技能只寫這件事特有的部分(帳號、篩選規則、語氣、數量),開頭寫「先 use_skill 讀「<網站名> 網站地圖」」。這次學到的是網站本身的事、而且已經有這個網站的地圖,就用地圖的名稱存,把新的陷阱合併進地圖,不要抄進做事的技能。 + +AnyBot 自己的問題另外寫,不要寫進技能:工具回錯的結果、工具明明開著卻說找不到、某個工具一用就出錯、要繞路才做得到(例如只能用剪貼簿貼上多行字)、Bot 一直誤用某個工具——這些寫進 tool_issues,一句一件,寫出哪個工具、發生什麼事;技能裡不要寫「絕對不要用某工具」「某工具壞了」這種句子,那是 AnyBot 要修的。網站本身的規矩和陷阱(要先等頁面載入、某按鈕找不到要換一個字找)才寫進技能的「注意:」。只發生一次、下次不太會再遇到的小失誤,兩邊都不用寫。 + 只回一個 JSON,不要別的字: -不用存:{\"save\": false, \"why\": \"一句話說為什麼\"} -要存:{\"save\": true, \"name\": \"短名稱\", \"description\": \"一行:什麼時候用\", \"instructions\": \"做法\", \"replay\": [步驟編號]} +不用存:{\"save\": false, \"why\": \"一句話說為什麼\", \"tool_issues\": []} +要存:{\"save\": true, \"name\": \"短名稱\", \"description\": \"一行:什麼時候用\", \"instructions\": \"做法\", \"replay\": [步驟編號], \"tool_issues\": []} replay:下次做同一件事時可以原樣照做的步驟編號(上面清單的號碼,照順序)。只列這次真的成功、必要、會改變東西的步驟(不含截圖、讀取這類只是看的步驟,不含失敗或繞路的步驟);內容每次會不一樣的工作(發文的文字、要回覆的留言、檔名)不要列,給空陣列 []。"; @@ -376,6 +380,20 @@ pub fn learn_brief(turn: &[crate::model::Message], skills: &[Skill]) -> String { } /// The skill in the model's answer, when it chose to save one. +/// AnyBot's own problems the look back found (tool_issues): kept for whoever fixes AnyBot, never +/// in a skill — the Threads skills had grown "never use browser_fill_contact" rules that the +/// system, not the bot, had to fix (encode lessons in structure). +pub fn learned_issues(text: &str) -> Vec { + let t = text.trim(); + let Some(json) = t.find('{').and_then(|a| t.rfind('}').filter(|b| *b >= a).map(|b| &t[a..=b])) else { return vec![] }; + let v: serde_json::Value = serde_json::from_str(json).unwrap_or_default(); + v["tool_issues"].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).map(|s| s.trim().chars().take(ISSUE_CHARS).collect::()).filter(|s| !s.is_empty()).take(MAX_ISSUES_PER_TURN).collect()).unwrap_or_default() +} + +/// Longest tool issue kept, and how many one turn may report. +const ISSUE_CHARS: usize = 200; +const MAX_ISSUES_PER_TURN: usize = 5; + pub fn learned_skill(text: &str) -> Option { let t = text.trim(); let json = t.find('{').and_then(|a| t.rfind('}').filter(|b| *b >= a).map(|b| &t[a..=b]))?; @@ -947,6 +965,17 @@ pub fn api_write(state: &mut crate::model::State, b: &serde_json::Value) -> serd mod tests { use super::*; + #[test] + fn anybots_own_problems_are_reported_apart_from_the_skill() { + let out = r#"{"save": true, "name": "Threads 回覆", "description": "回覆貼文", "instructions": "1. 開貼文", "replay": [], "tool_issues": ["browser_fill_contact 被誤用來打字", " ", "多行字只能用剪貼簿貼上"]}"#; + assert_eq!(learned_issues(out), vec!["browser_fill_contact 被誤用來打字", "多行字只能用剪貼簿貼上"]); + assert!(learned_skill(out).is_some()); + assert!(learned_issues(r#"{"save": false, "why": "閒聊"}"#).is_empty()); + assert!(learned_issues("不是 JSON").is_empty()); + assert!(LEARN_SYSTEM.contains("tool_issues") && LEARN_SYSTEM.contains("不要寫進技能")); + assert!(LEARN_SYSTEM.contains("網站地圖") && LEARN_SYSTEM.contains("## 陷阱")); + } + #[test] fn the_shelf_is_searched_not_carried_whole() { let list = vec!["我喜歡靠窗的座位".to_string(), "週五下午不開會".to_string()]; diff --git a/src/model.rs b/src/model.rs index 4f919b2..a0a9039 100644 --- a/src/model.rs +++ b/src/model.rs @@ -109,6 +109,10 @@ pub struct Message { /// never sent to the model. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub note: bool, + /// The routine this wake message runs (0: none): how the turn's end is kept as that + /// routine's run. + #[serde(default, skip_serializing_if = "is_zero")] + pub routine: u64, /// Sent by someone other than the owner (a team `member` or an external messaging channel): /// turns started by this message never inherit owner memories, `appctl`, `direct_mode` or /// host-side grants. @@ -700,6 +704,18 @@ pub struct State { /// 頁面 the bots made and keep up to date. #[serde(default)] pub pages: Vec, + /// 待改進: AnyBot's own problems the bots ran into (garden.rs), for whoever fixes AnyBot. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub improvements: Vec, + /// 園丁報告: a line in the primary bot's chat on weekday mornings when something went wrong, + /// and on Mondays when a routine costs too much (garden.rs). On by default. + #[serde(default = "yes")] + pub garden_reports: bool, + /// The days (yyyymmdd) the daily and the weekly report were last made. + #[serde(default)] + pub garden_daily: u32, + #[serde(default)] + pub garden_weekly: u32, #[serde(default = "first_routine_id")] pub next_page_id: u64, /// 手機與帳號: phone access, the relay account and backups. @@ -1158,6 +1174,10 @@ impl State { branch_bots: vec![], skills_seeded: false, pages: vec![], + improvements: vec![], + garden_reports: true, + garden_daily: 0, + garden_weekly: 0, next_page_id: 1, remote: Default::default(), language: auto_lang(), @@ -1222,6 +1242,8 @@ impl State { last_run: None, computer: String::new(), trigger: None, + runs: vec![], + paused_why: String::new(), }]; s.next_routine_id = 2; s.bots[1].messages = vec![ diff --git a/src/providers.rs b/src/providers.rs index 60ea6a6..97c17e2 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -253,6 +253,9 @@ pub enum StreamEvent { /// The pictures were taken out of the chat to make room: the chat lets go of them too, so /// the next turn doesn't send them again. PicturesDropped, + /// AnyBot's own problems the look back after a turn found (memory::learned_issues): queued + /// in 待改進, never written into a skill. + Issues(Vec), /// 目標: the check after a turn has spoken (for the goal set at this time, ms). Goal(i64, crate::goal::Judged), Done, diff --git a/src/routines.rs b/src/routines.rs index 94d9c3d..9c64cb6 100644 --- a/src/routines.rs +++ b/src/routines.rs @@ -91,6 +91,162 @@ pub struct Routine { /// Run when something happens instead of on the schedule. #[serde(default, skip_serializing_if = "Option::is_none")] pub trigger: Option, + /// How its latest runs went, oldest first (at most RUNS_KEPT): what the person and the bot + /// look at to know whether it works — it used to keep only when it last started. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub runs: Vec, + /// Why AnyBot paused it (failed PAUSE_AFTER_FAILURES times in a row); empty when the person did. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub paused_why: String, +} + +/// How one run went. +#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Debug)] +#[serde(rename_all = "lowercase")] +pub enum RunOutcome { + Running, + Succeeded, + Failed, + /// The person (or the 15-minute approval watchdog's stop) ended it. + Stopped, + /// AnyBot closed while it ran: part of it may be done. + Interrupted, +} + +/// One run of a routine. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +pub struct RoutineRun { + /// Seconds since 1970 (UTC). + pub started: i64, + #[serde(default)] + pub ended: i64, + pub outcome: RunOutcome, + /// Why it failed or stopped; for a run that went through, the first words of its report. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub note: String, + /// Steps it took, and how many of them failed or were refused. + #[serde(default)] + pub steps: u32, + #[serde(default)] + pub failed_steps: u32, + /// Steps that sent something out and went through (evidence::sends): the system's count, + /// beside whatever the report says. + #[serde(default)] + pub sent: u32, +} + +/// Runs kept per routine (Grok Bot keeps 20 run records per routine). +pub const RUNS_KEPT: usize = 20; +/// Failed runs in a row after which AnyBot pauses the routine and says why (noodle: "If an item +/// has failed 2+ times in recent_history, deschedule or split it"). +pub const PAUSE_AFTER_FAILURES: usize = 2; +/// What an interrupted run says. +const INTERRUPTED_NOTE: &str = "AnyBot 在執行中被關掉,可能做到一半"; + +impl Routine { + /// A run begins. + pub fn run_started(&mut self, at: i64) { + self.runs.push(RoutineRun { started: at, ended: 0, outcome: RunOutcome::Running, note: String::new(), steps: 0, failed_steps: 0, sent: 0 }); + let extra = self.runs.len().saturating_sub(RUNS_KEPT); + self.runs.drain(..extra); + } + + /// The run in progress ended. True when that makes PAUSE_AFTER_FAILURES failures in a row: + /// the routine is then paused, with the reason kept for the person. + pub fn run_ended(&mut self, at: i64, outcome: RunOutcome, note: &str, steps: u32, failed_steps: u32, sent: u32) -> bool { + let note = note.trim().to_string(); + match self.runs.iter_mut().rev().find(|r| r.outcome == RunOutcome::Running) { + Some(r) => { + r.ended = at; + r.outcome = outcome; + r.note = note.clone(); + r.steps = steps; + r.failed_steps = failed_steps; + r.sent = sent; + } + // (Started before runs were kept, or by a path that didn't note the start.) + None => { + self.runs.push(RoutineRun { started: at, ended: at, outcome, note: note.clone(), steps, failed_steps, sent }); + let extra = self.runs.len().saturating_sub(RUNS_KEPT); + self.runs.drain(..extra); + } + } + let failed_in_a_row = self.runs.iter().rev().take_while(|r| r.outcome == RunOutcome::Failed).count(); + if outcome == RunOutcome::Failed && failed_in_a_row >= PAUSE_AFTER_FAILURES && !self.paused { + self.paused = true; + self.paused_why = format!("連續 {failed_in_a_row} 次失敗,AnyBot 先暫停了。最近一次:{note}"); + return true; + } + false + } + + /// Runs AnyBot was closed during (found when it starts again). + pub fn mark_interrupted(&mut self) { + for r in self.runs.iter_mut().filter(|r| r.outcome == RunOutcome::Running) { + r.outcome = RunOutcome::Interrupted; + r.note = INTERRUPTED_NOTE.into(); + } + } + + /// The latest finished run, when it didn't go through (what the next run is told about). + pub fn last_trouble(&self) -> Option<&RoutineRun> { + self.runs.iter().rev().find(|r| r.outcome != RunOutcome::Running).filter(|r| matches!(r.outcome, RunOutcome::Failed | RunOutcome::Interrupted)) + } +} + +/// What a turn that just ended says about the routine run it was. None when the turn wasn't a +/// routine's. +pub struct TurnResult { + pub routine: u64, + pub outcome: RunOutcome, + pub note: String, + pub tally: crate::evidence::Tally, +} + +pub fn turn_result(msgs: &[crate::model::Message], outcome: crate::model::TurnOutcome) -> Option { + use crate::model::{Role, TurnOutcome}; + let start = msgs.iter().rposition(|m| m.role == Role::User && !m.steer)?; + let routine = msgs[start].routine; + if routine == 0 { + return None; + } + let turn = &msgs[start..]; + let tally = crate::evidence::tally(turn); + // A report's first real line (not a heading), short. + let line = |t: &str| -> String { t.lines().map(str::trim).find(|l| !l.is_empty() && !l.starts_with('#')).unwrap_or("").chars().take(120).collect() }; + let (run, note) = match outcome { + TurnOutcome::Success => (RunOutcome::Succeeded, turn.iter().rev().find(|m| m.role == Role::Assistant && !m.note && !m.text.trim().is_empty()).map(|m| line(&m.text)).unwrap_or_default()), + TurnOutcome::Error => (RunOutcome::Failed, turn.iter().rev().find(|m| m.error).map(|m| line(&m.text)).filter(|l| !l.is_empty()).unwrap_or_else(|| "出錯了".into())), + TurnOutcome::Cancelled => (RunOutcome::Stopped, "被停止".into()), + }; + Some(TurnResult { routine, outcome: run, note, tally }) +} + +/// One run in a line: 「11/14 17:00 失敗(35 分鐘,87 步,12 步沒成功):原因」. +pub fn describe_run(r: &RoutineRun, timezone: &str) -> String { + let tz = tz_of(timezone); + let when = Utc.timestamp_opt(r.started, 0).single().map(|t| t.with_timezone(&tz).format("%m/%d %H:%M").to_string()).unwrap_or_default(); + let word = match r.outcome { + RunOutcome::Running => "執行中", + RunOutcome::Succeeded => "完成", + RunOutcome::Failed => "失敗", + RunOutcome::Stopped => "被停止", + RunOutcome::Interrupted => "中斷", + }; + let mut facts = vec![]; + if r.ended > r.started { + let mins = (r.ended - r.started + 59) / 60; + facts.push(format!("{mins} 分鐘")); + } + if r.steps > 0 { + facts.push(if r.failed_steps > 0 { format!("{} 步,{} 步沒成功", r.steps, r.failed_steps) } else { format!("{} 步", r.steps) }); + } + if r.sent > 0 { + facts.push(format!("系統記到送出 {} 次", r.sent)); + } + let facts = if facts.is_empty() { String::new() } else { format!("({})", facts.join(",")) }; + let note = if r.note.is_empty() { String::new() } else { format!(":{}", r.note) }; + format!("{when} {word}{facts}{note}") } pub fn local_timezone() -> String { @@ -411,6 +567,89 @@ mod tests { s.trim_end_matches("(Asia/Taipei)").to_string() } + fn routine() -> Routine { + Routine { id: 7, title: "貓咪海巡".into(), prompt: "找 15 篇貼文".into(), schedule: sched(Frequency::Daily), paused: false, created_at: 0, last_run: None, next_run: None, computer: String::new(), trigger: None, runs: vec![], paused_why: String::new() } + } + + #[test] + fn two_failures_in_a_row_pause_a_routine_and_say_why() { + let mut r = routine(); + r.run_started(100); + assert_eq!(r.runs[0].outcome, RunOutcome::Running); + assert!(!r.run_ended(160, RunOutcome::Failed, "對話太長了", 12, 3, 0)); + assert_eq!(r.runs[0], RoutineRun { started: 100, ended: 160, outcome: RunOutcome::Failed, note: "對話太長了".into(), steps: 12, failed_steps: 3, sent: 0 }); + // A success in between: the count starts again. + r.run_started(200); + r.run_ended(260, RunOutcome::Succeeded, "送出 15 則", 80, 2, 0); + r.run_started(300); + assert!(!r.run_ended(360, RunOutcome::Failed, "找不到回覆框", 5, 5, 0)); + // The person stopping it, or AnyBot closing, isn't the routine failing. + r.run_started(400); + r.run_ended(460, RunOutcome::Stopped, "被停止", 2, 0, 0); + assert!(!r.paused); + r.run_started(500); + assert!(!r.run_ended(560, RunOutcome::Failed, "找不到回覆框", 5, 5, 0) && !r.paused, "a stop came between"); + r.run_started(600); + assert!(r.run_ended(660, RunOutcome::Failed, "登入過期", 3, 3, 0)); + assert!(r.paused && r.paused_why.contains("連續 2 次失敗") && r.paused_why.contains("登入過期"), "{}", r.paused_why); + // Already paused: no second notice. + assert!(!r.run_ended(700, RunOutcome::Failed, "x", 0, 0, 0)); + } + + #[test] + fn runs_are_kept_twenty_at_most_and_a_cut_off_one_is_interrupted() { + let mut r = routine(); + for i in 0..25 { + r.run_started(i * 100); + r.run_ended(i * 100 + 10, RunOutcome::Succeeded, "", 1, 0, 0); + } + assert_eq!(r.runs.len(), RUNS_KEPT); + assert_eq!(r.runs[0].started, 500, "the oldest went"); + r.run_started(9_000); + r.mark_interrupted(); + assert_eq!(r.runs.last().unwrap().outcome, RunOutcome::Interrupted); + assert_eq!(r.last_trouble().unwrap().outcome, RunOutcome::Interrupted); + // A run that ends with no start on record is still kept. + let mut fresh = routine(); + fresh.run_ended(50, RunOutcome::Succeeded, "好了", 4, 0, 0); + assert_eq!(fresh.runs.len(), 1); + assert!(fresh.last_trouble().is_none()); + } + + #[test] + fn a_turn_tells_how_its_routine_run_went() { + use crate::model::{Message, Role, ToolCall, ToolStatus, TurnOutcome}; + let call = |id: &str, st: ToolStatus| ToolCall { id: id.into(), name: "browser_click".into(), args: "{}".into(), status: st }; + let wake = Message { wake: true, routine: 7, ..Message::user("[例行任務]「貓咪海巡」時間到了") }; + let mut msgs = vec![Message::user("昨天的事"), Message::assistant("好", ""), wake]; + msgs.push(Message { tool_calls: vec![call("a", ToolStatus::Done), call("b", ToolStatus::Failed)], ..Message::assistant("", "") }); + msgs.push(Message { steer: true, ..Message::user("順便看一下私訊") }); + msgs.push(Message { tool_calls: vec![call("c", ToolStatus::Denied)], ..Message::assistant("", "") }); + msgs.push(Message::assistant("## 回報\n\n送出 12 則,跳過 3 則。\n細節…", "")); + let got = turn_result(&msgs, TurnOutcome::Success).unwrap(); + assert_eq!((got.routine, got.outcome, got.note.as_str(), got.tally.steps, got.tally.failed), (7, RunOutcome::Succeeded, "送出 12 則,跳過 3 則。", 3, 2)); + let mut err = msgs.clone(); + err.push(Message { error: true, ..Message::assistant("對話太長了,超過這個模型能讀的長度。\n(Prompt is 178553 tokens)", "") }); + assert_eq!(turn_result(&err, TurnOutcome::Error).unwrap().note, "對話太長了,超過這個模型能讀的長度。"); + assert_eq!(turn_result(&msgs, TurnOutcome::Cancelled).unwrap().outcome, RunOutcome::Stopped); + // The person's own turn is no routine's. + msgs.push(Message::user("謝謝")); + msgs.push(Message::assistant("不客氣", "")); + assert!(turn_result(&msgs, TurnOutcome::Success).is_none()); + assert_eq!(msgs.iter().filter(|m| m.role == Role::User).count(), 4); + } + + #[test] + fn a_run_reads_in_one_line() { + let r = RoutineRun { started: ts(2026, 11, 14, 17, 0), ended: ts(2026, 11, 14, 17, 35), outcome: RunOutcome::Failed, note: "找不到回覆框".into(), steps: 87, failed_steps: 12, sent: 0 }; + assert_eq!(describe_run(&r, "Asia/Taipei"), "11/14 17:00 失敗(35 分鐘,87 步,12 步沒成功):找不到回覆框"); + // The system's own count of sends, beside the report's words. + let posted = RoutineRun { outcome: RunOutcome::Succeeded, note: "送出 2 則".into(), sent: 1, ..r.clone() }; + assert_eq!(describe_run(&posted, "Asia/Taipei"), "11/14 17:00 完成(35 分鐘,87 步,12 步沒成功,系統記到送出 1 次):送出 2 則"); + let going = RoutineRun { started: ts(2026, 11, 14, 9, 0), ended: 0, outcome: RunOutcome::Running, note: String::new(), steps: 0, failed_steps: 0, sent: 0 }; + assert_eq!(describe_run(&going, "Asia/Taipei"), "11/14 09:00 執行中"); + } + fn sched(f: Frequency) -> Schedule { Schedule { frequency: f, interval: 1, days_of_week: vec![], month_day: None, weekday_of_month: None, month: None, time: "09:00".into(), timezone: "Asia/Taipei".into(), once: false, flexible: false } }