BlueGit

ict rusty-teams

fix(agents): run steps survive a restart, API retries show on the chip

- Steps were only saved on state changes, so an auto-resumed run came back with just
  "Resumed after restart". Steps are now saved while running, at most every 5 s.
- Claude stream-json api_error/api_retry events show as "API not responding - retrying
  in 10 min" instead of a silent chip; the run stays running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
a7f20c02c3fb19921e5d416789cd020c818f911b
Parent
c70d5111
4 files changed +183 −7
crates/agents/src/parse/claude.rs +35 −3
@@ -1,4 +1,5 @@
1 1 use std::path::Path;
2 use std::time::Duration;
2 3
3 4 use serde_json::Value;
4 5
@@ -11,9 +12,11 @@ pub(super) fn parse_line(line: &str) -> Vec<RunEvent> {
11 12 return Vec::new();
12 13 };
13 14 match value.get("type").and_then(Value::as_str) {
14 Some("system") if value.get("subtype").and_then(Value::as_str) == Some("init") => {
15 session_id_events(&value)
16 }
15 Some("system") => match value.get("subtype").and_then(Value::as_str) {
16 Some("init") => session_id_events(&value),
17 Some("api_error" | "api_retry") => vec![api_retry_event(&value)],
18 _ => Vec::new(),
19 },
17 20 Some("assistant") => assistant_events(&value),
18 21 Some("result") => result_events(&value),
19 22 _ => Vec::new(),
@@ -28,6 +31,35 @@ fn session_id_events(value: &Value) -> Vec<RunEvent> {
28 31 .unwrap_or_default()
29 32 }
30 33
34 fn api_retry_event(value: &Value) -> RunEvent {
35 let error = value.get("error");
36 let message = error
37 .and_then(|error| {
38 error.as_str().or_else(|| {
39 ["formatted", "message"]
40 .iter()
41 .find_map(|key| error.get(*key).and_then(Value::as_str))
42 })
43 })
44 .unwrap_or("API error")
45 .to_string();
46 let retry_milliseconds = [
47 error.and_then(|error| error.pointer("/noResponse/retryWaitMs")),
48 error.and_then(|error| error.get("retryWaitMs")),
49 value.get("retry_delay_ms"),
50 value.get("retryWaitMs"),
51 ]
52 .into_iter()
53 .flatten()
54 .find_map(Value::as_f64);
55 RunEvent::ApiRetry {
56 message,
57 retry_in: retry_milliseconds
58 .filter(|milliseconds| *milliseconds >= 0.0)
59 .map(|milliseconds| Duration::from_millis(milliseconds as u64)),
60 }
61 }
62
31 63 fn assistant_events(value: &Value) -> Vec<RunEvent> {
32 64 let Some(blocks) = value.pointer("/message/content").and_then(Value::as_array) else {
33 65 return Vec::new();
@@ -1,4 +1,5 @@
1use std::path::Path;
1use std::path::Path;
2use std::time::Duration;
2
3
3use serde_json::Value;
4use serde_json::Value;
4
5
@@ -11,9 +12,11 @@ pub(super) fn parse_line(line: &str) -> Vec<RunEvent> {
11 return Vec::new();
12 return Vec::new();
12 };
13 };
13 match value.get("type").and_then(Value::as_str) {
14 match value.get("type").and_then(Value::as_str) {
14 Some("system") if value.get("subtype").and_then(Value::as_str) == Some("init") => {
15 Some("system") => match value.get("subtype").and_then(Value::as_str) {
15 session_id_events(&value)
16 Some("init") => session_id_events(&value),
16 }
17 Some("api_error" | "api_retry") => vec![api_retry_event(&value)],
18 _ => Vec::new(),
19 },
17 Some("assistant") => assistant_events(&value),
20 Some("assistant") => assistant_events(&value),
18 Some("result") => result_events(&value),
21 Some("result") => result_events(&value),
19 _ => Vec::new(),
22 _ => Vec::new(),
@@ -28,6 +31,35 @@ fn session_id_events(value: &Value) -> Vec<RunEvent> {
28 .unwrap_or_default()
31 .unwrap_or_default()
29}
32}
30
33
34fn api_retry_event(value: &Value) -> RunEvent {
35 let error = value.get("error");
36 let message = error
37 .and_then(|error| {
38 error.as_str().or_else(|| {
39 ["formatted", "message"]
40 .iter()
41 .find_map(|key| error.get(*key).and_then(Value::as_str))
42 })
43 })
44 .unwrap_or("API error")
45 .to_string();
46 let retry_milliseconds = [
47 error.and_then(|error| error.pointer("/noResponse/retryWaitMs")),
48 error.and_then(|error| error.get("retryWaitMs")),
49 value.get("retry_delay_ms"),
50 value.get("retryWaitMs"),
51 ]
52 .into_iter()
53 .flatten()
54 .find_map(Value::as_f64);
55 RunEvent::ApiRetry {
56 message,
57 retry_in: retry_milliseconds
58 .filter(|milliseconds| *milliseconds >= 0.0)
59 .map(|milliseconds| Duration::from_millis(milliseconds as u64)),
60 }
61}
62
31fn assistant_events(value: &Value) -> Vec<RunEvent> {
63fn assistant_events(value: &Value) -> Vec<RunEvent> {
32 let Some(blocks) = value.pointer("/message/content").and_then(Value::as_array) else {
64 let Some(blocks) = value.pointer("/message/content").and_then(Value::as_array) else {
33 return Vec::new();
65 return Vec::new();
crates/agents/src/parse/mod.rs +6 −0
@@ -2,6 +2,8 @@ mod claude;
2 2 mod copilot;
3 3 mod text;
4 4
5 use std::time::Duration;
6
5 7 use crate::profile::OutputFormat;
6 8
7 9 #[derive(Clone, Debug, PartialEq, Eq)]
@@ -11,6 +13,10 @@ pub enum RunEvent {
11 13 Final(String),
12 14 SessionId(String),
13 15 Failed(String),
16 ApiRetry {
17 message: String,
18 retry_in: Option<Duration>,
19 },
14 20 }
15 21
16 22 #[derive(Debug)]
@@ -2,6 +2,8 @@ mod claude;
2mod copilot;
2mod copilot;
3mod text;
3mod text;
4
4
5use std::time::Duration;
6
5use crate::profile::OutputFormat;
7use crate::profile::OutputFormat;
6
8
7#[derive(Clone, Debug, PartialEq, Eq)]
9#[derive(Clone, Debug, PartialEq, Eq)]
@@ -11,6 +13,10 @@ pub enum RunEvent {
11 Final(String),
13 Final(String),
12 SessionId(String),
14 SessionId(String),
13 Failed(String),
15 Failed(String),
16 ApiRetry {
17 message: String,
18 retry_in: Option<Duration>,
19 },
14}
20}
15
21
16#[derive(Debug)]
22#[derive(Debug)]
crates/agents/tests/parsers.rs +28 −0
@@ -1,3 +1,5 @@
1 use std::time::Duration;
2
1 3 use agents::{OutputFormat, OutputParser, RunEvent, parse_line};
2 4
3 5 fn parse_fixture(format: OutputFormat, name: &str) -> Vec<RunEvent> {
@@ -98,3 +100,29 @@ fn text_format_accumulates() {
98 100 vec![RunEvent::Final("hello\n\nworld".to_string())]
99 101 );
100 102 }
103
104 #[test]
105 fn claude_api_error_becomes_an_api_retry() {
106 let line = r#"{"type":"system","subtype":"api_error","error":{"message":"Connection error.","formatted":"No response from API","connection":{"code":"StreamNoResponse"},"noResponse":{"waitedMs":190000,"retryWaitMs":599000}},"session_id":"abc"}"#;
107 let events = parse_line(OutputFormat::ClaudeStreamJson, line);
108 assert_eq!(
109 events,
110 vec![RunEvent::ApiRetry {
111 message: "No response from API".to_string(),
112 retry_in: Some(Duration::from_millis(599_000)),
113 }]
114 );
115 }
116
117 #[test]
118 fn claude_api_error_without_a_delay_has_no_retry_time() {
119 let line = r#"{"type":"system","subtype":"api_error","error":"Connection error."}"#;
120 let events = parse_line(OutputFormat::ClaudeStreamJson, line);
121 assert_eq!(
122 events,
123 vec![RunEvent::ApiRetry {
124 message: "Connection error.".to_string(),
125 retry_in: None,
126 }]
127 );
128 }
@@ -1,3 +1,5 @@
1use std::time::Duration;
2
1use agents::{OutputFormat, OutputParser, RunEvent, parse_line};
3use agents::{OutputFormat, OutputParser, RunEvent, parse_line};
2
4
3fn parse_fixture(format: OutputFormat, name: &str) -> Vec<RunEvent> {
5fn parse_fixture(format: OutputFormat, name: &str) -> Vec<RunEvent> {
@@ -98,3 +100,29 @@ fn text_format_accumulates() {
98 vec![RunEvent::Final("hello\n\nworld".to_string())]
100 vec![RunEvent::Final("hello\n\nworld".to_string())]
99 );
101 );
100}
102}
103
104#[test]
105fn claude_api_error_becomes_an_api_retry() {
106 let line = r#"{"type":"system","subtype":"api_error","error":{"message":"Connection error.","formatted":"No response from API","connection":{"code":"StreamNoResponse"},"noResponse":{"waitedMs":190000,"retryWaitMs":599000}},"session_id":"abc"}"#;
107 let events = parse_line(OutputFormat::ClaudeStreamJson, line);
108 assert_eq!(
109 events,
110 vec![RunEvent::ApiRetry {
111 message: "No response from API".to_string(),
112 retry_in: Some(Duration::from_millis(599_000)),
113 }]
114 );
115}
116
117#[test]
118fn claude_api_error_without_a_delay_has_no_retry_time() {
119 let line = r#"{"type":"system","subtype":"api_error","error":"Connection error."}"#;
120 let events = parse_line(OutputFormat::ClaudeStreamJson, line);
121 assert_eq!(
122 events,
123 vec![RunEvent::ApiRetry {
124 message: "Connection error.".to_string(),
125 retry_in: None,
126 }]
127 );
128}
crates/app/src/agents/runs.rs +114 −4
@@ -1,5 +1,5 @@
1 1 use std::collections::{HashMap, HashSet, VecDeque};
2 use std::time::Duration;
2 use std::time::{Duration, Instant};
3 3
4 4 use agents::{
5 5 AgentAction, AgentProfile, AgentSettings, McpEndpoint, RunEvent, RunOutcome, RunStatus,
@@ -25,6 +25,7 @@ const VISIBLE_LOG_LINES: usize = 20;
25 25 const TEXT_STEP_CHARS: usize = 80;
26 26 const DONE_STEP_CHARS: usize = 60;
27 27 const TICK: Duration = Duration::from_secs(1);
28 const PROGRESS_PERSIST_INTERVAL: Duration = Duration::from_secs(5);
28 29 const RESUME_PARALLEL_LIMIT: usize = 3;
29 30 const QUEUED_STEP: &str = "Queued";
30 31 const OPENED_NOTICE: &str = "Session opened in a terminal - send cancelled";
@@ -172,6 +173,19 @@ pub fn format_elapsed(duration: Duration) -> String {
172 173 format!("{}:{:02}", seconds / 60, seconds % 60)
173 174 }
174 175
176 fn api_retry_text(message: &str, retry_in: Option<Duration>) -> String {
177 let Some(retry_in) = retry_in else {
178 return format!("API not responding - retrying ({message})");
179 };
180 let seconds = retry_in.as_secs();
181 let wait = if seconds >= 60 {
182 format!("{} min", seconds.div_ceil(60))
183 } else {
184 format!("{seconds} s")
185 };
186 format!("API not responding - retrying in {wait}")
187 }
188
175 189 fn first_line(text: &str) -> &str {
176 190 text.lines()
177 191 .find(|line| !line.trim().is_empty())
@@ -255,6 +269,8 @@ pub struct AgentRuns {
255 269 open_deferred: HashSet<u64>,
256 270 next_id: u64,
257 271 ticking: bool,
272 progress_saved_at: Option<Instant>,
273 progress_unsaved: bool,
258 274 }
259 275
260 276 impl EventEmitter<AgentRunsEvent> for AgentRuns {}
@@ -314,6 +330,8 @@ impl AgentRuns {
314 330 open_deferred: HashSet::new(),
315 331 next_id,
316 332 ticking: false,
333 progress_saved_at: None,
334 progress_unsaved: false,
317 335 };
318 336 agent_runs.ensure_ticking(cx);
319 337 agent_runs.start_resumes(cx);
@@ -516,8 +534,21 @@ impl AgentRuns {
516 534 self.runs.iter_mut().find(|run| run.id == run_id)
517 535 }
518 536
519 fn persist(&self, cx: &App) {
537 fn persist(&mut self, cx: &App) {
520 538 run_store::save_runs(&self.app.read(cx).store, &self.runs);
539 self.progress_saved_at = Some(Instant::now());
540 self.progress_unsaved = false;
541 }
542
543 fn persist_progress(&mut self, cx: &App) {
544 let due = self
545 .progress_saved_at
546 .is_none_or(|saved_at| saved_at.elapsed() >= PROGRESS_PERSIST_INTERVAL);
547 if !due {
548 self.progress_unsaved = true;
549 return;
550 }
551 self.persist(cx);
521 552 }
522 553
523 554 pub fn start(
@@ -846,10 +877,16 @@ impl AgentRuns {
846 877 return;
847 878 };
848 879 match event {
849 RunEvent::Step(text) => run.push_step(text),
880 RunEvent::Step(text) => {
881 run.push_step(text);
882 self.persist_progress(cx);
883 }
850 884 RunEvent::Text(text) => {
851 885 run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)
852 886 }
887 RunEvent::ApiRetry { message, retry_in } => {
888 run.current_step = api_retry_text(&message, retry_in)
889 }
853 890 RunEvent::SessionId(session_id) if session_id != run.session_id => {
854 891 let previous = std::mem::replace(&mut run.session_id, session_id.clone());
855 892 self.move_lane(&previous, &session_id);
@@ -968,6 +1005,9 @@ impl AgentRuns {
968 1005 let keep_going = this
969 1006 .update(cx, |runs, cx| {
970 1007 runs.ticking = runs.running_count() > 0;
1008 if runs.progress_unsaved {
1009 runs.persist_progress(cx);
1010 }
971 1011 if runs.ticking {
972 1012 cx.notify();
973 1013 }
@@ -1114,7 +1154,8 @@ pub(super) mod tests {
1114 1154 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1115 1155
1116 1156 use super::{
1117 AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, format_elapsed, run_store,
1157 AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, api_retry_text,
1158 format_elapsed, run_store,
1118 1159 };
1119 1160 use crate::app_state::{AppState, Mode};
1120 1161
@@ -1925,6 +1966,75 @@ pub(super) mod tests {
1925 1966 assert_eq!(run.steps[1].1, "Resumed after restart");
1926 1967 }
1927 1968
1969 #[gpui_kit::test]
1970 fn steps_survive_a_restart_while_the_run_is_running(cx: &mut TestAppContext) {
1971 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
1972 let reloaded_run = cx.update(|cx| {
1973 let mut settings = fake_settings(RESUMABLE_COMMAND);
1974 settings.resume_interrupted_runs = true;
1975 run_store::save_settings(&app.read(cx).store, &settings);
1976 let mut run = running_run(5);
1977 run.steps.clear();
1978 runs.update(cx, |runs, cx| {
1979 runs.runs.push(run);
1980 runs.apply_update(
1981 5,
1982 agents::RunUpdate::Event(agents::RunEvent::Step("Reading notes".to_owned())),
1983 cx,
1984 );
1985 });
1986 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
1987 reloaded.read(cx).get(5).unwrap().clone()
1988 });
1989 let step_texts: Vec<&str> = reloaded_run
1990 .steps
1991 .iter()
1992 .map(|(_, text)| text.as_str())
1993 .collect();
1994 assert_eq!(step_texts, ["Reading notes", "Resumed after restart"]);
1995 }
1996
1997 #[gpui_kit::test]
1998 fn an_api_retry_shows_as_the_current_step_and_a_text_replaces_it(cx: &mut TestAppContext) {
1999 let (_, runs) = setup(cx, RESUMABLE_COMMAND);
2000 cx.update(|cx| {
2001 runs.update(cx, |runs, cx| {
2002 runs.runs.push(running_run(5));
2003 runs.apply_update(
2004 5,
2005 agents::RunUpdate::Event(agents::RunEvent::ApiRetry {
2006 message: "No response from API".to_owned(),
2007 retry_in: Some(Duration::from_secs(599)),
2008 }),
2009 cx,
2010 );
2011 });
2012 let run = runs.read(cx).get(5).unwrap().clone();
2013 assert_eq!(run.current_step, "API not responding - retrying in 10 min");
2014 assert_eq!(run.state, RunState::Running);
2015 runs.update(cx, |runs, cx| {
2016 runs.apply_update(
2017 5,
2018 agents::RunUpdate::Event(agents::RunEvent::Text("Back again".to_owned())),
2019 cx,
2020 );
2021 });
2022 assert_eq!(runs.read(cx).get(5).unwrap().current_step, "Back again");
2023 });
2024 }
2025
2026 #[test]
2027 fn api_retry_text_formats_minutes_and_seconds() {
2028 assert_eq!(
2029 api_retry_text("x", Some(Duration::from_secs(45))),
2030 "API not responding - retrying in 45 s"
2031 );
2032 assert_eq!(
2033 api_retry_text("x", Some(Duration::from_secs(120))),
2034 "API not responding - retrying in 2 min"
2035 );
2036 }
2037
1928 2038 fn reload_many(cx: &mut TestAppContext, run_count: u64) -> (Entity<AgentRuns>, Vec<u64>) {
1929 2039 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
1930 2040 let ids: Vec<u64> = (1..=run_count).collect();
@@ -1,5 +1,5 @@
1use std::collections::{HashMap, HashSet, VecDeque};
1use std::collections::{HashMap, HashSet, VecDeque};
2use std::time::Duration;
2use std::time::{Duration, Instant};
3
3
4use agents::{
4use agents::{
5 AgentAction, AgentProfile, AgentSettings, McpEndpoint, RunEvent, RunOutcome, RunStatus,
5 AgentAction, AgentProfile, AgentSettings, McpEndpoint, RunEvent, RunOutcome, RunStatus,
@@ -25,6 +25,7 @@ const VISIBLE_LOG_LINES: usize = 20;
25const TEXT_STEP_CHARS: usize = 80;
25const TEXT_STEP_CHARS: usize = 80;
26const DONE_STEP_CHARS: usize = 60;
26const DONE_STEP_CHARS: usize = 60;
27const TICK: Duration = Duration::from_secs(1);
27const TICK: Duration = Duration::from_secs(1);
28const PROGRESS_PERSIST_INTERVAL: Duration = Duration::from_secs(5);
28const RESUME_PARALLEL_LIMIT: usize = 3;
29const RESUME_PARALLEL_LIMIT: usize = 3;
29const QUEUED_STEP: &str = "Queued";
30const QUEUED_STEP: &str = "Queued";
30const OPENED_NOTICE: &str = "Session opened in a terminal - send cancelled";
31const OPENED_NOTICE: &str = "Session opened in a terminal - send cancelled";
@@ -172,6 +173,19 @@ pub fn format_elapsed(duration: Duration) -> String {
172 format!("{}:{:02}", seconds / 60, seconds % 60)
173 format!("{}:{:02}", seconds / 60, seconds % 60)
173}
174}
174
175
176fn api_retry_text(message: &str, retry_in: Option<Duration>) -> String {
177 let Some(retry_in) = retry_in else {
178 return format!("API not responding - retrying ({message})");
179 };
180 let seconds = retry_in.as_secs();
181 let wait = if seconds >= 60 {
182 format!("{} min", seconds.div_ceil(60))
183 } else {
184 format!("{seconds} s")
185 };
186 format!("API not responding - retrying in {wait}")
187}
188
175fn first_line(text: &str) -> &str {
189fn first_line(text: &str) -> &str {
176 text.lines()
190 text.lines()
177 .find(|line| !line.trim().is_empty())
191 .find(|line| !line.trim().is_empty())
@@ -255,6 +269,8 @@ pub struct AgentRuns {
255 open_deferred: HashSet<u64>,
269 open_deferred: HashSet<u64>,
256 next_id: u64,
270 next_id: u64,
257 ticking: bool,
271 ticking: bool,
272 progress_saved_at: Option<Instant>,
273 progress_unsaved: bool,
258}
274}
259
275
260impl EventEmitter<AgentRunsEvent> for AgentRuns {}
276impl EventEmitter<AgentRunsEvent> for AgentRuns {}
@@ -314,6 +330,8 @@ impl AgentRuns {
314 open_deferred: HashSet::new(),
330 open_deferred: HashSet::new(),
315 next_id,
331 next_id,
316 ticking: false,
332 ticking: false,
333 progress_saved_at: None,
334 progress_unsaved: false,
317 };
335 };
318 agent_runs.ensure_ticking(cx);
336 agent_runs.ensure_ticking(cx);
319 agent_runs.start_resumes(cx);
337 agent_runs.start_resumes(cx);
@@ -516,8 +534,21 @@ impl AgentRuns {
516 self.runs.iter_mut().find(|run| run.id == run_id)
534 self.runs.iter_mut().find(|run| run.id == run_id)
517 }
535 }
518
536
519 fn persist(&self, cx: &App) {
537 fn persist(&mut self, cx: &App) {
520 run_store::save_runs(&self.app.read(cx).store, &self.runs);
538 run_store::save_runs(&self.app.read(cx).store, &self.runs);
539 self.progress_saved_at = Some(Instant::now());
540 self.progress_unsaved = false;
541 }
542
543 fn persist_progress(&mut self, cx: &App) {
544 let due = self
545 .progress_saved_at
546 .is_none_or(|saved_at| saved_at.elapsed() >= PROGRESS_PERSIST_INTERVAL);
547 if !due {
548 self.progress_unsaved = true;
549 return;
550 }
551 self.persist(cx);
521 }
552 }
522
553
523 pub fn start(
554 pub fn start(
@@ -846,10 +877,16 @@ impl AgentRuns {
846 return;
877 return;
847 };
878 };
848 match event {
879 match event {
849 RunEvent::Step(text) => run.push_step(text),
880 RunEvent::Step(text) => {
881 run.push_step(text);
882 self.persist_progress(cx);
883 }
850 RunEvent::Text(text) => {
884 RunEvent::Text(text) => {
851 run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)
885 run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)
852 }
886 }
887 RunEvent::ApiRetry { message, retry_in } => {
888 run.current_step = api_retry_text(&message, retry_in)
889 }
853 RunEvent::SessionId(session_id) if session_id != run.session_id => {
890 RunEvent::SessionId(session_id) if session_id != run.session_id => {
854 let previous = std::mem::replace(&mut run.session_id, session_id.clone());
891 let previous = std::mem::replace(&mut run.session_id, session_id.clone());
855 self.move_lane(&previous, &session_id);
892 self.move_lane(&previous, &session_id);
@@ -968,6 +1005,9 @@ impl AgentRuns {
968 let keep_going = this
1005 let keep_going = this
969 .update(cx, |runs, cx| {
1006 .update(cx, |runs, cx| {
970 runs.ticking = runs.running_count() > 0;
1007 runs.ticking = runs.running_count() > 0;
1008 if runs.progress_unsaved {
1009 runs.persist_progress(cx);
1010 }
971 if runs.ticking {
1011 if runs.ticking {
972 cx.notify();
1012 cx.notify();
973 }
1013 }
@@ -1114,7 +1154,8 @@ pub(super) mod tests {
1114 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1154 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1115
1155
1116 use super::{
1156 use super::{
1117 AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, format_elapsed, run_store,
1157 AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, api_retry_text,
1158 format_elapsed, run_store,
1118 };
1159 };
1119 use crate::app_state::{AppState, Mode};
1160 use crate::app_state::{AppState, Mode};
1120
1161
@@ -1925,6 +1966,75 @@ pub(super) mod tests {
1925 assert_eq!(run.steps[1].1, "Resumed after restart");
1966 assert_eq!(run.steps[1].1, "Resumed after restart");
1926 }
1967 }
1927
1968
1969 #[gpui_kit::test]
1970 fn steps_survive_a_restart_while_the_run_is_running(cx: &mut TestAppContext) {
1971 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
1972 let reloaded_run = cx.update(|cx| {
1973 let mut settings = fake_settings(RESUMABLE_COMMAND);
1974 settings.resume_interrupted_runs = true;
1975 run_store::save_settings(&app.read(cx).store, &settings);
1976 let mut run = running_run(5);
1977 run.steps.clear();
1978 runs.update(cx, |runs, cx| {
1979 runs.runs.push(run);
1980 runs.apply_update(
1981 5,
1982 agents::RunUpdate::Event(agents::RunEvent::Step("Reading notes".to_owned())),
1983 cx,
1984 );
1985 });
1986 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
1987 reloaded.read(cx).get(5).unwrap().clone()
1988 });
1989 let step_texts: Vec<&str> = reloaded_run
1990 .steps
1991 .iter()
1992 .map(|(_, text)| text.as_str())
1993 .collect();
1994 assert_eq!(step_texts, ["Reading notes", "Resumed after restart"]);
1995 }
1996
1997 #[gpui_kit::test]
1998 fn an_api_retry_shows_as_the_current_step_and_a_text_replaces_it(cx: &mut TestAppContext) {
1999 let (_, runs) = setup(cx, RESUMABLE_COMMAND);
2000 cx.update(|cx| {
2001 runs.update(cx, |runs, cx| {
2002 runs.runs.push(running_run(5));
2003 runs.apply_update(
2004 5,
2005 agents::RunUpdate::Event(agents::RunEvent::ApiRetry {
2006 message: "No response from API".to_owned(),
2007 retry_in: Some(Duration::from_secs(599)),
2008 }),
2009 cx,
2010 );
2011 });
2012 let run = runs.read(cx).get(5).unwrap().clone();
2013 assert_eq!(run.current_step, "API not responding - retrying in 10 min");
2014 assert_eq!(run.state, RunState::Running);
2015 runs.update(cx, |runs, cx| {
2016 runs.apply_update(
2017 5,
2018 agents::RunUpdate::Event(agents::RunEvent::Text("Back again".to_owned())),
2019 cx,
2020 );
2021 });
2022 assert_eq!(runs.read(cx).get(5).unwrap().current_step, "Back again");
2023 });
2024 }
2025
2026 #[test]
2027 fn api_retry_text_formats_minutes_and_seconds() {
2028 assert_eq!(
2029 api_retry_text("x", Some(Duration::from_secs(45))),
2030 "API not responding - retrying in 45 s"
2031 );
2032 assert_eq!(
2033 api_retry_text("x", Some(Duration::from_secs(120))),
2034 "API not responding - retrying in 2 min"
2035 );
2036 }
2037
1928 fn reload_many(cx: &mut TestAppContext, run_count: u64) -> (Entity<AgentRuns>, Vec<u64>) {
2038 fn reload_many(cx: &mut TestAppContext, run_count: u64) -> (Entity<AgentRuns>, Vec<u64>) {
1929 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
2039 let (app, runs) = setup(cx, RESUMABLE_COMMAND);
1930 let ids: Vec<u64> = (1..=run_count).collect();
2040 let ids: Vec<u64> = (1..=run_count).collect();