BlueGit

ict rusty-teams

Files

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

runs.rs

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