agentmux_srv/server/account_episodes/
machine.rs1use std::collections::{BTreeMap, HashMap, HashSet};
10
11use crate::backend::agent_state::AgentState;
12
13pub(crate) const SESSION_WINDOW: &str = "five_hour";
16
17pub(crate) const REOPEN_GRACE_MS: u64 = 5 * 60_000;
21
22#[derive(Debug, Clone, PartialEq, Eq)]
24pub(crate) struct BlockedPane {
25 pub block_id: String,
26 pub agent_id: String,
28 pub agent_name: String,
29 pub account_id: String,
30 pub provider: String,
32 pub state: AgentState,
33 pub resets_at_ms: Option<u64>,
34 pub limit_window: Option<String>,
35 pub signature: String,
38}
39
40impl BlockedPane {
41 fn wants_toast(&self) -> bool {
44 self.state == AgentState::SignedOut || self.limit_window.as_deref() != Some(SESSION_WINDOW)
45 }
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
50pub(crate) struct Episode {
51 pub account_id: String,
52 pub provider: String,
53 pub opened_at_ms: u64,
54 pub panes: Vec<BlockedPane>,
56 pub toasted: bool,
58 pub announced: HashSet<String>,
60 pub told: HashSet<String>,
62}
63
64impl Episode {
65 pub fn state(&self) -> AgentState {
67 if self.panes.iter().any(|p| p.state == AgentState::SignedOut) {
68 AgentState::SignedOut
69 } else {
70 AgentState::Limited
71 }
72 }
73
74 pub fn resets_at_ms(&self) -> Option<u64> {
77 if self.state() == AgentState::SignedOut {
78 return None;
79 }
80 self.panes.iter().filter_map(|p| p.resets_at_ms).max()
81 }
82
83 pub fn limit_window(&self) -> Option<String> {
85 let latest = self.resets_at_ms();
86 self.panes
87 .iter()
88 .find(|p| latest.is_some() && p.resets_at_ms == latest)
89 .or_else(|| self.panes.iter().find(|p| p.limit_window.is_some()))
90 .and_then(|p| p.limit_window.clone())
91 }
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
96pub(crate) enum Effect {
97 Changed(Episode),
99 Toast(Episode),
101 Announce { episode: Episode, panes: Vec<BlockedPane> },
103 Closed { account_id: String, provider: String },
105}
106
107#[derive(Debug, Default)]
109pub(crate) struct Episodes {
110 open: BTreeMap<String, Episode>,
111 baseline: HashMap<String, String>,
114 closed: HashMap<String, (Episode, u64)>,
116}
117
118impl Episodes {
119 pub fn new(baseline: HashMap<String, String>) -> Self {
120 Episodes { open: BTreeMap::new(), baseline, closed: HashMap::new() }
121 }
122
123 pub fn list(&self) -> impl Iterator<Item = &Episode> {
124 self.open.values()
125 }
126
127 pub fn get(&self, account_id: &str) -> Option<&Episode> {
128 self.open.get(account_id)
129 }
130
131 pub fn first_notes(&mut self, account_id: &str, requesters: impl IntoIterator<Item = String>) -> Vec<String> {
135 let Some(ep) = self.open.get_mut(account_id) else { return Vec::new() };
136 requesters.into_iter().filter(|r| ep.told.insert(r.to_lowercase())).collect()
137 }
138
139 pub fn update(&mut self, panes: Vec<BlockedPane>, now_ms: u64) -> Vec<Effect> {
141 let mut by_account: BTreeMap<String, Vec<BlockedPane>> = BTreeMap::new();
142 for p in panes {
143 by_account.entry(p.account_id.clone()).or_default().push(p);
144 }
145 let mut out = Vec::new();
146 self.closed.retain(|_, (_, at)| now_ms.saturating_sub(*at) <= REOPEN_GRACE_MS);
147 let closed: Vec<String> = self.open.keys().filter(|a| !by_account.contains_key(*a)).cloned().collect();
148 for account_id in closed {
149 if let Some(ep) = self.open.remove(&account_id) {
150 out.push(Effect::Closed { account_id: account_id.clone(), provider: ep.provider.clone() });
151 self.closed.insert(account_id, (ep, now_ms));
152 }
153 }
154 for (account_id, mut panes) in by_account {
155 panes.sort_by(|a, b| a.agent_name.to_lowercase().cmp(&b.agent_name.to_lowercase()).then(a.block_id.cmp(&b.block_id)));
156 panes.dedup_by(|a, b| a.block_id == b.block_id);
157 if !self.open.contains_key(&account_id) {
158 let fresh = Episode {
159 account_id: account_id.clone(),
160 provider: panes[0].provider.clone(),
161 opened_at_ms: now_ms,
162 panes: panes.clone(),
163 toasted: false,
164 announced: HashSet::new(),
165 told: HashSet::new(),
166 };
167 let reopened = match self.closed.remove(&account_id) {
169 Some((old, _)) if old.resets_at_ms() == fresh.resets_at_ms() && old.state() == fresh.state() => {
170 Episode { panes: Vec::new(), ..old }
171 }
172 _ => Episode { panes: Vec::new(), ..fresh },
173 };
174 self.open.insert(account_id.clone(), reopened);
175 }
176 let ep = self.open.get_mut(&account_id).expect("just inserted");
177 ep.announced.retain(|b| panes.iter().any(|p| &p.block_id == b));
179 let changed = ep.panes != panes;
180 if changed {
181 ep.panes = panes;
182 }
183 let fresh: Vec<BlockedPane> = ep.panes.iter().filter(|p| !ep.announced.contains(&p.block_id)).cloned().collect();
184 let mut news = Vec::new();
185 for p in fresh {
186 ep.announced.insert(p.block_id.clone());
187 let rebuilt = self.baseline.get(&p.block_id) == Some(&p.signature);
188 self.baseline.remove(&p.block_id);
189 if !rebuilt {
190 news.push(p);
191 }
192 }
193 if changed {
194 out.push(Effect::Changed(ep.clone()));
195 }
196 if !ep.toasted && news.iter().any(BlockedPane::wants_toast) {
197 ep.toasted = true;
198 out.push(Effect::Toast(ep.clone()));
199 }
200 if !news.is_empty() {
201 out.push(Effect::Announce { episode: ep.clone(), panes: news });
202 }
203 }
204 out
205 }
206}
207
208pub(crate) fn until_label(resets_at_ms: u64) -> Option<String> {
210 let t = chrono::DateTime::from_timestamp_millis(resets_at_ms as i64)?;
211 Some(format!("until {}", t.with_timezone(&chrono::Local).format("%a %-I:%M %p")))
212}
213
214pub(crate) fn toast_body(ep: &Episode) -> String {
216 let n = ep.panes.len();
217 let agents = if n == 1 { "1 agent".to_string() } else { format!("{n} agents") };
218 match ep.state() {
219 AgentState::SignedOut => format!("{agents} {} you to sign in again", if n == 1 { "needs" } else { "need" }),
220 _ => {
221 let verb = if n == 1 { "is" } else { "are" };
222 match ep.resets_at_ms().and_then(until_label) {
223 Some(until) => format!("{agents} {verb} out of quota {until}"),
224 None => format!("{agents} {verb} out of quota"),
225 }
226 }
227 }
228}
229
230fn task_list(refs: &[String]) -> String {
232 match refs {
233 [] => String::new(),
234 [one] => one.clone(),
235 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
236 }
237}
238
239pub(crate) fn leader_note(items: &[(&BlockedPane, &[String])]) -> String {
243 let clauses: Vec<String> = items
244 .iter()
245 .map(|(pane, refs)| {
246 let why = match pane.state {
247 AgentState::SignedOut => "needs the user to sign in again".to_string(),
248 _ => match pane.resets_at_ms.and_then(until_label) {
249 Some(until) => format!("is out of quota {until}"),
250 None => "is out of quota".to_string(),
251 },
252 };
253 format!("{} {why} and holds {}", pane.agent_name, task_list(refs))
254 })
255 .collect();
256 let signed_out = items.iter().filter(|(p, _)| p.state == AgentState::SignedOut).count();
259 let after = match (items.len(), signed_out) {
260 (1, 0) => "Until then, a message to it starts a turn that fails; move it to another account or wait for the reset.",
261 (1, _) => "Until it is signed in again, a message to it starts a turn that fails; sign it in again or move it to another account.",
262 (_, 0) => "Until then, a message to one of them starts a turn that fails; move them to another account or wait for the reset.",
263 (n, s) if n == s => {
264 "Until they are signed in again, a message to one of them starts a turn that fails; sign them in again or move them to another account."
265 }
266 _ => "Until then, a message to one of them starts a turn that fails; sign them in again, move them to another account or wait for the reset.",
267 };
268 format!("{}. {after}", clauses.join("; "))
269}
270
271#[cfg(test)]
272#[path = "machine_tests.rs"]
273mod tests;