agentmux_srv/server/account_episodes/
resume.rs1use std::collections::HashMap;
25use std::sync::{Mutex, OnceLock};
26use std::time::Duration;
27
28use tokio::task::JoinSet;
29
30pub(super) const BATCH: usize = 3;
32
33pub(super) const BATCH_GAP: Duration = Duration::from_secs(2);
35
36const ONCE_MS: i64 = 60_000;
38
39const NOTE_KEY: &str = "signed-in-again";
41
42#[derive(Debug, Clone, PartialEq, Eq)]
44pub(super) struct Failed {
45 pub block_id: String,
46 pub failed_at_ms: Option<u64>,
48}
49
50pub(super) fn note_for(signed_in_ms: i64, failed_at_ms: Option<u64>) -> String {
52 use crate::muxbus::delivery_status::notes::hhmm;
53 let turn = match failed_at_ms {
54 Some(at) => format!("Your turn at {}", hhmm(i64::try_from(at).unwrap_or(0))),
55 None => "Your last turn".to_string(),
56 };
57 format!(
58 "Signed in again at {}. {turn} did not run because the login had expired. Carry on from where you were and say in a line or two where things stand.",
59 hhmm(signed_in_ms)
60 )
61}
62
63pub(super) fn batches(failed: Vec<Failed>) -> Vec<Vec<Failed>> {
65 failed.chunks(BATCH).map(<[Failed]>::to_vec).collect()
66}
67
68pub(super) fn not_just_told(told: &mut HashMap<String, i64>, failed: Vec<Failed>, now_ms: i64) -> Vec<Failed> {
70 told.retain(|_, at| now_ms - *at < ONCE_MS);
71 failed
72 .into_iter()
73 .filter(|f| {
74 if told.contains_key(&f.block_id) {
75 return false;
76 }
77 told.insert(f.block_id.clone(), now_ms);
78 true
79 })
80 .collect()
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85enum Told {
86 Turn,
88 Held,
90 Busy,
92 Failed,
94}
95
96fn tell(block_id: &str, text: &str) -> Told {
98 let Some(status) = crate::backend::blockcontroller::get_block_controller_status(block_id) else {
99 crate::backend::blockcontroller::system_note_into_turn_or_hold(block_id, NOTE_KEY, text);
100 return Told::Held;
101 };
102 if status.turn_active {
103 return Told::Busy;
104 }
105 let marked = crate::backend::reactive::sanitize::with_system_note_marker(text);
106 match crate::backend::reactive::get_global_handler().send_system_turn(block_id, &marked) {
107 Ok(crate::backend::reactive::SenderDelivery::Pty) => {
108 crate::backend::blockcontroller::system_note_into_turn_or_hold(block_id, NOTE_KEY, text);
110 Told::Held
111 }
112 Ok(_) => Told::Turn,
113 Err(e) => {
114 tracing::warn!(block_id = %block_id, error = %e, "sign-in: couldn't start the turn that tells an agent it is signed in; the note waits");
115 crate::backend::blockcontroller::system_note_into_turn_or_hold(block_id, NOTE_KEY, text);
116 Told::Failed
117 }
118 }
119}
120
121async fn run(failed: Vec<Failed>, signed_in_ms: i64) {
122 for (i, group) in batches(failed).into_iter().enumerate() {
123 if i > 0 {
124 tokio::time::sleep(BATCH_GAP).await;
125 }
126 let mut set = JoinSet::new();
127 for f in group {
128 let text = note_for(signed_in_ms, f.failed_at_ms);
129 set.spawn_blocking(move || (tell(&f.block_id, &text), f.block_id));
130 }
131 while let Some(done) = set.join_next().await {
132 if let Ok((told, block_id)) = done {
133 tracing::info!(block_id = %block_id, ?told, "sign-in: an agent whose turn failed on the login was told");
134 }
135 }
136 }
137}
138
139pub(super) fn start(failed: Vec<Failed>, signed_in_ms: i64) {
141 static TOLD: OnceLock<Mutex<HashMap<String, i64>>> = OnceLock::new();
142 let failed = not_just_told(&mut TOLD.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner()), failed, signed_in_ms);
143 if failed.is_empty() {
144 return;
145 }
146 let Ok(handle) = tokio::runtime::Handle::try_current() else {
147 tracing::warn!(panes = failed.len(), "sign-in: no runtime to tell the signed-in agents on");
148 return;
149 };
150 tracing::info!(panes = failed.len(), batch = BATCH, gap_ms = BATCH_GAP.as_millis() as u64, "sign-in: telling the agents whose turn failed on the login");
151 handle.spawn(run(failed, signed_in_ms));
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 fn failed(ids: &[&str]) -> Vec<Failed> {
159 ids.iter().map(|id| Failed { block_id: id.to_string(), failed_at_ms: Some(1_000) }).collect()
160 }
161
162 #[test]
163 fn the_note_says_when_it_signed_in_and_which_turn_did_not_run_and_asks_for_the_status() {
164 let note = note_for(1_700_000_100_000, Some(1_700_000_000_000));
165 assert!(note.starts_with("Signed in again at "), "{note}");
166 assert!(note.contains("Your turn at ") && note.contains("did not run because the login had expired"), "{note}");
167 assert!(note.ends_with("say in a line or two where things stand."), "{note}");
168 let unknown = note_for(1_700_000_100_000, None);
169 assert!(unknown.contains("Your last turn did not run"), "{unknown}");
170 }
171
172 #[test]
173 fn panes_are_told_a_few_at_a_time_in_the_order_they_failed_in() {
174 let groups = batches(failed(&["a", "b", "c", "d", "e", "f", "g"]));
175 let ids: Vec<Vec<&str>> = groups.iter().map(|g| g.iter().map(|f| f.block_id.as_str()).collect()).collect();
176 assert_eq!(ids, [vec!["a", "b", "c"], vec!["d", "e", "f"], vec!["g"]]);
177 assert!(groups.iter().all(|g| g.len() <= BATCH));
178 assert!(batches(Vec::new()).is_empty(), "no pane failed: nothing to tell");
179 }
180
181 #[test]
182 fn a_pane_told_a_moment_ago_is_not_told_again_but_is_after_a_while() {
183 let mut told = HashMap::new();
184 assert_eq!(not_just_told(&mut told, failed(&["a", "b"]), 1_000).len(), 2);
185 assert!(not_just_told(&mut told, failed(&["a", "b"]), 2_000).is_empty(), "the second report of the same sign-in");
186 assert_eq!(not_just_told(&mut told, failed(&["a", "c"]), 3_000), failed(&["c"]));
187 assert_eq!(not_just_told(&mut told, failed(&["a"]), 1_000 + ONCE_MS).len(), 1, "a later failure is told");
188 }
189
190 #[test]
191 fn a_pane_with_no_controller_keeps_the_note_for_its_next_turn_and_is_not_started() {
192 let block = format!("resume-test-{}", uuid::Uuid::new_v4());
193 assert_eq!(tell(&block, "Signed in again at 09:05."), Told::Held);
194 let (message, _held) = crate::backend::reactive::held_notes::attach(&block, "hello");
195 assert!(message.contains("Signed in again at 09:05."), "{message}");
196 }
197}