BlueGit

ict rusty-teams

Files

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

runs.rs

d39bdfed History
runs.rs 75.5 KiB Download Raw
1use std::collections::{HashMap, HashSet, VecDeque};
2use std::time::{Duration, Instant};
3
4use agents::{
5 AgentAction, AgentProfile, AgentSettings, McpEndpoint, RunEvent, RunOutcome, RunStatus,
6 RunUpdate,
7};
8use chrono::{DateTime, Utc};
9use gpui_kit::*;
10use serde::{Deserialize, Serialize};
11use tokio::sync::{mpsc, oneshot};
12
13use super::lanes::{Admit, Lanes, RestoreInfo};
14use super::{
15 MCP_POLL_INTERVAL, MCP_WAIT_LIMIT, demo, kills, mcp_bridge, mcp_config_directory,
16 message_context, open_run_session, raise_notice, store as run_store,
17};
18use crate::app_state::AppState;
19use crate::notice::truncated;
20use crate::runtime;
21
22const STEP_LIMIT: usize = 50;
23const VISIBLE_STEPS: usize = 6;
24const VISIBLE_LOG_LINES: usize = 20;
25const TEXT_STEP_CHARS: usize = 80;
26const DONE_STEP_CHARS: usize = 60;
27const TICK: Duration = Duration::from_secs(1);
28const PROGRESS_PERSIST_INTERVAL: Duration = Duration::from_secs(5);
29const RESUME_PARALLEL_LIMIT: usize = 3;
30const QUEUED_STEP: &str = "Queued";
31const OPENED_NOTICE: &str = "Session opened in a terminal - send cancelled";
32const RESUMED_STEP: &str = "Resumed after restart";
33const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";
34
35#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
36pub enum RunState {
37 Running,
38 Done,
39 Failed { message: String, log: Vec<String> },
40 Stopped,
41}
42
43#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
44pub struct AgentRun {
45 pub id: u64,
46 pub action_id: String,
47 pub action_label: String,
48 pub agent_id: String,
49 pub agent_name: String,
50 pub conversation_id: String,
51 pub message_id: String,
52 pub chat_title: String,
53 pub sender_name: String,
54 pub session_id: String,
55 pub working_dir: String,
56 pub extra: String,
57 pub state: RunState,
58 pub current_step: String,
59 pub steps: Vec<(Duration, String)>,
60 pub final_text: String,
61 pub started_at: DateTime<Utc>,
62 pub ended_at: Option<DateTime<Utc>>,
63 #[serde(skip)]
64 pub expanded: bool,
65 pub dismissed: bool,
66 #[serde(default)]
67 pub process_id: Option<u32>,
68 #[serde(default)]
69 pub pending_prompt: Option<String>,
70 #[serde(default)]
71 pub sent_to: Option<SessionTarget>,
72 #[serde(default)]
73 pub launch_session_id: Option<String>,
74 #[serde(default = "launched_by_default")]
75 pub launched: bool,
76}
77
78fn launched_by_default() -> bool {
79 true
80}
81
82impl AgentRun {
83 pub fn is_running(&self) -> bool {
84 self.state == RunState::Running
85 }
86
87 pub fn is_queued(&self) -> bool {
88 self.pending_prompt.is_some()
89 }
90
91 pub fn is_finished(&self) -> bool {
92 !self.is_running()
93 }
94
95 pub fn elapsed(&self) -> Duration {
96 let end = self.ended_at.unwrap_or_else(Utc::now);
97 (end - self.started_at).to_std().unwrap_or_default()
98 }
99
100 pub fn elapsed_text(&self) -> String {
101 format_elapsed(self.elapsed())
102 }
103
104 pub fn visible_steps(&self) -> &[(Duration, String)] {
105 let skipped = self.steps.len().saturating_sub(VISIBLE_STEPS);
106 &self.steps[skipped..]
107 }
108
109 pub fn log_lines(&self) -> &[String] {
110 match &self.state {
111 RunState::Failed { log, .. } => {
112 let skipped = log.len().saturating_sub(VISIBLE_LOG_LINES);
113 &log[skipped..]
114 }
115 _ => &[],
116 }
117 }
118
119 pub fn layout_key(&self) -> (usize, bool) {
120 let rows = match (&self.state, self.expanded) {
121 (_, false) => 0,
122 (RunState::Failed { .. }, true) => self.log_lines().len().max(1),
123 (_, true) => self.visible_steps().len().max(1),
124 };
125 (rows, self.is_running())
126 }
127
128 fn mark_interrupted(&mut self) {
129 let message = "Interrupted - the app was closed during the run".to_owned();
130 self.current_step = message.clone();
131 self.state = RunState::Failed {
132 message,
133 log: Vec::new(),
134 };
135 self.ended_at = Some(Utc::now());
136 }
137
138 fn push_step(&mut self, text: String) {
139 let elapsed = (Utc::now() - self.started_at).to_std().unwrap_or_default();
140 self.steps.push((elapsed, text.clone()));
141 if self.steps.len() > STEP_LIMIT {
142 self.steps.remove(0);
143 }
144 self.current_step = text;
145 }
146}
147
148fn can_resume(settings: &AgentSettings, run: &AgentRun) -> bool {
149 settings.resume_interrupted_runs
150 && run.launched
151 && !run.session_id.is_empty()
152 && settings
153 .agents
154 .iter()
155 .find(|agent| agent.id == run.agent_id)
156 .is_some_and(agents::supports_resume)
157}
158
159fn remove_stale_mcp_configs() {
160 let Some(directory) = mcp_config_directory() else {
161 return;
162 };
163 let Ok(entries) = std::fs::read_dir(directory) else {
164 return;
165 };
166 for entry in entries.flatten() {
167 let _ = std::fs::remove_file(entry.path());
168 }
169}
170
171pub fn format_elapsed(duration: Duration) -> String {
172 let seconds = duration.as_secs();
173 format!("{}:{:02}", seconds / 60, seconds % 60)
174}
175
176fn api_retry_text(message: &str, retry_in: Option<Duration>) -> String {
177 let Some(retry_in) = retry_in else {
178 return format!("API not responding - retrying ({message})");
179 };
180 let seconds = retry_in.as_secs();
181 let wait = if seconds >= 60 {
182 format!("{} min", seconds.div_ceil(60))
183 } else {
184 format!("{seconds} s")
185 };
186 format!("API not responding - retrying in {wait}")
187}
188
189fn first_line(text: &str) -> &str {
190 text.lines()
191 .find(|line| !line.trim().is_empty())
192 .unwrap_or("")
193 .trim()
194}
195
196#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
197pub struct SessionTarget {
198 pub session_id: String,
199 pub working_dir: String,
200 pub fork: bool,
201}
202
203#[derive(Clone, Debug, Default, PartialEq, Eq)]
204pub struct StartOptions {
205 pub working_dir: Option<String>,
206 pub remember_working_dir: bool,
207 pub session: Option<SessionTarget>,
208}
209
210fn plan_for(
211 profile: &AgentProfile,
212 action: &AgentAction,
213 prompt: &str,
214 session_id: &str,
215 target: Option<&SessionTarget>,
216 endpoint: Option<&McpEndpoint>,
217) -> Result<agents::RunPlan, agents::InvocationError> {
218 let directory = mcp_config_directory();
219 match target {
220 None => agents::build_invocation(
221 profile,
222 action,
223 prompt,
224 session_id,
225 endpoint,
226 directory.as_deref(),
227 ),
228 Some(target) if target.fork => agents::fork_invocation(
229 profile,
230 action,
231 prompt,
232 &target.session_id,
233 session_id,
234 endpoint,
235 directory.as_deref(),
236 ),
237 Some(_) => agents::resume_invocation(
238 profile,
239 action,
240 prompt,
241 session_id,
242 endpoint,
243 directory.as_deref(),
244 ),
245 }
246}
247
248pub struct AgentRunsHandle(pub Entity<AgentRuns>);
249
250impl Global for AgentRunsHandle {}
251
252#[derive(Clone, Debug, PartialEq, Eq)]
253pub struct StartRequest {
254 pub action_id: String,
255 pub conversation_id: String,
256 pub message_id: String,
257}
258
259pub fn needs_dialog(action: &AgentAction, chat_allowed: bool) -> bool {
260 action.ask_extra_instructions || !chat_allowed
261}
262
263pub enum AgentRunsEvent {
264 Finished(u64),
265 StartRequested(StartRequest),
266 OpenSettings,
267}
268
269pub struct AgentRuns {
270 app: Entity<AppState>,
271 settings: AgentSettings,
272 runs: Vec<AgentRun>,
273 stops: HashMap<u64, oneshot::Sender<()>>,
274 resume_queue: VecDeque<u64>,
275 lanes: Lanes,
276 startup_kills: Vec<(String, agents::Invocation)>,
277 resuming: HashSet<u64>,
278 stopping: HashSet<u64>,
279 open_after_stop: HashSet<u64>,
280 open_deferred: HashSet<u64>,
281 next_id: u64,
282 ticking: bool,
283 progress_saved_at: Option<Instant>,
284 progress_unsaved: bool,
285}
286
287impl EventEmitter<AgentRunsEvent> for AgentRuns {}
288
289impl AgentRuns {
290 pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
291 let store = app.read(cx).store.clone();
292 let settings = run_store::load_settings(&store);
293 let mut runs = run_store::load_runs(&store);
294 let interrupted = runs.iter().any(AgentRun::is_running);
295 let infos: Vec<RestoreInfo> = runs
296 .iter()
297 .filter(|run| run.is_running())
298 .map(|run| RestoreInfo {
299 id: run.id,
300 session_id: run.session_id.clone(),
301 queued: run.is_queued(),
302 kill: kills::startup_kill(&settings, run),
303 })
304 .collect();
305 let restored = Lanes::restore(&infos, |run_id| {
306 runs.iter()
307 .find(|run| run.id == run_id)
308 .is_some_and(|run| can_resume(&settings, run))
309 });
310 for run in runs.iter_mut() {
311 if restored.resume_queue.contains(&run.id) {
312 run.push_step(RESUMED_STEP.to_owned());
313 } else if restored.interrupted.contains(&run.id) {
314 run.mark_interrupted();
315 }
316 }
317 let (lanes, resume_queue, startup_kills) = (
318 restored.lanes,
319 VecDeque::from(restored.resume_queue),
320 restored.kills,
321 );
322 if interrupted {
323 run_store::save_runs(&store, &runs);
324 }
325 remove_stale_mcp_configs();
326 if runs.is_empty() && app.read(cx).mode.demo {
327 runs = demo::runs(app.read(cx));
328 }
329 let next_id = runs.iter().map(|run| run.id).max().map_or(1, |id| id + 1);
330 let mut agent_runs = AgentRuns {
331 app,
332 settings,
333 runs,
334 stops: HashMap::new(),
335 resume_queue,
336 lanes,
337 startup_kills,
338 resuming: HashSet::new(),
339 stopping: HashSet::new(),
340 open_after_stop: HashSet::new(),
341 open_deferred: HashSet::new(),
342 next_id,
343 ticking: false,
344 progress_saved_at: None,
345 progress_unsaved: false,
346 };
347 agent_runs.ensure_ticking(cx);
348 agent_runs.start_resumes(cx);
349 agent_runs
350 }
351
352 fn start_resumes(&mut self, cx: &mut Context<Self>) {
353 if self.lanes.is_empty() {
354 return;
355 }
356 let needs_mcp = self.runs.iter().any(|run| {
357 run.is_running()
358 && (self.resume_queue.contains(&run.id) || run.is_queued())
359 && self
360 .settings
361 .agents
362 .iter()
363 .find(|agent| agent.id == run.agent_id)
364 .is_some_and(|agent| !agent.mcp_config_flag.is_empty())
365 });
366 cx.spawn(async move |this, cx| {
367 let mut waited = Duration::ZERO;
368 while needs_mcp
369 && waited < MCP_WAIT_LIMIT
370 && !cx.update(|cx| mcp_bridge::endpoint(cx).is_some())
371 {
372 cx.background_executor().timer(MCP_POLL_INTERVAL).await;
373 waited += MCP_POLL_INTERVAL;
374 }
375 this.update(cx, |runs, cx| {
376 runs.resume_next(cx);
377 for (session_id, kill) in std::mem::take(&mut runs.startup_kills) {
378 runs.run_kill(&session_id, Some(kill), cx);
379 }
380 for session_id in runs.lanes.idle_sessions() {
381 runs.release(&session_id, cx);
382 }
383 })
384 .ok();
385 })
386 .detach();
387 }
388
389 fn resume_next(&mut self, cx: &mut Context<Self>) {
390 while self.resuming.len() < RESUME_PARALLEL_LIMIT {
391 let Some(run_id) = self.resume_queue.pop_front() else {
392 return;
393 };
394 self.begin_resume(run_id, cx);
395 }
396 }
397
398 fn resume_plan(
399 &self,
400 run: &AgentRun,
401 cx: &App,
402 ) -> Result<(agents::RunPlan, agents::OutputFormat), String> {
403 let action = self
404 .settings
405 .actions
406 .iter()
407 .find(|action| action.id == run.action_id)
408 .cloned()
409 .ok_or("the action no longer exists")?;
410 let profile = self
411 .settings
412 .agents
413 .iter()
414 .find(|profile| profile.id == run.agent_id)
415 .ok_or("the agent no longer exists")?;
416 let action = AgentAction {
417 working_dir: run.working_dir.clone(),
418 ..action
419 };
420 let plan = agents::resume_invocation(
421 profile,
422 &action,
423 RESUME_PROMPT,
424 &run.session_id,
425 mcp_bridge::endpoint(cx).as_ref(),
426 mcp_config_directory().as_deref(),
427 )
428 .map_err(|error| error.to_string())?;
429 Ok((plan, profile.output))
430 }
431
432 fn begin_resume(&mut self, run_id: u64, cx: &mut Context<Self>) {
433 let Some(run) = self.get(run_id).cloned() else {
434 return;
435 };
436 if !run.is_running() {
437 self.finish_kill(&run.session_id, cx);
438 return;
439 }
440 self.resuming.insert(run_id);
441 let session_id = run.session_id.clone();
442 match self.resume_plan(&run, cx) {
443 Ok((plan, format)) => {
444 let stop = kills::kill_for(&run, &plan, |launched| {
445 self.resume_plan(launched, cx).ok().map(|(plan, _)| plan)
446 });
447 cx.spawn(async move |this, cx| {
448 if let Some(stop) = stop {
449 kills::execute(stop).await;
450 }
451 this.update(cx, |runs, cx| {
452 let still_resuming = runs.resuming.contains(&run_id)
453 && runs.get(run_id).is_some_and(AgentRun::is_running);
454 runs.finish_kill(&session_id, cx);
455 if still_resuming {
456 runs.spawn(run_id, plan, format, cx);
457 } else {
458 for path in &plan.cleanup {
459 let _ = std::fs::remove_file(path);
460 }
461 }
462 })
463 .ok();
464 })
465 .detach();
466 }
467 Err(reason) => {
468 let stop = kills::startup_kill(&self.settings, &run);
469 self.finish(
470 run_id,
471 Some(RunOutcome {
472 status: RunStatus::Failed {
473 message: format!("Could not resume - {reason}"),
474 stderr_tail: Vec::new(),
475 },
476 exit_code: None,
477 }),
478 cx,
479 );
480 self.run_kill(&session_id, stop, cx);
481 }
482 }
483 }
484
485 pub fn settings(&self) -> &AgentSettings {
486 &self.settings
487 }
488
489 pub fn update_settings(
490 &mut self,
491 change: impl FnOnce(&mut AgentSettings),
492 cx: &mut Context<Self>,
493 ) {
494 change(&mut self.settings);
495 run_store::save_settings(&self.app.read(cx).store, &self.settings);
496 cx.notify();
497 }
498
499 pub fn get(&self, run_id: u64) -> Option<&AgentRun> {
500 self.runs.iter().find(|run| run.id == run_id)
501 }
502
503 pub fn by_session(&self, session_id: &str) -> Option<&AgentRun> {
504 self.runs
505 .iter()
506 .rev()
507 .find(|run| run.session_id == session_id)
508 }
509
510 pub fn for_conversation<'a>(
511 &'a self,
512 conversation_id: &'a str,
513 ) -> impl Iterator<Item = &'a AgentRun> {
514 self.runs
515 .iter()
516 .filter(move |run| run.conversation_id == conversation_id && !run.dismissed)
517 }
518
519 pub fn for_agent(&self, agent_id: &str) -> Vec<&AgentRun> {
520 self.runs
521 .iter()
522 .rev()
523 .filter(|run| run.agent_id == agent_id)
524 .collect()
525 }
526
527 pub fn session_ids(&self) -> HashSet<String> {
528 self.runs.iter().map(|run| run.session_id.clone()).collect()
529 }
530
531 pub fn running_count(&self) -> usize {
532 self.runs.iter().filter(|run| run.is_running()).count()
533 }
534
535 pub fn recent(&self, limit: usize) -> Vec<&AgentRun> {
536 self.runs
537 .iter()
538 .rev()
539 .filter(|run| !run.dismissed)
540 .take(limit)
541 .collect()
542 }
543
544 fn run_mut(&mut self, run_id: u64) -> Option<&mut AgentRun> {
545 self.runs.iter_mut().find(|run| run.id == run_id)
546 }
547
548 fn persist(&mut self, cx: &App) {
549 run_store::save_runs(&self.app.read(cx).store, &self.runs);
550 self.progress_saved_at = Some(Instant::now());
551 self.progress_unsaved = false;
552 }
553
554 fn persist_progress(&mut self, cx: &App) {
555 let due = self
556 .progress_saved_at
557 .is_none_or(|saved_at| saved_at.elapsed() >= PROGRESS_PERSIST_INTERVAL);
558 if !due {
559 self.progress_unsaved = true;
560 return;
561 }
562 self.persist(cx);
563 }
564
565 pub fn start_with(
566 &mut self,
567 action_id: &str,
568 conversation_id: &str,
569 message_id: &str,
570 extra: &str,
571 options: StartOptions,
572 cx: &mut Context<Self>,
573 ) -> Result<u64, String> {
574 let mut action = self
575 .settings
576 .actions
577 .iter()
578 .find(|action| action.id == action_id)
579 .cloned()
580 .ok_or("This action no longer exists")?;
581 let profile = self
582 .settings
583 .agents
584 .iter()
585 .find(|profile| profile.id == action.agent_id)
586 .cloned()
587 .ok_or("The agent of this action no longer exists")?;
588 let context = message_context::build(self.app.read(cx), conversation_id, message_id)
589 .ok_or("The message is no longer available")?;
590 let chosen_working_dir = options
591 .working_dir
592 .clone()
593 .filter(|_| options.session.is_none() && options.remember_working_dir);
594 if let Some(target) = &options.session {
595 action.working_dir = target.working_dir.clone();
596 } else if let Some(working_dir) = &options.working_dir {
597 action.working_dir = working_dir.clone();
598 }
599 let (session_id, prompt) = match &options.session {
600 Some(target) => {
601 let session_id = if target.fork {
602 agents::new_session_id()
603 } else {
604 target.session_id.clone()
605 };
606 let prompt =
607 agents::build_session_prompt(&context, extra, &session_id, &profile.id);
608 (session_id, prompt)
609 }
610 None => {
611 let session_id = agents::new_session_id();
612 let prompt =
613 agents::build_prompt(&action, &context, extra, &session_id, &profile.id);
614 (session_id, prompt)
615 }
616 };
617 let run_id = self.next_id;
618 self.next_id += 1;
619 self.runs.push(AgentRun {
620 id: run_id,
621 action_id: action.id.clone(),
622 action_label: action.label.clone(),
623 agent_id: profile.id.clone(),
624 agent_name: profile.name.clone(),
625 conversation_id: conversation_id.to_owned(),
626 message_id: message_id.to_owned(),
627 chat_title: context.chat.clone(),
628 sender_name: context.sender.clone(),
629 session_id,
630 working_dir: action.working_dir.clone(),
631 extra: extra.to_owned(),
632 state: RunState::Running,
633 current_step: "Starting".to_owned(),
634 steps: Vec::new(),
635 final_text: String::new(),
636 started_at: Utc::now(),
637 ended_at: None,
638 expanded: false,
639 dismissed: false,
640 process_id: None,
641 pending_prompt: Some(prompt),
642 sent_to: options.session.clone(),
643 launch_session_id: None,
644 launched: false,
645 });
646 if mcp_bridge::endpoint(cx).is_none()
647 && let Some(run) = self.run_mut(run_id)
648 {
649 run.push_step("MCP server is off - no reply proposal possible".to_owned());
650 }
651 self.dispatch(run_id, cx);
652 if let Some(working_dir) = chosen_working_dir {
653 self.update_settings(
654 |settings| settings.remember_working_dir(&profile.id, &working_dir),
655 cx,
656 );
657 }
658 self.persist(cx);
659 self.ensure_ticking(cx);
660 cx.notify();
661 Ok(run_id)
662 }
663
664 fn dispatch(&mut self, run_id: u64, cx: &mut Context<Self>) {
665 let Some(session_id) = self.get(run_id).map(|run| run.session_id.clone()) else {
666 return;
667 };
668 match self.lanes.admit(&session_id, run_id) {
669 Admit::Launch => self.launch(run_id, cx),
670 Admit::Queued => {
671 if let Some(run) = self.run_mut(run_id) {
672 run.push_step(QUEUED_STEP.to_owned());
673 }
674 }
675 }
676 }
677
678 fn release(&mut self, session_id: &str, cx: &mut Context<Self>) {
679 let runs = &self.runs;
680 let next = self.lanes.next(session_id, |run_id| {
681 runs.iter().any(|run| run.id == run_id && run.is_queued())
682 });
683 if let Some(next) = next {
684 self.launch(next, cx);
685 }
686 }
687
688 fn finish_kill(&mut self, session_id: &str, cx: &mut Context<Self>) {
689 let session_id = &self.lanes.resolve(session_id);
690 self.lanes.kill_done(session_id);
691 self.open_deferred_for(session_id, cx);
692 self.release(session_id, cx);
693 }
694
695 fn open_deferred_for(&mut self, session_id: &str, cx: &mut Context<Self>) {
696 if self.lanes.has_kills_pending(session_id) {
697 return;
698 }
699 let ready: Vec<u64> = self
700 .open_deferred
701 .iter()
702 .copied()
703 .filter(|run_id| {
704 self.get(*run_id)
705 .is_some_and(|run| run.session_id == session_id)
706 })
707 .collect();
708 for run_id in ready {
709 self.open_deferred.remove(&run_id);
710 if let Some(run) = self.get(run_id).cloned() {
711 self.open_and_cancel(&run, cx);
712 }
713 }
714 }
715
716 fn run_kill(
717 &mut self,
718 session_id: &str,
719 stop: Option<agents::Invocation>,
720 cx: &mut Context<Self>,
721 ) {
722 let Some(stop) = stop else {
723 self.finish_kill(session_id, cx);
724 return;
725 };
726 let session_id = session_id.to_owned();
727 cx.spawn(async move |this, cx| {
728 kills::execute(stop).await;
729 this.update(cx, |runs, cx| runs.finish_kill(&session_id, cx))
730 .ok();
731 })
732 .detach();
733 }
734
735 fn open_and_cancel(&mut self, run: &AgentRun, cx: &mut Context<Self>) {
736 open_run_session(run, cx);
737 let waiting = self.lanes.drain_waiting(&run.session_id);
738 for run_id in &waiting {
739 if let Some(waiting_run) = self.run_mut(*run_id) {
740 waiting_run.pending_prompt = None;
741 }
742 self.finish(
743 *run_id,
744 Some(RunOutcome {
745 status: RunStatus::Stopped,
746 exit_code: None,
747 }),
748 cx,
749 );
750 if let Some(waiting_run) = self.run_mut(*run_id) {
751 waiting_run.current_step = OPENED_NOTICE.to_owned();
752 }
753 }
754 if !waiting.is_empty() {
755 self.persist(cx);
756 raise_notice(OPENED_NOTICE.to_owned(), cx);
757 }
758 self.release(&run.session_id, cx);
759 }
760
761 fn launch(&mut self, run_id: u64, cx: &mut Context<Self>) {
762 let Some(run) = self.get(run_id).cloned() else {
763 return;
764 };
765 let prompt = run.pending_prompt.clone().unwrap_or_default();
766 let planned = self.launch_plan(&run, &prompt, cx);
767 if let Some(run) = self.run_mut(run_id) {
768 run.pending_prompt = None;
769 if run.current_step == QUEUED_STEP {
770 run.started_at = Utc::now();
771 run.push_step("Starting".to_owned());
772 }
773 }
774 match planned {
775 Ok((plan, format)) => self.spawn(run_id, plan, format, cx),
776 Err(message) => self.finish(
777 run_id,
778 Some(RunOutcome {
779 status: RunStatus::Failed {
780 message,
781 stderr_tail: Vec::new(),
782 },
783 exit_code: None,
784 }),
785 cx,
786 ),
787 }
788 self.persist(cx);
789 }
790
791 fn launch_plan(
792 &self,
793 run: &AgentRun,
794 prompt: &str,
795 cx: &App,
796 ) -> Result<(agents::RunPlan, agents::OutputFormat), String> {
797 let action = self
798 .settings
799 .actions
800 .iter()
801 .find(|action| action.id == run.action_id)
802 .cloned()
803 .ok_or("the action no longer exists")?;
804 let profile = self
805 .settings
806 .agents
807 .iter()
808 .find(|profile| profile.id == run.agent_id)
809 .ok_or("the agent no longer exists")?;
810 let action = AgentAction {
811 working_dir: run.working_dir.clone(),
812 ..action
813 };
814 plan_for(
815 profile,
816 &action,
817 prompt,
818 &run.session_id,
819 run.sent_to.as_ref(),
820 mcp_bridge::endpoint(cx).as_ref(),
821 )
822 .map(|plan| (plan, profile.output))
823 .map_err(|error| error.to_string())
824 }
825
826 fn spawn(
827 &mut self,
828 run_id: u64,
829 plan: agents::RunPlan,
830 format: agents::OutputFormat,
831 cx: &mut Context<Self>,
832 ) {
833 let (updates_sender, mut updates) = mpsc::unbounded_channel();
834 let (stop_sender, stop_receiver) = oneshot::channel();
835 self.stops.insert(run_id, stop_sender);
836 if let Some(run) = self.run_mut(run_id) {
837 run.launch_session_id = Some(run.session_id.clone());
838 }
839 let outcome = runtime::spawn(agents::run(plan, format, updates_sender, stop_receiver));
840 cx.spawn(async move |this, cx| {
841 while let Some(update) = updates.recv().await {
842 if this
843 .update(cx, |runs, cx| runs.apply_update(run_id, update, cx))
844 .is_err()
845 {
846 return;
847 }
848 }
849 let outcome = outcome.await.ok();
850 this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))
851 .ok();
852 })
853 .detach();
854 }
855
856 fn apply_update(&mut self, run_id: u64, update: RunUpdate, cx: &mut Context<Self>) {
857 let event = match update {
858 RunUpdate::Event(event) => event,
859 RunUpdate::Started(process_id) => {
860 if let Some(run) = self.run_mut(run_id) {
861 run.process_id = Some(process_id);
862 run.launched = true;
863 self.persist(cx);
864 }
865 return;
866 }
867 RunUpdate::Stderr(_) => return,
868 };
869 let Some(run) = self.run_mut(run_id) else {
870 return;
871 };
872 match event {
873 RunEvent::Step(text) => {
874 run.push_step(text);
875 self.persist_progress(cx);
876 }
877 RunEvent::Text(text) => {
878 run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)
879 }
880 RunEvent::ApiRetry { message, retry_in } => {
881 run.current_step = api_retry_text(&message, retry_in)
882 }
883 RunEvent::SessionId(session_id) if session_id != run.session_id => {
884 let previous = std::mem::replace(&mut run.session_id, session_id.clone());
885 self.move_lane(&previous, &session_id);
886 self.persist(cx);
887 }
888 _ => return,
889 }
890 cx.notify();
891 }
892
893 fn move_lane(&mut self, from: &str, to: &str) {
894 for run_id in self.lanes.rename(from, to) {
895 if let Some(run) = self.run_mut(run_id) {
896 run.session_id = to.to_owned();
897 if let Some(target) = run.sent_to.as_mut().filter(|target| !target.fork) {
898 target.session_id = to.to_owned();
899 }
900 }
901 }
902 }
903
904 fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {
905 self.stops.remove(&run_id);
906 self.stopping.remove(&run_id);
907 let was_resuming = self.resuming.remove(&run_id);
908 let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) else {
909 return;
910 };
911 run.ended_at = Some(Utc::now());
912 run.process_id = None;
913 match outcome.map(|outcome| outcome.status) {
914 Some(RunStatus::Completed { final_text }) => {
915 let line = truncated(first_line(&final_text), DONE_STEP_CHARS);
916 run.current_step = if line.is_empty() {
917 "Done".to_owned()
918 } else {
919 format!("Done - {line}")
920 };
921 run.final_text = final_text;
922 run.state = RunState::Done;
923 }
924 Some(RunStatus::Failed {
925 message,
926 stderr_tail,
927 }) => {
928 let message = if was_resuming && message.starts_with("cannot start") {
929 format!("Could not resume - {message}")
930 } else {
931 message
932 };
933 run.current_step = message.clone();
934 run.state = RunState::Failed {
935 message,
936 log: stderr_tail,
937 };
938 }
939 Some(RunStatus::Stopped) => {
940 run.current_step = "Stopped".to_owned();
941 run.state = RunState::Stopped;
942 }
943 None => {
944 let message = "The run was cancelled".to_owned();
945 run.current_step = message.clone();
946 run.state = RunState::Failed {
947 message,
948 log: Vec::new(),
949 };
950 }
951 }
952 let stopped = run.state == RunState::Stopped;
953 let failed_or_done = !stopped;
954 let snapshot = run.clone();
955 self.prune_finished();
956 self.persist(cx);
957 if failed_or_done {
958 cx.emit(AgentRunsEvent::Finished(run_id));
959 }
960 let session_id = snapshot.session_id.clone();
961 let was_active = self.lanes.finished(&session_id, run_id);
962 if self.open_after_stop.remove(&run_id) {
963 if self.lanes.has_kills_pending(&session_id) {
964 self.open_deferred.insert(run_id);
965 } else {
966 self.open_and_cancel(&snapshot, cx);
967 }
968 }
969 if was_resuming {
970 self.resume_next(cx);
971 }
972 if was_active {
973 self.release(&session_id, cx);
974 }
975 cx.notify();
976 }
977
978 fn prune_finished(&mut self) {
979 let finished = self.runs.iter().filter(|run| run.is_finished()).count();
980 let mut excess = finished.saturating_sub(run_store::RUNS_HISTORY_LIMIT);
981 self.runs.retain(|run| {
982 if excess > 0 && run.is_finished() {
983 excess -= 1;
984 return false;
985 }
986 true
987 });
988 }
989
990 fn ensure_ticking(&mut self, cx: &mut Context<Self>) {
991 if self.ticking || self.running_count() == 0 {
992 return;
993 }
994 self.ticking = true;
995 cx.spawn(async move |this, cx| {
996 loop {
997 cx.background_executor().timer(TICK).await;
998 let keep_going = this
999 .update(cx, |runs, cx| {
1000 runs.ticking = runs.running_count() > 0;
1001 if runs.progress_unsaved {
1002 runs.persist_progress(cx);
1003 }
1004 if runs.ticking {
1005 cx.notify();
1006 }
1007 runs.ticking
1008 })
1009 .unwrap_or(false);
1010 if !keep_going {
1011 break;
1012 }
1013 }
1014 })
1015 .detach();
1016 }
1017
1018 pub fn stop(&mut self, run_id: u64, cx: &mut Context<Self>) {
1019 if self.stopping.contains(&run_id) {
1020 return;
1021 }
1022 if let Some(stop) = self.stops.remove(&run_id) {
1023 self.stopping.insert(run_id);
1024 let _ = stop.send(());
1025 if let Some(run) = self.run_mut(run_id) {
1026 run.current_step = "Stopping".to_owned();
1027 }
1028 cx.notify();
1029 } else if self.get(run_id).is_some_and(AgentRun::is_queued) {
1030 let session_id = self.get(run_id).map(|run| run.session_id.clone());
1031 if let Some(session_id) = session_id {
1032 self.lanes.remove_waiting(&session_id, run_id);
1033 }
1034 if let Some(run) = self.run_mut(run_id) {
1035 run.pending_prompt = None;
1036 }
1037 self.finish(
1038 run_id,
1039 Some(RunOutcome {
1040 status: RunStatus::Stopped,
1041 exit_code: None,
1042 }),
1043 cx,
1044 );
1045 } else if self.resuming.contains(&run_id) || self.resume_queue.contains(&run_id) {
1046 let orphan_stop = self
1047 .resume_queue
1048 .contains(&run_id)
1049 .then(|| {
1050 self.get(run_id).and_then(|run| {
1051 kills::orphan_kill(run, |candidate| {
1052 self.resume_plan(candidate, cx).ok().map(|(plan, _)| plan)
1053 })
1054 })
1055 })
1056 .flatten();
1057 let was_queued_for_resume = self.resume_queue.contains(&run_id);
1058 let session_id = self.get(run_id).map(|run| run.session_id.clone());
1059 self.resume_queue.retain(|queued| *queued != run_id);
1060 self.finish(
1061 run_id,
1062 Some(RunOutcome {
1063 status: RunStatus::Stopped,
1064 exit_code: None,
1065 }),
1066 cx,
1067 );
1068 if let (true, Some(session_id)) = (was_queued_for_resume, session_id) {
1069 self.run_kill(&session_id, orphan_stop, cx);
1070 }
1071 }
1072 }
1073
1074 pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) {
1075 let Some(run) = self.get(run_id).cloned() else {
1076 return;
1077 };
1078 if run.is_finished() {
1079 if self.lanes.has_kills_pending(&run.session_id) {
1080 self.open_deferred.insert(run_id);
1081 } else {
1082 self.open_and_cancel(&run, cx);
1083 }
1084 return;
1085 }
1086 if !run.is_queued() {
1087 self.open_after_stop.insert(run_id);
1088 }
1089 self.stop(run_id, cx);
1090 }
1091
1092 pub fn retry(&mut self, run_id: u64, cx: &mut Context<Self>) -> Result<u64, String> {
1093 let run = self
1094 .get(run_id)
1095 .cloned()
1096 .ok_or("This run no longer exists")?;
1097 let options = StartOptions {
1098 working_dir: run.sent_to.is_none().then(|| run.working_dir.clone()),
1099 remember_working_dir: false,
1100 session: run.sent_to.clone().map(|target| SessionTarget {
1101 session_id: if target.fork {
1102 target.session_id
1103 } else {
1104 run.session_id.clone()
1105 },
1106 ..target
1107 }),
1108 };
1109 let started = self.start_with(
1110 &run.action_id,
1111 &run.conversation_id,
1112 &run.message_id,
1113 &run.extra,
1114 options,
1115 cx,
1116 )?;
1117 self.dismiss(run_id, cx);
1118 Ok(started)
1119 }
1120
1121 pub fn dismiss(&mut self, run_id: u64, cx: &mut Context<Self>) {
1122 let Some(run) = self.run_mut(run_id).filter(|run| run.is_finished()) else {
1123 return;
1124 };
1125 run.dismissed = true;
1126 self.persist(cx);
1127 cx.notify();
1128 }
1129
1130 pub fn toggle_expanded(&mut self, run_id: u64, cx: &mut Context<Self>) {
1131 if let Some(run) = self.run_mut(run_id) {
1132 run.expanded = !run.expanded;
1133 cx.notify();
1134 }
1135 }
1136}
1137
1138#[cfg(test)]
1139pub(super) mod tests {
1140 use std::sync::Arc;
1141 use std::time::Duration;
1142
1143 use agents::{AgentAction, AgentProfile, AgentSettings, Environment, OutputFormat};
1144 use chrono::TimeZone;
1145 use store::{MessageRecord, Store};
1146
1147 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1148
1149 use super::super::fixtures::finished_run;
1150 use super::{
1151 AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, api_retry_text,
1152 format_elapsed, needs_dialog, run_store,
1153 };
1154 use crate::app_state::{AppState, Mode};
1155
1156 #[test]
1157 fn the_dialog_shows_for_extra_instructions_or_a_chat_agents_cannot_see() {
1158 let quiet = AgentAction::answer_this("claude");
1159 let asking = AgentAction::build_this("claude");
1160 assert!(!needs_dialog(&quiet, true));
1161 assert!(needs_dialog(&quiet, false));
1162 assert!(needs_dialog(&asking, true));
1163 }
1164
1165 fn fake_settings(command: &str) -> AgentSettings {
1166 let profile = AgentProfile {
1167 id: "fake".to_owned(),
1168 name: "Fake".to_owned(),
1169 environment: Environment::Host,
1170 command: command.to_owned(),
1171 output: OutputFormat::ClaudeStreamJson,
1172 open_session_command: String::new(),
1173 mcp_config_flag: String::new(),
1174 };
1175 let action = AgentAction {
1176 id: "ask".to_owned(),
1177 label: "Ask".to_owned(),
1178 agent_id: "fake".to_owned(),
1179 working_dir: std::env::temp_dir().to_string_lossy().into_owned(),
1180 prompt_template: "{message}".to_owned(),
1181 ask_extra_instructions: false,
1182 extra_args: String::new(),
1183 };
1184 AgentSettings {
1185 agents: vec![profile],
1186 actions: vec![action],
1187 resume_interrupted_runs: true,
1188 ..AgentSettings::default()
1189 }
1190 }
1191
1192 fn setup(cx: &mut TestAppContext, command: &str) -> (Entity<AppState>, Entity<AgentRuns>) {
1193 cx.executor().allow_parking();
1194 let store = Arc::new(Store::open_in_memory().unwrap());
1195 store
1196 .upsert_messages(&[MessageRecord {
1197 conversation_id: "19:chat".to_owned(),
1198 message_id: "m1".to_owned(),
1199 sender_name: Some("Ada".to_owned()),
1200 created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
1201 body_html: "<p>Where is the report?</p>".to_owned(),
1202 attachments_json: "[]".to_owned(),
1203 reactions_json: "[]".to_owned(),
1204 mentions_json: "[]".to_owned(),
1205 links_json: "[]".to_owned(),
1206 ..MessageRecord::default()
1207 }])
1208 .unwrap();
1209 run_store::save_settings(&store, &fake_settings(command));
1210 cx.update(|cx| {
1211 let app = cx.new(|_| AppState::new(store, Mode::default()));
1212 let runs = cx.new(|cx| AgentRuns::new(app.clone(), cx));
1213 (app, runs)
1214 })
1215 }
1216
1217 fn wait_until_finished(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) {
1218 for _ in 0..500 {
1219 cx.run_until_parked();
1220 let finished = cx.update(|cx| {
1221 runs.read(cx)
1222 .get(run_id)
1223 .is_some_and(|run| run.is_finished())
1224 });
1225 if finished {
1226 return;
1227 }
1228 std::thread::sleep(Duration::from_millis(10));
1229 }
1230 panic!("the run did not finish");
1231 }
1232
1233 #[cfg(unix)]
1234 mod shell_runs {
1235 use std::time::Duration;
1236
1237 use gpui_kit::AppContext as _;
1238
1239 use super::{
1240 AgentRun, AgentRuns, Entity, RunState, SessionTarget, StartOptions, TestAppContext,
1241 run_store, setup, wait_until_finished,
1242 };
1243
1244 const SESSION_COMMAND: &str = "sh -c 'sleep 1' --session-id {session_id}";
1245
1246 fn target_of(session_id: String) -> StartOptions {
1247 StartOptions {
1248 working_dir: None,
1249 remember_working_dir: false,
1250 session: Some(SessionTarget {
1251 session_id,
1252 working_dir: std::env::temp_dir().to_string_lossy().into_owned(),
1253 fork: false,
1254 }),
1255 }
1256 }
1257
1258 type LaneView = Option<(Option<u64>, Vec<u64>)>;
1259
1260 fn lane_of(
1261 cx: &mut TestAppContext,
1262 runs: &Entity<AgentRuns>,
1263 session_id: &str,
1264 ) -> LaneView {
1265 cx.update(|cx| {
1266 runs.read(cx).lanes.get(session_id).map(|lane| {
1267 (
1268 lane.active.first().copied(),
1269 lane.waiting.iter().copied().collect::<Vec<u64>>(),
1270 )
1271 })
1272 })
1273 }
1274
1275 fn send_chain(
1276 cx: &mut TestAppContext,
1277 runs: &Entity<AgentRuns>,
1278 ) -> (u64, u64, u64, String) {
1279 cx.update(|cx| {
1280 runs.update(cx, |runs, cx| {
1281 let first = runs
1282 .start_with("ask", "19:chat", "m1", "", StartOptions::default(), cx)
1283 .unwrap();
1284 let session_id = runs.get(first).unwrap().session_id.clone();
1285 let second = runs
1286 .start_with(
1287 "ask",
1288 "19:chat",
1289 "m1",
1290 "two",
1291 target_of(session_id.clone()),
1292 cx,
1293 )
1294 .unwrap();
1295 let third = runs
1296 .start_with(
1297 "ask",
1298 "19:chat",
1299 "m1",
1300 "three",
1301 target_of(session_id.clone()),
1302 cx,
1303 )
1304 .unwrap();
1305 (first, second, third, session_id)
1306 })
1307 })
1308 }
1309
1310 fn started_and_ended(
1311 cx: &mut TestAppContext,
1312 runs: &Entity<AgentRuns>,
1313 run_id: u64,
1314 ) -> (chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>) {
1315 cx.update(|cx| {
1316 let run = runs.read(cx).get(run_id).unwrap();
1317 (run.started_at, run.ended_at.unwrap())
1318 })
1319 }
1320
1321 #[gpui_kit::test]
1322 fn two_sends_to_one_session_run_strictly_one_after_another(cx: &mut TestAppContext) {
1323 let (_, runs) = setup(cx, SESSION_COMMAND);
1324 let (first, second, third, session_id) = send_chain(cx, &runs);
1325 assert_eq!(
1326 lane_of(cx, &runs, &session_id),
1327 Some((Some(first), vec![second, third]))
1328 );
1329 cx.update(|cx| {
1330 let queued = runs.read(cx).get(second).unwrap();
1331 assert_eq!(queued.current_step, "Queued");
1332 let prompt = queued.pending_prompt.clone().unwrap();
1333 assert!(prompt.contains("propose_message") && prompt.contains("m1"));
1334 assert!(prompt.ends_with("\n\ntwo"));
1335 assert_eq!(queued.extra, "two");
1336 assert_eq!(queued.session_id, session_id);
1337 });
1338 wait_until_finished(cx, &runs, first);
1339 assert_eq!(
1340 lane_of(cx, &runs, &session_id),
1341 Some((Some(second), vec![third]))
1342 );
1343 cx.update(|cx| {
1344 assert!(!runs.read(cx).get(second).unwrap().is_queued());
1345 assert!(runs.read(cx).get(third).unwrap().is_queued());
1346 });
1347 wait_until_finished(cx, &runs, second);
1348 assert_eq!(lane_of(cx, &runs, &session_id), Some((Some(third), vec![])));
1349 wait_until_finished(cx, &runs, third);
1350 assert_eq!(lane_of(cx, &runs, &session_id), None);
1351 let (_, first_ended) = started_and_ended(cx, &runs, first);
1352 let (second_started, second_ended) = started_and_ended(cx, &runs, second);
1353 let (third_started, _) = started_and_ended(cx, &runs, third);
1354 assert!(second_started >= first_ended);
1355 assert!(third_started >= second_ended);
1356 }
1357
1358 #[gpui_kit::test]
1359 fn a_reported_session_id_moves_the_whole_lane_and_its_waiting_runs(
1360 cx: &mut TestAppContext,
1361 ) {
1362 let (_, runs) = setup(cx, SESSION_COMMAND);
1363 let (first, second, third, session_id) = send_chain(cx, &runs);
1364 cx.update(|cx| {
1365 runs.update(cx, |runs, cx| {
1366 runs.apply_update(
1367 first,
1368 agents::RunUpdate::Event(agents::RunEvent::SessionId("adopted".to_owned())),
1369 cx,
1370 )
1371 });
1372 let runs = runs.read(cx);
1373 assert_eq!(
1374 runs.get(first).unwrap().launch_session_id,
1375 Some(session_id.clone())
1376 );
1377 assert_eq!(runs.get(first).unwrap().session_id, "adopted");
1378 for run_id in [second, third] {
1379 assert_eq!(runs.get(run_id).unwrap().session_id, "adopted");
1380 }
1381 });
1382 assert_eq!(lane_of(cx, &runs, &session_id), None);
1383 assert_eq!(
1384 lane_of(cx, &runs, "adopted"),
1385 Some((Some(first), vec![second, third]))
1386 );
1387 wait_until_finished(cx, &runs, first);
1388 assert_eq!(
1389 lane_of(cx, &runs, "adopted"),
1390 Some((Some(second), vec![third]))
1391 );
1392 wait_until_finished(cx, &runs, second);
1393 wait_until_finished(cx, &runs, third);
1394 }
1395
1396 #[gpui_kit::test]
1397 fn stopping_a_waiting_send_only_removes_it_from_the_lane(cx: &mut TestAppContext) {
1398 let (_, runs) = setup(cx, SESSION_COMMAND);
1399 let (first, second, third, session_id) = send_chain(cx, &runs);
1400 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(second, cx)));
1401 cx.update(|cx| {
1402 let stopped = runs.read(cx).get(second).unwrap();
1403 assert_eq!(stopped.state, RunState::Stopped);
1404 assert!(!stopped.is_queued());
1405 });
1406 assert_eq!(
1407 lane_of(cx, &runs, &session_id),
1408 Some((Some(first), vec![third]))
1409 );
1410 wait_until_finished(cx, &runs, first);
1411 assert_eq!(lane_of(cx, &runs, &session_id), Some((Some(third), vec![])));
1412 wait_until_finished(cx, &runs, third);
1413 }
1414
1415 #[gpui_kit::test]
1416 fn stop_and_open_cancels_every_waiting_send_of_the_lane(cx: &mut TestAppContext) {
1417 let (app, runs) = setup(cx, SESSION_COMMAND);
1418 let (first, second, third, session_id) = send_chain(cx, &runs);
1419 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop_and_open_session(first, cx)));
1420 wait_until_finished(cx, &runs, first);
1421 cx.update(|cx| {
1422 for run_id in [second, third] {
1423 let run = runs.read(cx).get(run_id).unwrap();
1424 assert_eq!(run.state, RunState::Stopped);
1425 assert_eq!(
1426 run.current_step,
1427 "Session opened in a terminal - send cancelled"
1428 );
1429 assert!(!run.is_queued());
1430 }
1431 assert!(runs.read(cx).open_after_stop.is_empty());
1432 });
1433 assert_eq!(lane_of(cx, &runs, &session_id), None);
1434 cx.update(|cx| {
1435 let stored = run_store::load_runs(&app.read(cx).store);
1436 let notice = stored.iter().find(|run| run.id == second).unwrap();
1437 assert_eq!(
1438 notice.current_step,
1439 "Session opened in a terminal - send cancelled"
1440 );
1441 });
1442 }
1443
1444 #[gpui_kit::test]
1445 fn a_requested_open_fires_whatever_the_outcome_of_the_run(cx: &mut TestAppContext) {
1446 let (_, runs) = setup(cx, "sh -c 'sleep 1; exit 3' --session-id {session_id}");
1447 let (first, second, _, session_id) = send_chain(cx, &runs);
1448 cx.update(|cx| runs.update(cx, |runs, _| runs.open_after_stop.insert(first)));
1449 wait_until_finished(cx, &runs, first);
1450 cx.update(|cx| {
1451 assert!(matches!(
1452 runs.read(cx).get(first).unwrap().state,
1453 RunState::Failed { .. }
1454 ));
1455 assert_eq!(runs.read(cx).get(second).unwrap().state, RunState::Stopped);
1456 assert!(runs.read(cx).open_after_stop.is_empty());
1457 });
1458 assert_eq!(lane_of(cx, &runs, &session_id), None);
1459 }
1460
1461 #[gpui_kit::test]
1462 fn a_run_that_never_launched_is_interrupted_not_resumed(cx: &mut TestAppContext) {
1463 let (app, _) = setup(cx, SESSION_COMMAND);
1464 let mut never_started = super::running_run(5);
1465 never_started.launched = false;
1466 let reloaded = reload(cx, &app, vec![never_started]);
1467 cx.update(|cx| {
1468 assert!(reloaded.read(cx).get(5).unwrap().is_finished());
1469 });
1470 assert_eq!(lane_of(cx, &reloaded, "session-5"), None);
1471 }
1472
1473 #[gpui_kit::test]
1474 fn stop_and_open_waits_for_the_orphan_kill_before_cancelling_the_lane(
1475 cx: &mut TestAppContext,
1476 ) {
1477 let (app, _) = setup(cx, SESSION_COMMAND);
1478 let mut orphan = super::running_run(5);
1479 orphan.session_id = "shared".to_owned();
1480 orphan.process_id = Some(1);
1481 let reloaded = reload(cx, &app, vec![orphan, queued_run(7)]);
1482 cx.update(|cx| {
1483 reloaded.update(cx, |runs, cx| runs.stop_and_open_session(5, cx));
1484 let runs = reloaded.read(cx);
1485 assert!(runs.get(5).unwrap().is_finished());
1486 assert!(runs.open_deferred.contains(&5));
1487 assert!(runs.get(7).unwrap().is_queued());
1488 assert!(runs.lanes.has_kills_pending("shared"));
1489 });
1490 for _ in 0..200 {
1491 cx.run_until_parked();
1492 if lane_of(cx, &reloaded, "shared").is_none() {
1493 break;
1494 }
1495 std::thread::sleep(Duration::from_millis(10));
1496 }
1497 cx.update(|cx| {
1498 let runs = reloaded.read(cx);
1499 assert_eq!(runs.get(7).unwrap().state, RunState::Stopped);
1500 assert!(runs.open_after_stop.is_empty() && runs.open_deferred.is_empty());
1501 });
1502 }
1503
1504 #[gpui_kit::test]
1505 fn a_send_during_an_in_flight_kill_waits_for_the_resumed_run(cx: &mut TestAppContext) {
1506 let (app, _) = setup(cx, SESSION_COMMAND);
1507 let mut orphan = super::running_run(5);
1508 orphan.session_id = "shared".to_owned();
1509 orphan.process_id = Some(1);
1510 let reloaded = reload(cx, &app, vec![orphan]);
1511 let sent = cx.update(|cx| {
1512 reloaded.update(cx, |runs, cx| {
1513 runs.start_with(
1514 "ask",
1515 "19:chat",
1516 "m1",
1517 "hi",
1518 target_of("shared".to_owned()),
1519 cx,
1520 )
1521 .unwrap()
1522 })
1523 });
1524 assert_eq!(
1525 lane_of(cx, &reloaded, "shared"),
1526 Some((Some(5), vec![sent]))
1527 );
1528 wait_until_finished(cx, &reloaded, 5);
1529 wait_until_finished(cx, &reloaded, sent);
1530 let (_, resumed_ended) = started_and_ended(cx, &reloaded, 5);
1531 let (sent_started, _) = started_and_ended(cx, &reloaded, sent);
1532 assert!(sent_started >= resumed_ended);
1533 }
1534
1535 #[test]
1536 fn old_saved_runs_with_a_chain_id_still_load() {
1537 let mut value = serde_json::to_value(super::running_run(3)).unwrap();
1538 let object = value.as_object_mut().unwrap();
1539 for key in ["sent_to", "launch_session_id", "launched", "pending_prompt"] {
1540 object.remove(key);
1541 }
1542 object.insert("after_run_id".to_owned(), serde_json::json!(2));
1543 object.insert("pending_prompt".to_owned(), serde_json::json!("saved"));
1544 let run: AgentRun = serde_json::from_value(value).unwrap();
1545 assert!(run.is_queued());
1546 assert!(run.launched);
1547 assert_eq!(run.sent_to, None);
1548 }
1549
1550 #[gpui_kit::test]
1551 fn a_forked_send_gets_a_fresh_session_id_and_adopts_a_reported_one(
1552 cx: &mut TestAppContext,
1553 ) {
1554 let (app, runs) = setup(cx, SESSION_COMMAND);
1555 let forked = cx.update(|cx| {
1556 runs.update(cx, |runs, cx| {
1557 let mut options = target_of("live-session".to_owned());
1558 options.session.as_mut().unwrap().fork = true;
1559 runs.start_with("ask", "19:chat", "m1", "hi", options, cx)
1560 .unwrap()
1561 })
1562 });
1563 cx.update(|cx| {
1564 let run = runs.read(cx).get(forked).unwrap().clone();
1565 assert_ne!(run.session_id, "live-session");
1566 assert!(run.sent_to.as_ref().unwrap().fork);
1567 assert!(!run.is_queued());
1568 runs.update(cx, |runs, cx| {
1569 runs.apply_update(
1570 forked,
1571 agents::RunUpdate::Event(agents::RunEvent::SessionId(
1572 "reported".to_owned(),
1573 )),
1574 cx,
1575 )
1576 });
1577 assert_eq!(runs.read(cx).get(forked).unwrap().session_id, "reported");
1578 let stored = run_store::load_runs(&app.read(cx).store);
1579 assert_eq!(stored[0].session_id, "reported");
1580 });
1581 wait_until_finished(cx, &runs, forked);
1582 }
1583
1584 #[gpui_kit::test]
1585 fn retrying_a_plain_run_keeps_its_chosen_working_dir_without_recording_it(
1586 cx: &mut TestAppContext,
1587 ) {
1588 let (_, runs) = setup(cx, SESSION_COMMAND);
1589 let started = cx.update(|cx| {
1590 runs.update(cx, |runs, cx| {
1591 runs.start_with(
1592 "ask",
1593 "19:chat",
1594 "m1",
1595 "",
1596 StartOptions {
1597 working_dir: Some("/srv/chosen".to_owned()),
1598 remember_working_dir: false,
1599 session: None,
1600 },
1601 cx,
1602 )
1603 .unwrap()
1604 })
1605 });
1606 wait_until_finished(cx, &runs, started);
1607 let retried =
1608 cx.update(|cx| runs.update(cx, |runs, cx| runs.retry(started, cx)).unwrap());
1609 cx.update(|cx| {
1610 assert_eq!(
1611 runs.read(cx).get(retried).unwrap().working_dir,
1612 "/srv/chosen"
1613 );
1614 assert!(
1615 runs.read(cx)
1616 .settings()
1617 .recent_working_dirs_of("fake")
1618 .is_empty()
1619 );
1620 });
1621 wait_until_finished(cx, &runs, retried);
1622 }
1623
1624 #[gpui_kit::test]
1625 fn retrying_a_session_send_sends_to_the_same_session_again(cx: &mut TestAppContext) {
1626 let (_, runs) = setup(cx, SESSION_COMMAND);
1627 let sent = cx.update(|cx| {
1628 runs.update(cx, |runs, cx| {
1629 runs.start_with(
1630 "ask",
1631 "19:chat",
1632 "m1",
1633 "again please",
1634 target_of("old-session".to_owned()),
1635 cx,
1636 )
1637 .unwrap()
1638 })
1639 });
1640 wait_until_finished(cx, &runs, sent);
1641 let retried = cx.update(|cx| runs.update(cx, |runs, cx| runs.retry(sent, cx)).unwrap());
1642 cx.update(|cx| {
1643 let run = runs.read(cx).get(retried).unwrap();
1644 assert_eq!(run.session_id, "old-session");
1645 assert_eq!(run.extra, "again please");
1646 assert_eq!(run.sent_to.as_ref().unwrap().session_id, "old-session");
1647 });
1648 wait_until_finished(cx, &runs, retried);
1649 }
1650
1651 fn queued_run(id: u64) -> AgentRun {
1652 let mut run = super::running_run(id);
1653 run.session_id = "shared".to_owned();
1654 run.current_step = "Queued".to_owned();
1655 run.pending_prompt = Some("saved prompt".to_owned());
1656 run
1657 }
1658
1659 fn reload(
1660 cx: &mut TestAppContext,
1661 app: &Entity<crate::app_state::AppState>,
1662 stored: Vec<AgentRun>,
1663 ) -> Entity<AgentRuns> {
1664 cx.update(|cx| {
1665 run_store::save_runs(&app.read(cx).store, &stored);
1666 cx.new(|cx| AgentRuns::new(app.clone(), cx))
1667 })
1668 }
1669
1670 #[gpui_kit::test]
1671 fn a_restart_rebuilds_the_lane_and_never_runs_two_processes_on_one_session(
1672 cx: &mut TestAppContext,
1673 ) {
1674 let (app, _) = setup(cx, SESSION_COMMAND);
1675 let mut active = super::running_run(5);
1676 active.session_id = "shared".to_owned();
1677 let mut duplicate = super::running_run(6);
1678 duplicate.session_id = "shared".to_owned();
1679 let reloaded = reload(
1680 cx,
1681 &app,
1682 vec![active, duplicate, queued_run(7), queued_run(8)],
1683 );
1684 cx.update(|cx| {
1685 let runs = reloaded.read(cx);
1686 assert!(runs.get(6).unwrap().is_finished());
1687 assert!(runs.get(7).unwrap().is_queued() && runs.get(8).unwrap().is_queued());
1688 });
1689 assert_eq!(
1690 lane_of(cx, &reloaded, "shared"),
1691 Some((Some(5), vec![7, 8]))
1692 );
1693 wait_until_finished(cx, &reloaded, 5);
1694 assert_eq!(lane_of(cx, &reloaded, "shared"), Some((Some(7), vec![8])));
1695 wait_until_finished(cx, &reloaded, 7);
1696 wait_until_finished(cx, &reloaded, 8);
1697 let (_, ended_5) = started_and_ended(cx, &reloaded, 5);
1698 let (started_7, ended_7) = started_and_ended(cx, &reloaded, 7);
1699 let (started_8, _) = started_and_ended(cx, &reloaded, 8);
1700 assert!(started_7 >= ended_5 && started_8 >= ended_7);
1701 }
1702
1703 #[gpui_kit::test]
1704 fn a_waiting_send_without_a_predecessor_runs_after_a_restart(cx: &mut TestAppContext) {
1705 let (app, _) = setup(cx, SESSION_COMMAND);
1706 let reloaded = reload(cx, &app, vec![queued_run(7), queued_run(8)]);
1707 assert_eq!(lane_of(cx, &reloaded, "shared"), Some((None, vec![7, 8])));
1708 cx.run_until_parked();
1709 assert_eq!(lane_of(cx, &reloaded, "shared"), Some((Some(7), vec![8])));
1710 wait_until_finished(cx, &reloaded, 7);
1711 wait_until_finished(cx, &reloaded, 8);
1712 assert_eq!(lane_of(cx, &reloaded, "shared"), None);
1713 }
1714
1715 #[gpui_kit::test]
1716 fn a_message_to_an_idle_session_resumes_it_and_a_chosen_dir_becomes_recent(
1717 cx: &mut TestAppContext,
1718 ) {
1719 let (_, runs) = setup(cx, SESSION_COMMAND);
1720 let (resumed, other) = cx.update(|cx| {
1721 runs.update(cx, |runs, cx| {
1722 let resumed = runs
1723 .start_with(
1724 "ask",
1725 "19:chat",
1726 "m1",
1727 "hello",
1728 target_of("old-session".to_owned()),
1729 cx,
1730 )
1731 .unwrap();
1732 let other = runs
1733 .start_with(
1734 "ask",
1735 "19:chat",
1736 "m1",
1737 "",
1738 StartOptions {
1739 working_dir: Some("/srv/other".to_owned()),
1740 remember_working_dir: true,
1741 session: None,
1742 },
1743 cx,
1744 )
1745 .unwrap();
1746 (resumed, other)
1747 })
1748 });
1749 cx.update(|cx| {
1750 let resumed = runs.read(cx).get(resumed).unwrap().clone();
1751 assert_eq!(resumed.session_id, "old-session");
1752 assert_ne!(resumed.current_step, "Queued");
1753 let other = runs.read(cx).get(other).unwrap().clone();
1754 assert_eq!(other.working_dir, "/srv/other");
1755 assert_eq!(
1756 runs.read(cx).settings().recent_working_dirs_of("fake"),
1757 ["/srv/other"]
1758 );
1759 });
1760 wait_until_finished(cx, &runs, resumed);
1761 }
1762
1763 #[gpui_kit::test]
1764 fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {
1765 let fixture = concat!(
1766 env!("CARGO_MANIFEST_DIR"),
1767 "/../agents/tests/fixtures/claude-stream.jsonl"
1768 );
1769 let (app, runs) = setup(cx, &format!("sh -c 'cat {fixture}'"));
1770 let run_id = cx.update(|cx| {
1771 runs.update(cx, |runs, cx| {
1772 runs.start_with("ask", "19:chat", "m1", "", StartOptions::default(), cx)
1773 })
1774 .unwrap()
1775 });
1776 wait_until_finished(cx, &runs, run_id);
1777 cx.update(|cx| {
1778 let run = runs.read(cx).get(run_id).unwrap().clone();
1779 assert_eq!(run.state, RunState::Done);
1780 assert_eq!(
1781 run.current_step,
1782 "Done - The first word in `/etc/hostname` is `HOST01`."
1783 );
1784 assert_eq!(run.steps.len(), 2);
1785 assert_eq!(
1786 run.steps[0].1,
1787 "MCP server is off - no reply proposal possible"
1788 );
1789 assert_eq!(run.steps[1].1, "Reading hostname");
1790 assert_eq!(run.chat_title, "Chat");
1791 assert_eq!(run.sender_name, "Ada");
1792 let stored = run_store::load_runs(&app.read(cx).store);
1793 assert_eq!(stored.len(), 1);
1794 assert_eq!(stored[0].state, RunState::Done);
1795 assert_eq!(stored[0].session_id, run.session_id);
1796 assert_eq!(runs.read(cx).running_count(), 0);
1797 });
1798 }
1799
1800 #[gpui_kit::test]
1801 fn a_resumed_run_continues_and_finishes_done(cx: &mut TestAppContext) {
1802 let fixture = concat!(
1803 env!("CARGO_MANIFEST_DIR"),
1804 "/../agents/tests/fixtures/claude-stream.jsonl"
1805 );
1806 let command = format!("sh -c 'cat {fixture}' --session-id {{session_id}}");
1807 let (app, runs) = setup(cx, &command);
1808 cx.update(|cx| {
1809 runs.update(cx, |runs, cx| {
1810 runs.runs.push(super::running_run(5));
1811 runs.persist(cx);
1812 });
1813 });
1814 let reloaded = cx.update(|cx| cx.new(|cx| AgentRuns::new(app.clone(), cx)));
1815 wait_until_finished(cx, &reloaded, 5);
1816 cx.update(|cx| {
1817 let run = reloaded.read(cx).get(5).unwrap().clone();
1818 assert_eq!(run.state, RunState::Done);
1819 assert_eq!(run.session_id, "3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11");
1820 assert!(
1821 run.steps
1822 .iter()
1823 .any(|(_, text)| text == "Resumed after restart")
1824 );
1825 });
1826 }
1827
1828 #[gpui_kit::test]
1829 fn a_failing_command_ends_failed_with_its_stderr(cx: &mut TestAppContext) {
1830 let (app, runs) = setup(cx, "sh -c 'echo boom >&2; exit 3'");
1831 let run_id = cx.update(|cx| {
1832 runs.update(cx, |runs, cx| {
1833 runs.start_with("ask", "19:chat", "m1", "", StartOptions::default(), cx)
1834 })
1835 .unwrap()
1836 });
1837 wait_until_finished(cx, &runs, run_id);
1838 cx.update(|cx| {
1839 let run = runs.read(cx).get(run_id).unwrap().clone();
1840 assert_eq!(
1841 run.state,
1842 RunState::Failed {
1843 message: "boom".to_owned(),
1844 log: vec!["boom".to_owned()],
1845 }
1846 );
1847 assert_eq!(run.current_step, "boom");
1848 let stored = run_store::load_runs(&app.read(cx).store);
1849 assert_eq!(stored[0].state, run.state);
1850 });
1851 }
1852 }
1853
1854 #[gpui_kit::test]
1855 fn a_missing_action_is_an_error_and_starts_nothing(cx: &mut TestAppContext) {
1856 let (_, runs) = setup(cx, "true");
1857 cx.update(|cx| {
1858 let error = runs
1859 .update(cx, |runs, cx| {
1860 runs.start_with("ghost", "19:chat", "m1", "", StartOptions::default(), cx)
1861 })
1862 .unwrap_err();
1863 assert_eq!(error, "This action no longer exists");
1864 let error = runs
1865 .update(cx, |runs, cx| {
1866 runs.start_with("ask", "19:chat", "gone", "", StartOptions::default(), cx)
1867 })
1868 .unwrap_err();
1869 assert_eq!(error, "The message is no longer available");
1870 assert_eq!(runs.read(cx).running_count(), 0);
1871 });
1872 }
1873
1874 #[gpui_kit::test]
1875 fn dismissed_runs_hide_and_stay_dismissed_after_reload(cx: &mut TestAppContext) {
1876 let (app, runs) = setup(cx, "true");
1877 cx.update(|cx| {
1878 runs.update(cx, |runs, cx| {
1879 runs.runs.push(finished_run(7));
1880 runs.dismiss(7, cx);
1881 assert!(runs.for_conversation("19:chat").next().is_none());
1882 assert!(runs.recent(10).is_empty());
1883 });
1884 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
1885 let reloaded = reloaded.read(cx);
1886 assert!(reloaded.get(7).is_some_and(|run| run.dismissed));
1887 assert_eq!(reloaded.next_id, 8);
1888 });
1889 }
1890
1891 const RESUMABLE_COMMAND: &str = "sh -c 'sleep 30' --session-id {session_id}";
1892 const INTERRUPTED: &str = "Interrupted - the app was closed during the run";
1893
1894 fn running_run(id: u64) -> AgentRun {
1895 let mut running = finished_run(id);
1896 running.action_id = "ask".to_owned();
1897 running.agent_id = "fake".to_owned();
1898 running.state = RunState::Running;
1899 running.ended_at = None;
1900 running
1901 }
1902
1903 fn reload_with(
1904 cx: &mut TestAppContext,
1905 command: &str,
1906 run: AgentRun,
1907 change_settings: impl FnOnce(&mut AgentSettings),
1908 ) -> AgentRun {
1909 let (app, runs) = setup(cx, command);
1910 cx.update(|cx| {
1911 let mut settings = fake_settings(command);
1912 change_settings(&mut settings);
1913 run_store::save_settings(&app.read(cx).store, &settings);
1914 let run_id = run.id;
1915 runs.update(cx, |runs, cx| {
1916 runs.runs.push(run);
1917 runs.persist(cx);
1918 });
1919 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
1920 reloaded.read(cx).get(run_id).unwrap().clone()
1921 })
1922 }
1923
1924 fn assert_interrupted(run: &AgentRun) {
1925 assert!(matches!(
1926 run.state,
1927 RunState::Failed { ref message, .. } if message == INTERRUPTED
1928 ));
1929 assert!(run.ended_at.is_some());
1930 }
1931
1932 #[gpui_kit::test]
1933 fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) {
1934 let run = reload_with(cx, "true", running_run(5), |_| {});
1935 assert_interrupted(&run);
1936 assert_eq!(run.session_id, "session-5");
1937 }
1938
1939 #[gpui_kit::test]
1940 fn a_running_run_with_a_session_is_resumed(cx: &mut TestAppContext) {
1941 let original = running_run(5);
1942 let run = reload_with(cx, RESUMABLE_COMMAND, original.clone(), |_| {});
1943 assert_eq!(run.state, RunState::Running);
1944 assert_eq!(run.ended_at, None);
1945 assert_eq!(run.started_at, original.started_at);
1946 assert_eq!(run.current_step, "Resumed after restart");
1947 assert_eq!(run.steps.len(), 2);
1948 assert_eq!(run.steps[0], original.steps[0]);
1949 assert_eq!(run.steps[1].1, "Resumed after restart");
1950 }
1951
1952 #[gpui_kit::test]
1953 fn steps_survive_a_restart_while_the_run_is_running(cx: &mut TestAppContext) {
1954 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
1955 let reloaded_run = cx.update(|cx| {
1956 let mut settings = fake_settings(RESUMABLE_COMMAND);
1957 settings.resume_interrupted_runs = true;
1958 run_store::save_settings(&app.read(cx).store, &settings);
1959 let mut run = running_run(5);
1960 run.steps.clear();
1961 runs.update(cx, |runs, cx| {
1962 runs.runs.push(run);
1963 runs.apply_update(
1964 5,
1965 agents::RunUpdate::Event(agents::RunEvent::Step("Reading notes".to_owned())),
1966 cx,
1967 );
1968 });
1969 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
1970 reloaded.read(cx).get(5).unwrap().clone()
1971 });
1972 let step_texts: Vec<&str> = reloaded_run
1973 .steps
1974 .iter()
1975 .map(|(_, text)| text.as_str())
1976 .collect();
1977 assert_eq!(step_texts, ["Reading notes", "Resumed after restart"]);
1978 }
1979
1980 #[gpui_kit::test]
1981 fn an_api_retry_shows_as_the_current_step_and_a_text_replaces_it(cx: &mut TestAppContext) {
1982 let (_, runs) = setup(cx, RESUMABLE_COMMAND);
1983 cx.update(|cx| {
1984 runs.update(cx, |runs, cx| {
1985 runs.runs.push(running_run(5));
1986 runs.apply_update(
1987 5,
1988 agents::RunUpdate::Event(agents::RunEvent::ApiRetry {
1989 message: "No response from API".to_owned(),
1990 retry_in: Some(Duration::from_secs(599)),
1991 }),
1992 cx,
1993 );
1994 });
1995 let run = runs.read(cx).get(5).unwrap().clone();
1996 assert_eq!(run.current_step, "API not responding - retrying in 10 min");
1997 assert_eq!(run.state, RunState::Running);
1998 runs.update(cx, |runs, cx| {
1999 runs.apply_update(
2000 5,
2001 agents::RunUpdate::Event(agents::RunEvent::Text("Back again".to_owned())),
2002 cx,
2003 );
2004 });
2005 assert_eq!(runs.read(cx).get(5).unwrap().current_step, "Back again");
2006 });
2007 }
2008
2009 #[test]
2010 fn api_retry_text_formats_minutes_and_seconds() {
2011 assert_eq!(
2012 api_retry_text("x", Some(Duration::from_secs(45))),
2013 "API not responding - retrying in 45 s"
2014 );
2015 assert_eq!(
2016 api_retry_text("x", Some(Duration::from_secs(120))),
2017 "API not responding - retrying in 2 min"
2018 );
2019 }
2020
2021 fn reload_many(cx: &mut TestAppContext, run_count: u64) -> (Entity<AgentRuns>, Vec<u64>) {
2022 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
2023 let ids: Vec<u64> = (1..=run_count).collect();
2024 let reloaded = cx.update(|cx| {
2025 runs.update(cx, |runs, cx| {
2026 runs.runs.extend(ids.iter().map(|id| running_run(*id)));
2027 runs.persist(cx);
2028 });
2029 cx.new(|cx| AgentRuns::new(app.clone(), cx))
2030 });
2031 (reloaded, ids)
2032 }
2033
2034 fn state_of(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) -> RunState {
2035 cx.update(|cx| runs.read(cx).get(run_id).unwrap().state.clone())
2036 }
2037
2038 #[gpui_kit::test]
2039 fn at_most_three_resumes_run_and_the_fourth_starts_when_one_finishes(cx: &mut TestAppContext) {
2040 let (runs, _) = reload_many(cx, 4);
2041 cx.run_until_parked();
2042 cx.update(|cx| {
2043 let runs = runs.read(cx);
2044 assert_eq!(runs.stops.len(), 3);
2045 assert_eq!(runs.resume_queue, [4]);
2046 });
2047 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(1, cx)));
2048 wait_until_finished(cx, &runs, 1);
2049 cx.run_until_parked();
2050 cx.update(|cx| {
2051 let runs_ref = runs.read(cx);
2052 assert!(runs_ref.resume_queue.is_empty());
2053 assert!(runs_ref.stops.contains_key(&4));
2054 runs.update(cx, |runs, cx| {
2055 for run_id in [2, 3, 4] {
2056 runs.stop(run_id, cx);
2057 }
2058 });
2059 });
2060 wait_until_finished(cx, &runs, 4);
2061 }
2062
2063 #[gpui_kit::test]
2064 fn stopping_a_queued_resume_ends_it_without_spawning(cx: &mut TestAppContext) {
2065 let (runs, _) = reload_many(cx, 4);
2066 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(4, cx)));
2067 cx.run_until_parked();
2068 assert_eq!(state_of(cx, &runs, 4), RunState::Stopped);
2069 cx.update(|cx| {
2070 let runs_ref = runs.read(cx);
2071 assert!(!runs_ref.stops.contains_key(&4));
2072 assert_eq!(runs_ref.stops.len(), 3);
2073 runs.update(cx, |runs, cx| {
2074 for run_id in [1, 2, 3] {
2075 runs.stop(run_id, cx);
2076 }
2077 });
2078 });
2079 wait_until_finished(cx, &runs, 3);
2080 }
2081
2082 #[gpui_kit::test]
2083 fn stopping_during_the_stop_wait_ends_the_run_without_spawning(cx: &mut TestAppContext) {
2084 let (runs, _) = reload_many(cx, 1);
2085 cx.update(|cx| {
2086 runs.update(cx, |runs, cx| {
2087 runs.resume_queue.clear();
2088 runs.begin_resume(1, cx);
2089 runs.stop(1, cx);
2090 })
2091 });
2092 cx.run_until_parked();
2093 assert_eq!(state_of(cx, &runs, 1), RunState::Stopped);
2094 cx.update(|cx| assert!(runs.read(cx).stops.is_empty()));
2095 }
2096
2097 #[gpui_kit::test]
2098 fn a_running_run_without_a_session_is_interrupted(cx: &mut TestAppContext) {
2099 let mut original = running_run(5);
2100 original.session_id = String::new();
2101 let run = reload_with(cx, RESUMABLE_COMMAND, original, |_| {});
2102 assert_interrupted(&run);
2103 }
2104
2105 #[gpui_kit::test]
2106 fn a_profile_that_cannot_resume_is_interrupted(cx: &mut TestAppContext) {
2107 let run = reload_with(cx, "sh -c 'sleep 30'", running_run(5), |_| {});
2108 assert_interrupted(&run);
2109 }
2110
2111 #[gpui_kit::test]
2112 fn switching_resume_off_interrupts_the_run(cx: &mut TestAppContext) {
2113 let run = reload_with(cx, RESUMABLE_COMMAND, running_run(5), |settings| {
2114 settings.resume_interrupted_runs = false
2115 });
2116 assert_interrupted(&run);
2117 }
2118
2119 #[test]
2120 fn layout_key_counts_visible_detail_rows() {
2121 let mut run = finished_run(1);
2122 assert_eq!(run.layout_key(), (0, false));
2123 run.expanded = true;
2124 run.steps = (0..9)
2125 .map(|index| (Duration::from_secs(index), index.to_string()))
2126 .collect();
2127 assert_eq!(run.layout_key(), (6, false));
2128 assert_eq!(run.visible_steps()[0].1, "3");
2129 run.state = RunState::Running;
2130 assert_eq!(run.layout_key(), (6, true));
2131 }
2132
2133 #[test]
2134 fn elapsed_reads_as_minutes_and_seconds() {
2135 assert_eq!(format_elapsed(Duration::from_secs(42)), "0:42");
2136 assert_eq!(format_elapsed(Duration::from_secs(631)), "10:31");
2137 assert_eq!(finished_run(1).elapsed_text(), "1:00");
2138 }
2139}