BlueGit

ict rusty-teams

Files

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

runs.rs

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