BlueGit

ict rusty-teams

Files

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

runs.rs

runs.rs 82.7 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 if let Some(profile) = self
842 .settings
843 .agents
844 .iter()
845 .find(|agent| agent.id == run.agent_id)
846 .cloned()
847 .filter(|profile| profile.is_chat())
848 {
849 self.mark_launching(run_id);
850 let endpoint = mcp_bridge::endpoint(cx);
851 self.spawn_chat(run_id, profile, prompt, endpoint, cx);
852 self.persist(cx);
853 return;
854 }
855 let planned = self.launch_plan(&run, &prompt, cx);
856 self.mark_launching(run_id);
857 match planned {
858 Ok((plan, format)) => self.spawn(run_id, plan, format, cx),
859 Err(message) => self.finish(
860 run_id,
861 Some(RunOutcome {
862 status: RunStatus::Failed {
863 message,
864 stderr_tail: Vec::new(),
865 },
866 exit_code: None,
867 }),
868 cx,
869 ),
870 }
871 self.persist(cx);
872 }
873
874 fn launch_plan(
875 &self,
876 run: &AgentRun,
877 prompt: &str,
878 cx: &App,
879 ) -> Result<(agents::RunPlan, agents::OutputFormat), String> {
880 let action = self
881 .settings
882 .actions
883 .iter()
884 .find(|action| action.id == run.action_id)
885 .cloned()
886 .ok_or("the action no longer exists")?;
887 let profile = self
888 .settings
889 .agents
890 .iter()
891 .find(|profile| profile.id == run.agent_id)
892 .ok_or("the agent no longer exists")?;
893 let action = AgentAction {
894 working_dir: run.working_dir.clone(),
895 ..action
896 };
897 plan_for(
898 profile,
899 &action,
900 prompt,
901 &run.session_id,
902 run.sent_to.as_ref(),
903 mcp_bridge::endpoint(cx).as_ref(),
904 )
905 .map(|plan| (plan, profile.output))
906 .map_err(|error| error.to_string())
907 }
908
909 fn mark_launching(&mut self, run_id: u64) {
910 if let Some(run) = self.run_mut(run_id) {
911 run.pending_prompt = None;
912 if run.current_step == QUEUED_STEP {
913 run.started_at = Utc::now();
914 run.push_step("Starting".to_owned());
915 }
916 }
917 }
918
919 fn spawn_chat(
920 &mut self,
921 run_id: u64,
922 profile: AgentProfile,
923 prompt: String,
924 endpoint: Option<McpEndpoint>,
925 cx: &mut Context<Self>,
926 ) {
927 let (updates_sender, mut updates) = mpsc::unbounded_channel();
928 let (stop_sender, stop_receiver) = oneshot::channel();
929 self.stops.insert(run_id, stop_sender);
930 if let Some(run) = self.run_mut(run_id) {
931 run.launch_session_id = Some(run.session_id.clone());
932 run.launched = true;
933 }
934 let outcome = runtime::spawn(super::chat_run::run_chat(
935 profile,
936 prompt,
937 endpoint,
938 updates_sender,
939 stop_receiver,
940 ));
941 cx.spawn(async move |this, cx| {
942 while let Some(update) = updates.recv().await {
943 if this
944 .update(cx, |runs, cx| runs.apply_update(run_id, update, cx))
945 .is_err()
946 {
947 return;
948 }
949 }
950 let outcome = outcome.await.ok();
951 this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))
952 .ok();
953 })
954 .detach();
955 }
956
957 fn spawn(
958 &mut self,
959 run_id: u64,
960 plan: agents::RunPlan,
961 format: agents::OutputFormat,
962 cx: &mut Context<Self>,
963 ) {
964 let (updates_sender, mut updates) = mpsc::unbounded_channel();
965 let (stop_sender, stop_receiver) = oneshot::channel();
966 self.stops.insert(run_id, stop_sender);
967 if let Some(run) = self.run_mut(run_id) {
968 run.launch_session_id = Some(run.session_id.clone());
969 }
970 let outcome = runtime::spawn(agents::run(plan, format, updates_sender, stop_receiver));
971 cx.spawn(async move |this, cx| {
972 while let Some(update) = updates.recv().await {
973 if this
974 .update(cx, |runs, cx| runs.apply_update(run_id, update, cx))
975 .is_err()
976 {
977 return;
978 }
979 }
980 let outcome = outcome.await.ok();
981 this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))
982 .ok();
983 })
984 .detach();
985 }
986
987 fn apply_update(&mut self, run_id: u64, update: RunUpdate, cx: &mut Context<Self>) {
988 let event = match update {
989 RunUpdate::Event(event) => event,
990 RunUpdate::Started(process_id) => {
991 if let Some(run) = self.run_mut(run_id) {
992 run.process_id = Some(process_id);
993 run.launched = true;
994 self.persist(cx);
995 }
996 return;
997 }
998 RunUpdate::Stderr(_) => return,
999 };
1000 let Some(run) = self.run_mut(run_id) else {
1001 return;
1002 };
1003 match event {
1004 RunEvent::Step(text) => {
1005 run.push_step(text);
1006 self.persist_progress(cx);
1007 }
1008 RunEvent::Text(text) => {
1009 run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)
1010 }
1011 RunEvent::ApiRetry { message, retry_in } => {
1012 run.current_step = api_retry_text(&message, retry_in)
1013 }
1014 RunEvent::SessionId(session_id) if session_id != run.session_id => {
1015 let previous = std::mem::replace(&mut run.session_id, session_id.clone());
1016 self.move_lane(&previous, &session_id);
1017 self.persist(cx);
1018 }
1019 _ => return,
1020 }
1021 cx.notify();
1022 }
1023
1024 fn move_lane(&mut self, from: &str, to: &str) {
1025 for run_id in self.lanes.rename(from, to) {
1026 if let Some(run) = self.run_mut(run_id) {
1027 run.session_id = to.to_owned();
1028 if let Some(target) = run.sent_to.as_mut() {
1029 target.session_id = to.to_owned();
1030 }
1031 }
1032 }
1033 }
1034
1035 fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {
1036 self.stops.remove(&run_id);
1037 self.stopping.remove(&run_id);
1038 let was_resuming = self.resuming.remove(&run_id);
1039 let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) else {
1040 return;
1041 };
1042 run.ended_at = Some(Utc::now());
1043 run.process_id = None;
1044 match outcome.map(|outcome| outcome.status) {
1045 Some(RunStatus::Completed { final_text }) => {
1046 let line = truncated(first_line(&final_text), DONE_STEP_CHARS);
1047 run.current_step = if line.is_empty() {
1048 "Done".to_owned()
1049 } else {
1050 format!("Done - {line}")
1051 };
1052 run.final_text = final_text;
1053 run.state = RunState::Done;
1054 }
1055 Some(RunStatus::Failed {
1056 message,
1057 stderr_tail,
1058 }) => {
1059 let message = if was_resuming && message.starts_with("cannot start") {
1060 format!("Could not resume - {message}")
1061 } else {
1062 message
1063 };
1064 run.current_step = message.clone();
1065 run.state = RunState::Failed {
1066 message,
1067 log: stderr_tail,
1068 };
1069 }
1070 Some(RunStatus::Stopped) => {
1071 run.current_step = "Stopped".to_owned();
1072 run.state = RunState::Stopped;
1073 }
1074 None => {
1075 let message = "The run was cancelled".to_owned();
1076 run.current_step = message.clone();
1077 run.state = RunState::Failed {
1078 message,
1079 log: Vec::new(),
1080 };
1081 }
1082 }
1083 let stopped = run.state == RunState::Stopped;
1084 let failed_or_done = !stopped;
1085 let snapshot = run.clone();
1086 self.prune_finished();
1087 self.persist(cx);
1088 if failed_or_done {
1089 cx.emit(AgentRunsEvent::Finished(run_id));
1090 }
1091 let session_id = snapshot.session_id.clone();
1092 let was_active = self.lanes.finished(&session_id, run_id);
1093 if self.open_after_stop.remove(&run_id) {
1094 if self.lanes.has_kills_pending(&session_id) {
1095 self.open_deferred.insert(run_id);
1096 } else {
1097 self.open_and_cancel(&snapshot, cx);
1098 }
1099 }
1100 if was_resuming {
1101 self.resume_next(cx);
1102 }
1103 if was_active {
1104 self.release(&session_id, cx);
1105 }
1106 cx.notify();
1107 }
1108
1109 fn prune_finished(&mut self) {
1110 let finished = self.runs.iter().filter(|run| run.is_finished()).count();
1111 let mut excess = finished.saturating_sub(run_store::RUNS_HISTORY_LIMIT);
1112 self.runs.retain(|run| {
1113 if excess > 0 && run.is_finished() {
1114 excess -= 1;
1115 return false;
1116 }
1117 true
1118 });
1119 }
1120
1121 fn ensure_ticking(&mut self, cx: &mut Context<Self>) {
1122 if self.ticking || self.running_count() == 0 {
1123 return;
1124 }
1125 self.ticking = true;
1126 cx.spawn(async move |this, cx| {
1127 loop {
1128 cx.background_executor().timer(TICK).await;
1129 let keep_going = this
1130 .update(cx, |runs, cx| {
1131 runs.ticking = runs.running_count() > 0;
1132 if runs.progress_unsaved {
1133 runs.persist_progress(cx);
1134 }
1135 if runs.ticking {
1136 cx.notify();
1137 }
1138 runs.ticking
1139 })
1140 .unwrap_or(false);
1141 if !keep_going {
1142 break;
1143 }
1144 }
1145 })
1146 .detach();
1147 }
1148
1149 pub fn stop(&mut self, run_id: u64, cx: &mut Context<Self>) {
1150 if self.stopping.contains(&run_id) {
1151 return;
1152 }
1153 if let Some(stop) = self.stops.remove(&run_id) {
1154 self.stopping.insert(run_id);
1155 let _ = stop.send(());
1156 if let Some(run) = self.run_mut(run_id) {
1157 run.current_step = "Stopping".to_owned();
1158 }
1159 cx.notify();
1160 } else if self.get(run_id).is_some_and(AgentRun::is_queued) {
1161 let session_id = self.get(run_id).map(|run| run.session_id.clone());
1162 if let Some(session_id) = session_id {
1163 self.lanes.remove_waiting(&session_id, run_id);
1164 }
1165 if let Some(run) = self.run_mut(run_id) {
1166 run.pending_prompt = None;
1167 }
1168 self.finish(
1169 run_id,
1170 Some(RunOutcome {
1171 status: RunStatus::Stopped,
1172 exit_code: None,
1173 }),
1174 cx,
1175 );
1176 } else if self.resuming.contains(&run_id) || self.resume_queue.contains(&run_id) {
1177 let orphan_stop = self
1178 .resume_queue
1179 .contains(&run_id)
1180 .then(|| {
1181 self.get(run_id).and_then(|run| {
1182 kills::orphan_kill(run, |candidate| {
1183 self.resume_plan(candidate, cx).ok().map(|(plan, _)| plan)
1184 })
1185 })
1186 })
1187 .flatten();
1188 let was_queued_for_resume = self.resume_queue.contains(&run_id);
1189 let session_id = self.get(run_id).map(|run| run.session_id.clone());
1190 self.resume_queue.retain(|queued| *queued != run_id);
1191 self.finish(
1192 run_id,
1193 Some(RunOutcome {
1194 status: RunStatus::Stopped,
1195 exit_code: None,
1196 }),
1197 cx,
1198 );
1199 if let (true, Some(session_id)) = (was_queued_for_resume, session_id) {
1200 self.run_kill(&session_id, orphan_stop, cx);
1201 }
1202 }
1203 }
1204
1205 pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) {
1206 let Some(run) = self.get(run_id).cloned() else {
1207 return;
1208 };
1209 if run.is_finished() {
1210 if self.lanes.has_kills_pending(&run.session_id) {
1211 self.open_deferred.insert(run_id);
1212 } else {
1213 self.open_and_cancel(&run, cx);
1214 }
1215 return;
1216 }
1217 if !run.is_queued() {
1218 self.open_after_stop.insert(run_id);
1219 }
1220 self.stop(run_id, cx);
1221 }
1222
1223 pub fn retry(&mut self, run_id: u64, cx: &mut Context<Self>) -> Result<u64, String> {
1224 let run = self
1225 .get(run_id)
1226 .cloned()
1227 .ok_or("This run no longer exists")?;
1228 let options = StartOptions {
1229 working_dir: run.sent_to.is_none().then(|| run.working_dir.clone()),
1230 remember_working_dir: false,
1231 session: run.sent_to.clone().map(|target| SessionTarget {
1232 session_id: run.session_id.clone(),
1233 ..target
1234 }),
1235 };
1236 let started = self.start_with(
1237 &run.action_id,
1238 &run.conversation_id,
1239 &run.message_id,
1240 &run.extra,
1241 options,
1242 cx,
1243 )?;
1244 self.dismiss(run_id, cx);
1245 Ok(started)
1246 }
1247
1248 pub fn dismiss(&mut self, run_id: u64, cx: &mut Context<Self>) {
1249 let Some(run) = self.run_mut(run_id).filter(|run| run.is_finished()) else {
1250 return;
1251 };
1252 run.dismissed = true;
1253 self.persist(cx);
1254 cx.notify();
1255 }
1256
1257 pub fn toggle_expanded(&mut self, run_id: u64, cx: &mut Context<Self>) {
1258 if let Some(run) = self.run_mut(run_id) {
1259 run.expanded = !run.expanded;
1260 cx.notify();
1261 }
1262 }
1263}
1264
1265#[cfg(test)]
1266pub(super) mod tests {
1267 use std::sync::Arc;
1268 use std::time::Duration;
1269
1270 use agents::{AgentAction, AgentProfile, AgentSettings};
1271 use chrono::TimeZone;
1272 use store::{MessageRecord, Store};
1273
1274 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1275
1276 use super::super::fixtures::finished_run;
1277 use super::{
1278 AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, api_retry_text,
1279 format_elapsed, needs_dialog, run_store,
1280 };
1281 use crate::app_state::{AppState, Mode};
1282
1283 #[test]
1284 fn the_dialog_shows_for_extra_instructions_or_a_chat_agents_cannot_see() {
1285 let quiet = AgentAction::answer_this("claude");
1286 let asking = AgentAction::build_this("claude");
1287 assert!(!needs_dialog(&quiet, true));
1288 assert!(needs_dialog(&quiet, false));
1289 assert!(needs_dialog(&asking, true));
1290 }
1291
1292 fn fake_settings(command: &str) -> AgentSettings {
1293 let profile = AgentProfile {
1294 id: "fake".to_owned(),
1295 name: "Fake".to_owned(),
1296 command: command.to_owned(),
1297 ..AgentProfile::default()
1298 };
1299 let action = AgentAction {
1300 id: "ask".to_owned(),
1301 label: "Ask".to_owned(),
1302 agent_id: "fake".to_owned(),
1303 working_dir: std::env::temp_dir().to_string_lossy().into_owned(),
1304 prompt_template: "{message}".to_owned(),
1305 ask_extra_instructions: false,
1306 extra_args: String::new(),
1307 };
1308 AgentSettings {
1309 agents: vec![profile],
1310 actions: vec![action],
1311 resume_interrupted_runs: true,
1312 ..AgentSettings::default()
1313 }
1314 }
1315
1316 fn setup(cx: &mut TestAppContext, command: &str) -> (Entity<AppState>, Entity<AgentRuns>) {
1317 cx.executor().allow_parking();
1318 let store = Arc::new(Store::open_in_memory().unwrap());
1319 store
1320 .upsert_messages(&[MessageRecord {
1321 conversation_id: "19:chat".to_owned(),
1322 message_id: "m1".to_owned(),
1323 sender_name: Some("Ada".to_owned()),
1324 created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
1325 body_html: "<p>Where is the report?</p>".to_owned(),
1326 attachments_json: "[]".to_owned(),
1327 reactions_json: "[]".to_owned(),
1328 mentions_json: "[]".to_owned(),
1329 links_json: "[]".to_owned(),
1330 ..MessageRecord::default()
1331 }])
1332 .unwrap();
1333 run_store::save_settings(&store, &fake_settings(command));
1334 cx.update(|cx| {
1335 let app = cx.new(|_| AppState::new(store, Mode::default()));
1336 let runs = cx.new(|cx| AgentRuns::new(app.clone(), cx));
1337 (app, runs)
1338 })
1339 }
1340
1341 fn wait_until_finished(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) {
1342 for _ in 0..500 {
1343 cx.run_until_parked();
1344 let finished = cx.update(|cx| {
1345 runs.read(cx)
1346 .get(run_id)
1347 .is_some_and(|run| run.is_finished())
1348 });
1349 if finished {
1350 return;
1351 }
1352 std::thread::sleep(Duration::from_millis(10));
1353 }
1354 panic!("the run did not finish");
1355 }
1356
1357 #[cfg(unix)]
1358 mod shell_runs {
1359 use std::time::Duration;
1360
1361 use gpui_kit::AppContext as _;
1362
1363 use super::super::InboxTarget;
1364 use super::{
1365 AgentRun, AgentRuns, Entity, RunState, SessionTarget, StartOptions, TestAppContext,
1366 run_store, setup, wait_until_finished,
1367 };
1368
1369 const SESSION_COMMAND: &str = "sh -c 'sleep 1' --session-id {session_id}";
1370
1371 fn target_of(session_id: String) -> StartOptions {
1372 StartOptions {
1373 working_dir: None,
1374 remember_working_dir: false,
1375 session: Some(SessionTarget {
1376 session_id,
1377 working_dir: std::env::temp_dir().to_string_lossy().into_owned(),
1378 inbox: None,
1379 }),
1380 }
1381 }
1382
1383 type LaneView = Option<(Option<u64>, Vec<u64>)>;
1384
1385 fn lane_of(
1386 cx: &mut TestAppContext,
1387 runs: &Entity<AgentRuns>,
1388 session_id: &str,
1389 ) -> LaneView {
1390 cx.update(|cx| {
1391 runs.read(cx).lanes.get(session_id).map(|lane| {
1392 (
1393 lane.active.first().copied(),
1394 lane.waiting.iter().copied().collect::<Vec<u64>>(),
1395 )
1396 })
1397 })
1398 }
1399
1400 fn send_chain(
1401 cx: &mut TestAppContext,
1402 runs: &Entity<AgentRuns>,
1403 ) -> (u64, u64, u64, String) {
1404 cx.update(|cx| {
1405 runs.update(cx, |runs, cx| {
1406 let first = runs
1407 .start_with("ask", "19:chat", "m1", "", StartOptions::default(), cx)
1408 .unwrap();
1409 let session_id = runs.get(first).unwrap().session_id.clone();
1410 let second = runs
1411 .start_with(
1412 "ask",
1413 "19:chat",
1414 "m1",
1415 "two",
1416 target_of(session_id.clone()),
1417 cx,
1418 )
1419 .unwrap();
1420 let third = runs
1421 .start_with(
1422 "ask",
1423 "19:chat",
1424 "m1",
1425 "three",
1426 target_of(session_id.clone()),
1427 cx,
1428 )
1429 .unwrap();
1430 (first, second, third, session_id)
1431 })
1432 })
1433 }
1434
1435 fn started_and_ended(
1436 cx: &mut TestAppContext,
1437 runs: &Entity<AgentRuns>,
1438 run_id: u64,
1439 ) -> (chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>) {
1440 cx.update(|cx| {
1441 let run = runs.read(cx).get(run_id).unwrap();
1442 (run.started_at, run.ended_at.unwrap())
1443 })
1444 }
1445
1446 #[gpui_kit::test]
1447 fn two_sends_to_one_session_run_strictly_one_after_another(cx: &mut TestAppContext) {
1448 let (_, runs) = setup(cx, SESSION_COMMAND);
1449 let (first, second, third, session_id) = send_chain(cx, &runs);
1450 assert_eq!(
1451 lane_of(cx, &runs, &session_id),
1452 Some((Some(first), vec![second, third]))
1453 );
1454 cx.update(|cx| {
1455 let queued = runs.read(cx).get(second).unwrap();
1456 assert_eq!(queued.current_step, "Queued");
1457 let prompt = queued.pending_prompt.clone().unwrap();
1458 assert!(prompt.contains("write_message") && prompt.contains("m1"));
1459 assert!(prompt.ends_with("\n\ntwo"));
1460 assert_eq!(queued.extra, "two");
1461 assert_eq!(queued.session_id, session_id);
1462 });
1463 wait_until_finished(cx, &runs, first);
1464 assert_eq!(
1465 lane_of(cx, &runs, &session_id),
1466 Some((Some(second), vec![third]))
1467 );
1468 cx.update(|cx| {
1469 assert!(!runs.read(cx).get(second).unwrap().is_queued());
1470 assert!(runs.read(cx).get(third).unwrap().is_queued());
1471 });
1472 wait_until_finished(cx, &runs, second);
1473 assert_eq!(lane_of(cx, &runs, &session_id), Some((Some(third), vec![])));
1474 wait_until_finished(cx, &runs, third);
1475 assert_eq!(lane_of(cx, &runs, &session_id), None);
1476 let (_, first_ended) = started_and_ended(cx, &runs, first);
1477 let (second_started, second_ended) = started_and_ended(cx, &runs, second);
1478 let (third_started, _) = started_and_ended(cx, &runs, third);
1479 assert!(second_started >= first_ended);
1480 assert!(third_started >= second_ended);
1481 }
1482
1483 #[gpui_kit::test]
1484 fn a_reported_session_id_moves_the_whole_lane_and_its_waiting_runs(
1485 cx: &mut TestAppContext,
1486 ) {
1487 let (_, runs) = setup(cx, SESSION_COMMAND);
1488 let (first, second, third, session_id) = send_chain(cx, &runs);
1489 cx.update(|cx| {
1490 runs.update(cx, |runs, cx| {
1491 runs.apply_update(
1492 first,
1493 agents::RunUpdate::Event(agents::RunEvent::SessionId("adopted".to_owned())),
1494 cx,
1495 )
1496 });
1497 let runs = runs.read(cx);
1498 assert_eq!(
1499 runs.get(first).unwrap().launch_session_id,
1500 Some(session_id.clone())
1501 );
1502 assert_eq!(runs.get(first).unwrap().session_id, "adopted");
1503 for run_id in [second, third] {
1504 assert_eq!(runs.get(run_id).unwrap().session_id, "adopted");
1505 }
1506 });
1507 assert_eq!(lane_of(cx, &runs, &session_id), None);
1508 assert_eq!(
1509 lane_of(cx, &runs, "adopted"),
1510 Some((Some(first), vec![second, third]))
1511 );
1512 wait_until_finished(cx, &runs, first);
1513 assert_eq!(
1514 lane_of(cx, &runs, "adopted"),
1515 Some((Some(second), vec![third]))
1516 );
1517 wait_until_finished(cx, &runs, second);
1518 wait_until_finished(cx, &runs, third);
1519 }
1520
1521 #[gpui_kit::test]
1522 fn stopping_a_waiting_send_only_removes_it_from_the_lane(cx: &mut TestAppContext) {
1523 let (_, runs) = setup(cx, SESSION_COMMAND);
1524 let (first, second, third, session_id) = send_chain(cx, &runs);
1525 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(second, cx)));
1526 cx.update(|cx| {
1527 let stopped = runs.read(cx).get(second).unwrap();
1528 assert_eq!(stopped.state, RunState::Stopped);
1529 assert!(!stopped.is_queued());
1530 });
1531 assert_eq!(
1532 lane_of(cx, &runs, &session_id),
1533 Some((Some(first), vec![third]))
1534 );
1535 wait_until_finished(cx, &runs, first);
1536 assert_eq!(lane_of(cx, &runs, &session_id), Some((Some(third), vec![])));
1537 wait_until_finished(cx, &runs, third);
1538 }
1539
1540 #[gpui_kit::test]
1541 fn stop_and_open_cancels_every_waiting_send_of_the_lane(cx: &mut TestAppContext) {
1542 let (app, runs) = setup(cx, SESSION_COMMAND);
1543 let (first, second, third, session_id) = send_chain(cx, &runs);
1544 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop_and_open_session(first, cx)));
1545 wait_until_finished(cx, &runs, first);
1546 cx.update(|cx| {
1547 for run_id in [second, third] {
1548 let run = runs.read(cx).get(run_id).unwrap();
1549 assert_eq!(run.state, RunState::Stopped);
1550 assert_eq!(
1551 run.current_step,
1552 "Session opened in a terminal - send cancelled"
1553 );
1554 assert!(!run.is_queued());
1555 }
1556 assert!(runs.read(cx).open_after_stop.is_empty());
1557 });
1558 assert_eq!(lane_of(cx, &runs, &session_id), None);
1559 cx.update(|cx| {
1560 let stored = run_store::load_runs(&app.read(cx).store);
1561 let notice = stored.iter().find(|run| run.id == second).unwrap();
1562 assert_eq!(
1563 notice.current_step,
1564 "Session opened in a terminal - send cancelled"
1565 );
1566 });
1567 }
1568
1569 #[gpui_kit::test]
1570 fn a_requested_open_fires_whatever_the_outcome_of_the_run(cx: &mut TestAppContext) {
1571 let (_, runs) = setup(cx, "sh -c 'sleep 1; exit 3' --session-id {session_id}");
1572 let (first, second, _, session_id) = send_chain(cx, &runs);
1573 cx.update(|cx| runs.update(cx, |runs, _| runs.open_after_stop.insert(first)));
1574 wait_until_finished(cx, &runs, first);
1575 cx.update(|cx| {
1576 assert!(matches!(
1577 runs.read(cx).get(first).unwrap().state,
1578 RunState::Failed { .. }
1579 ));
1580 assert_eq!(runs.read(cx).get(second).unwrap().state, RunState::Stopped);
1581 assert!(runs.read(cx).open_after_stop.is_empty());
1582 });
1583 assert_eq!(lane_of(cx, &runs, &session_id), None);
1584 }
1585
1586 #[gpui_kit::test]
1587 fn a_run_that_never_launched_is_interrupted_not_resumed(cx: &mut TestAppContext) {
1588 let (app, _) = setup(cx, SESSION_COMMAND);
1589 let mut never_started = super::running_run(5);
1590 never_started.launched = false;
1591 let reloaded = reload(cx, &app, vec![never_started]);
1592 cx.update(|cx| {
1593 assert!(reloaded.read(cx).get(5).unwrap().is_finished());
1594 });
1595 assert_eq!(lane_of(cx, &reloaded, "session-5"), None);
1596 }
1597
1598 #[gpui_kit::test]
1599 fn stop_and_open_waits_for_the_orphan_kill_before_cancelling_the_lane(
1600 cx: &mut TestAppContext,
1601 ) {
1602 let (app, _) = setup(cx, SESSION_COMMAND);
1603 let mut orphan = super::running_run(5);
1604 orphan.session_id = "shared".to_owned();
1605 orphan.process_id = Some(1);
1606 let reloaded = reload(cx, &app, vec![orphan, queued_run(7)]);
1607 cx.update(|cx| {
1608 reloaded.update(cx, |runs, cx| runs.stop_and_open_session(5, cx));
1609 let runs = reloaded.read(cx);
1610 assert!(runs.get(5).unwrap().is_finished());
1611 assert!(runs.open_deferred.contains(&5));
1612 assert!(runs.get(7).unwrap().is_queued());
1613 assert!(runs.lanes.has_kills_pending("shared"));
1614 });
1615 for _ in 0..200 {
1616 cx.run_until_parked();
1617 if lane_of(cx, &reloaded, "shared").is_none() {
1618 break;
1619 }
1620 std::thread::sleep(Duration::from_millis(10));
1621 }
1622 cx.update(|cx| {
1623 let runs = reloaded.read(cx);
1624 assert_eq!(runs.get(7).unwrap().state, RunState::Stopped);
1625 assert!(runs.open_after_stop.is_empty() && runs.open_deferred.is_empty());
1626 });
1627 }
1628
1629 #[gpui_kit::test]
1630 fn a_send_during_an_in_flight_kill_waits_for_the_resumed_run(cx: &mut TestAppContext) {
1631 let (app, _) = setup(cx, SESSION_COMMAND);
1632 let mut orphan = super::running_run(5);
1633 orphan.session_id = "shared".to_owned();
1634 orphan.process_id = Some(1);
1635 let reloaded = reload(cx, &app, vec![orphan]);
1636 let sent = cx.update(|cx| {
1637 reloaded.update(cx, |runs, cx| {
1638 runs.start_with(
1639 "ask",
1640 "19:chat",
1641 "m1",
1642 "hi",
1643 target_of("shared".to_owned()),
1644 cx,
1645 )
1646 .unwrap()
1647 })
1648 });
1649 assert_eq!(
1650 lane_of(cx, &reloaded, "shared"),
1651 Some((Some(5), vec![sent]))
1652 );
1653 wait_until_finished(cx, &reloaded, 5);
1654 wait_until_finished(cx, &reloaded, sent);
1655 let (_, resumed_ended) = started_and_ended(cx, &reloaded, 5);
1656 let (sent_started, _) = started_and_ended(cx, &reloaded, sent);
1657 assert!(sent_started >= resumed_ended);
1658 }
1659
1660 #[test]
1661 fn old_saved_runs_with_a_chain_id_still_load() {
1662 let mut value = serde_json::to_value(super::running_run(3)).unwrap();
1663 let object = value.as_object_mut().unwrap();
1664 for key in ["sent_to", "launch_session_id", "launched", "pending_prompt"] {
1665 object.remove(key);
1666 }
1667 object.insert("after_run_id".to_owned(), serde_json::json!(2));
1668 object.insert("pending_prompt".to_owned(), serde_json::json!("saved"));
1669 let run: AgentRun = serde_json::from_value(value).unwrap();
1670 assert!(run.is_queued());
1671 assert!(run.launched);
1672 assert_eq!(run.sent_to, None);
1673 }
1674
1675 fn inbox_options(
1676 socket_path: &std::path::Path,
1677 sessions_dir: &std::path::Path,
1678 ) -> StartOptions {
1679 let mut options = target_of("live-session".to_owned());
1680 options.session.as_mut().unwrap().inbox = Some(InboxTarget {
1681 session: agents::RunningSession {
1682 session_id: "live-session".to_owned(),
1683 name: Some("Review".to_owned()),
1684 working_dir: "/srv".to_owned(),
1685 socket_path: Some(socket_path.to_string_lossy().into_owned()),
1686 process_id: 42,
1687 },
1688 sessions_dir: sessions_dir.to_path_buf(),
1689 });
1690 options
1691 }
1692
1693 #[gpui_kit::test]
1694 fn a_message_to_a_running_session_is_delivered_without_a_process(cx: &mut TestAppContext) {
1695 let (_, runs) = setup(cx, SESSION_COMMAND);
1696 let directory = tempfile::tempdir().unwrap();
1697 let socket_path = directory.path().join("s.sock");
1698 let listener = std::os::unix::net::UnixListener::bind(&socket_path).unwrap();
1699 std::fs::write(directory.path().join("42.ab.key"), r#"{"peerToken":"tok"}"#).unwrap();
1700 let reader = std::thread::spawn(move || {
1701 let (mut stream, _) = listener.accept().unwrap();
1702 let mut received = String::new();
1703 std::io::Read::read_to_string(&mut stream, &mut received).unwrap();
1704 received
1705 });
1706 let delivered = cx.update(|cx| {
1707 runs.update(cx, |runs, cx| {
1708 runs.start_with(
1709 "ask",
1710 "19:chat",
1711 "m1",
1712 "hi",
1713 inbox_options(&socket_path, directory.path()),
1714 cx,
1715 )
1716 .unwrap()
1717 })
1718 });
1719 wait_until_finished(cx, &runs, delivered);
1720 cx.update(|cx| {
1721 let run = runs.read(cx).get(delivered).unwrap();
1722 assert_eq!(run.state, RunState::Done);
1723 assert_eq!(run.current_step, "Delivered to Review");
1724 assert_eq!(run.session_id, "live-session");
1725 assert_eq!(run.process_id, None);
1726 assert!(run.final_text.contains("Teams draft"));
1727 });
1728 let received = reader.join().unwrap();
1729 assert!(received.contains("live-session"));
1730 assert!(received.contains("write_message"));
1731 assert!(received.contains("19:chat"));
1732 assert!(received.starts_with(r#"{"type":"auth","token":"tok"}"#));
1733 }
1734
1735 #[gpui_kit::test]
1736 fn a_session_that_ended_before_delivery_is_resumed_in_place(cx: &mut TestAppContext) {
1737 let (_, runs) = setup(cx, SESSION_COMMAND);
1738 let directory = tempfile::tempdir().unwrap();
1739 std::fs::write(directory.path().join("42.ab.key"), r#"{"peerToken":"tok"}"#).unwrap();
1740 let resumed = cx.update(|cx| {
1741 runs.update(cx, |runs, cx| {
1742 runs.start_with(
1743 "ask",
1744 "19:chat",
1745 "m1",
1746 "hi",
1747 inbox_options(&directory.path().join("gone.sock"), directory.path()),
1748 cx,
1749 )
1750 .unwrap()
1751 })
1752 });
1753 wait_until_finished(cx, &runs, resumed);
1754 cx.update(|cx| {
1755 let run = runs.read(cx).get(resumed).unwrap();
1756 assert!(run.steps.iter().any(|(_, step)| step.contains("resuming")));
1757 assert!(run.launched);
1758 assert_eq!(run.session_id, "live-session");
1759 });
1760 }
1761
1762 #[gpui_kit::test]
1763 fn a_delivery_failure_marks_the_run_failed_without_the_token(cx: &mut TestAppContext) {
1764 let (_, runs) = setup(cx, SESSION_COMMAND);
1765 let directory = tempfile::tempdir().unwrap();
1766 let failed = cx.update(|cx| {
1767 runs.update(cx, |runs, cx| {
1768 runs.start_with(
1769 "ask",
1770 "19:chat",
1771 "m1",
1772 "hi",
1773 inbox_options(&directory.path().join("s.sock"), directory.path()),
1774 cx,
1775 )
1776 .unwrap()
1777 })
1778 });
1779 wait_until_finished(cx, &runs, failed);
1780 cx.update(|cx| {
1781 assert!(matches!(
1782 runs.read(cx).get(failed).unwrap().state,
1783 RunState::Failed { .. }
1784 ));
1785 });
1786 }
1787
1788 #[gpui_kit::test]
1789 fn retrying_a_plain_run_keeps_its_chosen_working_dir_without_recording_it(
1790 cx: &mut TestAppContext,
1791 ) {
1792 let (_, runs) = setup(cx, SESSION_COMMAND);
1793 let started = cx.update(|cx| {
1794 runs.update(cx, |runs, cx| {
1795 runs.start_with(
1796 "ask",
1797 "19:chat",
1798 "m1",
1799 "",
1800 StartOptions {
1801 working_dir: Some("/srv/chosen".to_owned()),
1802 remember_working_dir: false,
1803 session: None,
1804 },
1805 cx,
1806 )
1807 .unwrap()
1808 })
1809 });
1810 wait_until_finished(cx, &runs, started);
1811 let retried =
1812 cx.update(|cx| runs.update(cx, |runs, cx| runs.retry(started, cx)).unwrap());
1813 cx.update(|cx| {
1814 assert_eq!(
1815 runs.read(cx).get(retried).unwrap().working_dir,
1816 "/srv/chosen"
1817 );
1818 assert!(
1819 runs.read(cx)
1820 .settings()
1821 .recent_working_dirs_of("fake")
1822 .is_empty()
1823 );
1824 });
1825 wait_until_finished(cx, &runs, retried);
1826 }
1827
1828 #[gpui_kit::test]
1829 fn retrying_a_session_send_sends_to_the_same_session_again(cx: &mut TestAppContext) {
1830 let (_, runs) = setup(cx, SESSION_COMMAND);
1831 let sent = cx.update(|cx| {
1832 runs.update(cx, |runs, cx| {
1833 runs.start_with(
1834 "ask",
1835 "19:chat",
1836 "m1",
1837 "again please",
1838 target_of("old-session".to_owned()),
1839 cx,
1840 )
1841 .unwrap()
1842 })
1843 });
1844 wait_until_finished(cx, &runs, sent);
1845 let retried = cx.update(|cx| runs.update(cx, |runs, cx| runs.retry(sent, cx)).unwrap());
1846 cx.update(|cx| {
1847 let run = runs.read(cx).get(retried).unwrap();
1848 assert_eq!(run.session_id, "old-session");
1849 assert_eq!(run.extra, "again please");
1850 assert_eq!(run.sent_to.as_ref().unwrap().session_id, "old-session");
1851 });
1852 wait_until_finished(cx, &runs, retried);
1853 }
1854
1855 fn queued_run(id: u64) -> AgentRun {
1856 let mut run = super::running_run(id);
1857 run.session_id = "shared".to_owned();
1858 run.current_step = "Queued".to_owned();
1859 run.pending_prompt = Some("saved prompt".to_owned());
1860 run
1861 }
1862
1863 fn reload(
1864 cx: &mut TestAppContext,
1865 app: &Entity<crate::app_state::AppState>,
1866 stored: Vec<AgentRun>,
1867 ) -> Entity<AgentRuns> {
1868 cx.update(|cx| {
1869 run_store::save_runs(&app.read(cx).store, &stored);
1870 cx.new(|cx| AgentRuns::new(app.clone(), cx))
1871 })
1872 }
1873
1874 #[gpui_kit::test]
1875 fn a_restart_rebuilds_the_lane_and_never_runs_two_processes_on_one_session(
1876 cx: &mut TestAppContext,
1877 ) {
1878 let (app, _) = setup(cx, SESSION_COMMAND);
1879 let mut active = super::running_run(5);
1880 active.session_id = "shared".to_owned();
1881 let mut duplicate = super::running_run(6);
1882 duplicate.session_id = "shared".to_owned();
1883 let reloaded = reload(
1884 cx,
1885 &app,
1886 vec![active, duplicate, queued_run(7), queued_run(8)],
1887 );
1888 cx.update(|cx| {
1889 let runs = reloaded.read(cx);
1890 assert!(runs.get(6).unwrap().is_finished());
1891 assert!(runs.get(7).unwrap().is_queued() && runs.get(8).unwrap().is_queued());
1892 });
1893 assert_eq!(
1894 lane_of(cx, &reloaded, "shared"),
1895 Some((Some(5), vec![7, 8]))
1896 );
1897 wait_until_finished(cx, &reloaded, 5);
1898 assert_eq!(lane_of(cx, &reloaded, "shared"), Some((Some(7), vec![8])));
1899 wait_until_finished(cx, &reloaded, 7);
1900 wait_until_finished(cx, &reloaded, 8);
1901 let (_, ended_5) = started_and_ended(cx, &reloaded, 5);
1902 let (started_7, ended_7) = started_and_ended(cx, &reloaded, 7);
1903 let (started_8, _) = started_and_ended(cx, &reloaded, 8);
1904 assert!(started_7 >= ended_5 && started_8 >= ended_7);
1905 }
1906
1907 #[gpui_kit::test]
1908 fn a_waiting_send_without_a_predecessor_runs_after_a_restart(cx: &mut TestAppContext) {
1909 let (app, _) = setup(cx, SESSION_COMMAND);
1910 let reloaded = reload(cx, &app, vec![queued_run(7), queued_run(8)]);
1911 assert_eq!(lane_of(cx, &reloaded, "shared"), Some((None, vec![7, 8])));
1912 cx.run_until_parked();
1913 assert_eq!(lane_of(cx, &reloaded, "shared"), Some((Some(7), vec![8])));
1914 wait_until_finished(cx, &reloaded, 7);
1915 wait_until_finished(cx, &reloaded, 8);
1916 assert_eq!(lane_of(cx, &reloaded, "shared"), None);
1917 }
1918
1919 #[gpui_kit::test]
1920 fn a_message_to_an_idle_session_resumes_it_and_a_chosen_dir_becomes_recent(
1921 cx: &mut TestAppContext,
1922 ) {
1923 let (_, runs) = setup(cx, SESSION_COMMAND);
1924 let (resumed, other) = cx.update(|cx| {
1925 runs.update(cx, |runs, cx| {
1926 let resumed = runs
1927 .start_with(
1928 "ask",
1929 "19:chat",
1930 "m1",
1931 "hello",
1932 target_of("old-session".to_owned()),
1933 cx,
1934 )
1935 .unwrap();
1936 let other = runs
1937 .start_with(
1938 "ask",
1939 "19:chat",
1940 "m1",
1941 "",
1942 StartOptions {
1943 working_dir: Some("/srv/other".to_owned()),
1944 remember_working_dir: true,
1945 session: None,
1946 },
1947 cx,
1948 )
1949 .unwrap();
1950 (resumed, other)
1951 })
1952 });
1953 cx.update(|cx| {
1954 let resumed = runs.read(cx).get(resumed).unwrap().clone();
1955 assert_eq!(resumed.session_id, "old-session");
1956 assert_ne!(resumed.current_step, "Queued");
1957 let other = runs.read(cx).get(other).unwrap().clone();
1958 assert_eq!(other.working_dir, "/srv/other");
1959 assert_eq!(
1960 runs.read(cx).settings().recent_working_dirs_of("fake"),
1961 ["/srv/other"]
1962 );
1963 });
1964 wait_until_finished(cx, &runs, resumed);
1965 }
1966
1967 #[gpui_kit::test]
1968 fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {
1969 let fixture = concat!(
1970 env!("CARGO_MANIFEST_DIR"),
1971 "/../agents/tests/fixtures/claude-stream.jsonl"
1972 );
1973 let (app, runs) = setup(cx, &format!("sh -c 'cat {fixture}'"));
1974 let run_id = cx.update(|cx| {
1975 runs.update(cx, |runs, cx| {
1976 runs.start_with("ask", "19:chat", "m1", "", StartOptions::default(), cx)
1977 })
1978 .unwrap()
1979 });
1980 wait_until_finished(cx, &runs, run_id);
1981 cx.update(|cx| {
1982 let run = runs.read(cx).get(run_id).unwrap().clone();
1983 assert_eq!(run.state, RunState::Done);
1984 assert_eq!(
1985 run.current_step,
1986 "Done - The first word in `/etc/hostname` is `HOST01`."
1987 );
1988 assert_eq!(run.steps.len(), 2);
1989 assert_eq!(
1990 run.steps[0].1,
1991 "MCP server is off - no reply proposal possible"
1992 );
1993 assert_eq!(run.steps[1].1, "Reading hostname");
1994 assert_eq!(run.chat_title, "Chat");
1995 assert_eq!(run.sender_name, "Ada");
1996 let stored = run_store::load_runs(&app.read(cx).store);
1997 assert_eq!(stored.len(), 1);
1998 assert_eq!(stored[0].state, RunState::Done);
1999 assert_eq!(stored[0].session_id, run.session_id);
2000 assert_eq!(runs.read(cx).running_count(), 0);
2001 });
2002 }
2003
2004 #[gpui_kit::test]
2005 fn a_resumed_run_continues_and_finishes_done(cx: &mut TestAppContext) {
2006 let fixture = concat!(
2007 env!("CARGO_MANIFEST_DIR"),
2008 "/../agents/tests/fixtures/claude-stream.jsonl"
2009 );
2010 let command = format!("sh -c 'cat {fixture}' --session-id {{session_id}}");
2011 let (app, runs) = setup(cx, &command);
2012 cx.update(|cx| {
2013 runs.update(cx, |runs, cx| {
2014 runs.runs.push(super::running_run(5));
2015 runs.persist(cx);
2016 });
2017 });
2018 let reloaded = cx.update(|cx| cx.new(|cx| AgentRuns::new(app.clone(), cx)));
2019 wait_until_finished(cx, &reloaded, 5);
2020 cx.update(|cx| {
2021 let run = reloaded.read(cx).get(5).unwrap().clone();
2022 assert_eq!(run.state, RunState::Done);
2023 assert_eq!(run.session_id, "3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11");
2024 assert!(
2025 run.steps
2026 .iter()
2027 .any(|(_, text)| text == "Resumed after restart")
2028 );
2029 });
2030 }
2031
2032 #[gpui_kit::test]
2033 fn a_failing_command_ends_failed_with_its_stderr(cx: &mut TestAppContext) {
2034 let (app, runs) = setup(cx, "sh -c 'echo boom >&2; exit 3'");
2035 let run_id = cx.update(|cx| {
2036 runs.update(cx, |runs, cx| {
2037 runs.start_with("ask", "19:chat", "m1", "", StartOptions::default(), cx)
2038 })
2039 .unwrap()
2040 });
2041 wait_until_finished(cx, &runs, run_id);
2042 cx.update(|cx| {
2043 let run = runs.read(cx).get(run_id).unwrap().clone();
2044 assert_eq!(
2045 run.state,
2046 RunState::Failed {
2047 message: "boom".to_owned(),
2048 log: vec!["boom".to_owned()],
2049 }
2050 );
2051 assert_eq!(run.current_step, "boom");
2052 let stored = run_store::load_runs(&app.read(cx).store);
2053 assert_eq!(stored[0].state, run.state);
2054 });
2055 }
2056 }
2057
2058 #[gpui_kit::test]
2059 fn a_missing_action_is_an_error_and_starts_nothing(cx: &mut TestAppContext) {
2060 let (_, runs) = setup(cx, "true");
2061 cx.update(|cx| {
2062 let error = runs
2063 .update(cx, |runs, cx| {
2064 runs.start_with("ghost", "19:chat", "m1", "", StartOptions::default(), cx)
2065 })
2066 .unwrap_err();
2067 assert_eq!(error, "This action no longer exists");
2068 let error = runs
2069 .update(cx, |runs, cx| {
2070 runs.start_with("ask", "19:chat", "gone", "", StartOptions::default(), cx)
2071 })
2072 .unwrap_err();
2073 assert_eq!(error, "The message is no longer available");
2074 assert_eq!(runs.read(cx).running_count(), 0);
2075 });
2076 }
2077
2078 #[gpui_kit::test]
2079 fn dismissed_runs_hide_and_stay_dismissed_after_reload(cx: &mut TestAppContext) {
2080 let (app, runs) = setup(cx, "true");
2081 cx.update(|cx| {
2082 runs.update(cx, |runs, cx| {
2083 runs.runs.push(finished_run(7));
2084 runs.dismiss(7, cx);
2085 assert!(runs.for_conversation("19:chat").next().is_none());
2086 assert!(runs.recent(10).is_empty());
2087 });
2088 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
2089 let reloaded = reloaded.read(cx);
2090 assert!(reloaded.get(7).is_some_and(|run| run.dismissed));
2091 assert_eq!(reloaded.next_id, 8);
2092 });
2093 }
2094
2095 const RESUMABLE_COMMAND: &str = "sh -c 'sleep 30' --session-id {session_id}";
2096 const INTERRUPTED: &str = "Interrupted - the app was closed during the run";
2097
2098 fn running_run(id: u64) -> AgentRun {
2099 let mut running = finished_run(id);
2100 running.action_id = "ask".to_owned();
2101 running.agent_id = "fake".to_owned();
2102 running.state = RunState::Running;
2103 running.ended_at = None;
2104 running
2105 }
2106
2107 fn reload_with(
2108 cx: &mut TestAppContext,
2109 command: &str,
2110 run: AgentRun,
2111 change_settings: impl FnOnce(&mut AgentSettings),
2112 ) -> AgentRun {
2113 let (app, runs) = setup(cx, command);
2114 cx.update(|cx| {
2115 let mut settings = fake_settings(command);
2116 change_settings(&mut settings);
2117 run_store::save_settings(&app.read(cx).store, &settings);
2118 let run_id = run.id;
2119 runs.update(cx, |runs, cx| {
2120 runs.runs.push(run);
2121 runs.persist(cx);
2122 });
2123 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
2124 reloaded.read(cx).get(run_id).unwrap().clone()
2125 })
2126 }
2127
2128 fn assert_interrupted(run: &AgentRun) {
2129 assert!(matches!(
2130 run.state,
2131 RunState::Failed { ref message, .. } if message == INTERRUPTED
2132 ));
2133 assert!(run.ended_at.is_some());
2134 }
2135
2136 #[gpui_kit::test]
2137 fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) {
2138 let run = reload_with(cx, "true", running_run(5), |_| {});
2139 assert_interrupted(&run);
2140 assert_eq!(run.session_id, "session-5");
2141 }
2142
2143 #[gpui_kit::test]
2144 fn a_running_run_with_a_session_is_resumed(cx: &mut TestAppContext) {
2145 let original = running_run(5);
2146 let run = reload_with(cx, RESUMABLE_COMMAND, original.clone(), |_| {});
2147 assert_eq!(run.state, RunState::Running);
2148 assert_eq!(run.ended_at, None);
2149 assert_eq!(run.started_at, original.started_at);
2150 assert_eq!(run.current_step, "Resumed after restart");
2151 assert_eq!(run.steps.len(), 2);
2152 assert_eq!(run.steps[0], original.steps[0]);
2153 assert_eq!(run.steps[1].1, "Resumed after restart");
2154 }
2155
2156 #[gpui_kit::test]
2157 fn steps_survive_a_restart_while_the_run_is_running(cx: &mut TestAppContext) {
2158 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
2159 let reloaded_run = cx.update(|cx| {
2160 let mut settings = fake_settings(RESUMABLE_COMMAND);
2161 settings.resume_interrupted_runs = true;
2162 run_store::save_settings(&app.read(cx).store, &settings);
2163 let mut run = running_run(5);
2164 run.steps.clear();
2165 runs.update(cx, |runs, cx| {
2166 runs.runs.push(run);
2167 runs.apply_update(
2168 5,
2169 agents::RunUpdate::Event(agents::RunEvent::Step("Reading notes".to_owned())),
2170 cx,
2171 );
2172 });
2173 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
2174 reloaded.read(cx).get(5).unwrap().clone()
2175 });
2176 let step_texts: Vec<&str> = reloaded_run
2177 .steps
2178 .iter()
2179 .map(|(_, text)| text.as_str())
2180 .collect();
2181 assert_eq!(step_texts, ["Reading notes", "Resumed after restart"]);
2182 }
2183
2184 #[gpui_kit::test]
2185 fn an_api_retry_shows_as_the_current_step_and_a_text_replaces_it(cx: &mut TestAppContext) {
2186 let (_, runs) = setup(cx, RESUMABLE_COMMAND);
2187 cx.update(|cx| {
2188 runs.update(cx, |runs, cx| {
2189 runs.runs.push(running_run(5));
2190 runs.apply_update(
2191 5,
2192 agents::RunUpdate::Event(agents::RunEvent::ApiRetry {
2193 message: "No response from API".to_owned(),
2194 retry_in: Some(Duration::from_secs(599)),
2195 }),
2196 cx,
2197 );
2198 });
2199 let run = runs.read(cx).get(5).unwrap().clone();
2200 assert_eq!(run.current_step, "API not responding - retrying in 10 min");
2201 assert_eq!(run.state, RunState::Running);
2202 runs.update(cx, |runs, cx| {
2203 runs.apply_update(
2204 5,
2205 agents::RunUpdate::Event(agents::RunEvent::Text("Back again".to_owned())),
2206 cx,
2207 );
2208 });
2209 assert_eq!(runs.read(cx).get(5).unwrap().current_step, "Back again");
2210 });
2211 }
2212
2213 #[test]
2214 fn api_retry_text_formats_minutes_and_seconds() {
2215 assert_eq!(
2216 api_retry_text("x", Some(Duration::from_secs(45))),
2217 "API not responding - retrying in 45 s"
2218 );
2219 assert_eq!(
2220 api_retry_text("x", Some(Duration::from_secs(120))),
2221 "API not responding - retrying in 2 min"
2222 );
2223 }
2224
2225 fn reload_many(cx: &mut TestAppContext, run_count: u64) -> (Entity<AgentRuns>, Vec<u64>) {
2226 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
2227 let ids: Vec<u64> = (1..=run_count).collect();
2228 let reloaded = cx.update(|cx| {
2229 runs.update(cx, |runs, cx| {
2230 runs.runs.extend(ids.iter().map(|id| running_run(*id)));
2231 runs.persist(cx);
2232 });
2233 cx.new(|cx| AgentRuns::new(app.clone(), cx))
2234 });
2235 (reloaded, ids)
2236 }
2237
2238 fn state_of(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) -> RunState {
2239 cx.update(|cx| runs.read(cx).get(run_id).unwrap().state.clone())
2240 }
2241
2242 #[gpui_kit::test]
2243 fn at_most_three_resumes_run_and_the_fourth_starts_when_one_finishes(cx: &mut TestAppContext) {
2244 let (runs, _) = reload_many(cx, 4);
2245 cx.run_until_parked();
2246 cx.update(|cx| {
2247 let runs = runs.read(cx);
2248 assert_eq!(runs.stops.len(), 3);
2249 assert_eq!(runs.resume_queue, [4]);
2250 });
2251 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(1, cx)));
2252 wait_until_finished(cx, &runs, 1);
2253 cx.run_until_parked();
2254 cx.update(|cx| {
2255 let runs_ref = runs.read(cx);
2256 assert!(runs_ref.resume_queue.is_empty());
2257 assert!(runs_ref.stops.contains_key(&4));
2258 runs.update(cx, |runs, cx| {
2259 for run_id in [2, 3, 4] {
2260 runs.stop(run_id, cx);
2261 }
2262 });
2263 });
2264 wait_until_finished(cx, &runs, 4);
2265 }
2266
2267 #[gpui_kit::test]
2268 fn stopping_a_queued_resume_ends_it_without_spawning(cx: &mut TestAppContext) {
2269 let (runs, _) = reload_many(cx, 4);
2270 cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(4, cx)));
2271 cx.run_until_parked();
2272 assert_eq!(state_of(cx, &runs, 4), RunState::Stopped);
2273 cx.update(|cx| {
2274 let runs_ref = runs.read(cx);
2275 assert!(!runs_ref.stops.contains_key(&4));
2276 assert_eq!(runs_ref.stops.len(), 3);
2277 runs.update(cx, |runs, cx| {
2278 for run_id in [1, 2, 3] {
2279 runs.stop(run_id, cx);
2280 }
2281 });
2282 });
2283 wait_until_finished(cx, &runs, 3);
2284 }
2285
2286 #[gpui_kit::test]
2287 fn stopping_during_the_stop_wait_ends_the_run_without_spawning(cx: &mut TestAppContext) {
2288 let (runs, _) = reload_many(cx, 1);
2289 cx.update(|cx| {
2290 runs.update(cx, |runs, cx| {
2291 runs.resume_queue.clear();
2292 runs.begin_resume(1, cx);
2293 runs.stop(1, cx);
2294 })
2295 });
2296 cx.run_until_parked();
2297 assert_eq!(state_of(cx, &runs, 1), RunState::Stopped);
2298 cx.update(|cx| assert!(runs.read(cx).stops.is_empty()));
2299 }
2300
2301 #[gpui_kit::test]
2302 fn a_running_run_without_a_session_is_interrupted(cx: &mut TestAppContext) {
2303 let mut original = running_run(5);
2304 original.session_id = String::new();
2305 let run = reload_with(cx, RESUMABLE_COMMAND, original, |_| {});
2306 assert_interrupted(&run);
2307 }
2308
2309 #[gpui_kit::test]
2310 fn a_profile_that_cannot_resume_is_interrupted(cx: &mut TestAppContext) {
2311 let run = reload_with(cx, "sh -c 'sleep 30'", running_run(5), |_| {});
2312 assert_interrupted(&run);
2313 }
2314
2315 #[gpui_kit::test]
2316 fn switching_resume_off_interrupts_the_run(cx: &mut TestAppContext) {
2317 let run = reload_with(cx, RESUMABLE_COMMAND, running_run(5), |settings| {
2318 settings.resume_interrupted_runs = false
2319 });
2320 assert_interrupted(&run);
2321 }
2322
2323 #[test]
2324 fn layout_key_counts_visible_detail_rows() {
2325 let mut run = finished_run(1);
2326 assert_eq!(run.layout_key(), (0, false));
2327 run.expanded = true;
2328 run.steps = (0..9)
2329 .map(|index| (Duration::from_secs(index), index.to_string()))
2330 .collect();
2331 assert_eq!(run.layout_key(), (6, false));
2332 assert_eq!(run.visible_steps()[0].1, "3");
2333 run.state = RunState::Running;
2334 assert_eq!(run.layout_key(), (6, true));
2335 }
2336
2337 #[test]
2338 fn elapsed_reads_as_minutes_and_seconds() {
2339 assert_eq!(format_elapsed(Duration::from_secs(42)), "0:42");
2340 assert_eq!(format_elapsed(Duration::from_secs(631)), "10:31");
2341 assert_eq!(finished_run(1).elapsed_text(), "1:00");
2342 }
2343}