784 lines
37 KiB
Rust
784 lines
37 KiB
Rust
// Routines: tasks a bot repeats on a schedule. The schedule has the same shape as the original's
|
||
// (index.eager-app @1508626, `Prt` / `Irt`): frequency daily|weekly|monthly|yearly, an interval,
|
||
// weekdays MO..SU (`yA`), a day of the month or "the Nth weekday", a month, a time "HH:MM" and a
|
||
// time zone. Descriptions use the original's zh-TW wording (ids UdWx3W, orHQyz, W+dYrs, Y8bJts,
|
||
// kToBIG, kfbKQI, h3xQKP, ni0dzI, 1HiPWu, hlCyZb, kGmiCr, GGSF1N, gjpnJh, jjNxA6).
|
||
|
||
use chrono::{Datelike, Duration, NaiveDate, NaiveTime, TimeZone, Utc, Weekday};
|
||
use chrono_tz::Tz;
|
||
use serde::{Deserialize, Serialize};
|
||
|
||
/// The original's weekday order (`yA=["MO","TU","WE","TH","FR","SA","SU"]`).
|
||
pub const WEEKDAYS: [&str; 7] = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
|
||
pub const WORKWEEK: [&str; 5] = ["MO", "TU", "WE", "TH", "FR"];
|
||
const WEEKDAY_ZH: [&str; 7] = ["週一", "週二", "週三", "週四", "週五", "週六", "週日"];
|
||
const WEEKDAY_ZH_LONG: [&str; 7] = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
|
||
/// How far ahead to look for the next run (estimated).
|
||
const SEARCH_DAYS: i64 = 366 * 5;
|
||
|
||
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Debug)]
|
||
#[serde(rename_all = "lowercase")]
|
||
pub enum Frequency {
|
||
/// 每 N 分鐘 (counted from when it was made).
|
||
Minutely,
|
||
/// 每小時 / 每 N 小時, at the minute of `time`.
|
||
Hourly,
|
||
Daily,
|
||
Weekly,
|
||
Monthly,
|
||
Yearly,
|
||
}
|
||
|
||
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
|
||
pub struct WeekdayOfMonth {
|
||
/// 1..=4, or -1 for the last one.
|
||
pub week: i32,
|
||
pub day: String,
|
||
}
|
||
|
||
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
|
||
pub struct Schedule {
|
||
pub frequency: Frequency,
|
||
#[serde(default = "one")]
|
||
pub interval: u32,
|
||
#[serde(default, rename = "daysOfWeek", skip_serializing_if = "Vec::is_empty")]
|
||
pub days_of_week: Vec<String>,
|
||
#[serde(default, rename = "monthDay", skip_serializing_if = "Option::is_none")]
|
||
pub month_day: Option<u32>,
|
||
#[serde(default, rename = "weekdayOfMonth", skip_serializing_if = "Option::is_none")]
|
||
pub weekday_of_month: Option<WeekdayOfMonth>,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub month: Option<u32>,
|
||
/// "HH:MM", 24-hour.
|
||
pub time: String,
|
||
pub timezone: String,
|
||
/// 僅一次: runs once, then stops.
|
||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||
pub once: bool,
|
||
/// 「左右」: a flexible time, anywhere in ±FLEX_MINUTES (the original's flexible mode).
|
||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||
pub flexible: bool,
|
||
}
|
||
|
||
/// How far a flexible ("左右") time may move either way (estimated; the original has a window).
|
||
pub const FLEX_MINUTES: i64 = 15;
|
||
/// Shortest repeat for 每 N 分鐘 (estimated).
|
||
pub const MIN_MINUTES: u32 = 5;
|
||
|
||
fn one() -> u32 {
|
||
1
|
||
}
|
||
|
||
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||
pub struct Routine {
|
||
pub id: u64,
|
||
pub title: String,
|
||
/// What the bot is asked to do each time.
|
||
pub prompt: String,
|
||
pub schedule: Schedule,
|
||
#[serde(default)]
|
||
pub paused: bool,
|
||
/// Seconds since 1970 (UTC).
|
||
#[serde(default)]
|
||
pub created_at: i64,
|
||
#[serde(default)]
|
||
pub last_run: Option<i64>,
|
||
#[serde(default)]
|
||
pub next_run: Option<i64>,
|
||
/// Which computer to work on ("" = the bot's default).
|
||
#[serde(default)]
|
||
pub computer: String,
|
||
/// Run when something happens instead of on the schedule.
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub trigger: Option<crate::triggers::Trigger>,
|
||
/// 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<RoutineRun>,
|
||
/// 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 many sends a run is to make (0: none). The system counts them (not the
|
||
/// bot): no send past it, a run that ends short of it failed, and a run that makes none for
|
||
/// two check-ins in a row is stopped.
|
||
#[serde(default, skip_serializing_if = "is_zero_u32")]
|
||
pub target_sends: u32,
|
||
}
|
||
|
||
fn is_zero_u32(n: &u32) -> bool {
|
||
*n == 0
|
||
}
|
||
|
||
/// 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,
|
||
/// What went out and where, as the system saw it (「回覆 <post> → <reply's address>」): the
|
||
/// evidence, at most SENDS_KEPT.
|
||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||
pub sends: Vec<String>,
|
||
}
|
||
|
||
/// Evidence lines kept per run.
|
||
pub const SENDS_KEPT: usize = 30;
|
||
|
||
/// 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, sends: vec![] });
|
||
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, tally: &crate::evidence::Tally) -> bool {
|
||
let note = note.trim().to_string();
|
||
let (steps, failed_steps, sent) = (tally.steps, tally.failed, tally.sent);
|
||
// 完成條件: a run that says it is done but sent fewer than it was to (by the system's
|
||
// count) didn't make it.
|
||
let (outcome, note) = if self.target_sends > 0 && outcome == RunOutcome::Succeeded && sent < self.target_sends {
|
||
(RunOutcome::Failed, format!("只送出 {sent}/{} 則(系統計數){}", self.target_sends, if note.is_empty() { String::new() } else { format!(":{note}") }))
|
||
} else {
|
||
(outcome, note)
|
||
};
|
||
let sends: Vec<String> = tally.sends.iter().take(SENDS_KEPT).cloned().collect();
|
||
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;
|
||
r.sends = sends;
|
||
}
|
||
// (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, sends });
|
||
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<TurnResult> {
|
||
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 {
|
||
iana_time_zone::get_timezone().unwrap_or_else(|_| "Asia/Taipei".into())
|
||
}
|
||
|
||
/// The person's time zone (their setting), for times shown to them by an AnyBot whose own clock
|
||
/// may be elsewhere: a brain on a server runs in UTC, and a page 「更新於 今天 01:03」 meant 09:03.
|
||
static PERSON_TZ: std::sync::Mutex<String> = std::sync::Mutex::new(String::new());
|
||
|
||
/// A zone that only says where the computer is, not where the person is (a server's UTC).
|
||
pub fn is_server_default_zone(tz: &str) -> bool {
|
||
matches!(tz.trim(), "" | "UTC" | "Etc/UTC" | "Etc/Universal" | "Universal" | "Zulu" | "GMT" | "Etc/GMT")
|
||
}
|
||
|
||
pub fn set_person_timezone(tz: &str) {
|
||
*PERSON_TZ.lock().unwrap_or_else(|e| e.into_inner()) = tz.to_string();
|
||
}
|
||
|
||
pub fn person_tz() -> Tz {
|
||
tz_of(&PERSON_TZ.lock().unwrap_or_else(|e| e.into_inner()))
|
||
}
|
||
|
||
pub fn tz_of(name: &str) -> Tz {
|
||
name.parse::<Tz>().or_else(|_| local_timezone().parse::<Tz>()).unwrap_or(chrono_tz::Asia::Taipei)
|
||
}
|
||
|
||
fn weekday_code(w: Weekday) -> &'static str {
|
||
WEEKDAYS[w.num_days_from_monday() as usize]
|
||
}
|
||
|
||
fn weekday_index(code: &str) -> Option<usize> {
|
||
WEEKDAYS.iter().position(|w| w.eq_ignore_ascii_case(code))
|
||
}
|
||
|
||
pub fn parse_time(s: &str) -> Option<NaiveTime> {
|
||
NaiveTime::parse_from_str(s.trim(), "%H:%M").ok()
|
||
}
|
||
|
||
/// Check a schedule a model wrote, and tidy it.
|
||
pub fn validate(mut s: Schedule) -> Result<Schedule, String> {
|
||
if s.interval == 0 {
|
||
s.interval = 1;
|
||
}
|
||
if parse_time(&s.time).is_none() {
|
||
return Err(format!("時間「{}」看不懂,請用 24 小時制的 HH:MM,例如 09:00", s.time));
|
||
}
|
||
if s.timezone.trim().is_empty() || s.timezone.parse::<Tz>().is_err() {
|
||
s.timezone = local_timezone();
|
||
}
|
||
s.days_of_week = s.days_of_week.iter().filter_map(|d| weekday_index(d).map(|i| WEEKDAYS[i].to_string())).collect();
|
||
s.days_of_week.sort_by_key(|d| weekday_index(d));
|
||
s.days_of_week.dedup();
|
||
if s.frequency == Frequency::Minutely && s.interval < MIN_MINUTES {
|
||
return Err(format!("每 N 分鐘最少 {MIN_MINUTES} 分鐘"));
|
||
}
|
||
// Keep the "next run" maths (which searches interval-sized steps) bounded, and absurd
|
||
// intervals out: a huge hourly interval used to spin the UI thread for minutes on create.
|
||
let cap: u32 = match s.frequency {
|
||
Frequency::Minutely => 7 * 24 * 60,
|
||
Frequency::Hourly => 31 * 24,
|
||
Frequency::Daily => 366,
|
||
Frequency::Weekly => 53,
|
||
Frequency::Monthly => 120,
|
||
Frequency::Yearly => 10,
|
||
};
|
||
if s.interval > cap {
|
||
return Err(format!("間隔太大(這種頻率最多每 {cap} 單位一次)"));
|
||
}
|
||
if s.frequency == Frequency::Yearly {
|
||
let (m, d) = (s.month.unwrap_or(1), s.month_day.unwrap_or(1));
|
||
// 2 月 31 日永遠不會來:這個排程建立即失效,當初卻毫無警告。
|
||
if chrono::NaiveDate::from_ymd_opt(2024, m, d).is_none() {
|
||
return Err(format!("每年 {m} 月 {d} 日不存在,無法排入"));
|
||
}
|
||
}
|
||
match s.frequency {
|
||
Frequency::Weekly if s.days_of_week.is_empty() => return Err("每週的例行任務要指定星期幾(daysOfWeek,例如 [\"MO\",\"WE\"])".into()),
|
||
Frequency::Monthly if s.month_day.is_none() && s.weekday_of_month.is_none() => s.month_day = Some(1),
|
||
Frequency::Yearly if s.month.is_none() => s.month = Some(1),
|
||
_ => {}
|
||
}
|
||
if let Some(d) = s.month_day {
|
||
if !(1..=31).contains(&d) {
|
||
return Err("每月的日期要在 1 到 31 之間".into());
|
||
}
|
||
}
|
||
Ok(s)
|
||
}
|
||
|
||
/// "每週的週一、週三 09:00" in the original's wording.
|
||
pub fn describe(s: &Schedule) -> String {
|
||
let n = s.interval.max(1);
|
||
if s.frequency == Frequency::Minutely {
|
||
return format!("每 {n} 分鐘{}", if s.once { "(僅一次)" } else { "" });
|
||
}
|
||
if s.frequency == Frequency::Hourly {
|
||
let minute = parse_time(&s.time).map(|t| chrono::Timelike::minute(&t)).unwrap_or(0);
|
||
let base = if n > 1 { format!("每 {n} 小時") } else { "每小時".into() };
|
||
return format!("{base}的 {minute:02} 分{}{}", if s.flexible { "左右" } else { "" }, if s.once { "(僅一次)" } else { "" });
|
||
}
|
||
let unit = match s.frequency {
|
||
Frequency::Minutely | Frequency::Hourly => unreachable!(),
|
||
Frequency::Daily => "天",
|
||
Frequency::Weekly => "週",
|
||
Frequency::Monthly => "個月",
|
||
Frequency::Yearly => "年",
|
||
};
|
||
let duration = format!("{n} {unit}");
|
||
let repeats = match s.frequency {
|
||
Frequency::Minutely | Frequency::Hourly => unreachable!(),
|
||
Frequency::Daily => if n > 1 { format!("每{duration}") } else { "每天".into() },
|
||
Frequency::Weekly => {
|
||
let all_work = s.days_of_week.len() == WORKWEEK.len() && WORKWEEK.iter().all(|w| s.days_of_week.iter().any(|d| d == w));
|
||
if n == 1 && all_work {
|
||
"每個工作日".into()
|
||
} else {
|
||
let names: Vec<&str> = s.days_of_week.iter().filter_map(|d| weekday_index(d)).map(|i| WEEKDAY_ZH[i]).collect();
|
||
let names = names.join("、");
|
||
if n > 1 { format!("每{duration}的{names}") } else { format!("每週的{names}") }
|
||
}
|
||
}
|
||
Frequency::Monthly => match &s.weekday_of_month {
|
||
None => {
|
||
let d = s.month_day.unwrap_or(1);
|
||
if n > 1 { format!("每{duration}的{d}日") } else { format!("每月{d}日") }
|
||
}
|
||
Some(w) => {
|
||
let week = if w.week < 0 { "最後一個".to_string() } else { format!("第{}個", w.week) };
|
||
let day = weekday_index(&w.day).map(|i| WEEKDAY_ZH_LONG[i]).unwrap_or("");
|
||
if n > 1 { format!("每{duration}的{week}{day}") } else { format!("每月的{week}{day}") }
|
||
}
|
||
},
|
||
Frequency::Yearly => {
|
||
let date = format!("{}月{}日", s.month.unwrap_or(1), s.month_day.unwrap_or(1));
|
||
if n > 1 { format!("每{duration}的{date}") } else { format!("每年{date}") }
|
||
}
|
||
};
|
||
let sentence = format!("{}{repeats} {}{}", if s.once { "僅一次:" } else { "" }, s.time, if s.flexible { "左右" } else { "" });
|
||
if s.timezone == local_timezone() { sentence } else { format!("{sentence}({})", s.timezone) }
|
||
}
|
||
|
||
fn months_between(a: NaiveDate, b: NaiveDate) -> i64 {
|
||
(b.year() as i64 - a.year() as i64) * 12 + b.month() as i64 - a.month() as i64
|
||
}
|
||
|
||
fn nth_weekday_matches(d: NaiveDate, w: &WeekdayOfMonth) -> bool {
|
||
let Some(i) = weekday_index(&w.day) else { return false };
|
||
if d.weekday().num_days_from_monday() as usize != i {
|
||
return false;
|
||
}
|
||
if w.week < 0 {
|
||
(d + Duration::days(7)).month() != d.month()
|
||
} else {
|
||
((d.day() - 1) / 7 + 1) as i32 == w.week
|
||
}
|
||
}
|
||
|
||
fn day_matches(s: &Schedule, anchor: NaiveDate, d: NaiveDate) -> bool {
|
||
let n = s.interval.max(1) as i64;
|
||
match s.frequency {
|
||
Frequency::Minutely | Frequency::Hourly => true,
|
||
Frequency::Daily => (d - anchor).num_days().rem_euclid(n) == 0,
|
||
Frequency::Weekly => {
|
||
let week0 = anchor - Duration::days(anchor.weekday().num_days_from_monday() as i64);
|
||
let weeks = (d - week0).num_days().div_euclid(7);
|
||
weeks.rem_euclid(n) == 0 && s.days_of_week.iter().any(|w| w == weekday_code(d.weekday()))
|
||
}
|
||
Frequency::Monthly => {
|
||
months_between(anchor, d).rem_euclid(n) == 0
|
||
&& match &s.weekday_of_month {
|
||
Some(w) => nth_weekday_matches(d, w),
|
||
// A day past the month's end runs on its last day.
|
||
None => {
|
||
let want = s.month_day.unwrap_or(1);
|
||
let last = (d + Duration::days(1)).month() != d.month();
|
||
d.day() == want || (last && d.day() < want)
|
||
}
|
||
}
|
||
}
|
||
Frequency::Yearly => {
|
||
(d.year() - anchor.year()) as i64 % n == 0 && d.month() == s.month.unwrap_or(1) && d.day() == s.month_day.unwrap_or(1)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The first run strictly after `after`, counting intervals from `created`. A flexible time moves
|
||
/// by a steady amount within ±FLEX_MINUTES; a one-time schedule has no run after its first.
|
||
pub fn next_run(s: &Schedule, created: i64, after: i64) -> Option<i64> {
|
||
if s.once {
|
||
let first = exact_next(s, created, created - 1)?;
|
||
// A one-time run is never flexed: flexing its only moment into the past made the task
|
||
// born already-late and it died silently (next_run = None).
|
||
return (first > after).then_some(first);
|
||
}
|
||
// Look a little earlier so a time pulled forward by "左右" isn't skipped.
|
||
let pad = if s.flexible { FLEX_MINUTES * 60 } else { 0 };
|
||
let mut from = after - pad;
|
||
for _ in 0..4 {
|
||
let t = exact_next(s, created, from)?;
|
||
let f = flex(s, created, t);
|
||
if f > after {
|
||
return Some(f);
|
||
}
|
||
from = t;
|
||
}
|
||
None
|
||
}
|
||
|
||
fn flex(s: &Schedule, created: i64, t: i64) -> i64 {
|
||
if !s.flexible {
|
||
return t;
|
||
}
|
||
// A steady shift per run (same routine + same slot → same moment).
|
||
let h = (created as u64 ^ (t as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)).wrapping_mul(0xBF58_476D_1CE4_E5B9) >> 33;
|
||
t + (h % (2 * FLEX_MINUTES as u64 * 60 + 1)) as i64 - FLEX_MINUTES * 60
|
||
}
|
||
|
||
fn exact_next(s: &Schedule, created: i64, after: i64) -> Option<i64> {
|
||
let n = s.interval.max(1) as i64;
|
||
if s.frequency == Frequency::Minutely {
|
||
let step = n * 60;
|
||
let k = ((after - created).div_euclid(step) + 1).max(1);
|
||
return Some(created + k * step);
|
||
}
|
||
if s.frequency == Frequency::Hourly {
|
||
let minute = parse_time(&s.time).map(|t| chrono::Timelike::minute(&t) as i64).unwrap_or(0);
|
||
// Count hours in the schedule's own local wall clock (using each candidate hour's own
|
||
// UTC offset rather than `created`'s fixed offset, so +05:30/+05:45 AND DST transitions
|
||
// stay aligned to the local clock).
|
||
let tz = tz_of(&s.timezone);
|
||
let created_local = Utc.timestamp_opt(created, 0).single()?.with_timezone(&tz).naive_local();
|
||
let created_slot = created_local.date().and_hms_opt(chrono::Timelike::hour(&created_local), 0, 0)?;
|
||
let after_local = Utc.timestamp_opt(after, 0).single()?.with_timezone(&tz).naive_local();
|
||
let start_slot = after_local.date().and_hms_opt(chrono::Timelike::hour(&after_local), 0, 0)?;
|
||
for step in 0..(n * 3 + 4) {
|
||
let slot = start_slot + Duration::hours(step);
|
||
if (slot - created_slot).num_hours().rem_euclid(n) != 0 {
|
||
continue;
|
||
}
|
||
let local = slot + Duration::minutes(minute);
|
||
let at = match tz.from_local_datetime(&local) {
|
||
chrono::LocalResult::Single(at) => at,
|
||
chrono::LocalResult::Ambiguous(at, _) => at,
|
||
chrono::LocalResult::None => match tz.from_local_datetime(&(local + Duration::hours(1))).earliest() {
|
||
Some(at) => at,
|
||
None => continue,
|
||
},
|
||
};
|
||
let ts = at.timestamp();
|
||
if ts > after {
|
||
return Some(ts);
|
||
}
|
||
}
|
||
return None;
|
||
}
|
||
let tz = tz_of(&s.timezone);
|
||
let time = parse_time(&s.time)?;
|
||
let anchor = Utc.timestamp_opt(created, 0).single()?.with_timezone(&tz).date_naive();
|
||
let start = Utc.timestamp_opt(after, 0).single()?.with_timezone(&tz).date_naive();
|
||
for i in 0..SEARCH_DAYS {
|
||
let d = start + Duration::days(i);
|
||
if !day_matches(s, anchor, d) {
|
||
continue;
|
||
}
|
||
// Skipped or doubled clock times (summer time): a doubled time takes its first
|
||
// occurrence; a skipped one (spring-forward) runs just after the gap, not never.
|
||
let local = d.and_time(time);
|
||
let at = match tz.from_local_datetime(&local) {
|
||
chrono::LocalResult::Single(at) => at,
|
||
chrono::LocalResult::Ambiguous(at, _) => at,
|
||
chrono::LocalResult::None => match tz.from_local_datetime(&(local + Duration::hours(1))).earliest() {
|
||
Some(at) => at,
|
||
None => continue,
|
||
},
|
||
};
|
||
let ts = at.timestamp();
|
||
if ts > after {
|
||
return Some(ts);
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// "今天 09:00", "明天 09:00" or "11月5日 09:00" in the routine's time zone.
|
||
pub fn describe_when(ts: i64, timezone: &str) -> String {
|
||
let tz = tz_of(timezone);
|
||
let Some(t) = Utc.timestamp_opt(ts, 0).single().map(|t| t.with_timezone(&tz)) else { return String::new() };
|
||
let today = Utc::now().with_timezone(&tz).date_naive();
|
||
let day = match (t.date_naive() - today).num_days() {
|
||
0 => "今天".to_string(),
|
||
1 => "明天".to_string(),
|
||
_ => format!("{}月{}日", t.month(), t.day()),
|
||
};
|
||
format!("{day} {}", t.format("%H:%M"))
|
||
}
|
||
|
||
pub fn now() -> i64 {
|
||
Utc::now().timestamp()
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn a_servers_utc_is_not_the_persons_zone() {
|
||
assert!(super::is_server_default_zone("Etc/UTC") && super::is_server_default_zone("") && super::is_server_default_zone("UTC"));
|
||
assert!(!super::is_server_default_zone("Asia/Taipei") && !super::is_server_default_zone("Europe/London"));
|
||
}
|
||
|
||
use super::*;
|
||
|
||
fn ts(y: i32, m: u32, d: u32, h: u32, mi: u32) -> i64 {
|
||
chrono_tz::Asia::Taipei.with_ymd_and_hms(y, m, d, h, mi, 0).unwrap().timestamp()
|
||
}
|
||
|
||
/// Drop the "(Asia/Taipei)" a computer in another timezone adds.
|
||
fn here(s: String) -> String {
|
||
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(), target_sends: 0 }
|
||
}
|
||
|
||
#[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, "對話太長了", &crate::evidence::Tally { steps: 12, failed: 3, sent: 0, sends: vec![] }));
|
||
assert_eq!(r.runs[0], RoutineRun { started: 100, ended: 160, outcome: RunOutcome::Failed, note: "對話太長了".into(), steps: 12, failed_steps: 3, sent: 0, sends: vec![] });
|
||
// A success in between: the count starts again.
|
||
r.run_started(200);
|
||
r.run_ended(260, RunOutcome::Succeeded, "送出 15 則", &crate::evidence::Tally { steps: 80, failed: 2, sent: 0, sends: vec![] });
|
||
r.run_started(300);
|
||
assert!(!r.run_ended(360, RunOutcome::Failed, "找不到回覆框", &crate::evidence::Tally { steps: 5, failed: 5, sent: 0, sends: vec![] }));
|
||
// The person stopping it, or AnyBot closing, isn't the routine failing.
|
||
r.run_started(400);
|
||
r.run_ended(460, RunOutcome::Stopped, "被停止", &crate::evidence::Tally { steps: 2, failed: 0, sent: 0, sends: vec![] });
|
||
assert!(!r.paused);
|
||
r.run_started(500);
|
||
assert!(!r.run_ended(560, RunOutcome::Failed, "找不到回覆框", &crate::evidence::Tally { steps: 5, failed: 5, sent: 0, sends: vec![] }) && !r.paused, "a stop came between");
|
||
r.run_started(600);
|
||
assert!(r.run_ended(660, RunOutcome::Failed, "登入過期", &crate::evidence::Tally { steps: 3, failed: 3, sent: 0, sends: vec![] }));
|
||
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", &crate::evidence::Tally { steps: 0, failed: 0, sent: 0, sends: vec![] }));
|
||
}
|
||
|
||
#[test]
|
||
fn a_run_short_of_its_completion_condition_failed_whatever_it_says() {
|
||
let mut r = Routine { target_sends: 5, ..routine() };
|
||
let sends = |n: u32| crate::evidence::Tally { steps: 40, failed: 0, sent: n, sends: (0..n).map(|i| format!("回覆 https://www.threads.com/@a/post/X{i} → https://www.threads.com/@me/post/Y{i}")).collect() };
|
||
r.run_started(100);
|
||
r.run_ended(160, RunOutcome::Succeeded, "已完成 5 則回覆", &sends(3));
|
||
let run = &r.runs[0];
|
||
assert_eq!(run.outcome, RunOutcome::Failed);
|
||
assert_eq!(run.note, "只送出 3/5 則(系統計數):已完成 5 則回覆");
|
||
assert_eq!(run.sends.len(), 3, "the evidence is kept");
|
||
r.run_started(200);
|
||
r.run_ended(260, RunOutcome::Succeeded, "好了", &sends(5));
|
||
assert_eq!(r.runs[1].outcome, RunOutcome::Succeeded);
|
||
// No condition: what the turn said.
|
||
let mut free = routine();
|
||
free.run_started(100);
|
||
free.run_ended(160, RunOutcome::Succeeded, "好了", &sends(0));
|
||
assert_eq!(free.runs[0].outcome, RunOutcome::Succeeded);
|
||
}
|
||
|
||
#[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, "", &crate::evidence::Tally { steps: 1, failed: 0, sent: 0, sends: vec![] });
|
||
}
|
||
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, "好了", &crate::evidence::Tally { steps: 4, failed: 0, sent: 0, sends: vec![] });
|
||
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, sends: vec![] };
|
||
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, sends: vec![] };
|
||
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 }
|
||
}
|
||
|
||
#[test]
|
||
fn hourly_minutes_once_and_flexible() {
|
||
let mut h = sched(Frequency::Hourly);
|
||
h.time = "00:15".into();
|
||
assert_eq!(next_run(&h, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 20)), Some(ts(2026, 11, 3, 9, 15)));
|
||
h.interval = 3;
|
||
assert_eq!(next_run(&h, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 20)), Some(ts(2026, 11, 3, 11, 15)));
|
||
assert_eq!(describe(&h), "每 3 小時的 15 分");
|
||
// Across DST (America/New_York: EST UTC-5 in Jan, EDT UTC-4 in Jul), an hourly schedule stays aligned to wall-clock minutes and hours.
|
||
let mut ny = Schedule { interval: 2, time: "00:15".into(), timezone: "America/New_York".into(), ..sched(Frequency::Hourly) };
|
||
let jan = chrono_tz::America::New_York.with_ymd_and_hms(2026, 1, 10, 8, 0, 0).unwrap().timestamp();
|
||
let jul = chrono_tz::America::New_York.with_ymd_and_hms(2026, 7, 10, 8, 20, 0).unwrap().timestamp();
|
||
let next_jul = next_run(&ny, jan, jul).unwrap();
|
||
let ny_dt = Utc.timestamp_opt(next_jul, 0).unwrap().with_timezone(&chrono_tz::America::New_York);
|
||
assert_eq!(chrono::Timelike::minute(&ny_dt), 15);
|
||
ny.timezone = "Australia/Lord_Howe".into(); // 30-minute DST shift!
|
||
let lh_jan = chrono_tz::Australia::Lord_Howe.with_ymd_and_hms(2026, 1, 10, 8, 0, 0).unwrap().timestamp();
|
||
let lh_jul = chrono_tz::Australia::Lord_Howe.with_ymd_and_hms(2026, 7, 10, 8, 20, 0).unwrap().timestamp();
|
||
let next_lh = next_run(&ny, lh_jan, lh_jul).unwrap();
|
||
assert_eq!(chrono::Timelike::minute(&Utc.timestamp_opt(next_lh, 0).unwrap().with_timezone(&chrono_tz::Australia::Lord_Howe)), 15);
|
||
let mut m = sched(Frequency::Minutely);
|
||
m.interval = 30;
|
||
assert_eq!(next_run(&m, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 31)), Some(ts(2026, 11, 3, 9, 0)));
|
||
m.interval = 2;
|
||
assert!(validate(m).is_err());
|
||
let mut o = sched(Frequency::Daily);
|
||
o.once = true;
|
||
assert_eq!(next_run(&o, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 0)), Some(ts(2026, 11, 3, 9, 0)));
|
||
assert_eq!(next_run(&o, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 9, 0)), None);
|
||
let mut f = sched(Frequency::Daily);
|
||
f.flexible = true;
|
||
let t = next_run(&f, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 0)).unwrap();
|
||
assert!((t - ts(2026, 11, 3, 9, 0)).abs() <= FLEX_MINUTES * 60);
|
||
assert_eq!(next_run(&f, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 0)), Some(t));
|
||
assert!(here(describe(&f)).ends_with("09:00左右"));
|
||
let t2 = next_run(&f, ts(2026, 11, 3, 8, 0), t).unwrap();
|
||
assert!(t2 > t && (t2 - ts(2026, 11, 4, 9, 0)).abs() <= FLEX_MINUTES * 60);
|
||
}
|
||
|
||
#[test]
|
||
fn daily_and_weekly() {
|
||
let s = sched(Frequency::Daily);
|
||
// 2026-11-03 is a Tuesday.
|
||
assert_eq!(next_run(&s, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 0)), Some(ts(2026, 11, 3, 9, 0)));
|
||
assert_eq!(next_run(&s, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 9, 0)), Some(ts(2026, 11, 4, 9, 0)));
|
||
let mut w = sched(Frequency::Weekly);
|
||
w.days_of_week = vec!["MO".into(), "FR".into()];
|
||
assert_eq!(next_run(&w, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 0)), Some(ts(2026, 11, 6, 9, 0)));
|
||
w.interval = 2;
|
||
assert_eq!(next_run(&w, ts(2026, 11, 3, 8, 0), ts(2026, 11, 7, 8, 0)), Some(ts(2026, 11, 16, 9, 0)));
|
||
assert_eq!(here(describe(&w)), "每2 週的週一、週五 09:00");
|
||
w.interval = 1;
|
||
w.days_of_week = WORKWEEK.iter().map(|s| s.to_string()).collect();
|
||
assert_eq!(here(describe(&w)), "每個工作日 09:00");
|
||
}
|
||
|
||
#[test]
|
||
fn monthly_rules() {
|
||
let mut m = sched(Frequency::Monthly);
|
||
m.month_day = Some(31);
|
||
// November has 30 days: runs on the 30th.
|
||
assert_eq!(next_run(&m, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 0)), Some(ts(2026, 11, 30, 9, 0)));
|
||
m.month_day = None;
|
||
m.weekday_of_month = Some(WeekdayOfMonth { week: -1, day: "FR".into() });
|
||
assert_eq!(next_run(&m, ts(2026, 11, 3, 8, 0), ts(2026, 11, 3, 8, 0)), Some(ts(2026, 11, 27, 9, 0)));
|
||
assert_eq!(here(describe(&m)), "每月的最後一個星期五 09:00");
|
||
}
|
||
|
||
#[test]
|
||
fn validation() {
|
||
let mut w = sched(Frequency::Weekly);
|
||
assert!(validate(w.clone()).is_err());
|
||
w.days_of_week = vec!["fr".into(), "MO".into(), "MO".into()];
|
||
w.time = "7:30".into();
|
||
let v = validate(w).unwrap();
|
||
assert_eq!(v.days_of_week, vec!["MO", "FR"]);
|
||
let mut bad = sched(Frequency::Daily);
|
||
bad.time = "noon".into();
|
||
assert!(validate(bad).is_err());
|
||
}
|
||
}
|