fix(app): schedules fire their latest time, count speech only when heard, survive stops

- A repeating schedule the app was off for is judged by its latest time up to
  now, so today's reminder is not skipped after a night off.
- A spoken reminder counts as delivered only when its speech ends played to
  the end; speech that failed or was stopped goes to the chat channel.
- A schedule being delivered is marked firing; one still marked at the next
  start gets a failed outcome instead of vanishing without a reason.
- Deliveries run in the loop's JoinSet, so stopping the services stops them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-14 16:34:28 +09:00
parent ea2d3ba958
commit 5aa014543c
3 changed files with 175 additions and 20 deletions

View File

@@ -54,6 +54,10 @@ pub struct Schedule {
pub created: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last: Option<Outcome>,
/// Handed out by `take_due` and not finished yet; still set at the next start means the app
/// stopped while delivering it (`recover`).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub firing: bool,
}
#[derive(Debug, Default, Serialize, Deserialize)]
@@ -183,7 +187,8 @@ impl Store {
}
f.next_id += 1;
let item = Schedule { id: f.next_id, user, name: name.to_owned(), kind: kind.into(), text,
repeat: repeat.into(), next: Some(next), via: via.into(), channel, created: now, last: None };
repeat: repeat.into(), next: Some(next), via: via.into(), channel, created: now, last: None,
firing: false };
f.items.push(item.clone());
Ok(item)
})
@@ -198,22 +203,33 @@ impl Store {
})
}
/// The schedules due at `now`. A repeating one moves on to its next time; a one-off one stops
/// (`next` None) until `finished` records how it went. One more than `GRACE_SECS` late is not
/// handed out and is recorded as missed.
/// The schedules due at `now`. A repeating one is judged by its latest time up to `now` (the
/// ones before it, while the app was off, are passed over) and moves on to its next time; a
/// one-off one stops (`next` None). Each one handed out is `firing` until `finished` records how
/// it went. One more than `GRACE_SECS` late is not handed out and is recorded as missed.
pub fn take_due(&self, now: i64) -> Result<Vec<Due>, String> {
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let mut file = self.load()?;
let mut due = vec![];
let mut changed = false;
for item in file.items.iter_mut() {
let Some(t) = item.next.filter(|t| *t <= now) else { continue };
let Some(mut t) = item.next.filter(|t| *t <= now) else { continue };
changed = true;
if item.repeat != "none" {
loop {
let n = step(t, &item.repeat);
if n > now {
break;
}
t = n;
}
}
item.next = (item.repeat != "none").then(|| first_time(t, &item.repeat, now));
if now - t > GRACE_SECS {
item.last = Some(Outcome { at: now, ok: false, note: Some("앱이 꺼져 있어 제때 전하지 못함".into()) });
crate::warn_log!("schedule", "Warning: schedule {} missed ({} s late)", item.id, now - t);
} else {
item.firing = true;
due.push(Due { item: item.clone(), due: t });
}
}
@@ -232,6 +248,7 @@ impl Store {
f.items.remove(pos);
} else {
f.items[pos].last = Some(outcome);
f.items[pos].firing = false;
}
}
Ok(())
@@ -239,6 +256,23 @@ impl Store {
}
}
impl Store {
/// At start: the schedules a previous run handed out and never finished (it stopped while
/// delivering them) get a failed outcome. How many.
pub fn recover(&self, now: i64) -> Result<usize, String> {
self.change(|f| {
let mut n = 0;
for i in f.items.iter_mut().filter(|i| i.firing) {
i.firing = false;
i.last = Some(Outcome { at: now, ok: false, note: Some("전하는 도중 앱이 멈춤".into()) });
crate::warn_log!("schedule", "Warning: schedule {} was being delivered when the app stopped", i.id);
n += 1;
}
Ok(n)
})
}
}
/// A schedule as the brain's tool sees it.
pub fn brain_item(s: &Schedule) -> Value {
json!({"id": s.id.to_string(), "kind": s.kind, "text": s.text, "repeat": s.repeat,
@@ -272,8 +306,9 @@ pub fn act(store: &Store, a: &ScheduleAction, name: &str, now: i64) -> Result<Va
pub trait Deliver: Send + Sync {
/// The person is in Jarvis's voice channel.
fn hears(&self, user: u64) -> bool;
/// Speak in the voice channel; false when not in one.
fn say(&self, text: &str) -> bool;
/// Speak in the voice channel and wait until it was heard to the end; false when not in one,
/// or when the speech failed or was stopped.
async fn say(&self, text: &str) -> bool;
/// Post in a registered chat channel (never pinging anyone).
async fn post(&self, channel: u64, text: &str) -> Result<(), String>;
/// Run a task in the brain (read-only tools) and wait for its answer.
@@ -296,7 +331,8 @@ pub async fn deliver(d: &dyn Deliver, due: &Due, fallback: Option<u64>) -> Outco
s.text.clone()
};
let text = format!("{}님, {}", s.name, body.trim());
if s.via == "voice" && d.hears(s.user) && d.say(&text) {
// Speech that did not finish goes to the chat channel like a person who is not there.
if s.via == "voice" && d.hears(s.user) && d.say(&text).await {
crate::debug_log!("schedule", "schedule {} spoken chars={}", s.id, text.chars().count());
return Outcome { at: now(), ok: true, note: None };
}
@@ -316,13 +352,19 @@ pub async fn deliver(d: &dyn Deliver, due: &Due, fallback: Option<u64>) -> Outco
}
/// Fire due schedules until the task is aborted. Each delivery runs on its own, so a slow task does
/// not hold up a reminder due meanwhile.
/// not hold up a reminder due meanwhile; aborting the loop aborts the deliveries it started (they
/// are recorded as interrupted at the next start, `recover`).
pub async fn run(store: std::sync::Arc<Store>, d: std::sync::Arc<dyn Deliver>, fallback: Option<u64>) {
if let Err(e) = store.recover(chrono::Utc::now().timestamp()) {
crate::warn_log!("schedule", "Warning: {e}");
}
let mut deliveries = tokio::task::JoinSet::new();
loop {
while deliveries.try_join_next().is_some() {}
match store.take_due(chrono::Utc::now().timestamp()) {
Ok(due) => for item in due {
let (store, d) = (store.clone(), d.clone());
tokio::spawn(async move {
deliveries.spawn(async move {
let out = deliver(d.as_ref(), &item, fallback).await;
crate::info_log!("schedule", "schedule {} {}", item.item.id, if out.ok { "delivered" } else { "not delivered" });
if let Err(e) = store.finished(item.item.id, out) {
@@ -342,6 +384,7 @@ pub async fn run(store: std::sync::Arc<Store>, d: std::sync::Arc<dyn Deliver>, f
mod tests {
use super::*;
use chrono::Timelike;
use std::sync::Arc;
fn local(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> i64 {
Local.with_ymd_and_hms(y, mo, d, h, mi, 0).earliest().unwrap().timestamp()
@@ -435,6 +478,11 @@ mod tests {
#[derive(Default)]
struct Fake {
hears: bool,
/// The speech does not finish (it failed or was stopped).
speech_fails: bool,
/// task() never answers; `hung` is set while it waits and cleared when it is dropped.
hang: bool,
hung: Arc<std::sync::atomic::AtomicBool>,
said: Mutex<Vec<String>>,
posted: Mutex<Vec<(u64, String)>>,
post_fails: bool,
@@ -447,9 +495,9 @@ mod tests {
fn hears(&self, _user: u64) -> bool {
self.hears
}
fn say(&self, text: &str) -> bool {
async fn say(&self, text: &str) -> bool {
self.said.lock().unwrap().push(text.into());
true
!self.speech_fails
}
async fn post(&self, channel: u64, text: &str) -> Result<(), String> {
if self.post_fails {
@@ -460,13 +508,88 @@ mod tests {
}
async fn task(&self, _id: &str, user: u64, text: &str) -> Option<String> {
self.tasks.lock().unwrap().push((user, text.into()));
if self.hang {
struct Clear(Arc<std::sync::atomic::AtomicBool>);
impl Drop for Clear {
fn drop(&mut self) {
self.0.store(false, std::sync::atomic::Ordering::SeqCst);
}
}
self.hung.store(true, std::sync::atomic::Ordering::SeqCst);
let _clear = Clear(self.hung.clone());
std::future::pending::<()>().await;
}
self.answer.clone()
}
}
#[tokio::test]
async fn speech_that_does_not_finish_falls_back_to_the_chat_channel_or_fails() {
let f = Fake { hears: true, speech_fails: true, ..Default::default() };
assert!(deliver(&f, &due("remind", "voice", None), Some(9)).await.ok);
assert_eq!(*f.posted.lock().unwrap(), vec![(9, "철수님, 회의".to_string())]);
let out = deliver(&f, &due("remind", "voice", None), None).await;
assert!(!out.ok && out.note.is_some());
}
#[test]
fn a_repeating_schedule_the_app_was_off_for_still_fires_its_latest_time_when_recent() {
let s = store();
// Set on the 12th; the app was off until a minute after 9:00 on the 14th.
let d = s.add(1, "가", "remind", "b", local(2026, 11, 12, 9, 0), "daily", "voice", None,
local(2026, 11, 12, 8, 0)).unwrap();
let due = s.take_due(local(2026, 11, 14, 9, 1)).unwrap();
assert_eq!(due.iter().map(|d| (d.item.id, d.due)).collect::<Vec<_>>(), vec![(d.id, local(2026, 11, 14, 9, 0))]);
assert_eq!(s.all().unwrap()[0].next, Some(local(2026, 11, 15, 9, 0)));
// Off past the grace: that day's is missed, the next one stays.
let late = s.take_due(local(2026, 11, 15, 9, 30)).unwrap();
assert!(late.is_empty());
let item = s.all().unwrap()[0].clone();
assert_eq!(item.next, Some(local(2026, 11, 16, 9, 0)));
assert!(!item.last.unwrap().ok);
}
#[test]
fn a_schedule_taken_but_never_finished_is_recorded_as_interrupted_at_the_next_start() {
let s = store();
let a = s.add(1, "가", "remind", "a", 2000, "none", "voice", None, 1000).unwrap();
let b = s.add(1, "가", "remind", "b", 2000, "none", "voice", None, 1000).unwrap();
assert_eq!(s.take_due(2000).unwrap().len(), 2);
s.finished(b.id, Outcome { at: 2001, ok: false, note: Some("x".into()) }).unwrap();
// The app quit while `a` was being delivered.
assert_eq!(s.recover(3000).unwrap(), 1);
let all = s.all().unwrap();
let find = |id| all.iter().find(|i| i.id == id).unwrap().clone();
let last = find(a.id).last.unwrap();
assert!(!last.ok && last.note.is_some() && last.at == 3000);
assert_eq!(find(b.id).last.unwrap().note.as_deref(), Some("x"));
assert_eq!(s.recover(3001).unwrap(), 0);
}
#[tokio::test]
async fn stopping_the_loop_stops_the_deliveries_it_started() {
let data = crate::datadir::temp_dir("schedule-run");
let s = Arc::new(Store::new(&data));
let now = chrono::Utc::now().timestamp();
s.add(1, "가", "task", "x", now + 1, "none", "chat", Some(77), now).unwrap();
let f = Arc::new(Fake { hang: true, ..Default::default() });
let run = tokio::spawn(run(s.clone(), f.clone(), None));
let hung = f.hung.clone();
tokio::time::timeout(Duration::from_secs(10), async {
while !hung.load(std::sync::atomic::Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(50)).await;
}
}).await.expect("the task started");
run.abort();
let _ = run.await;
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(!hung.load(std::sync::atomic::Ordering::SeqCst), "the delivery was not stopped");
assert!(f.posted.lock().unwrap().is_empty());
}
fn due(kind: &str, via: &str, channel: Option<u64>) -> Due {
Due { item: Schedule { id: 1, user: 5, name: "철수".into(), kind: kind.into(), text: "회의".into(),
repeat: "none".into(), next: None, via: via.into(), channel, created: 0, last: None }, due: 10 }
repeat: "none".into(), next: None, via: via.into(), channel, created: 0, last: None, firing: false }, due: 10 }
}
#[tokio::test]