BlueGit

ict rusty-teams

Files

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

runs.rs

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