BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / agents / runs.rs

runs.rs

runs.rs 38.0 KiB Download Raw
1use std::collections::{HashMap, HashSet, VecDeque};
2use std::time::Duration;
3
4use agents::{AgentAction, AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate};
5use chrono::{DateTime, Utc};
6use gpui_kit::*;
7use serde::{Deserialize, Serialize};
8use tokio::sync::{mpsc, oneshot};
9
10use super::{
11 MCP_POLL_INTERVAL, MCP_WAIT_LIMIT, StartRequest, demo, mcp_bridge, mcp_config_directory,
12 message_context, open_run_session, store as run_store,
13};
14use crate::app_state::AppState;
15use crate::notice::truncated;
16use crate::runtime;
17
18const STEP_LIMIT: usize = 50;
19const VISIBLE_STEPS: usize = 6;
20const VISIBLE_LOG_LINES: usize = 20;
21const TEXT_STEP_CHARS: usize = 80;
22const DONE_STEP_CHARS: usize = 60;
23const TICK: Duration = Duration::from_secs(1);
24const RESUME_PARALLEL_LIMIT: usize = 3;
25const RESUMED_STEP: &str = "Resumed after restart";
26const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";
27
28#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
29pub enum RunState {
30 Running,
31 Done,
32 Failed { message: String, log: Vec<String> },
33 Stopped,
34}
35
36#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
37pub struct AgentRun {
38 pub id: u64,
39 pub action_id: String,
40 pub action_label: String,
41 pub agent_id: String,
42 pub agent_name: String,
43 pub conversation_id: String,
44 pub message_id: String,
45 pub chat_title: String,
46 pub sender_name: String,
47 pub session_id: String,
48 pub working_dir: String,
49 pub extra: String,
50 pub state: RunState,
51 pub current_step: String,
52 pub steps: Vec<(Duration, String)>,
53 pub final_text: String,
54 pub started_at: DateTime<Utc>,
55 pub ended_at: Option<DateTime<Utc>>,
56 #[serde(skip)]
57 pub expanded: bool,
58 pub dismissed: bool,
59 #[serde(default)]
60 pub process_id: Option<u32>,
61}
62
63impl AgentRun {
64 pub fn is_running(&self) -> bool {
65 self.state == RunState::Running
66 }
67
68 pub fn is_finished(&self) -> bool {
69 !self.is_running()
70 }
71
72 pub fn elapsed(&self) -> Duration {
73 let end = self.ended_at.unwrap_or_else(Utc::now);
74 (end - self.started_at).to_std().unwrap_or_default()
75 }
76
77 pub fn elapsed_text(&self) -> String {
78 format_elapsed(self.elapsed())
79 }
80
81 pub fn visible_steps(&self) -> &[(Duration, String)] {
82 let skipped = self.steps.len().saturating_sub(VISIBLE_STEPS);
83 &self.steps[skipped..]
84 }
85
86 pub fn log_lines(&self) -> &[String] {
87 match &self.state {
88 RunState::Failed { log, .. } => {
89 let skipped = log.len().saturating_sub(VISIBLE_LOG_LINES);
90 &log[skipped..]
91 }
92 _ => &[],
93 }
94 }
95
96 pub fn layout_key(&self) -> (usize, bool) {
97 let rows = match (&self.state, self.expanded) {
98 (_, false) => 0,
99 (RunState::Failed { .. }, true) => self.log_lines().len().max(1),
100 (_, true) => self.visible_steps().len().max(1),
101 };
102 (rows, self.is_running())
103 }
104
105 fn mark_interrupted(&mut self) {
106 let message = "Interrupted - the app was closed during the run".to_owned();
107 self.current_step = message.clone();
108 self.state = RunState::Failed {
109 message,
110 log: Vec::new(),
111 };
112 self.ended_at = Some(Utc::now());
113 }
114
115 fn push_step(&mut self, text: String) {
116 let elapsed = (Utc::now() - self.started_at).to_std().unwrap_or_default();
117 self.steps.push((elapsed, text.clone()));
118 if self.steps.len() > STEP_LIMIT {
119 self.steps.remove(0);
120 }
121 self.current_step = text;
122 }
123}
124
125fn orphan_stop(run: &AgentRun, plan: &agents::RunPlan) -> Option<agents::Invocation> {
126 plan.stop.clone().or_else(|| {
127 run.process_id
128 .and_then(|process_id| agents::kill_process_invocation(process_id, &run.session_id))
129 })
130}
131
132fn can_resume(settings: &AgentSettings, run: &AgentRun) -> bool {
133 settings.resume_interrupted_runs
134 && !run.session_id.is_empty()
135 && settings
136 .agents
137 .iter()
138 .find(|agent| agent.id == run.agent_id)
139 .is_some_and(agents::supports_resume)
140}
141
142fn remove_stale_mcp_configs() {
143 let Some(directory) = mcp_config_directory() else {
144 return;
145 };
146 let Ok(entries) = std::fs::read_dir(directory) else {
147 return;
148 };
149 for entry in entries.flatten() {
150 let _ = std::fs::remove_file(entry.path());
151 }
152}
153
154pub fn format_elapsed(duration: Duration) -> String {
155 let seconds = duration.as_secs();
156 format!("{}:{:02}", seconds / 60, seconds % 60)
157}
158
159fn first_line(text: &str) -> &str {
160 text.lines()
161 .find(|line| !line.trim().is_empty())
162 .unwrap_or("")
163 .trim()
164}
165
166pub struct AgentRunsHandle(pub Entity<AgentRuns>);
167
168impl Global for AgentRunsHandle {}
169
170pub enum AgentRunsEvent {
171 Finished(u64),
172 StartRequested(StartRequest),
173 OpenSettings,
174}
175
176pub struct AgentRuns {
177 app: Entity<AppState>,
178 settings: AgentSettings,
179 runs: Vec<AgentRun>,
180 stops: HashMap<u64, oneshot::Sender<()>>,
181 resume_queue: VecDeque<u64>,
182 resuming: HashSet<u64>,
183 stopping: HashSet<u64>,
184 open_after_stop: HashSet<u64>,
185 next_id: u64,
186 ticking: bool,
187}
188
189impl EventEmitter<AgentRunsEvent> for AgentRuns {}
190
191impl AgentRuns {
192 pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
193 let store = app.read(cx).store.clone();
194 let settings = run_store::load_settings(&store);
195 let mut runs = run_store::load_runs(&store);
196 let interrupted = runs.iter().any(AgentRun::is_running);
197 let mut resume_queue = VecDeque::new();
198 for run in runs.iter_mut().filter(|run| run.is_running()) {
199 if can_resume(&settings, run) {
200 run.push_step(RESUMED_STEP.to_owned());
201 resume_queue.push_back(run.id);
202 } else {
203 run.mark_interrupted();
204 }
205 }
206 if interrupted {
207 run_store::save_runs(&store, &runs);
208 }
209 remove_stale_mcp_configs();
210 if runs.is_empty() && app.read(cx).mode.demo {
211 runs = demo::runs(app.read(cx));
212 }
213 let next_id = runs.iter().map(|run| run.id).max().map_or(1, |id| id + 1);
214 let mut agent_runs = AgentRuns {
215 app,
216 settings,
217 runs,
218 stops: HashMap::new(),
219 resume_queue,
220 resuming: HashSet::new(),
221 stopping: HashSet::new(),
222 open_after_stop: HashSet::new(),
223 next_id,
224 ticking: false,
225 };
226 agent_runs.ensure_ticking(cx);
227 agent_runs.start_resumes(cx);
228 agent_runs
229 }
230
231 fn start_resumes(&mut self, cx: &mut Context<Self>) {
232 if self.resume_queue.is_empty() {
233 return;
234 }
235 let needs_mcp = self.resume_queue.iter().any(|run_id| {
236 self.get(*run_id)
237 .and_then(|run| {
238 self.settings
239 .agents
240 .iter()
241 .find(|agent| agent.id == run.agent_id)
242 })
243 .is_some_and(|agent| !agent.mcp_config_flag.is_empty())
244 });
245 cx.spawn(async move |this, cx| {
246 let mut waited = Duration::ZERO;
247 while needs_mcp
248 && waited < MCP_WAIT_LIMIT
249 && !cx.update(|cx| mcp_bridge::endpoint(cx).is_some())
250 {
251 cx.background_executor().timer(MCP_POLL_INTERVAL).await;
252 waited += MCP_POLL_INTERVAL;
253 }
254 this.update(cx, |runs, cx| runs.resume_next(cx)).ok();
255 })
256 .detach();
257 }
258
259 fn resume_next(&mut self, cx: &mut Context<Self>) {
260 while self.resuming.len() < RESUME_PARALLEL_LIMIT {
261 let Some(run_id) = self.resume_queue.pop_front() else {
262 return;
263 };
264 self.begin_resume(run_id, cx);
265 }
266 }
267
268 fn resume_plan(
269 &self,
270 run: &AgentRun,
271 cx: &App,
272 ) -> Result<(agents::RunPlan, agents::OutputFormat), String> {
273 let action = self
274 .settings
275 .actions
276 .iter()
277 .find(|action| action.id == run.action_id)
278 .cloned()
279 .ok_or("the action no longer exists")?;
280 let profile = self
281 .settings
282 .agents
283 .iter()
284 .find(|profile| profile.id == run.agent_id)
285 .ok_or("the agent no longer exists")?;
286 let action = AgentAction {
287 working_dir: run.working_dir.clone(),
288 ..action
289 };
290 let plan = agents::resume_invocation(
291 profile,
292 &action,
293 RESUME_PROMPT,
294 &run.session_id,
295 mcp_bridge::endpoint(cx).as_ref(),
296 mcp_config_directory().as_deref(),
297 )
298 .map_err(|error| error.to_string())?;
299 Ok((plan, profile.output))
300 }
301
302 fn begin_resume(&mut self, run_id: u64, cx: &mut Context<Self>) {
303 let Some(run) = self.get(run_id).filter(|run| run.is_running()).cloned() else {
304 return;
305 };
306 self.resuming.insert(run_id);
307 match self.resume_plan(&run, cx) {
308 Ok((plan, format)) => {
309 let stop = orphan_stop(&run, &plan);
310 cx.spawn(async move |this, cx| {
311 if let Some(stop) = stop {
312 let _ =
313 runtime::spawn(async move { agents::run_stop_invocation(&stop).await })
314 .await;
315 }
316 this.update(cx, |runs, cx| {
317 let still_resuming = runs.resuming.contains(&run_id)
318 && runs.get(run_id).is_some_and(AgentRun::is_running);
319 if still_resuming {
320 runs.spawn(run_id, plan, format, cx);
321 } else {
322 for path in &plan.cleanup {
323 let _ = std::fs::remove_file(path);
324 }
325 }
326 })
327 .ok();
328 })
329 .detach();
330 }
331 Err(reason) => self.finish(
332 run_id,
333 Some(RunOutcome {
334 status: RunStatus::Failed {
335 message: format!("Could not resume - {reason}"),
336 stderr_tail: Vec::new(),
337 },
338 exit_code: None,
339 }),
340 cx,
341 ),
342 }
343 }
344
345 pub fn settings(&self) -> &AgentSettings {
346 &self.settings
347 }
348
349 pub fn update_settings(
350 &mut self,
351 change: impl FnOnce(&mut AgentSettings),
352 cx: &mut Context<Self>,
353 ) {
354 change(&mut self.settings);
355 run_store::save_settings(&self.app.read(cx).store, &self.settings);
356 cx.notify();
357 }
358
359 pub fn get(&self, run_id: u64) -> Option<&AgentRun> {
360 self.runs.iter().find(|run| run.id == run_id)
361 }
362
363 pub fn by_session(&self, session_id: &str) -> Option<&AgentRun> {
364 self.runs
365 .iter()
366 .rev()
367 .find(|run| run.session_id == session_id)
368 }
369
370 pub fn for_conversation<'a>(
371 &'a self,
372 conversation_id: &'a str,
373 ) -> impl Iterator<Item = &'a AgentRun> {
374 self.runs
375 .iter()
376 .filter(move |run| run.conversation_id == conversation_id && !run.dismissed)
377 }
378
379 pub fn running_count(&self) -> usize {
380 self.runs.iter().filter(|run| run.is_running()).count()
381 }
382
383 pub fn recent(&self, limit: usize) -> Vec<&AgentRun> {
384 self.runs
385 .iter()
386 .rev()
387 .filter(|run| !run.dismissed)
388 .take(limit)
389 .collect()
390 }
391
392 fn run_mut(&mut self, run_id: u64) -> Option<&mut AgentRun> {
393 self.runs.iter_mut().find(|run| run.id == run_id)
394 }
395
396 fn persist(&self, cx: &App) {
397 run_store::save_runs(&self.app.read(cx).store, &self.runs);
398 }
399
400 pub fn start(
401 &mut self,
402 action_id: &str,
403 conversation_id: &str,
404 message_id: &str,
405 extra: &str,
406 cx: &mut Context<Self>,
407 ) -> Result<u64, String> {
408 let action = self
409 .settings
410 .actions
411 .iter()
412 .find(|action| action.id == action_id)
413 .cloned()
414 .ok_or("This action no longer exists")?;
415 let profile = self
416 .settings
417 .agents
418 .iter()
419 .find(|profile| profile.id == action.agent_id)
420 .cloned()
421 .ok_or("The agent of this action no longer exists")?;
422 let context = message_context::build(self.app.read(cx), conversation_id, message_id)
423 .ok_or("The message is no longer available")?;
424 let session_id = agents::new_session_id();
425 let prompt = agents::build_prompt(&action, &context, extra, &session_id, &profile.id);
426 let endpoint = mcp_bridge::endpoint(cx);
427 let plan = agents::build_invocation(
428 &profile,
429 &action,
430 &prompt,
431 &session_id,
432 endpoint.as_ref(),
433 mcp_config_directory().as_deref(),
434 );
435 let run_id = self.next_id;
436 self.next_id += 1;
437 self.runs.push(AgentRun {
438 id: run_id,
439 action_id: action.id.clone(),
440 action_label: action.label.clone(),
441 agent_id: profile.id.clone(),
442 agent_name: profile.name.clone(),
443 conversation_id: conversation_id.to_owned(),
444 message_id: message_id.to_owned(),
445 chat_title: context.chat.clone(),
446 sender_name: context.sender.clone(),
447 session_id,
448 working_dir: action.working_dir.clone(),
449 extra: extra.to_owned(),
450 state: RunState::Running,
451 current_step: "Starting".to_owned(),
452 steps: Vec::new(),
453 final_text: String::new(),
454 started_at: Utc::now(),
455 ended_at: None,
456 expanded: false,
457 dismissed: false,
458 process_id: None,
459 });
460 if endpoint.is_none()
461 && let Some(run) = self.run_mut(run_id)
462 {
463 run.push_step("MCP server is off - no reply proposal possible".to_owned());
464 }
465 match plan {
466 Ok(plan) => self.spawn(run_id, plan, profile.output, cx),
467 Err(error) => self.finish(
468 run_id,
469 Some(RunOutcome {
470 status: RunStatus::Failed {
471 message: error.to_string(),
472 stderr_tail: Vec::new(),
473 },
474 exit_code: None,
475 }),
476 cx,
477 ),
478 }
479 self.persist(cx);
480 self.ensure_ticking(cx);
481 cx.notify();
482 Ok(run_id)
483 }
484
485 fn spawn(
486 &mut self,
487 run_id: u64,
488 plan: agents::RunPlan,
489 format: agents::OutputFormat,
490 cx: &mut Context<Self>,
491 ) {
492 let (updates_sender, mut updates) = mpsc::unbounded_channel();
493 let (stop_sender, stop_receiver) = oneshot::channel();
494 self.stops.insert(run_id, stop_sender);
495 let outcome = runtime::spawn(agents::run(plan, format, updates_sender, stop_receiver));
496 cx.spawn(async move |this, cx| {
497 while let Some(update) = updates.recv().await {
498 if this
499 .update(cx, |runs, cx| runs.apply_update(run_id, update, cx))
500 .is_err()
501 {
502 return;
503 }
504 }
505 let outcome = outcome.await.ok();
506 this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))
507 .ok();
508 })
509 .detach();
510 }
511
512 fn apply_update(&mut self, run_id: u64, update: RunUpdate, cx: &mut Context<Self>) {
513 let event = match update {
514 RunUpdate::Event(event) => event,
515 RunUpdate::Started(process_id) => {
516 if let Some(run) = self.run_mut(run_id) {
517 run.process_id = Some(process_id);
518 self.persist(cx);
519 }
520 return;
521 }
522 RunUpdate::Stderr(_) => return,
523 };
524 let Some(run) = self.run_mut(run_id) else {
525 return;
526 };
527 match event {
528 RunEvent::Step(text) => run.push_step(text),
529 RunEvent::Text(text) => {
530 run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)
531 }
532 _ => return,
533 }
534 cx.notify();
535 }
536
537 fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {
538 self.stops.remove(&run_id);
539 self.stopping.remove(&run_id);
540 let was_resuming = self.resuming.remove(&run_id);
541 let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) else {
542 return;
543 };
544 run.ended_at = Some(Utc::now());
545 run.process_id = None;
546 match outcome.map(|outcome| outcome.status) {
547 Some(RunStatus::Completed { final_text }) => {
548 let line = truncated(first_line(&final_text), DONE_STEP_CHARS);
549 run.current_step = if line.is_empty() {
550 "Done".to_owned()
551 } else {
552 format!("Done - {line}")
553 };
554 run.final_text = final_text;
555 run.state = RunState::Done;
556 }
557 Some(RunStatus::Failed {
558 message,
559 stderr_tail,
560 }) => {
561 let message = if was_resuming && message.starts_with("cannot start") {
562 format!("Could not resume - {message}")
563 } else {
564 message
565 };
566 run.current_step = message.clone();
567 run.state = RunState::Failed {
568 message,
569 log: stderr_tail,
570 };
571 }
572 Some(RunStatus::Stopped) => {
573 run.current_step = "Stopped".to_owned();
574 run.state = RunState::Stopped;
575 }
576 None => {
577 let message = "The run was cancelled".to_owned();
578 run.current_step = message.clone();
579 run.state = RunState::Failed {
580 message,
581 log: Vec::new(),
582 };
583 }
584 }
585 let stopped = run.state == RunState::Stopped;
586 let failed_or_done = !stopped;
587 let snapshot = run.clone();
588 self.prune_finished();
589 self.persist(cx);
590 if failed_or_done {
591 cx.emit(AgentRunsEvent::Finished(run_id));
592 }
593 if self.open_after_stop.remove(&run_id) && stopped {
594 open_run_session(&snapshot, cx);
595 }
596 if was_resuming {
597 self.resume_next(cx);
598 }
599 cx.notify();
600 }
601
602 fn prune_finished(&mut self) {
603 let finished = self.runs.iter().filter(|run| run.is_finished()).count();
604 let mut excess = finished.saturating_sub(run_store::RUNS_HISTORY_LIMIT);
605 self.runs.retain(|run| {
606 if excess > 0 && run.is_finished() {
607 excess -= 1;
608 return false;
609 }
610 true
611 });
612 }
613
614 fn ensure_ticking(&mut self, cx: &mut Context<Self>) {
615 if self.ticking || self.running_count() == 0 {
616 return;
617 }
618 self.ticking = true;
619 cx.spawn(async move |this, cx| {
620 loop {
621 cx.background_executor().timer(TICK).await;
622 let keep_going = this
623 .update(cx, |runs, cx| {
624 runs.ticking = runs.running_count() > 0;
625 if runs.ticking {
626 cx.notify();
627 }
628 runs.ticking
629 })
630 .unwrap_or(false);
631 if !keep_going {
632 break;
633 }
634 }
635 })
636 .detach();
637 }
638
639 pub fn stop(&mut self, run_id: u64, cx: &mut Context<Self>) {
640 if self.stopping.contains(&run_id) {
641 return;
642 }
643 if let Some(stop) = self.stops.remove(&run_id) {
644 self.stopping.insert(run_id);
645 let _ = stop.send(());
646 if let Some(run) = self.run_mut(run_id) {
647 run.current_step = "Stopping".to_owned();
648 }
649 cx.notify();
650 } else if self.resuming.contains(&run_id) || self.resume_queue.contains(&run_id) {
651 if self.resume_queue.contains(&run_id) {
652 self.stop_orphan(run_id, cx);
653 }
654 self.resume_queue.retain(|queued| *queued != run_id);
655 self.finish(
656 run_id,
657 Some(RunOutcome {
658 status: RunStatus::Stopped,
659 exit_code: None,
660 }),
661 cx,
662 );
663 }
664 }
665
666 fn stop_orphan(&self, run_id: u64, cx: &App) {
667 let Some(run) = self.get(run_id) else {
668 return;
669 };
670 let Ok((plan, _)) = self.resume_plan(run, cx) else {
671 return;
672 };
673 for path in &plan.cleanup {
674 let _ = std::fs::remove_file(path);
675 }
676 if let Some(stop) = orphan_stop(run, &plan) {
677 drop(runtime::spawn(async move {
678 agents::run_stop_invocation(&stop).await
679 }));
680 }
681 }
682
683 pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) {
684 self.open_after_stop.insert(run_id);
685 self.stop(run_id, cx);
686 }
687
688 pub fn retry(&mut self, run_id: u64, cx: &mut Context<Self>) -> Result<u64, String> {
689 let run = self
690 .get(run_id)
691 .cloned()
692 .ok_or("This run no longer exists")?;
693 let started = self.start(
694 &run.action_id,
695 &run.conversation_id,
696 &run.message_id,
697 &run.extra,
698 cx,
699 )?;
700 self.dismiss(run_id, cx);
701 Ok(started)
702 }
703
704 pub fn dismiss(&mut self, run_id: u64, cx: &mut Context<Self>) {
705 let Some(run) = self.run_mut(run_id).filter(|run| run.is_finished()) else {
706 return;
707 };
708 run.dismissed = true;
709 self.persist(cx);
710 cx.notify();
711 }
712
713 pub fn toggle_expanded(&mut self, run_id: u64, cx: &mut Context<Self>) {
714 if let Some(run) = self.run_mut(run_id) {
715 run.expanded = !run.expanded;
716 cx.notify();
717 }
718 }
719}
720
721#[cfg(test)]
722pub(super) mod tests {
723 use std::sync::Arc;
724 use std::time::Duration;
725
726 use agents::{AgentAction, AgentProfile, AgentSettings, Environment, OutputFormat};
727 use chrono::TimeZone;
728 use store::{MessageRecord, Store};
729
730 use gpui_kit::{AppContext as _, Entity, TestAppContext};
731
732 use super::{AgentRun, AgentRuns, RunState, Utc, format_elapsed, run_store};
733 use crate::app_state::{AppState, Mode};
734
735 pub fn finished_run(id: u64) -> AgentRun {
736 AgentRun {
737 id,
738 action_id: "answer-this".to_owned(),
739 action_label: "Answer this".to_owned(),
740 agent_id: "claude".to_owned(),
741 agent_name: "Claude Code".to_owned(),
742 conversation_id: "19:chat".to_owned(),
743 message_id: format!("m{id}"),
744 chat_title: "Ops".to_owned(),
745 sender_name: "Ada".to_owned(),
746 session_id: format!("session-{id}"),
747 working_dir: "~".to_owned(),
748 extra: String::new(),
749 state: RunState::Done,
750 current_step: "Done".to_owned(),
751 steps: vec![(Duration::from_secs(3), "Read a.rs".to_owned())],
752 final_text: "ok".to_owned(),
753 started_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
754 ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),
755 expanded: false,
756 dismissed: false,
757 process_id: None,
758 }
759 }
760
761 fn fake_settings(command: &str) -> AgentSettings {
762 let profile = AgentProfile {
763 id: "fake".to_owned(),
764 name: "Fake".to_owned(),
765 environment: Environment::Host,
766 command: command.to_owned(),
767 output: OutputFormat::ClaudeStreamJson,
768 open_session_command: String::new(),
769 mcp_config_flag: String::new(),
770 };
771 let action = AgentAction {
772 id: "ask".to_owned(),
773 label: "Ask".to_owned(),
774 agent_id: "fake".to_owned(),
775 working_dir: std::env::temp_dir().to_string_lossy().into_owned(),
776 prompt_template: "{message}".to_owned(),
777 ask_extra_instructions: false,
778 extra_args: String::new(),
779 };
780 AgentSettings {
781 agents: vec![profile],
782 actions: vec![action],
783 resume_interrupted_runs: true,
784 }
785 }
786
787 fn setup(cx: &mut TestAppContext, command: &str) -> (Entity<AppState>, Entity<AgentRuns>) {
788 cx.executor().allow_parking();
789 let store = Arc::new(Store::open_in_memory().unwrap());
790 store
791 .upsert_messages(&[MessageRecord {
792 conversation_id: "19:chat".to_owned(),
793 message_id: "m1".to_owned(),
794 sender_name: Some("Ada".to_owned()),
795 created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
796 body_html: "<p>Where is the report?</p>".to_owned(),
797 attachments_json: "[]".to_owned(),
798 reactions_json: "[]".to_owned(),
799 mentions_json: "[]".to_owned(),
800 links_json: "[]".to_owned(),
801 ..MessageRecord::default()
802 }])
803 .unwrap();
804 run_store::save_settings(&store, &fake_settings(command));
805 cx.update(|cx| {
806 let app = cx.new(|_| AppState::new(store, Mode::default()));
807 let runs = cx.new(|cx| AgentRuns::new(app.clone(), cx));
808 (app, runs)
809 })
810 }
811
812 fn wait_until_finished(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) {
813 for _ in 0..500 {
814 cx.run_until_parked();
815 let finished = cx.update(|cx| {
816 runs.read(cx)
817 .get(run_id)
818 .is_some_and(|run| run.is_finished())
819 });
820 if finished {
821 return;
822 }
823 std::thread::sleep(Duration::from_millis(10));
824 }
825 panic!("the run did not finish");
826 }
827
828 #[cfg(unix)]
829 mod shell_runs {
830 use gpui_kit::AppContext as _;
831
832 use super::{AgentRuns, RunState, TestAppContext, run_store, setup, wait_until_finished};
833
834 #[gpui_kit::test]
835 fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {
836 let fixture = concat!(
837 env!("CARGO_MANIFEST_DIR"),
838 "/../agents/tests/fixtures/claude-stream.jsonl"
839 );
840 let (app, runs) = setup(cx, &format!("sh -c 'cat {fixture}'"));
841 let run_id = cx.update(|cx| {
842 runs.update(cx, |runs, cx| runs.start("ask", "19:chat", "m1", "", cx))
843 .unwrap()
844 });
845 wait_until_finished(cx, &runs, run_id);
846 cx.update(|cx| {
847 let run = runs.read(cx).get(run_id).unwrap().clone();
848 assert_eq!(run.state, RunState::Done);
849 assert_eq!(
850 run.current_step,
851 "Done - The first word in `/etc/hostname` is `HOST01`."
852 );
853 assert_eq!(run.steps.len(), 2);
854 assert_eq!(
855 run.steps[0].1,
856 "MCP server is off - no reply proposal possible"
857 );
858 assert_eq!(run.steps[1].1, "Reading hostname");
859 assert_eq!(run.chat_title, "Chat");
860 assert_eq!(run.sender_name, "Ada");
861 let stored = run_store::load_runs(&app.read(cx).store);
862 assert_eq!(stored.len(), 1);
863 assert_eq!(stored[0].state, RunState::Done);
864 assert_eq!(stored[0].session_id, run.session_id);
865 assert_eq!(runs.read(cx).running_count(), 0);
866 });
867 }
868
869 #[gpui_kit::test]
870 fn a_resumed_run_continues_and_finishes_done(cx: &mut TestAppContext) {
871 let fixture = concat!(
872 env!("CARGO_MANIFEST_DIR"),
873 "/../agents/tests/fixtures/claude-stream.jsonl"
874 );
875 let command = format!("sh -c 'cat {fixture}' --session-id {{session_id}}");
876 let (app, runs) = setup(cx, &command);
877 cx.update(|cx| {
878 runs.update(cx, |runs, cx| {
879 runs.runs.push(super::running_run(5));
880 runs.persist(cx);
881 });
882 });
883 let reloaded = cx.update(|cx| cx.new(|cx| AgentRuns::new(app.clone(), cx)));
884 wait_until_finished(cx, &reloaded, 5);
885 cx.update(|cx| {
886 let run = reloaded.read(cx).get(5).unwrap().clone();
887 assert_eq!(run.state, RunState::Done);
888 assert_eq!(run.session_id, "session-5");
889 assert!(
890 run.steps
891 .iter()
892 .any(|(_, text)| text == "Resumed after restart")
893 );
894 });
895 }
896
897 #[gpui_kit::test]
898 fn a_failing_command_ends_failed_with_its_stderr(cx: &mut TestAppContext) {
899 let (app, runs) = setup(cx, "sh -c 'echo boom >&2; exit 3'");
900 let run_id = cx.update(|cx| {
901 runs.update(cx, |runs, cx| runs.start("ask", "19:chat", "m1", "", cx))
902 .unwrap()
903 });
904 wait_until_finished(cx, &runs, run_id);
905 cx.update(|cx| {
906 let run = runs.read(cx).get(run_id).unwrap().clone();
907 assert_eq!(
908 run.state,
909 RunState::Failed {
910 message: "boom".to_owned(),
911 log: vec!["boom".to_owned()],
912 }
913 );
914 assert_eq!(run.current_step, "boom");
915 let stored = run_store::load_runs(&app.read(cx).store);
916 assert_eq!(stored[0].state, run.state);
917 });
918 }
919 }
920
921 #[gpui_kit::test]
922 fn a_missing_action_is_an_error_and_starts_nothing(cx: &mut TestAppContext) {
923 let (_, runs) = setup(cx, "true");
924 cx.update(|cx| {
925 let error = runs
926 .update(cx, |runs, cx| runs.start("ghost", "19:chat", "m1", "", cx))
927 .unwrap_err();
928 assert_eq!(error, "This action no longer exists");
929 let error = runs
930 .update(cx, |runs, cx| runs.start("ask", "19:chat", "gone", "", cx))
931 .unwrap_err();
932 assert_eq!(error, "The message is no longer available");
933 assert_eq!(runs.read(cx).running_count(), 0);
934 });
935 }
936
937 #[gpui_kit::test]
938 fn dismissed_runs_hide_and_stay_dismissed_after_reload(cx: &mut TestAppContext) {
939 let (app, runs) = setup(cx, "true");
940 cx.update(|cx| {
941 runs.update(cx, |runs, cx| {
942 runs.runs.push(finished_run(7));
943 runs.dismiss(7, cx);
944 assert!(runs.for_conversation("19:chat").next().is_none());
945 assert!(runs.recent(10).is_empty());
946 });
947 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
948 let reloaded = reloaded.read(cx);
949 assert!(reloaded.get(7).is_some_and(|run| run.dismissed));
950 assert_eq!(reloaded.next_id, 8);
951 });
952 }
953
954 const RESUMABLE_COMMAND: &str = "sh -c 'sleep 30' --session-id {session_id}";
955 const INTERRUPTED: &str = "Interrupted - the app was closed during the run";
956
957 fn running_run(id: u64) -> AgentRun {
958 let mut running = finished_run(id);
959 running.action_id = "ask".to_owned();
960 running.agent_id = "fake".to_owned();
961 running.state = RunState::Running;
962 running.ended_at = None;
963 running
964 }
965
966 fn reload_with(
967 cx: &mut TestAppContext,
968 command: &str,
969 run: AgentRun,
970 change_settings: impl FnOnce(&mut AgentSettings),
971 ) -> AgentRun {
972 let (app, runs) = setup(cx, command);
973 cx.update(|cx| {
974 let mut settings = fake_settings(command);
975 change_settings(&mut settings);
976 run_store::save_settings(&app.read(cx).store, &settings);
977 let run_id = run.id;
978 runs.update(cx, |runs, cx| {
979 runs.runs.push(run);
980 runs.persist(cx);
981 });
982 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
983 reloaded.read(cx).get(run_id).unwrap().clone()
984 })
985 }
986
987 fn assert_interrupted(run: &AgentRun) {
988 assert!(matches!(
989 run.state,
990 RunState::Failed { ref message, .. } if message == INTERRUPTED
991 ));
992 assert!(run.ended_at.is_some());
993 }
994
995 #[gpui_kit::test]
996 fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) {
997 let run = reload_with(cx, "true", running_run(5), |_| {});
998 assert_interrupted(&run);
999 assert_eq!(run.session_id, "session-5");
1000 }
1001
1002 #[gpui_kit::test]
1003 fn a_running_run_with_a_session_is_resumed(cx: &mut TestAppContext) {
1004 let original = running_run(5);
1005 let run = reload_with(cx, RESUMABLE_COMMAND, original.clone(), |_| {});
1006 assert_eq!(run.state, RunState::Running);
1007 assert_eq!(run.ended_at, None);
1008 assert_eq!(run.started_at, original.started_at);
1009 assert_eq!(run.current_step, "Resumed after restart");
1010 assert_eq!(run.steps.len(), 2);
1011 assert_eq!(run.steps[0], original.steps[0]);
1012 assert_eq!(run.steps[1].1, "Resumed after restart");
1013 }
1014
1015 fn reload_many(cx: &mut TestAppContext, run_count: u64) -> (Entity<AgentRuns>, Vec<u64>) {
1016 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
1017 let ids: Vec<u64> = (1..=run_count).collect();
1018 let reloaded = cx.update(|cx| {
1019 runs.update(cx, |runs, cx| {
1020 runs.runs.extend(ids.iter().map(|id| running_run(*id)));
1021 runs.persist(cx);
1022 });
1023 cx.new(|cx| AgentRuns::new(app.clone(), cx))
1024 });
1025 (reloaded, ids)
1026 }
1027
1028 fn state_of(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) -> RunState {
1029 cx.update(|cx| runs.read(cx).get(run_id).unwrap().state.clone())
1030 }
1031
1032 #[gpui_kit::test]
1033 fn at_most_three_resumes_run_and_the_fourth_starts_when_one_finishes(cx: &mut TestAppContext) {
1034 let (runs, _) = reload_many(cx, 4);
1035 cx.run_until_parked();
1036 cx.update(|cx| {
1037 let runs = runs.read(cx);
1038 assert_eq!(runs.stops.len(), 3);
1039 assert_eq!(runs.resume_queue, [4]);
1040 });
1041 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(1, cx)));
1042 wait_until_finished(cx, &runs, 1);
1043 cx.run_until_parked();
1044 cx.update(|cx| {
1045 let runs_ref = runs.read(cx);
1046 assert!(runs_ref.resume_queue.is_empty());
1047 assert!(runs_ref.stops.contains_key(&4));
1048 runs.update(cx, |runs, cx| {
1049 for run_id in [2, 3, 4] {
1050 runs.stop(run_id, cx);
1051 }
1052 });
1053 });
1054 wait_until_finished(cx, &runs, 4);
1055 }
1056
1057 #[gpui_kit::test]
1058 fn stopping_a_queued_resume_ends_it_without_spawning(cx: &mut TestAppContext) {
1059 let (runs, _) = reload_many(cx, 4);
1060 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(4, cx)));
1061 cx.run_until_parked();
1062 assert_eq!(state_of(cx, &runs, 4), RunState::Stopped);
1063 cx.update(|cx| {
1064 let runs_ref = runs.read(cx);
1065 assert!(!runs_ref.stops.contains_key(&4));
1066 assert_eq!(runs_ref.stops.len(), 3);
1067 runs.update(cx, |runs, cx| {
1068 for run_id in [1, 2, 3] {
1069 runs.stop(run_id, cx);
1070 }
1071 });
1072 });
1073 wait_until_finished(cx, &runs, 3);
1074 }
1075
1076 #[gpui_kit::test]
1077 fn stopping_during_the_stop_wait_ends_the_run_without_spawning(cx: &mut TestAppContext) {
1078 let (runs, _) = reload_many(cx, 1);
1079 cx.update(|cx| {
1080 runs.update(cx, |runs, cx| {
1081 runs.resume_queue.clear();
1082 runs.begin_resume(1, cx);
1083 runs.stop(1, cx);
1084 })
1085 });
1086 cx.run_until_parked();
1087 assert_eq!(state_of(cx, &runs, 1), RunState::Stopped);
1088 cx.update(|cx| assert!(runs.read(cx).stops.is_empty()));
1089 }
1090
1091 #[gpui_kit::test]
1092 fn a_running_run_without_a_session_is_interrupted(cx: &mut TestAppContext) {
1093 let mut original = running_run(5);
1094 original.session_id = String::new();
1095 let run = reload_with(cx, RESUMABLE_COMMAND, original, |_| {});
1096 assert_interrupted(&run);
1097 }
1098
1099 #[gpui_kit::test]
1100 fn a_profile_that_cannot_resume_is_interrupted(cx: &mut TestAppContext) {
1101 let run = reload_with(cx, "sh -c 'sleep 30'", running_run(5), |_| {});
1102 assert_interrupted(&run);
1103 }
1104
1105 #[gpui_kit::test]
1106 fn switching_resume_off_interrupts_the_run(cx: &mut TestAppContext) {
1107 let run = reload_with(cx, RESUMABLE_COMMAND, running_run(5), |settings| {
1108 settings.resume_interrupted_runs = false
1109 });
1110 assert_interrupted(&run);
1111 }
1112
1113 #[test]
1114 fn layout_key_counts_visible_detail_rows() {
1115 let mut run = finished_run(1);
1116 assert_eq!(run.layout_key(), (0, false));
1117 run.expanded = true;
1118 run.steps = (0..9)
1119 .map(|index| (Duration::from_secs(index), index.to_string()))
1120 .collect();
1121 assert_eq!(run.layout_key(), (6, false));
1122 assert_eq!(run.visible_steps()[0].1, "3");
1123 run.state = RunState::Running;
1124 assert_eq!(run.layout_key(), (6, true));
1125 }
1126
1127 #[test]
1128 fn elapsed_reads_as_minutes_and_seconds() {
1129 assert_eq!(format_elapsed(Duration::from_secs(42)), "0:42");
1130 assert_eq!(format_elapsed(Duration::from_secs(631)), "10:31");
1131 assert_eq!(finished_run(1).elapsed_text(), "1:00");
1132 }
1133}