| 1 | use chrono::Local; |
| 2 | |
| 3 | use super::*; |
| 4 | |
| 5 | const WAKEUPS_KEY: &str = "agents.wakeups"; |
| 6 | |
| 7 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 8 | pub struct PendingWakeup { |
| 9 | pub session_id: String, |
| 10 | pub due_at: DateTime<Utc>, |
| 11 | pub prompt: String, |
| 12 | pub reason: String, |
| 13 | } |
| 14 | |
| 15 | impl PendingWakeup { |
| 16 | fn step(&self) -> String { |
| 17 | format!( |
| 18 | "Wakes up at {} - {}", |
| 19 | self.due_at |
| 20 | .with_timezone(&Local) |
| 21 | .format(app_base::format::clock_format()), |
| 22 | self.reason |
| 23 | ) |
| 24 | } |
| 25 | |
| 26 | fn prompt_text(&self) -> String { |
| 27 | format!("Scheduled wake-up ({}): {}", self.reason, self.prompt) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | pub(super) fn load(store: &store::Store) -> Vec<PendingWakeup> { |
| 32 | store |
| 33 | .meta(WAKEUPS_KEY) |
| 34 | .ok() |
| 35 | .flatten() |
| 36 | .and_then(|json| serde_json::from_str(&json).ok()) |
| 37 | .unwrap_or_default() |
| 38 | } |
| 39 | |
| 40 | fn save(store: &store::Store, wakeups: &[PendingWakeup]) { |
| 41 | if let Ok(json) = serde_json::to_string(wakeups) { |
| 42 | let _ = store.set_meta(WAKEUPS_KEY, &json); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl AgentRuns { |
| 47 | pub fn schedule_wakeup(&mut self, wakeup: mcp::Wakeup, cx: &mut Context<Self>) { |
| 48 | let pending = PendingWakeup { |
| 49 | session_id: wakeup.session_id, |
| 50 | due_at: wakeup.due_at, |
| 51 | prompt: wakeup.prompt, |
| 52 | reason: wakeup.reason, |
| 53 | }; |
| 54 | self.wakeups |
| 55 | .retain(|existing| existing.session_id != pending.session_id); |
| 56 | self.wakeups.push(pending.clone()); |
| 57 | self.save_wakeups(cx); |
| 58 | if let Some(run_id) = self.latest_run_of(&pending.session_id) |
| 59 | && let Some(run) = self.run_mut(run_id) |
| 60 | { |
| 61 | run.push_step(pending.step()); |
| 62 | } |
| 63 | self.arm(pending, cx); |
| 64 | self.persist(cx); |
| 65 | cx.notify(); |
| 66 | } |
| 67 | |
| 68 | pub fn wakeup_of(&self, session_id: &str) -> Option<&PendingWakeup> { |
| 69 | self.wakeups |
| 70 | .iter() |
| 71 | .find(|wakeup| wakeup.session_id == session_id) |
| 72 | } |
| 73 | |
| 74 | pub(super) fn wakeup_step(&self, session_id: &str) -> Option<String> { |
| 75 | self.wakeup_of(session_id).map(PendingWakeup::step) |
| 76 | } |
| 77 | |
| 78 | pub(super) fn app_session_ids(&self) -> HashSet<String> { |
| 79 | self.runs |
| 80 | .iter() |
| 81 | .filter(|run| run.launched) |
| 82 | .map(|run| run.session_id.clone()) |
| 83 | .collect() |
| 84 | } |
| 85 | |
| 86 | pub(super) fn arm_wakeups(&mut self, cx: &mut Context<Self>) { |
| 87 | for wakeup in self.wakeups.clone() { |
| 88 | self.arm(wakeup, cx); |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | pub(super) fn cancel_wakeup(&mut self, session_id: &str, cx: &mut Context<Self>) { |
| 93 | let before = self.wakeups.len(); |
| 94 | self.wakeups |
| 95 | .retain(|wakeup| wakeup.session_id != session_id); |
| 96 | if self.wakeups.len() != before { |
| 97 | self.save_wakeups(cx); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | fn arm(&self, wakeup: PendingWakeup, cx: &mut Context<Self>) { |
| 102 | let delay = (wakeup.due_at - Utc::now()).to_std().unwrap_or_default(); |
| 103 | let needs_mcp = self.uses_mcp(&wakeup.session_id); |
| 104 | cx.spawn(async move |this, cx| { |
| 105 | if !delay.is_zero() { |
| 106 | cx.background_executor().timer(delay).await; |
| 107 | } |
| 108 | let mut waited = Duration::ZERO; |
| 109 | while needs_mcp |
| 110 | && waited < MCP_WAIT_LIMIT |
| 111 | && !cx.update(|cx| mcp_bridge::endpoint(cx).is_some()) |
| 112 | { |
| 113 | cx.background_executor().timer(MCP_POLL_INTERVAL).await; |
| 114 | waited += MCP_POLL_INTERVAL; |
| 115 | } |
| 116 | this.update(cx, |runs, cx| runs.fire(&wakeup, cx)).ok(); |
| 117 | }) |
| 118 | .detach(); |
| 119 | } |
| 120 | |
| 121 | fn fire(&mut self, wakeup: &PendingWakeup, cx: &mut Context<Self>) { |
| 122 | if !self.wakeups.contains(wakeup) { |
| 123 | return; |
| 124 | } |
| 125 | self.cancel_wakeup(&wakeup.session_id, cx); |
| 126 | let Some(origin) = self |
| 127 | .latest_run_of(&wakeup.session_id) |
| 128 | .and_then(|run_id| self.get(run_id).cloned()) |
| 129 | else { |
| 130 | return; |
| 131 | }; |
| 132 | let run_id = self.next_id; |
| 133 | self.next_id += 1; |
| 134 | let mut run = AgentRun { |
| 135 | id: run_id, |
| 136 | state: RunState::Running, |
| 137 | current_step: String::new(), |
| 138 | steps: Vec::new(), |
| 139 | final_text: String::new(), |
| 140 | started_at: Utc::now(), |
| 141 | ended_at: None, |
| 142 | expanded: false, |
| 143 | dismissed: false, |
| 144 | process_id: None, |
| 145 | pending_prompt: Some(wakeup.prompt_text()), |
| 146 | sent_to: Some(SessionTarget { |
| 147 | session_id: origin.session_id.clone(), |
| 148 | working_dir: origin.working_dir.clone(), |
| 149 | inbox: None, |
| 150 | }), |
| 151 | launch_session_id: None, |
| 152 | launched: false, |
| 153 | ..origin |
| 154 | }; |
| 155 | run.push_step(format!("Woke up - {}", wakeup.reason)); |
| 156 | self.runs.push(run); |
| 157 | self.dispatch(run_id, cx); |
| 158 | self.persist(cx); |
| 159 | self.ensure_ticking(cx); |
| 160 | cx.notify(); |
| 161 | } |
| 162 | |
| 163 | fn uses_mcp(&self, session_id: &str) -> bool { |
| 164 | self.latest_run_of(session_id) |
| 165 | .and_then(|run_id| self.get(run_id)) |
| 166 | .and_then(|run| { |
| 167 | self.settings |
| 168 | .agents |
| 169 | .iter() |
| 170 | .find(|agent| agent.id == run.agent_id) |
| 171 | }) |
| 172 | .is_some_and(|agent| !agent.mcp_config_flag.is_empty()) |
| 173 | } |
| 174 | |
| 175 | fn latest_run_of(&self, session_id: &str) -> Option<u64> { |
| 176 | self.runs |
| 177 | .iter() |
| 178 | .filter(|run| run.session_id == session_id) |
| 179 | .map(|run| run.id) |
| 180 | .max() |
| 181 | } |
| 182 | |
| 183 | pub(super) fn save_wakeups(&self, cx: &App) { |
| 184 | save(&self.app.read(cx).store, &self.wakeups); |
| 185 | } |
| 186 | } |