AnyBot/src/schedule.rs

222 lines
11 KiB
Rust
Raw Normal View History

日程:每個 Bot 被設定要做的事放在同一個日曆上(照 OpenBot 日程的排版,風格是 AnyBot 自己的),不用一個個問 Bot「你今天要幹嘛」。另外修好獨立審查在工作流(351ce3f)找到的問題。 日程(schedule.rs 算資料、app/schedule_ui.rs 畫): - 側邊欄最上面一排多了日曆按鈕(所有檔案、工作流、日程、任務…);「日/週/月」「‹ 今天 ›」、右上角寫時區。 - 例行任務(照排程的)和有排程的工作流:跑過的照執行紀錄(✓ 完成、✗ 失敗或中斷、■ 停止、圓點執行中),還沒到的用排程本身的 next_run 算(暫停的變灰帶 ‖);事件觸發的只看得到跑過的;每個一段期間最多 200 次。 - 週:每天一欄,時間+頭像,下面是名稱;月:每天三筆+「還有 N 個」,點那天換成日看法;日:照時間一列列。下面「即將執行」:所有 Bot 最先要跑的六筆。 - 點一筆打開卡片:時間、狀態、怎麼重複、最近一次、要它做什麼;打開聊天/立即執行/暫停繼續(工作流:打開工作流/立即執行)。「+ 新增例行任務」回到聊天、輸入框先放「每天早上 9 點幫我」。 - 功能地圖新的一區 schedule.md;library.md 的座標 76,30 → 32,30(最上面那排多了按鈕)。 工作流的審查(新開脈絡照 workflow.md 審 351ce3f,提了 6 個 P0/P1、3 個 P2,全修): 1. 停止時,還排在忙碌 Bot 後面的那步問題直接拿掉,不再停掉 Bot 手上不相干的那一輪(以前停掉了,排著的問題之後照樣送出)。 2. 交付遇到 Bot 正在回答:等那一輪結束才放進聊天(以前塞進去會被串流蓋掉)。 3. 重開 AnyBot:正在跑的那次標成失敗「AnyBot 在執行中被關掉…」(以前永遠卡住、排程從此不跑);等你確認的留著。 4. 刪除的允許卡片:要刪哪一個在問的當下就定下來寫進呼叫(以前卡片寫 B、按了刪 A);id 給錯(0、"x"、不存在)是錯誤,不會換成別的。 5. edit 設「僅一次」從設的那一刻算(以前可能永遠不跑)。 6. edit 的排程錯了,整次都不留(以前名字照樣改掉)。 另外:只有你正看著的那個 Bot 改工作流才會換畫布,換的時候放掉正在打字/拖的東西;新步驟不會用到執行或版本裡還有的編號;步驟的 Bot 被刪掉,那次停下來;螢幕電腦的選單不能新建、改名、還原、刪除。 已驗證: cargo test 860 過(新:schedule:: 一週的日曆(跑過/即將/暫停/事件觸發/工作流/上限)、日月週的範圍和標題;workflow:: 指定目標和釘住、改一半不留/僅一次/編號不重用/重開時中斷;app::workflow_run 停止拿掉排隊問題不停 Bot、交付等那一輪、Bot 被刪、別的 Bot 不換畫布;layout_audit 日程三景,窄視窗時標題不壓到日週月);clippy 沒有新的(bin 8)。scratch 真資料:手機聊天裡建兩個例行任務、立即執行一次,桌面:側邊欄日曆打開日程(✓ 今天那次、之後的圓點、即將執行六筆帶頭像),卡片、按暫停後變灰且 state 的 paused 是 true;月、日看法;所有檔案在 32,30 打得開。 未驗證: 這輪工作流的修正沒有再跑一次 workflow.md 的六步(單元測試有走每一條);重開 AnyBot 那條只有單元測試(scratch 的截圖模式不走啟動時的收尾)。刪工作流的卡片改在 app.rs 的 AppAction 分支先定目標:動到審批路徑,照規定要你看過再發佈。手機還沒有日程。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
2026-11-21 10:58:15 +00:00
// 日程 (laid out like OpenBot's 日程): every time a bot is set to do something — each bot's
// routines on a schedule and the workflows with a scheduled trigger — on one calendar: what ran
// and how it went (from their run records), and what is coming (from their schedules, the same
// way the scheduler works it out), so the person sees what each bot will do without asking it.
// Routines started by an event (a trigger) have no times ahead: only their runs show.
use crate::model::State;
use crate::routines::{self, RunOutcome};
use crate::workflow::{NodeKind, RunState};
/// What an entry is about.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum What {
Routine { bot: u64, id: u64 },
Workflow { id: u64 },
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Status {
Done,
Failed,
Stopped,
Running,
/// Will run then.
Coming,
/// Would run then, but it is paused.
Paused,
}
/// One time on the calendar.
#[derive(Clone, PartialEq, Debug)]
pub struct Item {
/// Seconds since 1970.
pub at: i64,
pub what: What,
/// The bot it belongs to (a workflow: the bot of its first step; 0 when it has none).
pub bot: u64,
pub title: String,
/// How it repeats (「每天 09:00」), or what starts it.
pub when: String,
pub status: Status,
}
/// At most this many times of one routine or workflow in one range (one every 5 minutes would
/// fill a month).
pub const MAX_PER_THING: usize = 200;
/// Everything on the calendar from `from` up to `to` (seconds), oldest first: the runs that
/// started then, and — from `now` on — the times still to come.
pub fn items(state: &State, from: i64, to: i64, now: i64) -> Vec<Item> {
let mut out = vec![];
for b in &state.bots {
for r in &b.routines {
let what = What::Routine { bot: b.id, id: r.id };
let when = match &r.trigger {
Some(t) => t.describe(),
None => routines::describe(&r.schedule),
};
for run in r.runs.iter().filter(|x| x.started >= from && x.started < to) {
let status = match run.outcome {
RunOutcome::Succeeded => Status::Done,
RunOutcome::Failed | RunOutcome::Interrupted => Status::Failed,
RunOutcome::Stopped => Status::Stopped,
RunOutcome::Running => Status::Running,
};
out.push(Item { at: run.started, what, bot: b.id, title: r.title.clone(), when: when.clone(), status });
}
if r.trigger.is_none() {
let status = if r.paused { Status::Paused } else { Status::Coming };
for at in times(&r.schedule, r.created_at, from.max(now), to) {
out.push(Item { at, what, bot: b.id, title: r.title.clone(), when: when.clone(), status });
}
}
}
}
for w in &state.workflows {
let what = What::Workflow { id: w.id };
let bot = w.order().iter().find_map(|n| match w.node(*n).map(|n| &n.kind) {
Some(NodeKind::Step { bot, .. } | NodeKind::Check { bot, .. } | NodeKind::Deliver { bot }) => Some(*bot),
_ => None,
});
let bot = bot.unwrap_or(0);
let when = w.schedule().map(routines::describe).unwrap_or_else(|| "手動".into());
for run in w.runs.iter().filter(|x| x.started >= from && x.started < to) {
let status = match run.state {
RunState::Done => Status::Done,
RunState::Failed => Status::Failed,
RunState::Stopped => Status::Stopped,
RunState::Running | RunState::Waiting => Status::Running,
};
out.push(Item { at: run.started, what, bot, title: w.name.clone(), when: when.clone(), status });
}
if let Some(s) = w.schedule() {
for at in times(s, w.created_at, from.max(now), to) {
out.push(Item { at, what, bot, title: w.name.clone(), when: when.clone(), status: Status::Coming });
}
}
}
out.sort_by(|a, b| a.at.cmp(&b.at).then(a.title.cmp(&b.title)));
out
}
/// The next few times coming, across everything (即將執行): paused ones left out.
pub fn coming(state: &State, now: i64, n: usize) -> Vec<Item> {
let mut out: Vec<Item> = items(state, now, now + 14 * 86_400, now).into_iter().filter(|i| i.status == Status::Coming).collect();
out.truncate(n);
out
}
/// The times a schedule runs after `from` and before `to`.
fn times(s: &routines::Schedule, created: i64, from: i64, to: i64) -> Vec<i64> {
let mut out = vec![];
let mut after = from - 1;
while out.len() < MAX_PER_THING {
match routines::next_run(s, created, after) {
Some(t) if t < to && t > after => {
out.push(t);
after = t;
}
_ => break,
}
}
out
}
/// Midnight of a day in a time zone, as seconds (the calendar's days are the person's days).
pub fn day_start(day: chrono::NaiveDate, timezone: &str) -> i64 {
use chrono::TimeZone;
let tz = routines::tz_of(timezone);
let midnight = day.and_hms_opt(0, 0, 0).unwrap_or_default();
match tz.from_local_datetime(&midnight) {
chrono::LocalResult::Single(t) | chrono::LocalResult::Ambiguous(t, _) => t.timestamp(),
// (A day that starts in a summer-time gap: an hour later.)
chrono::LocalResult::None => tz.from_local_datetime(&(midnight + chrono::Duration::hours(1))).earliest().map(|t| t.timestamp()).unwrap_or(0),
}
}
/// The day (in a time zone) a moment falls on.
pub fn day_of(at: i64, timezone: &str) -> chrono::NaiveDate {
use chrono::TimeZone;
chrono::Utc.timestamp_opt(at, 0).single().map(|t| t.with_timezone(&routines::tz_of(timezone)).date_naive()).unwrap_or_default()
}
/// 「21:11」 in a time zone.
pub fn clock(at: i64, timezone: &str) -> String {
use chrono::TimeZone;
chrono::Utc.timestamp_opt(at, 0).single().map(|t| t.with_timezone(&routines::tz_of(timezone)).format("%H:%M").to_string()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::routines::{Routine, RoutineRun, Schedule};
fn sched(v: serde_json::Value) -> Schedule {
routines::validate(serde_json::from_value(v).unwrap()).unwrap()
}
fn routine(id: u64, title: &str, s: Schedule, created: i64) -> Routine {
serde_json::from_value(serde_json::json!({"id": id, "title": title, "prompt": "做事", "schedule": s, "created_at": created})).unwrap()
}
/// A week in Taipei: the daily one each day at its time, the workday one Monday to Friday,
/// the paused one as paused; what ran before now shows how it went; an event one only its
/// runs; a scheduled workflow with the bot of its first step.
#[test]
fn the_calendar_shows_what_ran_and_what_is_coming() {
let tz = "Asia/Taipei";
let mut st = State::demo();
st.workflows.clear();
for b in st.bots.iter_mut() {
b.routines.clear();
}
let mon = chrono::NaiveDate::from_ymd_opt(2026, 11, 16).unwrap();
let from = day_start(mon, tz);
let to = day_start(mon + chrono::Duration::days(7), tz);
let created = from - 30 * 86_400;
// Now: Saturday 21 at 12:00.
let now = day_start(mon + chrono::Duration::days(5), tz) + 12 * 3600;
let mut daily = routine(1, "競品掃描", sched(serde_json::json!({"frequency": "daily", "time": "08:30", "timezone": tz})), created);
daily.runs.push(RoutineRun { started: day_start(mon + chrono::Duration::days(4), tz) + 8 * 3600 + 1800, ended: 0, outcome: RunOutcome::Succeeded, note: String::new(), steps: 3, failed_steps: 0, sent: 0, sends: vec![] });
daily.runs.push(RoutineRun { started: day_start(mon + chrono::Duration::days(5), tz) + 8 * 3600 + 1800, ended: 0, outcome: RunOutcome::Failed, note: "沒網路".into(), steps: 1, failed_steps: 1, sent: 0, sends: vec![] });
let workdays = routine(2, "晨報", sched(serde_json::json!({"frequency": "weekly", "daysOfWeek": ["MO", "TU", "WE", "TH", "FR"], "time": "09:00", "timezone": tz})), created);
let mut paused = routine(3, "週報", sched(serde_json::json!({"frequency": "daily", "time": "18:00", "timezone": tz})), created);
paused.paused = true;
let mut event = routine(4, "PR 合併", sched(serde_json::json!({"frequency": "daily", "time": "09:00", "timezone": tz})), created);
event.trigger = Some(crate::triggers::Trigger::Webhook { secret: "s".into() });
st.bots[0].routines = vec![daily, workdays, paused, event];
let bot = st.bots[0].id;
let mut w = crate::workflow::Workflow::new(1, "Threads 早報", created);
if let NodeKind::Trigger { schedule } = &mut w.nodes[0].kind {
*schedule = Some(sched(serde_json::json!({"frequency": "daily", "time": "07:00", "timezone": tz})));
}
w.nodes.push(crate::workflow::Node { id: 2, kind: NodeKind::Step { bot, prompt: "找".into() }, x: 0.0, y: 190.0 });
w.connect(1, 2);
st.workflows.push(w);
let all = items(&st, from, to, now);
let of = |title: &str| all.iter().filter(|i| i.title == title).map(|i| (day_of(i.at, tz).format("%d").to_string(), clock(i.at, tz), i.status)).collect::<Vec<_>>();
// Before now only what ran; from now on the times coming (Saturday 08:30 is past).
assert_eq!(of("競品掃描"), vec![("20".into(), "08:30".into(), Status::Done), ("21".into(), "08:30".into(), Status::Failed), ("22".into(), "08:30".into(), Status::Coming)]);
assert!(of("晨報").is_empty(), "Saturday and Sunday: no workdays left this week");
assert_eq!(of("週報"), vec![("21".into(), "18:00".into(), Status::Paused), ("22".into(), "18:00".into(), Status::Paused)]);
assert!(of("PR 合併").is_empty(), "an event one has no times ahead");
assert_eq!(of("Threads 早報"), vec![("22".into(), "07:00".into(), Status::Coming)]);
assert!(all.iter().filter(|i| i.title == "Threads 早報").all(|i| i.bot == bot && i.what == What::Workflow { id: 1 }));
assert!(all.windows(2).all(|w| w[0].at <= w[1].at), "oldest first");
// 即將執行: across everything, paused left out.
let next = coming(&st, now, 4);
let day = |i: &Item| day_of(i.at, tz).format("%d").to_string();
assert_eq!(
next.iter().map(|i| (day(i), clock(i.at, tz), i.title.as_str())).collect::<Vec<_>>(),
vec![("22".into(), "07:00".into(), "Threads 早報"), ("22".into(), "08:30".into(), "競品掃描"), ("23".into(), "07:00".into(), "Threads 早報"), ("23".into(), "08:30".into(), "競品掃描")]
);
assert!(next.iter().all(|i| i.status == Status::Coming && i.title != "週報"));
assert!(next.windows(2).all(|w| w[0].at <= w[1].at));
// One every 5 minutes: capped.
st.bots[0].routines.push(routine(5, "盯盤", sched(serde_json::json!({"frequency": "minutely", "interval": 5, "time": "00:00", "timezone": tz})), created));
assert_eq!(items(&st, from, to, now).iter().filter(|i| i.title == "盯盤").count(), MAX_PER_THING);
}
}