| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use agents::{AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate}; |
| 5 | use chrono::{DateTime, Utc}; |
| 6 | use gpui_kit::*; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use tokio::sync::{mpsc, oneshot}; |
| 9 | |
| 10 | use super::{ |
| 11 | StartRequest, demo, mcp_bridge, mcp_config_directory, message_context, open_run_session, |
| 12 | store as run_store, |
| 13 | }; |
| 14 | use crate::app_state::AppState; |
| 15 | use crate::notice::truncated; |
| 16 | use crate::runtime; |
| 17 | |
| 18 | const STEP_LIMIT: usize = 50; |
| 19 | const VISIBLE_STEPS: usize = 6; |
| 20 | const VISIBLE_LOG_LINES: usize = 20; |
| 21 | const TEXT_STEP_CHARS: usize = 80; |
| 22 | const DONE_STEP_CHARS: usize = 60; |
| 23 | const TICK: Duration = Duration::from_secs(1); |
| 24 | |
| 25 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 26 | pub enum RunState { |
| 27 | Running, |
| 28 | Done, |
| 29 | Failed { message: String, log: Vec<String> }, |
| 30 | Stopped, |
| 31 | } |
| 32 | |
| 33 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 34 | pub struct AgentRun { |
| 35 | pub id: u64, |
| 36 | pub action_id: String, |
| 37 | pub action_label: String, |
| 38 | pub agent_id: String, |
| 39 | pub agent_name: String, |
| 40 | pub conversation_id: String, |
| 41 | pub message_id: String, |
| 42 | pub chat_title: String, |
| 43 | pub sender_name: String, |
| 44 | pub session_id: String, |
| 45 | pub working_dir: String, |
| 46 | pub extra: String, |
| 47 | pub state: RunState, |
| 48 | pub current_step: String, |
| 49 | pub steps: Vec<(Duration, String)>, |
| 50 | pub final_text: String, |
| 51 | pub started_at: DateTime<Utc>, |
| 52 | pub ended_at: Option<DateTime<Utc>>, |
| 53 | #[serde(skip)] |
| 54 | pub expanded: bool, |
| 55 | pub dismissed: bool, |
| 56 | } |
| 57 | |
| 58 | impl AgentRun { |
| 59 | pub fn is_running(&self) -> bool { |
| 60 | self.state == RunState::Running |
| 61 | } |
| 62 | |
| 63 | pub fn is_finished(&self) -> bool { |
| 64 | !self.is_running() |
| 65 | } |
| 66 | |
| 67 | pub fn elapsed(&self) -> Duration { |
| 68 | let end = self.ended_at.unwrap_or_else(Utc::now); |
| 69 | (end - self.started_at).to_std().unwrap_or_default() |
| 70 | } |
| 71 | |
| 72 | pub fn elapsed_text(&self) -> String { |
| 73 | format_elapsed(self.elapsed()) |
| 74 | } |
| 75 | |
| 76 | pub fn visible_steps(&self) -> &[(Duration, String)] { |
| 77 | let skipped = self.steps.len().saturating_sub(VISIBLE_STEPS); |
| 78 | &self.steps[skipped..] |
| 79 | } |
| 80 | |
| 81 | pub fn log_lines(&self) -> &[String] { |
| 82 | match &self.state { |
| 83 | RunState::Failed { log, .. } => { |
| 84 | let skipped = log.len().saturating_sub(VISIBLE_LOG_LINES); |
| 85 | &log[skipped..] |
| 86 | } |
| 87 | _ => &[], |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | pub fn layout_key(&self) -> (usize, bool) { |
| 92 | let rows = match (&self.state, self.expanded) { |
| 93 | (_, false) => 0, |
| 94 | (RunState::Failed { .. }, true) => self.log_lines().len().max(1), |
| 95 | (_, true) => self.visible_steps().len().max(1), |
| 96 | }; |
| 97 | (rows, self.is_running()) |
| 98 | } |
| 99 | |
| 100 | fn mark_interrupted(&mut self) { |
| 101 | let message = "Interrupted - the app was closed during the run".to_owned(); |
| 102 | self.current_step = message.clone(); |
| 103 | self.state = RunState::Failed { |
| 104 | message, |
| 105 | log: Vec::new(), |
| 106 | }; |
| 107 | self.ended_at = Some(Utc::now()); |
| 108 | } |
| 109 | |
| 110 | fn push_step(&mut self, text: String) { |
| 111 | let elapsed = (Utc::now() - self.started_at).to_std().unwrap_or_default(); |
| 112 | self.steps.push((elapsed, text.clone())); |
| 113 | if self.steps.len() > STEP_LIMIT { |
| 114 | self.steps.remove(0); |
| 115 | } |
| 116 | self.current_step = text; |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | fn remove_stale_mcp_configs() { |
| 121 | let Some(directory) = mcp_config_directory() else { |
| 122 | return; |
| 123 | }; |
| 124 | let Ok(entries) = std::fs::read_dir(directory) else { |
| 125 | return; |
| 126 | }; |
| 127 | for entry in entries.flatten() { |
| 128 | let _ = std::fs::remove_file(entry.path()); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | pub fn format_elapsed(duration: Duration) -> String { |
| 133 | let seconds = duration.as_secs(); |
| 134 | format!("{}:{:02}", seconds / 60, seconds % 60) |
| 135 | } |
| 136 | |
| 137 | fn first_line(text: &str) -> &str { |
| 138 | text.lines() |
| 139 | .find(|line| !line.trim().is_empty()) |
| 140 | .unwrap_or("") |
| 141 | .trim() |
| 142 | } |
| 143 | |
| 144 | pub struct AgentRunsHandle(pub Entity<AgentRuns>); |
| 145 | |
| 146 | impl Global for AgentRunsHandle {} |
| 147 | |
| 148 | pub enum AgentRunsEvent { |
| 149 | Finished(u64), |
| 150 | StartRequested(StartRequest), |
| 151 | OpenSettings, |
| 152 | } |
| 153 | |
| 154 | pub struct AgentRuns { |
| 155 | app: Entity<AppState>, |
| 156 | settings: AgentSettings, |
| 157 | runs: Vec<AgentRun>, |
| 158 | stops: HashMap<u64, oneshot::Sender<()>>, |
| 159 | open_after_stop: HashSet<u64>, |
| 160 | next_id: u64, |
| 161 | ticking: bool, |
| 162 | } |
| 163 | |
| 164 | impl EventEmitter<AgentRunsEvent> for AgentRuns {} |
| 165 | |
| 166 | impl AgentRuns { |
| 167 | pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self { |
| 168 | let store = app.read(cx).store.clone(); |
| 169 | let mut runs = run_store::load_runs(&store); |
| 170 | let interrupted = runs.iter().any(AgentRun::is_running); |
| 171 | for run in runs.iter_mut().filter(|run| run.is_running()) { |
| 172 | run.mark_interrupted(); |
| 173 | } |
| 174 | if interrupted { |
| 175 | run_store::save_runs(&store, &runs); |
| 176 | } |
| 177 | remove_stale_mcp_configs(); |
| 178 | if runs.is_empty() && app.read(cx).mode.demo { |
| 179 | runs = demo::runs(app.read(cx)); |
| 180 | } |
| 181 | let next_id = runs.iter().map(|run| run.id).max().map_or(1, |id| id + 1); |
| 182 | let mut agent_runs = AgentRuns { |
| 183 | app, |
| 184 | settings: run_store::load_settings(&store), |
| 185 | runs, |
| 186 | stops: HashMap::new(), |
| 187 | open_after_stop: HashSet::new(), |
| 188 | next_id, |
| 189 | ticking: false, |
| 190 | }; |
| 191 | agent_runs.ensure_ticking(cx); |
| 192 | agent_runs |
| 193 | } |
| 194 | |
| 195 | pub fn settings(&self) -> &AgentSettings { |
| 196 | &self.settings |
| 197 | } |
| 198 | |
| 199 | pub fn update_settings( |
| 200 | &mut self, |
| 201 | change: impl FnOnce(&mut AgentSettings), |
| 202 | cx: &mut Context<Self>, |
| 203 | ) { |
| 204 | change(&mut self.settings); |
| 205 | run_store::save_settings(&self.app.read(cx).store, &self.settings); |
| 206 | cx.notify(); |
| 207 | } |
| 208 | |
| 209 | pub fn get(&self, run_id: u64) -> Option<&AgentRun> { |
| 210 | self.runs.iter().find(|run| run.id == run_id) |
| 211 | } |
| 212 | |
| 213 | pub fn by_session(&self, session_id: &str) -> Option<&AgentRun> { |
| 214 | self.runs |
| 215 | .iter() |
| 216 | .rev() |
| 217 | .find(|run| run.session_id == session_id) |
| 218 | } |
| 219 | |
| 220 | pub fn for_conversation<'a>( |
| 221 | &'a self, |
| 222 | conversation_id: &'a str, |
| 223 | ) -> impl Iterator<Item = &'a AgentRun> { |
| 224 | self.runs |
| 225 | .iter() |
| 226 | .filter(move |run| run.conversation_id == conversation_id && !run.dismissed) |
| 227 | } |
| 228 | |
| 229 | pub fn running_count(&self) -> usize { |
| 230 | self.runs.iter().filter(|run| run.is_running()).count() |
| 231 | } |
| 232 | |
| 233 | pub fn recent(&self, limit: usize) -> Vec<&AgentRun> { |
| 234 | self.runs |
| 235 | .iter() |
| 236 | .rev() |
| 237 | .filter(|run| !run.dismissed) |
| 238 | .take(limit) |
| 239 | .collect() |
| 240 | } |
| 241 | |
| 242 | fn run_mut(&mut self, run_id: u64) -> Option<&mut AgentRun> { |
| 243 | self.runs.iter_mut().find(|run| run.id == run_id) |
| 244 | } |
| 245 | |
| 246 | fn persist(&self, cx: &App) { |
| 247 | run_store::save_runs(&self.app.read(cx).store, &self.runs); |
| 248 | } |
| 249 | |
| 250 | pub fn start( |
| 251 | &mut self, |
| 252 | action_id: &str, |
| 253 | conversation_id: &str, |
| 254 | message_id: &str, |
| 255 | extra: &str, |
| 256 | cx: &mut Context<Self>, |
| 257 | ) -> Result<u64, String> { |
| 258 | let action = self |
| 259 | .settings |
| 260 | .actions |
| 261 | .iter() |
| 262 | .find(|action| action.id == action_id) |
| 263 | .cloned() |
| 264 | .ok_or("This action no longer exists")?; |
| 265 | let profile = self |
| 266 | .settings |
| 267 | .agents |
| 268 | .iter() |
| 269 | .find(|profile| profile.id == action.agent_id) |
| 270 | .cloned() |
| 271 | .ok_or("The agent of this action no longer exists")?; |
| 272 | let context = message_context::build(self.app.read(cx), conversation_id, message_id) |
| 273 | .ok_or("The message is no longer available")?; |
| 274 | let session_id = agents::new_session_id(); |
| 275 | let prompt = agents::build_prompt(&action, &context, extra, &session_id, &profile.id); |
| 276 | let endpoint = mcp_bridge::endpoint(cx); |
| 277 | let plan = agents::build_invocation( |
| 278 | &profile, |
| 279 | &action, |
| 280 | &prompt, |
| 281 | &session_id, |
| 282 | endpoint.as_ref(), |
| 283 | mcp_config_directory().as_deref(), |
| 284 | ); |
| 285 | let run_id = self.next_id; |
| 286 | self.next_id += 1; |
| 287 | self.runs.push(AgentRun { |
| 288 | id: run_id, |
| 289 | action_id: action.id.clone(), |
| 290 | action_label: action.label.clone(), |
| 291 | agent_id: profile.id.clone(), |
| 292 | agent_name: profile.name.clone(), |
| 293 | conversation_id: conversation_id.to_owned(), |
| 294 | message_id: message_id.to_owned(), |
| 295 | chat_title: context.chat.clone(), |
| 296 | sender_name: context.sender.clone(), |
| 297 | session_id, |
| 298 | working_dir: action.working_dir.clone(), |
| 299 | extra: extra.to_owned(), |
| 300 | state: RunState::Running, |
| 301 | current_step: "Starting".to_owned(), |
| 302 | steps: Vec::new(), |
| 303 | final_text: String::new(), |
| 304 | started_at: Utc::now(), |
| 305 | ended_at: None, |
| 306 | expanded: false, |
| 307 | dismissed: false, |
| 308 | }); |
| 309 | if endpoint.is_none() |
| 310 | && let Some(run) = self.run_mut(run_id) |
| 311 | { |
| 312 | run.push_step("MCP server is off - no reply proposal possible".to_owned()); |
| 313 | } |
| 314 | match plan { |
| 315 | Ok(plan) => self.spawn(run_id, plan, profile.output, cx), |
| 316 | Err(error) => self.finish( |
| 317 | run_id, |
| 318 | Some(RunOutcome { |
| 319 | status: RunStatus::Failed { |
| 320 | message: error.to_string(), |
| 321 | stderr_tail: Vec::new(), |
| 322 | }, |
| 323 | exit_code: None, |
| 324 | }), |
| 325 | cx, |
| 326 | ), |
| 327 | } |
| 328 | self.persist(cx); |
| 329 | self.ensure_ticking(cx); |
| 330 | cx.notify(); |
| 331 | Ok(run_id) |
| 332 | } |
| 333 | |
| 334 | fn spawn( |
| 335 | &mut self, |
| 336 | run_id: u64, |
| 337 | plan: agents::RunPlan, |
| 338 | format: agents::OutputFormat, |
| 339 | cx: &mut Context<Self>, |
| 340 | ) { |
| 341 | let (updates_sender, mut updates) = mpsc::unbounded_channel(); |
| 342 | let (stop_sender, stop_receiver) = oneshot::channel(); |
| 343 | self.stops.insert(run_id, stop_sender); |
| 344 | let outcome = runtime::spawn(agents::run(plan, format, updates_sender, stop_receiver)); |
| 345 | cx.spawn(async move |this, cx| { |
| 346 | while let Some(update) = updates.recv().await { |
| 347 | if this |
| 348 | .update(cx, |runs, cx| runs.apply_update(run_id, update, cx)) |
| 349 | .is_err() |
| 350 | { |
| 351 | return; |
| 352 | } |
| 353 | } |
| 354 | let outcome = outcome.await.ok(); |
| 355 | this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx)) |
| 356 | .ok(); |
| 357 | }) |
| 358 | .detach(); |
| 359 | } |
| 360 | |
| 361 | fn apply_update(&mut self, run_id: u64, update: RunUpdate, cx: &mut Context<Self>) { |
| 362 | let RunUpdate::Event(event) = update else { |
| 363 | return; |
| 364 | }; |
| 365 | let Some(run) = self.run_mut(run_id) else { |
| 366 | return; |
| 367 | }; |
| 368 | match event { |
| 369 | RunEvent::Step(text) => run.push_step(text), |
| 370 | RunEvent::Text(text) => { |
| 371 | run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS) |
| 372 | } |
| 373 | _ => return, |
| 374 | } |
| 375 | cx.notify(); |
| 376 | } |
| 377 | |
| 378 | fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) { |
| 379 | self.stops.remove(&run_id); |
| 380 | let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) else { |
| 381 | return; |
| 382 | }; |
| 383 | run.ended_at = Some(Utc::now()); |
| 384 | match outcome.map(|outcome| outcome.status) { |
| 385 | Some(RunStatus::Completed { final_text }) => { |
| 386 | let line = truncated(first_line(&final_text), DONE_STEP_CHARS); |
| 387 | run.current_step = if line.is_empty() { |
| 388 | "Done".to_owned() |
| 389 | } else { |
| 390 | format!("Done - {line}") |
| 391 | }; |
| 392 | run.final_text = final_text; |
| 393 | run.state = RunState::Done; |
| 394 | } |
| 395 | Some(RunStatus::Failed { |
| 396 | message, |
| 397 | stderr_tail, |
| 398 | }) => { |
| 399 | run.current_step = message.clone(); |
| 400 | run.state = RunState::Failed { |
| 401 | message, |
| 402 | log: stderr_tail, |
| 403 | }; |
| 404 | } |
| 405 | Some(RunStatus::Stopped) => { |
| 406 | run.current_step = "Stopped".to_owned(); |
| 407 | run.state = RunState::Stopped; |
| 408 | } |
| 409 | None => { |
| 410 | let message = "The run was cancelled".to_owned(); |
| 411 | run.current_step = message.clone(); |
| 412 | run.state = RunState::Failed { |
| 413 | message, |
| 414 | log: Vec::new(), |
| 415 | }; |
| 416 | } |
| 417 | } |
| 418 | let stopped = run.state == RunState::Stopped; |
| 419 | let failed_or_done = !stopped; |
| 420 | let snapshot = run.clone(); |
| 421 | self.prune_finished(); |
| 422 | self.persist(cx); |
| 423 | if failed_or_done { |
| 424 | cx.emit(AgentRunsEvent::Finished(run_id)); |
| 425 | } |
| 426 | if self.open_after_stop.remove(&run_id) && stopped { |
| 427 | open_run_session(&snapshot, cx); |
| 428 | } |
| 429 | cx.notify(); |
| 430 | } |
| 431 | |
| 432 | fn prune_finished(&mut self) { |
| 433 | let finished = self.runs.iter().filter(|run| run.is_finished()).count(); |
| 434 | let mut excess = finished.saturating_sub(run_store::RUNS_HISTORY_LIMIT); |
| 435 | self.runs.retain(|run| { |
| 436 | if excess > 0 && run.is_finished() { |
| 437 | excess -= 1; |
| 438 | return false; |
| 439 | } |
| 440 | true |
| 441 | }); |
| 442 | } |
| 443 | |
| 444 | fn ensure_ticking(&mut self, cx: &mut Context<Self>) { |
| 445 | if self.ticking || self.running_count() == 0 { |
| 446 | return; |
| 447 | } |
| 448 | self.ticking = true; |
| 449 | cx.spawn(async move |this, cx| { |
| 450 | loop { |
| 451 | cx.background_executor().timer(TICK).await; |
| 452 | let keep_going = this |
| 453 | .update(cx, |runs, cx| { |
| 454 | runs.ticking = runs.running_count() > 0; |
| 455 | if runs.ticking { |
| 456 | cx.notify(); |
| 457 | } |
| 458 | runs.ticking |
| 459 | }) |
| 460 | .unwrap_or(false); |
| 461 | if !keep_going { |
| 462 | break; |
| 463 | } |
| 464 | } |
| 465 | }) |
| 466 | .detach(); |
| 467 | } |
| 468 | |
| 469 | pub fn stop(&mut self, run_id: u64, cx: &mut Context<Self>) { |
| 470 | if let Some(stop) = self.stops.remove(&run_id) { |
| 471 | let _ = stop.send(()); |
| 472 | if let Some(run) = self.run_mut(run_id) { |
| 473 | run.current_step = "Stopping".to_owned(); |
| 474 | } |
| 475 | cx.notify(); |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) { |
| 480 | self.open_after_stop.insert(run_id); |
| 481 | self.stop(run_id, cx); |
| 482 | } |
| 483 | |
| 484 | pub fn retry(&mut self, run_id: u64, cx: &mut Context<Self>) -> Result<u64, String> { |
| 485 | let run = self |
| 486 | .get(run_id) |
| 487 | .cloned() |
| 488 | .ok_or("This run no longer exists")?; |
| 489 | let started = self.start( |
| 490 | &run.action_id, |
| 491 | &run.conversation_id, |
| 492 | &run.message_id, |
| 493 | &run.extra, |
| 494 | cx, |
| 495 | )?; |
| 496 | self.dismiss(run_id, cx); |
| 497 | Ok(started) |
| 498 | } |
| 499 | |
| 500 | pub fn dismiss(&mut self, run_id: u64, cx: &mut Context<Self>) { |
| 501 | let Some(run) = self.run_mut(run_id).filter(|run| run.is_finished()) else { |
| 502 | return; |
| 503 | }; |
| 504 | run.dismissed = true; |
| 505 | self.persist(cx); |
| 506 | cx.notify(); |
| 507 | } |
| 508 | |
| 509 | pub fn toggle_expanded(&mut self, run_id: u64, cx: &mut Context<Self>) { |
| 510 | if let Some(run) = self.run_mut(run_id) { |
| 511 | run.expanded = !run.expanded; |
| 512 | cx.notify(); |
| 513 | } |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | #[cfg(test)] |
| 518 | pub(super) mod tests { |
| 519 | use std::sync::Arc; |
| 520 | use std::time::Duration; |
| 521 | |
| 522 | use agents::{AgentAction, AgentProfile, AgentSettings, Environment, OutputFormat}; |
| 523 | use chrono::TimeZone; |
| 524 | use store::{MessageRecord, Store}; |
| 525 | |
| 526 | use gpui_kit::{AppContext as _, Entity, TestAppContext}; |
| 527 | |
| 528 | use super::{AgentRun, AgentRuns, RunState, Utc, format_elapsed, run_store}; |
| 529 | use crate::app_state::{AppState, Mode}; |
| 530 | |
| 531 | pub fn finished_run(id: u64) -> AgentRun { |
| 532 | AgentRun { |
| 533 | id, |
| 534 | action_id: "answer-this".to_owned(), |
| 535 | action_label: "Answer this".to_owned(), |
| 536 | agent_id: "claude".to_owned(), |
| 537 | agent_name: "Claude Code".to_owned(), |
| 538 | conversation_id: "19:chat".to_owned(), |
| 539 | message_id: format!("m{id}"), |
| 540 | chat_title: "Ops".to_owned(), |
| 541 | sender_name: "Ada".to_owned(), |
| 542 | session_id: format!("session-{id}"), |
| 543 | working_dir: "~".to_owned(), |
| 544 | extra: String::new(), |
| 545 | state: RunState::Done, |
| 546 | current_step: "Done".to_owned(), |
| 547 | steps: vec![(Duration::from_secs(3), "Read a.rs".to_owned())], |
| 548 | final_text: "ok".to_owned(), |
| 549 | started_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(), |
| 550 | ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()), |
| 551 | expanded: false, |
| 552 | dismissed: false, |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | fn fake_settings(command: &str) -> AgentSettings { |
| 557 | let profile = AgentProfile { |
| 558 | id: "fake".to_owned(), |
| 559 | name: "Fake".to_owned(), |
| 560 | environment: Environment::Host, |
| 561 | command: command.to_owned(), |
| 562 | output: OutputFormat::ClaudeStreamJson, |
| 563 | open_session_command: String::new(), |
| 564 | mcp_config_flag: String::new(), |
| 565 | }; |
| 566 | let action = AgentAction { |
| 567 | id: "ask".to_owned(), |
| 568 | label: "Ask".to_owned(), |
| 569 | agent_id: "fake".to_owned(), |
| 570 | working_dir: std::env::temp_dir().to_string_lossy().into_owned(), |
| 571 | prompt_template: "{message}".to_owned(), |
| 572 | ask_extra_instructions: false, |
| 573 | extra_args: String::new(), |
| 574 | }; |
| 575 | AgentSettings { |
| 576 | agents: vec![profile], |
| 577 | actions: vec![action], |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | fn setup(cx: &mut TestAppContext, command: &str) -> (Entity<AppState>, Entity<AgentRuns>) { |
| 582 | cx.executor().allow_parking(); |
| 583 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 584 | store |
| 585 | .upsert_messages(&[MessageRecord { |
| 586 | conversation_id: "19:chat".to_owned(), |
| 587 | message_id: "m1".to_owned(), |
| 588 | sender_name: Some("Ada".to_owned()), |
| 589 | created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(), |
| 590 | body_html: "<p>Where is the report?</p>".to_owned(), |
| 591 | attachments_json: "[]".to_owned(), |
| 592 | reactions_json: "[]".to_owned(), |
| 593 | mentions_json: "[]".to_owned(), |
| 594 | links_json: "[]".to_owned(), |
| 595 | ..MessageRecord::default() |
| 596 | }]) |
| 597 | .unwrap(); |
| 598 | run_store::save_settings(&store, &fake_settings(command)); |
| 599 | cx.update(|cx| { |
| 600 | let app = cx.new(|_| AppState::new(store, Mode::default())); |
| 601 | let runs = cx.new(|cx| AgentRuns::new(app.clone(), cx)); |
| 602 | (app, runs) |
| 603 | }) |
| 604 | } |
| 605 | |
| 606 | fn wait_until_finished(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) { |
| 607 | for _ in 0..500 { |
| 608 | cx.run_until_parked(); |
| 609 | let finished = cx.update(|cx| { |
| 610 | runs.read(cx) |
| 611 | .get(run_id) |
| 612 | .is_some_and(|run| run.is_finished()) |
| 613 | }); |
| 614 | if finished { |
| 615 | return; |
| 616 | } |
| 617 | std::thread::sleep(Duration::from_millis(10)); |
| 618 | } |
| 619 | panic!("the run did not finish"); |
| 620 | } |
| 621 | |
| 622 | #[cfg(unix)] |
| 623 | mod shell_runs { |
| 624 | use super::{RunState, TestAppContext, run_store, setup, wait_until_finished}; |
| 625 | |
| 626 | #[gpui_kit::test] |
| 627 | fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) { |
| 628 | let fixture = concat!( |
| 629 | env!("CARGO_MANIFEST_DIR"), |
| 630 | "/../agents/tests/fixtures/claude-stream.jsonl" |
| 631 | ); |
| 632 | let (app, runs) = setup(cx, &format!("sh -c 'cat {fixture}'")); |
| 633 | let run_id = cx.update(|cx| { |
| 634 | runs.update(cx, |runs, cx| runs.start("ask", "19:chat", "m1", "", cx)) |
| 635 | .unwrap() |
| 636 | }); |
| 637 | wait_until_finished(cx, &runs, run_id); |
| 638 | cx.update(|cx| { |
| 639 | let run = runs.read(cx).get(run_id).unwrap().clone(); |
| 640 | assert_eq!(run.state, RunState::Done); |
| 641 | assert_eq!( |
| 642 | run.current_step, |
| 643 | "Done - The first word in `/etc/hostname` is `HOST01`." |
| 644 | ); |
| 645 | assert_eq!(run.steps.len(), 2); |
| 646 | assert_eq!( |
| 647 | run.steps[0].1, |
| 648 | "MCP server is off - no reply proposal possible" |
| 649 | ); |
| 650 | assert_eq!(run.steps[1].1, "Reading hostname"); |
| 651 | assert_eq!(run.chat_title, "Chat"); |
| 652 | assert_eq!(run.sender_name, "Ada"); |
| 653 | let stored = run_store::load_runs(&app.read(cx).store); |
| 654 | assert_eq!(stored.len(), 1); |
| 655 | assert_eq!(stored[0].state, RunState::Done); |
| 656 | assert_eq!(stored[0].session_id, run.session_id); |
| 657 | assert_eq!(runs.read(cx).running_count(), 0); |
| 658 | }); |
| 659 | } |
| 660 | |
| 661 | #[gpui_kit::test] |
| 662 | fn a_failing_command_ends_failed_with_its_stderr(cx: &mut TestAppContext) { |
| 663 | let (app, runs) = setup(cx, "sh -c 'echo boom >&2; exit 3'"); |
| 664 | let run_id = cx.update(|cx| { |
| 665 | runs.update(cx, |runs, cx| runs.start("ask", "19:chat", "m1", "", cx)) |
| 666 | .unwrap() |
| 667 | }); |
| 668 | wait_until_finished(cx, &runs, run_id); |
| 669 | cx.update(|cx| { |
| 670 | let run = runs.read(cx).get(run_id).unwrap().clone(); |
| 671 | assert_eq!( |
| 672 | run.state, |
| 673 | RunState::Failed { |
| 674 | message: "boom".to_owned(), |
| 675 | log: vec!["boom".to_owned()], |
| 676 | } |
| 677 | ); |
| 678 | assert_eq!(run.current_step, "boom"); |
| 679 | let stored = run_store::load_runs(&app.read(cx).store); |
| 680 | assert_eq!(stored[0].state, run.state); |
| 681 | }); |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | #[gpui_kit::test] |
| 686 | fn a_missing_action_is_an_error_and_starts_nothing(cx: &mut TestAppContext) { |
| 687 | let (_, runs) = setup(cx, "true"); |
| 688 | cx.update(|cx| { |
| 689 | let error = runs |
| 690 | .update(cx, |runs, cx| runs.start("ghost", "19:chat", "m1", "", cx)) |
| 691 | .unwrap_err(); |
| 692 | assert_eq!(error, "This action no longer exists"); |
| 693 | let error = runs |
| 694 | .update(cx, |runs, cx| runs.start("ask", "19:chat", "gone", "", cx)) |
| 695 | .unwrap_err(); |
| 696 | assert_eq!(error, "The message is no longer available"); |
| 697 | assert_eq!(runs.read(cx).running_count(), 0); |
| 698 | }); |
| 699 | } |
| 700 | |
| 701 | #[gpui_kit::test] |
| 702 | fn dismissed_runs_hide_and_stay_dismissed_after_reload(cx: &mut TestAppContext) { |
| 703 | let (app, runs) = setup(cx, "true"); |
| 704 | cx.update(|cx| { |
| 705 | runs.update(cx, |runs, cx| { |
| 706 | runs.runs.push(finished_run(7)); |
| 707 | runs.dismiss(7, cx); |
| 708 | assert!(runs.for_conversation("19:chat").next().is_none()); |
| 709 | assert!(runs.recent(10).is_empty()); |
| 710 | }); |
| 711 | let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx)); |
| 712 | let reloaded = reloaded.read(cx); |
| 713 | assert!(reloaded.get(7).is_some_and(|run| run.dismissed)); |
| 714 | assert_eq!(reloaded.next_id, 8); |
| 715 | }); |
| 716 | } |
| 717 | |
| 718 | #[gpui_kit::test] |
| 719 | fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) { |
| 720 | let (app, runs) = setup(cx, "true"); |
| 721 | cx.update(|cx| { |
| 722 | let mut running = finished_run(5); |
| 723 | running.state = RunState::Running; |
| 724 | running.ended_at = None; |
| 725 | runs.update(cx, |runs, cx| { |
| 726 | runs.runs.push(running); |
| 727 | runs.persist(cx); |
| 728 | }); |
| 729 | let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx)); |
| 730 | let run = reloaded.read(cx).get(5).unwrap().clone(); |
| 731 | assert!(matches!( |
| 732 | run.state, |
| 733 | RunState::Failed { ref message, .. } if message == "Interrupted - the app was closed during the run" |
| 734 | )); |
| 735 | assert!(run.ended_at.is_some()); |
| 736 | assert_eq!(run.session_id, "session-5"); |
| 737 | assert_eq!(reloaded.read(cx).running_count(), 0); |
| 738 | }); |
| 739 | } |
| 740 | |
| 741 | #[test] |
| 742 | fn layout_key_counts_visible_detail_rows() { |
| 743 | let mut run = finished_run(1); |
| 744 | assert_eq!(run.layout_key(), (0, false)); |
| 745 | run.expanded = true; |
| 746 | run.steps = (0..9) |
| 747 | .map(|index| (Duration::from_secs(index), index.to_string())) |
| 748 | .collect(); |
| 749 | assert_eq!(run.layout_key(), (6, false)); |
| 750 | assert_eq!(run.visible_steps()[0].1, "3"); |
| 751 | run.state = RunState::Running; |
| 752 | assert_eq!(run.layout_key(), (6, true)); |
| 753 | } |
| 754 | |
| 755 | #[test] |
| 756 | fn elapsed_reads_as_minutes_and_seconds() { |
| 757 | assert_eq!(format_elapsed(Duration::from_secs(42)), "0:42"); |
| 758 | assert_eq!(format_elapsed(Duration::from_secs(631)), "10:31"); |
| 759 | assert_eq!(finished_run(1).elapsed_text(), "1:00"); |
| 760 | } |
| 761 | } |