feat(agents): resume interrupted runs after restart, align the run chip
- Runs still going when the app closed resume their own session on the next start (--resume, same chip and timer, step "Resumed after restart"); max 3 at once. - Old process is ended first: WSL pkill, host kill only when the process command line contains the session id (no PID-reuse kills). Stop works on queued resumes. - Setting "Resume interrupted runs" in Settings > Agents, default on; off = old Interrupted chip. - Running chip is as wide as its panel (310 px); step times sit in a 30 px right-aligned column. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -5,6 +5,8 @@ use crate::profile::{AgentProfile, Environment};
5
5
use crate::template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};
6
6
7
7
const WSL_PROGRAM: &str = "wsl.exe";
8
const SESSION_FLAG: &str = "--session-id {session_id}";
9
const RESUME_FLAG: &str = "--resume {session_id}";
8
10
const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;
9
11
10
12
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -36,6 +38,8 @@ pub enum InvocationError {
36
38
UnknownPlaceholder(#[from] UnknownPlaceholder),
37
39
#[error("cannot write the MCP config: {0}")]
38
40
McpConfig(String),
41
#[error("the agent command has no \"{SESSION_FLAG}\" to resume with")]
42
CannotResume,
39
43
}
40
44
41
45
fn expand_home(path: &str) -> String {
@@ -211,6 +215,75 @@ pub fn build_invocation(
211
215
}
212
216
}
213
217
218
fn is_plain_session_id(session_id: &str) -> bool {
219
!session_id.is_empty()
220
&& session_id
221
.chars()
222
.all(|character| character.is_ascii_alphanumeric() || character == '-')
223
}
224
225
pub fn kill_process_invocation(process_id: u32, session_id: &str) -> Option<Invocation> {
226
if !is_plain_session_id(session_id) {
227
return None;
228
}
229
if cfg!(windows) {
230
let script = format!(
231
"$p = Get-CimInstance Win32_Process -Filter 'ProcessId={process_id}'; if ($p -and $p.CommandLine -like '*{session_id}*') {{ taskkill /PID {process_id} /T /F }}"
232
);
233
return Some(Invocation {
234
program: "powershell".to_string(),
235
args: ["-NoProfile", "-Command", &script]
236
.map(String::from)
237
.to_vec(),
238
cwd: None,
239
stdin: None,
240
});
241
}
242
Some(Invocation {
243
program: "sh".to_string(),
244
args: [
245
"-c",
246
r#"grep -qaF -- "$2" "/proc/$1/cmdline" && kill -9 "$1""#,
247
"sh",
248
&process_id.to_string(),
249
session_id,
250
]
251
.map(String::from)
252
.to_vec(),
253
cwd: None,
254
stdin: None,
255
})
256
}
257
258
pub fn supports_resume(profile: &AgentProfile) -> bool {
259
profile.command.contains(SESSION_FLAG)
260
}
261
262
pub fn resume_invocation(
263
profile: &AgentProfile,
264
action: &AgentAction,
265
prompt: &str,
266
session_id: &str,
267
mcp: Option<&McpEndpoint>,
268
mcp_config_directory: Option<&Path>,
269
) -> Result<RunPlan, InvocationError> {
270
if !supports_resume(profile) {
271
return Err(InvocationError::CannotResume);
272
}
273
let resuming_profile = AgentProfile {
274
command: profile.command.replace(SESSION_FLAG, RESUME_FLAG),
275
..profile.clone()
276
};
277
build_invocation(
278
&resuming_profile,
279
action,
280
prompt,
281
session_id,
282
mcp,
283
mcp_config_directory,
284
)
285
}
286
214
287
pub fn open_session_invocation(
215
288
profile: &AgentProfile,
216
289
action: &AgentAction,
@@ -534,4 +607,162 @@ mod tests {
534
607
.map(String::from)
535
608
);
536
609
}
610
611
#[test]
612
fn resume_swaps_the_session_flag_and_keeps_the_extra_args() {
613
let mut profile = AgentProfile::claude_wsl();
614
profile.environment = Environment::Wsl {
615
distro: Some("Ubuntu".to_string()),
616
};
617
let action = AgentAction::answer_this("claude");
618
let plan = resume_invocation(&profile, &action, "go on", "sid-9", None, None).unwrap();
619
let expected_args: Vec<String> = [
620
"-d",
621
"Ubuntu",
622
"-e",
623
"sh",
624
"-lc",
625
WSL_SCRIPT,
626
"sh",
627
"~",
628
"claude",
629
"-p",
630
"--output-format",
631
"stream-json",
632
"--verbose",
633
"--resume",
634
"sid-9",
635
"--allowedTools",
636
"WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",
637
]
638
.map(String::from)
639
.to_vec();
640
assert_eq!(plan.run.args, expected_args);
641
assert_eq!(plan.run.stdin.as_deref(), Some("go on"));
642
assert_eq!(
643
plan.stop.unwrap().args,
644
["-d", "Ubuntu", "-e", "pkill", "-f", "sid-9"].map(String::from)
645
);
646
}
647
648
#[test]
649
fn resume_on_the_host_keeps_the_permission_mode() {
650
let action = AgentAction::build_this("claude-host");
651
let plan = resume_invocation(
652
&AgentProfile::claude_host(),
653
&action,
654
"go on",
655
"sid-8",
656
None,
657
None,
658
)
659
.unwrap();
660
assert_eq!(plan.run.program, "claude");
661
assert!(!plan.run.args.contains(&"--session-id".to_string()));
662
assert!(
663
plan.run
664
.args
665
.windows(2)
666
.any(|pair| pair == ["--resume", "sid-8"])
667
);
668
assert!(
669
plan.run
670
.args
671
.ends_with(&["--permission-mode".to_string(), "auto".to_string()])
672
);
673
assert_eq!(plan.stop, None);
674
}
675
676
#[test]
677
fn copilot_resumes_with_the_prompt_in_its_args() {
678
let action = AgentAction::answer_this("copilot");
679
let plan = resume_invocation(
680
&AgentProfile::copilot_wsl(),
681
&action,
682
"go on",
683
"sid-7",
684
None,
685
None,
686
)
687
.unwrap();
688
assert_eq!(plan.run.stdin, None);
689
assert!(
690
plan.run
691
.args
692
.windows(2)
693
.any(|pair| pair == ["--resume", "sid-7"])
694
);
695
assert!(plan.run.args.contains(&"go on".to_string()));
696
}
697
698
#[test]
699
fn kill_refuses_a_session_id_that_is_not_plain() {
700
assert_eq!(kill_process_invocation(1, ""), None);
701
assert_eq!(kill_process_invocation(1, "a'; rm -rf /; '"), None);
702
assert_eq!(kill_process_invocation(1, "a b"), None);
703
}
704
705
#[cfg(windows)]
706
#[test]
707
fn kill_checks_the_command_line_before_taskkill() {
708
let invocation = kill_process_invocation(4242, "abc-123").unwrap();
709
assert_eq!(invocation.program, "powershell");
710
assert_eq!(
711
invocation.args[..2],
712
["-NoProfile", "-Command"].map(String::from)
713
);
714
let script = &invocation.args[2];
715
assert!(script.contains("ProcessId=4242"));
716
assert!(script.contains("-like '*abc-123*'"));
717
assert!(script.contains("taskkill /PID 4242 /T /F"));
718
}
719
720
#[cfg(unix)]
721
mod unix_kill {
722
use super::super::*;
723
724
fn spawn_sleeper(label: &str) -> std::process::Child {
725
std::process::Command::new("sh")
726
.args(["-c", "sleep 30", label])
727
.spawn()
728
.unwrap()
729
}
730
731
fn run_kill(process_id: u32, session_id: &str) {
732
let invocation = kill_process_invocation(process_id, session_id).unwrap();
733
std::process::Command::new(invocation.program)
734
.args(invocation.args)
735
.status()
736
.unwrap();
737
}
738
739
#[test]
740
fn kills_a_process_whose_command_line_has_the_session_id() {
741
let mut child = spawn_sleeper("fake-session-1");
742
run_kill(child.id(), "fake-session-1");
743
let status = child.wait().unwrap();
744
assert!(!status.success());
745
}
746
747
#[test]
748
fn leaves_a_process_without_the_session_id_alone() {
749
let mut child = spawn_sleeper("other-session");
750
run_kill(child.id(), "fake-session-2");
751
assert!(child.try_wait().unwrap().is_none());
752
child.kill().unwrap();
753
child.wait().unwrap();
754
}
755
}
756
757
#[test]
758
fn a_command_without_the_session_flag_cannot_resume() {
759
let mut profile = AgentProfile::claude_host();
760
profile.command = "tool -p".to_string();
761
let action = AgentAction::build_this("claude-host");
762
assert!(!supports_resume(&profile));
763
assert_eq!(
764
resume_invocation(&profile, &action, "go on", "sid", None, None),
765
Err(InvocationError::CannotResume)
766
);
767
}
537
768
}
@@ -5,6 +5,8 @@ use crate::profile::{AgentProfile, Environment};5
use crate::template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};5
use crate::template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};6
6
7
const WSL_PROGRAM: &str = "wsl.exe";7
const WSL_PROGRAM: &str = "wsl.exe";8
const SESSION_FLAG: &str = "--session-id {session_id}";9
const RESUME_FLAG: &str = "--resume {session_id}";8
const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;10
const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;9
11
10
#[derive(Clone, Debug, PartialEq, Eq)]12
#[derive(Clone, Debug, PartialEq, Eq)]@@ -36,6 +38,8 @@ pub enum InvocationError {36
UnknownPlaceholder(#[from] UnknownPlaceholder),38
UnknownPlaceholder(#[from] UnknownPlaceholder),37
#[error("cannot write the MCP config: {0}")]39
#[error("cannot write the MCP config: {0}")]38
McpConfig(String),40
McpConfig(String),41
#[error("the agent command has no \"{SESSION_FLAG}\" to resume with")]42
CannotResume,39
}43
}40
44
41
fn expand_home(path: &str) -> String {45
fn expand_home(path: &str) -> String {@@ -211,6 +215,75 @@ pub fn build_invocation(211
}215
}212
}216
}213
217
218
fn is_plain_session_id(session_id: &str) -> bool {219
!session_id.is_empty()220
&& session_id221
.chars()222
.all(|character| character.is_ascii_alphanumeric() || character == '-')223
}224
225
pub fn kill_process_invocation(process_id: u32, session_id: &str) -> Option<Invocation> {226
if !is_plain_session_id(session_id) {227
return None;228
}229
if cfg!(windows) {230
let script = format!(231
"$p = Get-CimInstance Win32_Process -Filter 'ProcessId={process_id}'; if ($p -and $p.CommandLine -like '*{session_id}*') {{ taskkill /PID {process_id} /T /F }}"232
);233
return Some(Invocation {234
program: "powershell".to_string(),235
args: ["-NoProfile", "-Command", &script]236
.map(String::from)237
.to_vec(),238
cwd: None,239
stdin: None,240
});241
}242
Some(Invocation {243
program: "sh".to_string(),244
args: [245
"-c",246
r#"grep -qaF -- "$2" "/proc/$1/cmdline" && kill -9 "$1""#,247
"sh",248
&process_id.to_string(),249
session_id,250
]251
.map(String::from)252
.to_vec(),253
cwd: None,254
stdin: None,255
})256
}257
258
pub fn supports_resume(profile: &AgentProfile) -> bool {259
profile.command.contains(SESSION_FLAG)260
}261
262
pub fn resume_invocation(263
profile: &AgentProfile,264
action: &AgentAction,265
prompt: &str,266
session_id: &str,267
mcp: Option<&McpEndpoint>,268
mcp_config_directory: Option<&Path>,269
) -> Result<RunPlan, InvocationError> {270
if !supports_resume(profile) {271
return Err(InvocationError::CannotResume);272
}273
let resuming_profile = AgentProfile {274
command: profile.command.replace(SESSION_FLAG, RESUME_FLAG),275
..profile.clone()276
};277
build_invocation(278
&resuming_profile,279
action,280
prompt,281
session_id,282
mcp,283
mcp_config_directory,284
)285
}286
214
pub fn open_session_invocation(287
pub fn open_session_invocation(215
profile: &AgentProfile,288
profile: &AgentProfile,216
action: &AgentAction,289
action: &AgentAction,@@ -534,4 +607,162 @@ mod tests {534
.map(String::from)607
.map(String::from)535
);608
);536
}609
}610
611
#[test]612
fn resume_swaps_the_session_flag_and_keeps_the_extra_args() {613
let mut profile = AgentProfile::claude_wsl();614
profile.environment = Environment::Wsl {615
distro: Some("Ubuntu".to_string()),616
};617
let action = AgentAction::answer_this("claude");618
let plan = resume_invocation(&profile, &action, "go on", "sid-9", None, None).unwrap();619
let expected_args: Vec<String> = [620
"-d",621
"Ubuntu",622
"-e",623
"sh",624
"-lc",625
WSL_SCRIPT,626
"sh",627
"~",628
"claude",629
"-p",630
"--output-format",631
"stream-json",632
"--verbose",633
"--resume",634
"sid-9",635
"--allowedTools",636
"WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",637
]638
.map(String::from)639
.to_vec();640
assert_eq!(plan.run.args, expected_args);641
assert_eq!(plan.run.stdin.as_deref(), Some("go on"));642
assert_eq!(643
plan.stop.unwrap().args,644
["-d", "Ubuntu", "-e", "pkill", "-f", "sid-9"].map(String::from)645
);646
}647
648
#[test]649
fn resume_on_the_host_keeps_the_permission_mode() {650
let action = AgentAction::build_this("claude-host");651
let plan = resume_invocation(652
&AgentProfile::claude_host(),653
&action,654
"go on",655
"sid-8",656
None,657
None,658
)659
.unwrap();660
assert_eq!(plan.run.program, "claude");661
assert!(!plan.run.args.contains(&"--session-id".to_string()));662
assert!(663
plan.run664
.args665
.windows(2)666
.any(|pair| pair == ["--resume", "sid-8"])667
);668
assert!(669
plan.run670
.args671
.ends_with(&["--permission-mode".to_string(), "auto".to_string()])672
);673
assert_eq!(plan.stop, None);674
}675
676
#[test]677
fn copilot_resumes_with_the_prompt_in_its_args() {678
let action = AgentAction::answer_this("copilot");679
let plan = resume_invocation(680
&AgentProfile::copilot_wsl(),681
&action,682
"go on",683
"sid-7",684
None,685
None,686
)687
.unwrap();688
assert_eq!(plan.run.stdin, None);689
assert!(690
plan.run691
.args692
.windows(2)693
.any(|pair| pair == ["--resume", "sid-7"])694
);695
assert!(plan.run.args.contains(&"go on".to_string()));696
}697
698
#[test]699
fn kill_refuses_a_session_id_that_is_not_plain() {700
assert_eq!(kill_process_invocation(1, ""), None);701
assert_eq!(kill_process_invocation(1, "a'; rm -rf /; '"), None);702
assert_eq!(kill_process_invocation(1, "a b"), None);703
}704
705
#[cfg(windows)]706
#[test]707
fn kill_checks_the_command_line_before_taskkill() {708
let invocation = kill_process_invocation(4242, "abc-123").unwrap();709
assert_eq!(invocation.program, "powershell");710
assert_eq!(711
invocation.args[..2],712
["-NoProfile", "-Command"].map(String::from)713
);714
let script = &invocation.args[2];715
assert!(script.contains("ProcessId=4242"));716
assert!(script.contains("-like '*abc-123*'"));717
assert!(script.contains("taskkill /PID 4242 /T /F"));718
}719
720
#[cfg(unix)]721
mod unix_kill {722
use super::super::*;723
724
fn spawn_sleeper(label: &str) -> std::process::Child {725
std::process::Command::new("sh")726
.args(["-c", "sleep 30", label])727
.spawn()728
.unwrap()729
}730
731
fn run_kill(process_id: u32, session_id: &str) {732
let invocation = kill_process_invocation(process_id, session_id).unwrap();733
std::process::Command::new(invocation.program)734
.args(invocation.args)735
.status()736
.unwrap();737
}738
739
#[test]740
fn kills_a_process_whose_command_line_has_the_session_id() {741
let mut child = spawn_sleeper("fake-session-1");742
run_kill(child.id(), "fake-session-1");743
let status = child.wait().unwrap();744
assert!(!status.success());745
}746
747
#[test]748
fn leaves_a_process_without_the_session_id_alone() {749
let mut child = spawn_sleeper("other-session");750
run_kill(child.id(), "fake-session-2");751
assert!(child.try_wait().unwrap().is_none());752
child.kill().unwrap();753
child.wait().unwrap();754
}755
}756
757
#[test]758
fn a_command_without_the_session_flag_cannot_resume() {759
let mut profile = AgentProfile::claude_host();760
profile.command = "tool -p".to_string();761
let action = AgentAction::build_this("claude-host");762
assert!(!supports_resume(&profile));763
assert_eq!(764
resume_invocation(&profile, &action, "go on", "sid", None, None),765
Err(InvocationError::CannotResume)766
);767
}537
}768
}@@ -10,12 +10,13 @@ mod template;
10
10
pub use action::AgentAction;
11
11
pub use context::{MessageContext, ThreadMessage, build_prompt};
12
12
pub use invocation::{
13
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, open_session_invocation,
14
version_check_invocation, wsl_path,
13
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, kill_process_invocation,
14
open_session_invocation, resume_invocation, supports_resume, version_check_invocation,
15
wsl_path,
15
16
};
16
17
pub use parse::{OutputParser, RunEvent, parse_line};
17
18
pub use profile::{AgentProfile, Environment, OutputFormat};
18
pub use runner::{RunOutcome, RunStatus, RunUpdate, probe, run};
19
pub use runner::{RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation};
19
20
pub use settings::{AgentSettings, SETTINGS_KEY, SettingsProblem};
20
21
pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};
21
22
@@ -10,12 +10,13 @@ mod template;10
pub use action::AgentAction;10
pub use action::AgentAction;11
pub use context::{MessageContext, ThreadMessage, build_prompt};11
pub use context::{MessageContext, ThreadMessage, build_prompt};12
pub use invocation::{12
pub use invocation::{13
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, open_session_invocation,13
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, kill_process_invocation,14
version_check_invocation, wsl_path,14
open_session_invocation, resume_invocation, supports_resume, version_check_invocation,15
wsl_path,15
};16
};16
pub use parse::{OutputParser, RunEvent, parse_line};17
pub use parse::{OutputParser, RunEvent, parse_line};17
pub use profile::{AgentProfile, Environment, OutputFormat};18
pub use profile::{AgentProfile, Environment, OutputFormat};18
pub use runner::{RunOutcome, RunStatus, RunUpdate, probe, run};19
pub use runner::{RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation};19
pub use settings::{AgentSettings, SETTINGS_KEY, SettingsProblem};20
pub use settings::{AgentSettings, SETTINGS_KEY, SettingsProblem};20
pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};21
pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};21
22
@@ -17,6 +17,7 @@ const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
17
17
pub enum RunUpdate {
18
18
Event(RunEvent),
19
19
Stderr(String),
20
Started(u32),
20
21
}
21
22
22
23
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -59,7 +60,7 @@ fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) ->
59
60
}
60
61
}
61
62
62
async fn run_stop_invocation(invocation: &Invocation) {
63
pub async fn run_stop_invocation(invocation: &Invocation) {
63
64
let mut command = command_for(invocation);
64
65
command
65
66
.stdin(Stdio::null())
@@ -111,6 +112,9 @@ async fn run_plan(
111
112
);
112
113
}
113
114
};
115
if let Some(process_id) = child.id() {
116
let _ = events.send(RunUpdate::Started(process_id));
117
}
114
118
let (Some(stdin), Some(stdout), Some(stderr)) =
115
119
(child.stdin.take(), child.stdout.take(), child.stderr.take())
116
120
else {
@@ -17,6 +17,7 @@ const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);17
pub enum RunUpdate {17
pub enum RunUpdate {18
Event(RunEvent),18
Event(RunEvent),19
Stderr(String),19
Stderr(String),20
Started(u32),20
}21
}21
22
22
#[derive(Clone, Debug, PartialEq, Eq)]23
#[derive(Clone, Debug, PartialEq, Eq)]@@ -59,7 +60,7 @@ fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) ->59
}60
}60
}61
}61
62
62
async fn run_stop_invocation(invocation: &Invocation) {63
pub async fn run_stop_invocation(invocation: &Invocation) {63
let mut command = command_for(invocation);64
let mut command = command_for(invocation);64
command65
command65
.stdin(Stdio::null())66
.stdin(Stdio::null())@@ -111,6 +112,9 @@ async fn run_plan(111
);112
);112
}113
}113
};114
};115
if let Some(process_id) = child.id() {116
let _ = events.send(RunUpdate::Started(process_id));117
}114
let (Some(stdin), Some(stdout), Some(stderr)) =118
let (Some(stdin), Some(stdout), Some(stderr)) =115
(child.stdin.take(), child.stdout.take(), child.stderr.take())119
(child.stdin.take(), child.stdout.take(), child.stderr.take())116
else {120
else {@@ -24,6 +24,7 @@ pub enum SettingsProblem {
24
24
pub struct AgentSettings {
25
25
pub agents: Vec<AgentProfile>,
26
26
pub actions: Vec<AgentAction>,
27
pub resume_interrupted_runs: bool,
27
28
}
28
29
29
30
impl Default for AgentSettings {
@@ -34,6 +35,7 @@ impl Default for AgentSettings {
34
35
AgentAction::answer_this("claude"),
35
36
AgentAction::build_this("claude"),
36
37
],
38
resume_interrupted_runs: true,
37
39
}
38
40
}
39
41
}
@@ -137,6 +139,17 @@ mod tests {
137
139
);
138
140
}
139
141
142
#[test]
143
fn resume_defaults_on_and_can_be_switched_off() {
144
assert!(
145
AgentSettings::from_json("{}")
146
.unwrap()
147
.resume_interrupted_runs
148
);
149
let off = AgentSettings::from_json(r#"{"resume_interrupted_runs":false}"#).unwrap();
150
assert!(!off.resume_interrupted_runs);
151
}
152
140
153
#[test]
141
154
fn partial_json_fills_missing_fields() {
142
155
let loaded = AgentSettings::from_json(
@@ -24,6 +24,7 @@ pub enum SettingsProblem {24
pub struct AgentSettings {24
pub struct AgentSettings {25
pub agents: Vec<AgentProfile>,25
pub agents: Vec<AgentProfile>,26
pub actions: Vec<AgentAction>,26
pub actions: Vec<AgentAction>,27
pub resume_interrupted_runs: bool,27
}28
}28
29
29
impl Default for AgentSettings {30
impl Default for AgentSettings {@@ -34,6 +35,7 @@ impl Default for AgentSettings {34
AgentAction::answer_this("claude"),35
AgentAction::answer_this("claude"),35
AgentAction::build_this("claude"),36
AgentAction::build_this("claude"),36
],37
],38
resume_interrupted_runs: true,37
}39
}38
}40
}39
}41
}@@ -137,6 +139,17 @@ mod tests {137
);139
);138
}140
}139
141
142
#[test]143
fn resume_defaults_on_and_can_be_switched_off() {144
assert!(145
AgentSettings::from_json("{}")146
.unwrap()147
.resume_interrupted_runs148
);149
let off = AgentSettings::from_json(r#"{"resume_interrupted_runs":false}"#).unwrap();150
assert!(!off.resume_interrupted_runs);151
}152
140
#[test]153
#[test]141
fn partial_json_fills_missing_fields() {154
fn partial_json_fills_missing_fields() {142
let loaded = AgentSettings::from_json(155
let loaded = AgentSettings::from_json(@@ -71,10 +71,8 @@ async fn failing_command_reports_stderr() {
71
71
}
72
72
other => panic!("unexpected status {other:?}"),
73
73
}
74
assert_eq!(
75
receiver.try_recv().ok(),
76
Some(RunUpdate::Stderr("boom".to_string()))
77
);
74
let updates: Vec<RunUpdate> = std::iter::from_fn(|| receiver.try_recv().ok()).collect();
75
assert!(updates.contains(&RunUpdate::Stderr("boom".to_string())));
78
76
}
79
77
80
78
#[tokio::test]
@@ -71,10 +71,8 @@ async fn failing_command_reports_stderr() {71
}71
}72
other => panic!("unexpected status {other:?}"),72
other => panic!("unexpected status {other:?}"),73
}73
}74
assert_eq!(74
let updates: Vec<RunUpdate> = std::iter::from_fn(|| receiver.try_recv().ok()).collect();75
receiver.try_recv().ok(),75
assert!(updates.contains(&RunUpdate::Stderr("boom".to_string())));76
Some(RunUpdate::Stderr("boom".to_string()))77
);78
}76
}79
77
80
#[tokio::test]78
#[tokio::test]@@ -51,6 +51,7 @@ fn run_for(
51
51
ended_at: finished.then(|| started_at + ChronoDuration::seconds(elapsed_seconds)),
52
52
expanded: false,
53
53
dismissed: false,
54
process_id: None,
54
55
}
55
56
}
56
57
@@ -51,6 +51,7 @@ fn run_for(51
ended_at: finished.then(|| started_at + ChronoDuration::seconds(elapsed_seconds)),51
ended_at: finished.then(|| started_at + ChronoDuration::seconds(elapsed_seconds)),52
expanded: false,52
expanded: false,53
dismissed: false,53
dismissed: false,54
process_id: None,54
}55
}55
}56
}56
57
@@ -1,3 +1,5 @@
1
use std::sync::Arc;
2
1
3
use gpui_kit::assets::IconName;
2
4
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
3
5
use gpui_kit::prelude::FluentBuilder as _;
@@ -13,6 +15,7 @@ const CHIP_HEIGHT: f32 = 28.;
13
15
const CHIP_MAX_WIDTH: f32 = 310.;
14
16
const BUTTON_HEIGHT: f32 = 22.;
15
17
const STATUS_ICON: f32 = 12.;
18
const STEP_TIME_WIDTH: f32 = 30.;
16
19
17
20
fn with_runs(cx: &mut App, change: impl FnOnce(&mut AgentRuns, &mut Context<AgentRuns>)) {
18
21
cx.global::<AgentRunsHandle>().0.clone().update(cx, change);
@@ -101,9 +104,10 @@ fn chip_row(run: &AgentRun, fill: Hsla) -> Stateful<Div> {
101
104
let action_label = run.action_label.clone();
102
105
match &run.state {
103
106
RunState::Running => row
107
.w(px(CHIP_MAX_WIDTH))
104
108
.child(spinner(STATUS_ICON))
105
109
.child(label(action_label, theme::text_soft()))
106
.child(step_text(run.current_step.clone()))
110
.child(step_text(run.current_step.clone()).flex_1())
107
111
.child(elapsed_text(run))
108
112
.child(
109
113
div()
@@ -191,7 +195,10 @@ fn step_row(elapsed: String, text: String, current: bool) -> Div {
191
195
})
192
196
.child(
193
197
div()
198
.w(px(STEP_TIME_WIDTH))
194
199
.flex_none()
200
.text_right()
201
.font_features(FontFeatures(Arc::new(vec![("tnum".to_owned(), 1)])))
195
202
.text_color(theme::text_faint())
196
203
.child(elapsed),
197
204
)
@@ -1,3 +1,5 @@1
use std::sync::Arc;2
1
use gpui_kit::assets::IconName;3
use gpui_kit::assets::IconName;2
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};4
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};3
use gpui_kit::prelude::FluentBuilder as _;5
use gpui_kit::prelude::FluentBuilder as _;@@ -13,6 +15,7 @@ const CHIP_HEIGHT: f32 = 28.;13
const CHIP_MAX_WIDTH: f32 = 310.;15
const CHIP_MAX_WIDTH: f32 = 310.;14
const BUTTON_HEIGHT: f32 = 22.;16
const BUTTON_HEIGHT: f32 = 22.;15
const STATUS_ICON: f32 = 12.;17
const STATUS_ICON: f32 = 12.;18
const STEP_TIME_WIDTH: f32 = 30.;16
19
17
fn with_runs(cx: &mut App, change: impl FnOnce(&mut AgentRuns, &mut Context<AgentRuns>)) {20
fn with_runs(cx: &mut App, change: impl FnOnce(&mut AgentRuns, &mut Context<AgentRuns>)) {18
cx.global::<AgentRunsHandle>().0.clone().update(cx, change);21
cx.global::<AgentRunsHandle>().0.clone().update(cx, change);@@ -101,9 +104,10 @@ fn chip_row(run: &AgentRun, fill: Hsla) -> Stateful<Div> {101
let action_label = run.action_label.clone();104
let action_label = run.action_label.clone();102
match &run.state {105
match &run.state {103
RunState::Running => row106
RunState::Running => row107
.w(px(CHIP_MAX_WIDTH))104
.child(spinner(STATUS_ICON))108
.child(spinner(STATUS_ICON))105
.child(label(action_label, theme::text_soft()))109
.child(label(action_label, theme::text_soft()))106
.child(step_text(run.current_step.clone()))110
.child(step_text(run.current_step.clone()).flex_1())107
.child(elapsed_text(run))111
.child(elapsed_text(run))108
.child(112
.child(109
div()113
div()@@ -191,7 +195,10 @@ fn step_row(elapsed: String, text: String, current: bool) -> Div {191
})195
})192
.child(196
.child(193
div()197
div()198
.w(px(STEP_TIME_WIDTH))194
.flex_none()199
.flex_none()200
.text_right()201
.font_features(FontFeatures(Arc::new(vec![("tnum".to_owned(), 1)])))195
.text_color(theme::text_faint())202
.text_color(theme::text_faint())196
.child(elapsed),203
.child(elapsed),197
)204
)@@ -1,15 +1,15 @@
1
use std::collections::{HashMap, HashSet};
1
use std::collections::{HashMap, HashSet, VecDeque};
2
2
use std::time::Duration;
3
3
4
use agents::{AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate};
4
use agents::{AgentAction, AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate};
5
5
use chrono::{DateTime, Utc};
6
6
use gpui_kit::*;
7
7
use serde::{Deserialize, Serialize};
8
8
use tokio::sync::{mpsc, oneshot};
9
9
10
10
use super::{
11
StartRequest, demo, mcp_bridge, mcp_config_directory, message_context, open_run_session,
12
store as run_store,
11
MCP_POLL_INTERVAL, MCP_WAIT_LIMIT, StartRequest, demo, mcp_bridge, mcp_config_directory,
12
message_context, open_run_session, store as run_store,
13
13
};
14
14
use crate::app_state::AppState;
15
15
use crate::notice::truncated;
@@ -21,6 +21,9 @@ const VISIBLE_LOG_LINES: usize = 20;
21
21
const TEXT_STEP_CHARS: usize = 80;
22
22
const DONE_STEP_CHARS: usize = 60;
23
23
const TICK: Duration = Duration::from_secs(1);
24
const RESUME_PARALLEL_LIMIT: usize = 3;
25
const RESUMED_STEP: &str = "Resumed after restart";
26
const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";
24
27
25
28
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26
29
pub enum RunState {
@@ -53,6 +56,8 @@ pub struct AgentRun {
53
56
#[serde(skip)]
54
57
pub expanded: bool,
55
58
pub dismissed: bool,
59
#[serde(default)]
60
pub process_id: Option<u32>,
56
61
}
57
62
58
63
impl AgentRun {
@@ -117,6 +122,23 @@ impl AgentRun {
117
122
}
118
123
}
119
124
125
fn orphan_stop(run: &AgentRun, plan: &agents::RunPlan) -> Option<agents::Invocation> {
126
plan.stop.clone().or_else(|| {
127
run.process_id
128
.and_then(|process_id| agents::kill_process_invocation(process_id, &run.session_id))
129
})
130
}
131
132
fn can_resume(settings: &AgentSettings, run: &AgentRun) -> bool {
133
settings.resume_interrupted_runs
134
&& !run.session_id.is_empty()
135
&& settings
136
.agents
137
.iter()
138
.find(|agent| agent.id == run.agent_id)
139
.is_some_and(agents::supports_resume)
140
}
141
120
142
fn remove_stale_mcp_configs() {
121
143
let Some(directory) = mcp_config_directory() else {
122
144
return;
@@ -156,6 +178,9 @@ pub struct AgentRuns {
156
178
settings: AgentSettings,
157
179
runs: Vec<AgentRun>,
158
180
stops: HashMap<u64, oneshot::Sender<()>>,
181
resume_queue: VecDeque<u64>,
182
resuming: HashSet<u64>,
183
stopping: HashSet<u64>,
159
184
open_after_stop: HashSet<u64>,
160
185
next_id: u64,
161
186
ticking: bool,
@@ -166,10 +191,17 @@ impl EventEmitter<AgentRunsEvent> for AgentRuns {}
166
191
impl AgentRuns {
167
192
pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
168
193
let store = app.read(cx).store.clone();
194
let settings = run_store::load_settings(&store);
169
195
let mut runs = run_store::load_runs(&store);
170
196
let interrupted = runs.iter().any(AgentRun::is_running);
197
let mut resume_queue = VecDeque::new();
171
198
for run in runs.iter_mut().filter(|run| run.is_running()) {
172
run.mark_interrupted();
199
if can_resume(&settings, run) {
200
run.push_step(RESUMED_STEP.to_owned());
201
resume_queue.push_back(run.id);
202
} else {
203
run.mark_interrupted();
204
}
173
205
}
174
206
if interrupted {
175
207
run_store::save_runs(&store, &runs);
@@ -181,17 +213,135 @@ impl AgentRuns {
181
213
let next_id = runs.iter().map(|run| run.id).max().map_or(1, |id| id + 1);
182
214
let mut agent_runs = AgentRuns {
183
215
app,
184
settings: run_store::load_settings(&store),
216
settings,
185
217
runs,
186
218
stops: HashMap::new(),
219
resume_queue,
220
resuming: HashSet::new(),
221
stopping: HashSet::new(),
187
222
open_after_stop: HashSet::new(),
188
223
next_id,
189
224
ticking: false,
190
225
};
191
226
agent_runs.ensure_ticking(cx);
227
agent_runs.start_resumes(cx);
192
228
agent_runs
193
229
}
194
230
231
fn start_resumes(&mut self, cx: &mut Context<Self>) {
232
if self.resume_queue.is_empty() {
233
return;
234
}
235
let needs_mcp = self.resume_queue.iter().any(|run_id| {
236
self.get(*run_id)
237
.and_then(|run| {
238
self.settings
239
.agents
240
.iter()
241
.find(|agent| agent.id == run.agent_id)
242
})
243
.is_some_and(|agent| !agent.mcp_config_flag.is_empty())
244
});
245
cx.spawn(async move |this, cx| {
246
let mut waited = Duration::ZERO;
247
while needs_mcp
248
&& waited < MCP_WAIT_LIMIT
249
&& !cx.update(|cx| mcp_bridge::endpoint(cx).is_some())
250
{
251
cx.background_executor().timer(MCP_POLL_INTERVAL).await;
252
waited += MCP_POLL_INTERVAL;
253
}
254
this.update(cx, |runs, cx| runs.resume_next(cx)).ok();
255
})
256
.detach();
257
}
258
259
fn resume_next(&mut self, cx: &mut Context<Self>) {
260
while self.resuming.len() < RESUME_PARALLEL_LIMIT {
261
let Some(run_id) = self.resume_queue.pop_front() else {
262
return;
263
};
264
self.begin_resume(run_id, cx);
265
}
266
}
267
268
fn resume_plan(
269
&self,
270
run: &AgentRun,
271
cx: &App,
272
) -> Result<(agents::RunPlan, agents::OutputFormat), String> {
273
let action = self
274
.settings
275
.actions
276
.iter()
277
.find(|action| action.id == run.action_id)
278
.cloned()
279
.ok_or("the action no longer exists")?;
280
let profile = self
281
.settings
282
.agents
283
.iter()
284
.find(|profile| profile.id == run.agent_id)
285
.ok_or("the agent no longer exists")?;
286
let action = AgentAction {
287
working_dir: run.working_dir.clone(),
288
..action
289
};
290
let plan = agents::resume_invocation(
291
profile,
292
&action,
293
RESUME_PROMPT,
294
&run.session_id,
295
mcp_bridge::endpoint(cx).as_ref(),
296
mcp_config_directory().as_deref(),
297
)
298
.map_err(|error| error.to_string())?;
299
Ok((plan, profile.output))
300
}
301
302
fn begin_resume(&mut self, run_id: u64, cx: &mut Context<Self>) {
303
let Some(run) = self.get(run_id).filter(|run| run.is_running()).cloned() else {
304
return;
305
};
306
self.resuming.insert(run_id);
307
match self.resume_plan(&run, cx) {
308
Ok((plan, format)) => {
309
let stop = orphan_stop(&run, &plan);
310
cx.spawn(async move |this, cx| {
311
if let Some(stop) = stop {
312
let _ =
313
runtime::spawn(async move { agents::run_stop_invocation(&stop).await })
314
.await;
315
}
316
this.update(cx, |runs, cx| {
317
let still_resuming = runs.resuming.contains(&run_id)
318
&& runs.get(run_id).is_some_and(AgentRun::is_running);
319
if still_resuming {
320
runs.spawn(run_id, plan, format, cx);
321
} else {
322
for path in &plan.cleanup {
323
let _ = std::fs::remove_file(path);
324
}
325
}
326
})
327
.ok();
328
})
329
.detach();
330
}
331
Err(reason) => self.finish(
332
run_id,
333
Some(RunOutcome {
334
status: RunStatus::Failed {
335
message: format!("Could not resume - {reason}"),
336
stderr_tail: Vec::new(),
337
},
338
exit_code: None,
339
}),
340
cx,
341
),
342
}
343
}
344
195
345
pub fn settings(&self) -> &AgentSettings {
196
346
&self.settings
197
347
}
@@ -305,6 +455,7 @@ impl AgentRuns {
305
455
ended_at: None,
306
456
expanded: false,
307
457
dismissed: false,
458
process_id: None,
308
459
});
309
460
if endpoint.is_none()
310
461
&& let Some(run) = self.run_mut(run_id)
@@ -359,8 +510,16 @@ impl AgentRuns {
359
510
}
360
511
361
512
fn apply_update(&mut self, run_id: u64, update: RunUpdate, cx: &mut Context<Self>) {
362
let RunUpdate::Event(event) = update else {
363
return;
513
let event = match update {
514
RunUpdate::Event(event) => event,
515
RunUpdate::Started(process_id) => {
516
if let Some(run) = self.run_mut(run_id) {
517
run.process_id = Some(process_id);
518
self.persist(cx);
519
}
520
return;
521
}
522
RunUpdate::Stderr(_) => return,
364
523
};
365
524
let Some(run) = self.run_mut(run_id) else {
366
525
return;
@@ -377,10 +536,13 @@ impl AgentRuns {
377
536
378
537
fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {
379
538
self.stops.remove(&run_id);
539
self.stopping.remove(&run_id);
540
let was_resuming = self.resuming.remove(&run_id);
380
541
let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) else {
381
542
return;
382
543
};
383
544
run.ended_at = Some(Utc::now());
545
run.process_id = None;
384
546
match outcome.map(|outcome| outcome.status) {
385
547
Some(RunStatus::Completed { final_text }) => {
386
548
let line = truncated(first_line(&final_text), DONE_STEP_CHARS);
@@ -396,6 +558,11 @@ impl AgentRuns {
396
558
message,
397
559
stderr_tail,
398
560
}) => {
561
let message = if was_resuming && message.starts_with("cannot start") {
562
format!("Could not resume - {message}")
563
} else {
564
message
565
};
399
566
run.current_step = message.clone();
400
567
run.state = RunState::Failed {
401
568
message,
@@ -426,6 +593,9 @@ impl AgentRuns {
426
593
if self.open_after_stop.remove(&run_id) && stopped {
427
594
open_run_session(&snapshot, cx);
428
595
}
596
if was_resuming {
597
self.resume_next(cx);
598
}
429
599
cx.notify();
430
600
}
431
601
@@ -467,12 +637,46 @@ impl AgentRuns {
467
637
}
468
638
469
639
pub fn stop(&mut self, run_id: u64, cx: &mut Context<Self>) {
640
if self.stopping.contains(&run_id) {
641
return;
642
}
470
643
if let Some(stop) = self.stops.remove(&run_id) {
644
self.stopping.insert(run_id);
471
645
let _ = stop.send(());
472
646
if let Some(run) = self.run_mut(run_id) {
473
647
run.current_step = "Stopping".to_owned();
474
648
}
475
649
cx.notify();
650
} else if self.resuming.contains(&run_id) || self.resume_queue.contains(&run_id) {
651
if self.resume_queue.contains(&run_id) {
652
self.stop_orphan(run_id, cx);
653
}
654
self.resume_queue.retain(|queued| *queued != run_id);
655
self.finish(
656
run_id,
657
Some(RunOutcome {
658
status: RunStatus::Stopped,
659
exit_code: None,
660
}),
661
cx,
662
);
663
}
664
}
665
666
fn stop_orphan(&self, run_id: u64, cx: &App) {
667
let Some(run) = self.get(run_id) else {
668
return;
669
};
670
let Ok((plan, _)) = self.resume_plan(run, cx) else {
671
return;
672
};
673
for path in &plan.cleanup {
674
let _ = std::fs::remove_file(path);
675
}
676
if let Some(stop) = orphan_stop(run, &plan) {
677
drop(runtime::spawn(async move {
678
agents::run_stop_invocation(&stop).await
679
}));
476
680
}
477
681
}
478
682
@@ -550,6 +754,7 @@ pub(super) mod tests {
550
754
ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),
551
755
expanded: false,
552
756
dismissed: false,
757
process_id: None,
553
758
}
554
759
}
555
760
@@ -575,6 +780,7 @@ pub(super) mod tests {
575
780
AgentSettings {
576
781
agents: vec![profile],
577
782
actions: vec![action],
783
resume_interrupted_runs: true,
578
784
}
579
785
}
580
786
@@ -621,7 +827,9 @@ pub(super) mod tests {
621
827
622
828
#[cfg(unix)]
623
829
mod shell_runs {
624
use super::{RunState, TestAppContext, run_store, setup, wait_until_finished};
830
use gpui_kit::AppContext as _;
831
832
use super::{AgentRuns, RunState, TestAppContext, run_store, setup, wait_until_finished};
625
833
626
834
#[gpui_kit::test]
627
835
fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {
@@ -658,6 +866,34 @@ pub(super) mod tests {
658
866
});
659
867
}
660
868
869
#[gpui_kit::test]
870
fn a_resumed_run_continues_and_finishes_done(cx: &mut TestAppContext) {
871
let fixture = concat!(
872
env!("CARGO_MANIFEST_DIR"),
873
"/../agents/tests/fixtures/claude-stream.jsonl"
874
);
875
let command = format!("sh -c 'cat {fixture}' --session-id {{session_id}}");
876
let (app, runs) = setup(cx, &command);
877
cx.update(|cx| {
878
runs.update(cx, |runs, cx| {
879
runs.runs.push(super::running_run(5));
880
runs.persist(cx);
881
});
882
});
883
let reloaded = cx.update(|cx| cx.new(|cx| AgentRuns::new(app.clone(), cx)));
884
wait_until_finished(cx, &reloaded, 5);
885
cx.update(|cx| {
886
let run = reloaded.read(cx).get(5).unwrap().clone();
887
assert_eq!(run.state, RunState::Done);
888
assert_eq!(run.session_id, "session-5");
889
assert!(
890
run.steps
891
.iter()
892
.any(|(_, text)| text == "Resumed after restart")
893
);
894
});
895
}
896
661
897
#[gpui_kit::test]
662
898
fn a_failing_command_ends_failed_with_its_stderr(cx: &mut TestAppContext) {
663
899
let (app, runs) = setup(cx, "sh -c 'echo boom >&2; exit 3'");
@@ -715,27 +951,163 @@ pub(super) mod tests {
715
951
});
716
952
}
717
953
718
#[gpui_kit::test]
719
fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) {
720
let (app, runs) = setup(cx, "true");
954
const RESUMABLE_COMMAND: &str = "sh -c 'sleep 30' --session-id {session_id}";
955
const INTERRUPTED: &str = "Interrupted - the app was closed during the run";
956
957
fn running_run(id: u64) -> AgentRun {
958
let mut running = finished_run(id);
959
running.action_id = "ask".to_owned();
960
running.agent_id = "fake".to_owned();
961
running.state = RunState::Running;
962
running.ended_at = None;
963
running
964
}
965
966
fn reload_with(
967
cx: &mut TestAppContext,
968
command: &str,
969
run: AgentRun,
970
change_settings: impl FnOnce(&mut AgentSettings),
971
) -> AgentRun {
972
let (app, runs) = setup(cx, command);
721
973
cx.update(|cx| {
722
let mut running = finished_run(5);
723
running.state = RunState::Running;
724
running.ended_at = None;
974
let mut settings = fake_settings(command);
975
change_settings(&mut settings);
976
run_store::save_settings(&app.read(cx).store, &settings);
977
let run_id = run.id;
725
978
runs.update(cx, |runs, cx| {
726
runs.runs.push(running);
979
runs.runs.push(run);
727
980
runs.persist(cx);
728
981
});
729
982
let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
730
let run = reloaded.read(cx).get(5).unwrap().clone();
731
assert!(matches!(
732
run.state,
733
RunState::Failed { ref message, .. } if message == "Interrupted - the app was closed during the run"
734
));
735
assert!(run.ended_at.is_some());
736
assert_eq!(run.session_id, "session-5");
737
assert_eq!(reloaded.read(cx).running_count(), 0);
983
reloaded.read(cx).get(run_id).unwrap().clone()
984
})
985
}
986
987
fn assert_interrupted(run: &AgentRun) {
988
assert!(matches!(
989
run.state,
990
RunState::Failed { ref message, .. } if message == INTERRUPTED
991
));
992
assert!(run.ended_at.is_some());
993
}
994
995
#[gpui_kit::test]
996
fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) {
997
let run = reload_with(cx, "true", running_run(5), |_| {});
998
assert_interrupted(&run);
999
assert_eq!(run.session_id, "session-5");
1000
}
1001
1002
#[gpui_kit::test]
1003
fn a_running_run_with_a_session_is_resumed(cx: &mut TestAppContext) {
1004
let original = running_run(5);
1005
let run = reload_with(cx, RESUMABLE_COMMAND, original.clone(), |_| {});
1006
assert_eq!(run.state, RunState::Running);
1007
assert_eq!(run.ended_at, None);
1008
assert_eq!(run.started_at, original.started_at);
1009
assert_eq!(run.current_step, "Resumed after restart");
1010
assert_eq!(run.steps.len(), 2);
1011
assert_eq!(run.steps[0], original.steps[0]);
1012
assert_eq!(run.steps[1].1, "Resumed after restart");
1013
}
1014
1015
fn reload_many(cx: &mut TestAppContext, run_count: u64) -> (Entity<AgentRuns>, Vec<u64>) {
1016
let (app, runs) = setup(cx, RESUMABLE_COMMAND);
1017
let ids: Vec<u64> = (1..=run_count).collect();
1018
let reloaded = cx.update(|cx| {
1019
runs.update(cx, |runs, cx| {
1020
runs.runs.extend(ids.iter().map(|id| running_run(*id)));
1021
runs.persist(cx);
1022
});
1023
cx.new(|cx| AgentRuns::new(app.clone(), cx))
1024
});
1025
(reloaded, ids)
1026
}
1027
1028
fn state_of(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) -> RunState {
1029
cx.update(|cx| runs.read(cx).get(run_id).unwrap().state.clone())
1030
}
1031
1032
#[gpui_kit::test]
1033
fn at_most_three_resumes_run_and_the_fourth_starts_when_one_finishes(cx: &mut TestAppContext) {
1034
let (runs, _) = reload_many(cx, 4);
1035
cx.run_until_parked();
1036
cx.update(|cx| {
1037
let runs = runs.read(cx);
1038
assert_eq!(runs.stops.len(), 3);
1039
assert_eq!(runs.resume_queue, [4]);
1040
});
1041
cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(1, cx)));
1042
wait_until_finished(cx, &runs, 1);
1043
cx.run_until_parked();
1044
cx.update(|cx| {
1045
let runs_ref = runs.read(cx);
1046
assert!(runs_ref.resume_queue.is_empty());
1047
assert!(runs_ref.stops.contains_key(&4));
1048
runs.update(cx, |runs, cx| {
1049
for run_id in [2, 3, 4] {
1050
runs.stop(run_id, cx);
1051
}
1052
});
1053
});
1054
wait_until_finished(cx, &runs, 4);
1055
}
1056
1057
#[gpui_kit::test]
1058
fn stopping_a_queued_resume_ends_it_without_spawning(cx: &mut TestAppContext) {
1059
let (runs, _) = reload_many(cx, 4);
1060
cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(4, cx)));
1061
cx.run_until_parked();
1062
assert_eq!(state_of(cx, &runs, 4), RunState::Stopped);
1063
cx.update(|cx| {
1064
let runs_ref = runs.read(cx);
1065
assert!(!runs_ref.stops.contains_key(&4));
1066
assert_eq!(runs_ref.stops.len(), 3);
1067
runs.update(cx, |runs, cx| {
1068
for run_id in [1, 2, 3] {
1069
runs.stop(run_id, cx);
1070
}
1071
});
1072
});
1073
wait_until_finished(cx, &runs, 3);
1074
}
1075
1076
#[gpui_kit::test]
1077
fn stopping_during_the_stop_wait_ends_the_run_without_spawning(cx: &mut TestAppContext) {
1078
let (runs, _) = reload_many(cx, 1);
1079
cx.update(|cx| {
1080
runs.update(cx, |runs, cx| {
1081
runs.resume_queue.clear();
1082
runs.begin_resume(1, cx);
1083
runs.stop(1, cx);
1084
})
1085
});
1086
cx.run_until_parked();
1087
assert_eq!(state_of(cx, &runs, 1), RunState::Stopped);
1088
cx.update(|cx| assert!(runs.read(cx).stops.is_empty()));
1089
}
1090
1091
#[gpui_kit::test]
1092
fn a_running_run_without_a_session_is_interrupted(cx: &mut TestAppContext) {
1093
let mut original = running_run(5);
1094
original.session_id = String::new();
1095
let run = reload_with(cx, RESUMABLE_COMMAND, original, |_| {});
1096
assert_interrupted(&run);
1097
}
1098
1099
#[gpui_kit::test]
1100
fn a_profile_that_cannot_resume_is_interrupted(cx: &mut TestAppContext) {
1101
let run = reload_with(cx, "sh -c 'sleep 30'", running_run(5), |_| {});
1102
assert_interrupted(&run);
1103
}
1104
1105
#[gpui_kit::test]
1106
fn switching_resume_off_interrupts_the_run(cx: &mut TestAppContext) {
1107
let run = reload_with(cx, RESUMABLE_COMMAND, running_run(5), |settings| {
1108
settings.resume_interrupted_runs = false
738
1109
});
1110
assert_interrupted(&run);
739
1111
}
740
1112
741
1113
#[test]
@@ -1,15 +1,15 @@1
use std::collections::{HashMap, HashSet};1
use std::collections::{HashMap, HashSet, VecDeque};2
use std::time::Duration;2
use std::time::Duration;3
3
4
use agents::{AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate};4
use agents::{AgentAction, AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate};5
use chrono::{DateTime, Utc};5
use chrono::{DateTime, Utc};6
use gpui_kit::*;6
use gpui_kit::*;7
use serde::{Deserialize, Serialize};7
use serde::{Deserialize, Serialize};8
use tokio::sync::{mpsc, oneshot};8
use tokio::sync::{mpsc, oneshot};9
9
10
use super::{10
use super::{11
StartRequest, demo, mcp_bridge, mcp_config_directory, message_context, open_run_session,11
MCP_POLL_INTERVAL, MCP_WAIT_LIMIT, StartRequest, demo, mcp_bridge, mcp_config_directory,12
store as run_store,12
message_context, open_run_session, store as run_store,13
};13
};14
use crate::app_state::AppState;14
use crate::app_state::AppState;15
use crate::notice::truncated;15
use crate::notice::truncated;@@ -21,6 +21,9 @@ const VISIBLE_LOG_LINES: usize = 20;21
const TEXT_STEP_CHARS: usize = 80;21
const TEXT_STEP_CHARS: usize = 80;22
const DONE_STEP_CHARS: usize = 60;22
const DONE_STEP_CHARS: usize = 60;23
const TICK: Duration = Duration::from_secs(1);23
const TICK: Duration = Duration::from_secs(1);24
const RESUME_PARALLEL_LIMIT: usize = 3;25
const RESUMED_STEP: &str = "Resumed after restart";26
const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";24
27
25
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]28
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]26
pub enum RunState {29
pub enum RunState {@@ -53,6 +56,8 @@ pub struct AgentRun {53
#[serde(skip)]56
#[serde(skip)]54
pub expanded: bool,57
pub expanded: bool,55
pub dismissed: bool,58
pub dismissed: bool,59
#[serde(default)]60
pub process_id: Option<u32>,56
}61
}57
62
58
impl AgentRun {63
impl AgentRun {@@ -117,6 +122,23 @@ impl AgentRun {117
}122
}118
}123
}119
124
125
fn orphan_stop(run: &AgentRun, plan: &agents::RunPlan) -> Option<agents::Invocation> {126
plan.stop.clone().or_else(|| {127
run.process_id128
.and_then(|process_id| agents::kill_process_invocation(process_id, &run.session_id))129
})130
}131
132
fn can_resume(settings: &AgentSettings, run: &AgentRun) -> bool {133
settings.resume_interrupted_runs134
&& !run.session_id.is_empty()135
&& settings136
.agents137
.iter()138
.find(|agent| agent.id == run.agent_id)139
.is_some_and(agents::supports_resume)140
}141
120
fn remove_stale_mcp_configs() {142
fn remove_stale_mcp_configs() {121
let Some(directory) = mcp_config_directory() else {143
let Some(directory) = mcp_config_directory() else {122
return;144
return;@@ -156,6 +178,9 @@ pub struct AgentRuns {156
settings: AgentSettings,178
settings: AgentSettings,157
runs: Vec<AgentRun>,179
runs: Vec<AgentRun>,158
stops: HashMap<u64, oneshot::Sender<()>>,180
stops: HashMap<u64, oneshot::Sender<()>>,181
resume_queue: VecDeque<u64>,182
resuming: HashSet<u64>,183
stopping: HashSet<u64>,159
open_after_stop: HashSet<u64>,184
open_after_stop: HashSet<u64>,160
next_id: u64,185
next_id: u64,161
ticking: bool,186
ticking: bool,@@ -166,10 +191,17 @@ impl EventEmitter<AgentRunsEvent> for AgentRuns {}166
impl AgentRuns {191
impl AgentRuns {167
pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {192
pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {168
let store = app.read(cx).store.clone();193
let store = app.read(cx).store.clone();194
let settings = run_store::load_settings(&store);169
let mut runs = run_store::load_runs(&store);195
let mut runs = run_store::load_runs(&store);170
let interrupted = runs.iter().any(AgentRun::is_running);196
let interrupted = runs.iter().any(AgentRun::is_running);197
let mut resume_queue = VecDeque::new();171
for run in runs.iter_mut().filter(|run| run.is_running()) {198
for run in runs.iter_mut().filter(|run| run.is_running()) {172
run.mark_interrupted();199
if can_resume(&settings, run) {200
run.push_step(RESUMED_STEP.to_owned());201
resume_queue.push_back(run.id);202
} else {203
run.mark_interrupted();204
}173
}205
}174
if interrupted {206
if interrupted {175
run_store::save_runs(&store, &runs);207
run_store::save_runs(&store, &runs);@@ -181,17 +213,135 @@ impl AgentRuns {181
let next_id = runs.iter().map(|run| run.id).max().map_or(1, |id| id + 1);213
let next_id = runs.iter().map(|run| run.id).max().map_or(1, |id| id + 1);182
let mut agent_runs = AgentRuns {214
let mut agent_runs = AgentRuns {183
app,215
app,184
settings: run_store::load_settings(&store),216
settings,185
runs,217
runs,186
stops: HashMap::new(),218
stops: HashMap::new(),219
resume_queue,220
resuming: HashSet::new(),221
stopping: HashSet::new(),187
open_after_stop: HashSet::new(),222
open_after_stop: HashSet::new(),188
next_id,223
next_id,189
ticking: false,224
ticking: false,190
};225
};191
agent_runs.ensure_ticking(cx);226
agent_runs.ensure_ticking(cx);227
agent_runs.start_resumes(cx);192
agent_runs228
agent_runs193
}229
}194
230
231
fn start_resumes(&mut self, cx: &mut Context<Self>) {232
if self.resume_queue.is_empty() {233
return;234
}235
let needs_mcp = self.resume_queue.iter().any(|run_id| {236
self.get(*run_id)237
.and_then(|run| {238
self.settings239
.agents240
.iter()241
.find(|agent| agent.id == run.agent_id)242
})243
.is_some_and(|agent| !agent.mcp_config_flag.is_empty())244
});245
cx.spawn(async move |this, cx| {246
let mut waited = Duration::ZERO;247
while needs_mcp248
&& waited < MCP_WAIT_LIMIT249
&& !cx.update(|cx| mcp_bridge::endpoint(cx).is_some())250
{251
cx.background_executor().timer(MCP_POLL_INTERVAL).await;252
waited += MCP_POLL_INTERVAL;253
}254
this.update(cx, |runs, cx| runs.resume_next(cx)).ok();255
})256
.detach();257
}258
259
fn resume_next(&mut self, cx: &mut Context<Self>) {260
while self.resuming.len() < RESUME_PARALLEL_LIMIT {261
let Some(run_id) = self.resume_queue.pop_front() else {262
return;263
};264
self.begin_resume(run_id, cx);265
}266
}267
268
fn resume_plan(269
&self,270
run: &AgentRun,271
cx: &App,272
) -> Result<(agents::RunPlan, agents::OutputFormat), String> {273
let action = self274
.settings275
.actions276
.iter()277
.find(|action| action.id == run.action_id)278
.cloned()279
.ok_or("the action no longer exists")?;280
let profile = self281
.settings282
.agents283
.iter()284
.find(|profile| profile.id == run.agent_id)285
.ok_or("the agent no longer exists")?;286
let action = AgentAction {287
working_dir: run.working_dir.clone(),288
..action289
};290
let plan = agents::resume_invocation(291
profile,292
&action,293
RESUME_PROMPT,294
&run.session_id,295
mcp_bridge::endpoint(cx).as_ref(),296
mcp_config_directory().as_deref(),297
)298
.map_err(|error| error.to_string())?;299
Ok((plan, profile.output))300
}301
302
fn begin_resume(&mut self, run_id: u64, cx: &mut Context<Self>) {303
let Some(run) = self.get(run_id).filter(|run| run.is_running()).cloned() else {304
return;305
};306
self.resuming.insert(run_id);307
match self.resume_plan(&run, cx) {308
Ok((plan, format)) => {309
let stop = orphan_stop(&run, &plan);310
cx.spawn(async move |this, cx| {311
if let Some(stop) = stop {312
let _ =313
runtime::spawn(async move { agents::run_stop_invocation(&stop).await })314
.await;315
}316
this.update(cx, |runs, cx| {317
let still_resuming = runs.resuming.contains(&run_id)318
&& runs.get(run_id).is_some_and(AgentRun::is_running);319
if still_resuming {320
runs.spawn(run_id, plan, format, cx);321
} else {322
for path in &plan.cleanup {323
let _ = std::fs::remove_file(path);324
}325
}326
})327
.ok();328
})329
.detach();330
}331
Err(reason) => self.finish(332
run_id,333
Some(RunOutcome {334
status: RunStatus::Failed {335
message: format!("Could not resume - {reason}"),336
stderr_tail: Vec::new(),337
},338
exit_code: None,339
}),340
cx,341
),342
}343
}344
195
pub fn settings(&self) -> &AgentSettings {345
pub fn settings(&self) -> &AgentSettings {196
&self.settings346
&self.settings197
}347
}@@ -305,6 +455,7 @@ impl AgentRuns {305
ended_at: None,455
ended_at: None,306
expanded: false,456
expanded: false,307
dismissed: false,457
dismissed: false,458
process_id: None,308
});459
});309
if endpoint.is_none()460
if endpoint.is_none()310
&& let Some(run) = self.run_mut(run_id)461
&& let Some(run) = self.run_mut(run_id)@@ -359,8 +510,16 @@ impl AgentRuns {359
}510
}360
511
361
fn apply_update(&mut self, run_id: u64, update: RunUpdate, cx: &mut Context<Self>) {512
fn apply_update(&mut self, run_id: u64, update: RunUpdate, cx: &mut Context<Self>) {362
let RunUpdate::Event(event) = update else {513
let event = match update {363
return;514
RunUpdate::Event(event) => event,515
RunUpdate::Started(process_id) => {516
if let Some(run) = self.run_mut(run_id) {517
run.process_id = Some(process_id);518
self.persist(cx);519
}520
return;521
}522
RunUpdate::Stderr(_) => return,364
};523
};365
let Some(run) = self.run_mut(run_id) else {524
let Some(run) = self.run_mut(run_id) else {366
return;525
return;@@ -377,10 +536,13 @@ impl AgentRuns {377
536
378
fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {537
fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {379
self.stops.remove(&run_id);538
self.stops.remove(&run_id);539
self.stopping.remove(&run_id);540
let was_resuming = self.resuming.remove(&run_id);380
let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) else {541
let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) else {381
return;542
return;382
};543
};383
run.ended_at = Some(Utc::now());544
run.ended_at = Some(Utc::now());545
run.process_id = None;384
match outcome.map(|outcome| outcome.status) {546
match outcome.map(|outcome| outcome.status) {385
Some(RunStatus::Completed { final_text }) => {547
Some(RunStatus::Completed { final_text }) => {386
let line = truncated(first_line(&final_text), DONE_STEP_CHARS);548
let line = truncated(first_line(&final_text), DONE_STEP_CHARS);@@ -396,6 +558,11 @@ impl AgentRuns {396
message,558
message,397
stderr_tail,559
stderr_tail,398
}) => {560
}) => {561
let message = if was_resuming && message.starts_with("cannot start") {562
format!("Could not resume - {message}")563
} else {564
message565
};399
run.current_step = message.clone();566
run.current_step = message.clone();400
run.state = RunState::Failed {567
run.state = RunState::Failed {401
message,568
message,@@ -426,6 +593,9 @@ impl AgentRuns {426
if self.open_after_stop.remove(&run_id) && stopped {593
if self.open_after_stop.remove(&run_id) && stopped {427
open_run_session(&snapshot, cx);594
open_run_session(&snapshot, cx);428
}595
}596
if was_resuming {597
self.resume_next(cx);598
}429
cx.notify();599
cx.notify();430
}600
}431
601
@@ -467,12 +637,46 @@ impl AgentRuns {467
}637
}468
638
469
pub fn stop(&mut self, run_id: u64, cx: &mut Context<Self>) {639
pub fn stop(&mut self, run_id: u64, cx: &mut Context<Self>) {640
if self.stopping.contains(&run_id) {641
return;642
}470
if let Some(stop) = self.stops.remove(&run_id) {643
if let Some(stop) = self.stops.remove(&run_id) {644
self.stopping.insert(run_id);471
let _ = stop.send(());645
let _ = stop.send(());472
if let Some(run) = self.run_mut(run_id) {646
if let Some(run) = self.run_mut(run_id) {473
run.current_step = "Stopping".to_owned();647
run.current_step = "Stopping".to_owned();474
}648
}475
cx.notify();649
cx.notify();650
} else if self.resuming.contains(&run_id) || self.resume_queue.contains(&run_id) {651
if self.resume_queue.contains(&run_id) {652
self.stop_orphan(run_id, cx);653
}654
self.resume_queue.retain(|queued| *queued != run_id);655
self.finish(656
run_id,657
Some(RunOutcome {658
status: RunStatus::Stopped,659
exit_code: None,660
}),661
cx,662
);663
}664
}665
666
fn stop_orphan(&self, run_id: u64, cx: &App) {667
let Some(run) = self.get(run_id) else {668
return;669
};670
let Ok((plan, _)) = self.resume_plan(run, cx) else {671
return;672
};673
for path in &plan.cleanup {674
let _ = std::fs::remove_file(path);675
}676
if let Some(stop) = orphan_stop(run, &plan) {677
drop(runtime::spawn(async move {678
agents::run_stop_invocation(&stop).await679
}));476
}680
}477
}681
}478
682
@@ -550,6 +754,7 @@ pub(super) mod tests {550
ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),754
ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),551
expanded: false,755
expanded: false,552
dismissed: false,756
dismissed: false,757
process_id: None,553
}758
}554
}759
}555
760
@@ -575,6 +780,7 @@ pub(super) mod tests {575
AgentSettings {780
AgentSettings {576
agents: vec![profile],781
agents: vec![profile],577
actions: vec![action],782
actions: vec![action],783
resume_interrupted_runs: true,578
}784
}579
}785
}580
786
@@ -621,7 +827,9 @@ pub(super) mod tests {621
827
622
#[cfg(unix)]828
#[cfg(unix)]623
mod shell_runs {829
mod shell_runs {624
use super::{RunState, TestAppContext, run_store, setup, wait_until_finished};830
use gpui_kit::AppContext as _;831
832
use super::{AgentRuns, RunState, TestAppContext, run_store, setup, wait_until_finished};625
833
626
#[gpui_kit::test]834
#[gpui_kit::test]627
fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {835
fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {@@ -658,6 +866,34 @@ pub(super) mod tests {658
});866
});659
}867
}660
868
869
#[gpui_kit::test]870
fn a_resumed_run_continues_and_finishes_done(cx: &mut TestAppContext) {871
let fixture = concat!(872
env!("CARGO_MANIFEST_DIR"),873
"/../agents/tests/fixtures/claude-stream.jsonl"874
);875
let command = format!("sh -c 'cat {fixture}' --session-id {{session_id}}");876
let (app, runs) = setup(cx, &command);877
cx.update(|cx| {878
runs.update(cx, |runs, cx| {879
runs.runs.push(super::running_run(5));880
runs.persist(cx);881
});882
});883
let reloaded = cx.update(|cx| cx.new(|cx| AgentRuns::new(app.clone(), cx)));884
wait_until_finished(cx, &reloaded, 5);885
cx.update(|cx| {886
let run = reloaded.read(cx).get(5).unwrap().clone();887
assert_eq!(run.state, RunState::Done);888
assert_eq!(run.session_id, "session-5");889
assert!(890
run.steps891
.iter()892
.any(|(_, text)| text == "Resumed after restart")893
);894
});895
}896
661
#[gpui_kit::test]897
#[gpui_kit::test]662
fn a_failing_command_ends_failed_with_its_stderr(cx: &mut TestAppContext) {898
fn a_failing_command_ends_failed_with_its_stderr(cx: &mut TestAppContext) {663
let (app, runs) = setup(cx, "sh -c 'echo boom >&2; exit 3'");899
let (app, runs) = setup(cx, "sh -c 'echo boom >&2; exit 3'");@@ -715,27 +951,163 @@ pub(super) mod tests {715
});951
});716
}952
}717
953
718
#[gpui_kit::test]954
const RESUMABLE_COMMAND: &str = "sh -c 'sleep 30' --session-id {session_id}";719
fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) {955
const INTERRUPTED: &str = "Interrupted - the app was closed during the run";720
let (app, runs) = setup(cx, "true");956
957
fn running_run(id: u64) -> AgentRun {958
let mut running = finished_run(id);959
running.action_id = "ask".to_owned();960
running.agent_id = "fake".to_owned();961
running.state = RunState::Running;962
running.ended_at = None;963
running964
}965
966
fn reload_with(967
cx: &mut TestAppContext,968
command: &str,969
run: AgentRun,970
change_settings: impl FnOnce(&mut AgentSettings),971
) -> AgentRun {972
let (app, runs) = setup(cx, command);721
cx.update(|cx| {973
cx.update(|cx| {722
let mut running = finished_run(5);974
let mut settings = fake_settings(command);723
running.state = RunState::Running;975
change_settings(&mut settings);724
running.ended_at = None;976
run_store::save_settings(&app.read(cx).store, &settings);977
let run_id = run.id;725
runs.update(cx, |runs, cx| {978
runs.update(cx, |runs, cx| {726
runs.runs.push(running);979
runs.runs.push(run);727
runs.persist(cx);980
runs.persist(cx);728
});981
});729
let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));982
let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));730
let run = reloaded.read(cx).get(5).unwrap().clone();983
reloaded.read(cx).get(run_id).unwrap().clone()731
assert!(matches!(984
})732
run.state,985
}733
RunState::Failed { ref message, .. } if message == "Interrupted - the app was closed during the run"986
734
));987
fn assert_interrupted(run: &AgentRun) {735
assert!(run.ended_at.is_some());988
assert!(matches!(736
assert_eq!(run.session_id, "session-5");989
run.state,737
assert_eq!(reloaded.read(cx).running_count(), 0);990
RunState::Failed { ref message, .. } if message == INTERRUPTED991
));992
assert!(run.ended_at.is_some());993
}994
995
#[gpui_kit::test]996
fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) {997
let run = reload_with(cx, "true", running_run(5), |_| {});998
assert_interrupted(&run);999
assert_eq!(run.session_id, "session-5");1000
}1001
1002
#[gpui_kit::test]1003
fn a_running_run_with_a_session_is_resumed(cx: &mut TestAppContext) {1004
let original = running_run(5);1005
let run = reload_with(cx, RESUMABLE_COMMAND, original.clone(), |_| {});1006
assert_eq!(run.state, RunState::Running);1007
assert_eq!(run.ended_at, None);1008
assert_eq!(run.started_at, original.started_at);1009
assert_eq!(run.current_step, "Resumed after restart");1010
assert_eq!(run.steps.len(), 2);1011
assert_eq!(run.steps[0], original.steps[0]);1012
assert_eq!(run.steps[1].1, "Resumed after restart");1013
}1014
1015
fn reload_many(cx: &mut TestAppContext, run_count: u64) -> (Entity<AgentRuns>, Vec<u64>) {1016
let (app, runs) = setup(cx, RESUMABLE_COMMAND);1017
let ids: Vec<u64> = (1..=run_count).collect();1018
let reloaded = cx.update(|cx| {1019
runs.update(cx, |runs, cx| {1020
runs.runs.extend(ids.iter().map(|id| running_run(*id)));1021
runs.persist(cx);1022
});1023
cx.new(|cx| AgentRuns::new(app.clone(), cx))1024
});1025
(reloaded, ids)1026
}1027
1028
fn state_of(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) -> RunState {1029
cx.update(|cx| runs.read(cx).get(run_id).unwrap().state.clone())1030
}1031
1032
#[gpui_kit::test]1033
fn at_most_three_resumes_run_and_the_fourth_starts_when_one_finishes(cx: &mut TestAppContext) {1034
let (runs, _) = reload_many(cx, 4);1035
cx.run_until_parked();1036
cx.update(|cx| {1037
let runs = runs.read(cx);1038
assert_eq!(runs.stops.len(), 3);1039
assert_eq!(runs.resume_queue, [4]);1040
});1041
cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(1, cx)));1042
wait_until_finished(cx, &runs, 1);1043
cx.run_until_parked();1044
cx.update(|cx| {1045
let runs_ref = runs.read(cx);1046
assert!(runs_ref.resume_queue.is_empty());1047
assert!(runs_ref.stops.contains_key(&4));1048
runs.update(cx, |runs, cx| {1049
for run_id in [2, 3, 4] {1050
runs.stop(run_id, cx);1051
}1052
});1053
});1054
wait_until_finished(cx, &runs, 4);1055
}1056
1057
#[gpui_kit::test]1058
fn stopping_a_queued_resume_ends_it_without_spawning(cx: &mut TestAppContext) {1059
let (runs, _) = reload_many(cx, 4);1060
cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(4, cx)));1061
cx.run_until_parked();1062
assert_eq!(state_of(cx, &runs, 4), RunState::Stopped);1063
cx.update(|cx| {1064
let runs_ref = runs.read(cx);1065
assert!(!runs_ref.stops.contains_key(&4));1066
assert_eq!(runs_ref.stops.len(), 3);1067
runs.update(cx, |runs, cx| {1068
for run_id in [1, 2, 3] {1069
runs.stop(run_id, cx);1070
}1071
});1072
});1073
wait_until_finished(cx, &runs, 3);1074
}1075
1076
#[gpui_kit::test]1077
fn stopping_during_the_stop_wait_ends_the_run_without_spawning(cx: &mut TestAppContext) {1078
let (runs, _) = reload_many(cx, 1);1079
cx.update(|cx| {1080
runs.update(cx, |runs, cx| {1081
runs.resume_queue.clear();1082
runs.begin_resume(1, cx);1083
runs.stop(1, cx);1084
})1085
});1086
cx.run_until_parked();1087
assert_eq!(state_of(cx, &runs, 1), RunState::Stopped);1088
cx.update(|cx| assert!(runs.read(cx).stops.is_empty()));1089
}1090
1091
#[gpui_kit::test]1092
fn a_running_run_without_a_session_is_interrupted(cx: &mut TestAppContext) {1093
let mut original = running_run(5);1094
original.session_id = String::new();1095
let run = reload_with(cx, RESUMABLE_COMMAND, original, |_| {});1096
assert_interrupted(&run);1097
}1098
1099
#[gpui_kit::test]1100
fn a_profile_that_cannot_resume_is_interrupted(cx: &mut TestAppContext) {1101
let run = reload_with(cx, "sh -c 'sleep 30'", running_run(5), |_| {});1102
assert_interrupted(&run);1103
}1104
1105
#[gpui_kit::test]1106
fn switching_resume_off_interrupts_the_run(cx: &mut TestAppContext) {1107
let run = reload_with(cx, RESUMABLE_COMMAND, running_run(5), |settings| {1108
settings.resume_interrupted_runs = false738
});1109
});1110
assert_interrupted(&run);739
}1111
}740
1112
741
#[test]1113
#[test]@@ -415,6 +415,37 @@ impl AgentsSettings {
415
415
}
416
416
}
417
417
418
pub(super) fn resume_toggle(resume: bool, settings: Entity<AgentsSettings>) -> Stateful<Div> {
419
h_flex()
420
.id("resume-interrupted-runs")
421
.w_full()
422
.px(px(PAGE_PADDING))
423
.pt(px(16.))
424
.gap(px(12.))
425
.items_center()
426
.cursor_pointer()
427
.child(
428
v_flex()
429
.flex_1()
430
.child(
431
div()
432
.text_size(px(14.))
433
.font_weight(FontWeight::SEMIBOLD)
434
.child("Resume interrupted runs"),
435
)
436
.child(
437
div()
438
.text_size(px(12.))
439
.text_color(theme::text_muted())
440
.child("Continue running agents after the app restarts"),
441
),
442
)
443
.child(switch(resume))
444
.on_click(move |_, _, cx| {
445
settings.update(cx, |this, cx| this.set_resume_interrupted_runs(!resume, cx))
446
})
447
}
448
418
449
#[cfg(test)]
419
450
mod tests {
420
451
use agents::Environment;
@@ -415,6 +415,37 @@ impl AgentsSettings {415
}415
}416
}416
}417
417
418
pub(super) fn resume_toggle(resume: bool, settings: Entity<AgentsSettings>) -> Stateful<Div> {419
h_flex()420
.id("resume-interrupted-runs")421
.w_full()422
.px(px(PAGE_PADDING))423
.pt(px(16.))424
.gap(px(12.))425
.items_center()426
.cursor_pointer()427
.child(428
v_flex()429
.flex_1()430
.child(431
div()432
.text_size(px(14.))433
.font_weight(FontWeight::SEMIBOLD)434
.child("Resume interrupted runs"),435
)436
.child(437
div()438
.text_size(px(12.))439
.text_color(theme::text_muted())440
.child("Continue running agents after the app restarts"),441
),442
)443
.child(switch(resume))444
.on_click(move |_, _, cx| {445
settings.update(cx, |this, cx| this.set_resume_interrupted_runs(!resume, cx))446
})447
}448
418
#[cfg(test)]449
#[cfg(test)]419
mod tests {450
mod tests {420
use agents::Environment;451
use agents::Environment;@@ -12,6 +12,7 @@ use gpui_kit::*;
12
12
use super::environment_label;
13
13
use super::runs::AgentRuns;
14
14
use super::settings_controls::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};
15
use super::settings_forms::resume_toggle;
15
16
use crate::runtime;
16
17
use crate::theme;
17
18
use crate::views::widgets::icon;
@@ -318,6 +319,12 @@ impl AgentsSettings {
318
319
self.update_action(cx, move |action| action.agent_id = agent_id);
319
320
}
320
321
322
pub(super) fn set_resume_interrupted_runs(&mut self, resume: bool, cx: &mut Context<Self>) {
323
self.runs.update(cx, |runs, cx| {
324
runs.update_settings(|settings| settings.resume_interrupted_runs = resume, cx)
325
});
326
}
327
321
328
pub(super) fn set_ask_extra(&mut self, ask: bool, cx: &mut Context<Self>) {
322
329
self.update_action(cx, move |action| action.ask_extra_instructions = ask);
323
330
}
@@ -665,6 +672,7 @@ impl AgentsSettings {
665
672
Some(add_action.into_any_element()),
666
673
))
667
674
.child(v_flex().w_full().px(px(8.)).children(action_rows))
675
.child(resume_toggle(settings.resume_interrupted_runs, this))
668
676
.child(
669
677
div()
670
678
.w_full()
@@ -12,6 +12,7 @@ use gpui_kit::*;12
use super::environment_label;12
use super::environment_label;13
use super::runs::AgentRuns;13
use super::runs::AgentRuns;14
use super::settings_controls::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};14
use super::settings_controls::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};15
use super::settings_forms::resume_toggle;15
use crate::runtime;16
use crate::runtime;16
use crate::theme;17
use crate::theme;17
use crate::views::widgets::icon;18
use crate::views::widgets::icon;@@ -318,6 +319,12 @@ impl AgentsSettings {318
self.update_action(cx, move |action| action.agent_id = agent_id);319
self.update_action(cx, move |action| action.agent_id = agent_id);319
}320
}320
321
322
pub(super) fn set_resume_interrupted_runs(&mut self, resume: bool, cx: &mut Context<Self>) {323
self.runs.update(cx, |runs, cx| {324
runs.update_settings(|settings| settings.resume_interrupted_runs = resume, cx)325
});326
}327
321
pub(super) fn set_ask_extra(&mut self, ask: bool, cx: &mut Context<Self>) {328
pub(super) fn set_ask_extra(&mut self, ask: bool, cx: &mut Context<Self>) {322
self.update_action(cx, move |action| action.ask_extra_instructions = ask);329
self.update_action(cx, move |action| action.ask_extra_instructions = ask);323
}330
}@@ -665,6 +672,7 @@ impl AgentsSettings {665
Some(add_action.into_any_element()),672
Some(add_action.into_any_element()),666
))673
))667
.child(v_flex().w_full().px(px(8.)).children(action_rows))674
.child(v_flex().w_full().px(px(8.)).children(action_rows))675
.child(resume_toggle(settings.resume_interrupted_runs, this))668
.child(676
.child(669
div()677
div()670
.w_full()678
.w_full()