feat(agents): start dialog picks the session and working dir per run
- Session picker: new session, recent runs of the agent, or other Claude Code sessions of the folder (terminal, Claude Desktop). Live sessions (~/.claude/sessions) get a copy (--resume S --fork-session --session-id N); a send to a running session waits its turn. - Working dir picker: action default, last 5 dirs per agent, Browse. - One lane per session id (lanes.rs): never two agent processes on one session; queued sends survive restart, follow session-id changes, stop-and-open cancels them. - Stop kills only the app's headless process of that session (by session-id role), never an interactive terminal or another fork; 15 s timeout; Windows taskkill /T. - Session sends carry the Teams message as context; retry keeps session and folder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -56,6 +56,27 @@ pub fn build_prompt(
56
56
rendered.trim().to_string()
57
57
}
58
58
59
pub fn build_session_prompt(
60
context: &MessageContext,
61
message: &str,
62
session_id: &str,
63
agent_id: &str,
64
) -> String {
65
let quoted = context
66
.message
67
.lines()
68
.map(|line| format!("> {line}"))
69
.collect::<Vec<_>>()
70
.join("\n");
71
format!(
72
"Context: {sender} wrote in the Teams chat \"{chat}\" (conversation_id \"{conversation_id}\", message_id \"{message_id}\"):\n\n{quoted}\n\nThe `teams` MCP server can show images of messages (`get_image`) and list the newest messages of other chats (`recent_messages`). To propose a reply, use the `propose_message` tool of the `teams` MCP server: conversation_id \"{conversation_id}\", reply_to_message_id \"{message_id}\", session_id \"{session_id}\", agent \"{agent_id}\". Never send anything yourself.\n\n{message}",
73
sender = context.sender,
74
chat = context.chat,
75
conversation_id = context.conversation_id,
76
message_id = context.message_id,
77
)
78
}
79
59
80
#[cfg(test)]
60
81
mod tests {
61
82
use super::*;
@@ -77,6 +98,17 @@ mod tests {
77
98
}
78
99
}
79
100
101
#[test]
102
fn a_session_prompt_carries_the_message_ids_and_the_typed_text_last() {
103
let prompt = build_session_prompt(&context(0), "and the tests?", "sid-9", "claude");
104
assert!(prompt.starts_with("Context: Ada wrote in the Teams chat \"Ops\""));
105
assert!(prompt.contains("conversation_id \"19:abc\", message_id \"42\""));
106
assert!(prompt.contains("\n> Where is the report?\n"));
107
assert!(prompt.contains("propose_message"));
108
assert!(prompt.contains("session_id \"sid-9\", agent \"claude\""));
109
assert!(prompt.ends_with("\n\nand the tests?"));
110
}
111
80
112
#[test]
81
113
fn answer_prompt_renders_ids() {
82
114
let prompt = build_prompt(
@@ -56,6 +56,27 @@ pub fn build_prompt(56
rendered.trim().to_string()56
rendered.trim().to_string()57
}57
}58
58
59
pub fn build_session_prompt(60
context: &MessageContext,61
message: &str,62
session_id: &str,63
agent_id: &str,64
) -> String {65
let quoted = context66
.message67
.lines()68
.map(|line| format!("> {line}"))69
.collect::<Vec<_>>()70
.join("\n");71
format!(72
"Context: {sender} wrote in the Teams chat \"{chat}\" (conversation_id \"{conversation_id}\", message_id \"{message_id}\"):\n\n{quoted}\n\nThe `teams` MCP server can show images of messages (`get_image`) and list the newest messages of other chats (`recent_messages`). To propose a reply, use the `propose_message` tool of the `teams` MCP server: conversation_id \"{conversation_id}\", reply_to_message_id \"{message_id}\", session_id \"{session_id}\", agent \"{agent_id}\". Never send anything yourself.\n\n{message}",73
sender = context.sender,74
chat = context.chat,75
conversation_id = context.conversation_id,76
message_id = context.message_id,77
)78
}79
59
#[cfg(test)]80
#[cfg(test)]60
mod tests {81
mod tests {61
use super::*;82
use super::*;@@ -77,6 +98,17 @@ mod tests {77
}98
}78
}99
}79
100
101
#[test]102
fn a_session_prompt_carries_the_message_ids_and_the_typed_text_last() {103
let prompt = build_session_prompt(&context(0), "and the tests?", "sid-9", "claude");104
assert!(prompt.starts_with("Context: Ada wrote in the Teams chat \"Ops\""));105
assert!(prompt.contains("conversation_id \"19:abc\", message_id \"42\""));106
assert!(prompt.contains("\n> Where is the report?\n"));107
assert!(prompt.contains("propose_message"));108
assert!(prompt.contains("session_id \"sid-9\", agent \"claude\""));109
assert!(prompt.ends_with("\n\nand the tests?"));110
}111
80
#[test]112
#[test]81
fn answer_prompt_renders_ids() {113
fn answer_prompt_renders_ids() {82
let prompt = build_prompt(114
let prompt = build_prompt(@@ -5,6 +5,7 @@ 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 APP_STOP_SCRIPT: &str = r#"for p in $(pgrep -f -- "$1"); do c=$(tr '\0' ' ' </proc/$p/cmdline 2>/dev/null) || continue; case "$c" in *app-stop-marker*) continue;; esac; case "$c" in *" -p "*|*" --print "*) ;; *) continue;; esac; case "$c" in *--output-format*) ;; *) continue;; esac; case "$c" in *"--session-id $1 "*) kill -9 "$p";; *"--resume $1 "*) case "$c" in *--fork-session*) ;; *) kill -9 "$p";; esac;; esac; done"#;
8
9
const SESSION_FLAG: &str = "--session-id {session_id}";
9
10
const RESUME_FLAG: &str = "--resume {session_id}";
10
11
const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;
@@ -40,6 +41,8 @@ pub enum InvocationError {
40
41
McpConfig(String),
41
42
#[error("the agent command has no \"{SESSION_FLAG}\" to resume with")]
42
43
CannotResume,
44
#[error("the session id is not valid")]
45
InvalidSessionId,
43
46
}
44
47
45
48
fn expand_home(path: &str) -> String {
@@ -66,6 +69,25 @@ fn mcp_config_json(endpoint: &McpEndpoint) -> String {
66
69
.to_string()
67
70
}
68
71
72
fn wsl_unc_rest(path: &str) -> Option<&str> {
73
path.strip_prefix(r"\\wsl.localhost\")
74
.or_else(|| path.strip_prefix(r"\\wsl$\"))
75
}
76
77
pub fn wsl_unc_distro(path: &str) -> Option<&str> {
78
wsl_unc_rest(path).map(|rest| rest.split('\\').next().unwrap_or(rest))
79
}
80
81
pub fn linux_path(path: &str) -> String {
82
match wsl_unc_rest(path) {
83
Some(rest) => match rest.split_once('\\') {
84
Some((_, relative)) => format!("/{}", relative.replace('\\', "/")),
85
None => "/".to_owned(),
86
},
87
None => wsl_path(path),
88
}
89
}
90
69
91
pub fn wsl_path(path: &str) -> String {
70
92
let mut characters = path.chars();
71
93
match (characters.next(), characters.next(), characters.next()) {
@@ -187,7 +209,6 @@ pub fn build_invocation(
187
209
}
188
210
Environment::Wsl { .. } => {
189
211
let mut args = wsl_prefix(&profile.environment);
190
let mut stop_args = args.clone();
191
212
args.extend(
192
213
["-e", "sh", "-lc", WSL_SCRIPT, "sh"]
193
214
.into_iter()
@@ -195,7 +216,6 @@ pub fn build_invocation(
195
216
);
196
217
args.push(working_dir);
197
218
args.extend(tokens);
198
stop_args.extend(["-e", "pkill", "-f", session_id].map(String::from));
199
219
Ok(RunPlan {
200
220
run: Invocation {
201
221
program: WSL_PROGRAM.to_string(),
@@ -203,18 +223,29 @@ pub fn build_invocation(
203
223
cwd: None,
204
224
stdin,
205
225
},
206
stop: Some(Invocation {
207
program: WSL_PROGRAM.to_string(),
208
args: stop_args,
209
cwd: None,
210
stdin: None,
211
}),
226
stop: Some(app_stop_invocation(&profile.environment, session_id)),
212
227
cleanup,
213
228
})
214
229
}
215
230
}
216
231
}
217
232
233
fn app_stop_invocation(environment: &Environment, session_id: &str) -> Invocation {
234
let mut args = wsl_prefix(environment);
235
args.extend(["-e", "sh", "-c", APP_STOP_SCRIPT, "sh", session_id].map(String::from));
236
Invocation {
237
program: WSL_PROGRAM.to_string(),
238
args,
239
cwd: None,
240
stdin: None,
241
}
242
}
243
244
pub fn wsl_stop_invocation(environment: &Environment, session_id: &str) -> Option<Invocation> {
245
(matches!(environment, Environment::Wsl { .. }) && is_plain_session_id(session_id))
246
.then(|| app_stop_invocation(environment, session_id))
247
}
248
218
249
fn is_plain_session_id(session_id: &str) -> bool {
219
250
!session_id.is_empty()
220
251
&& session_id
@@ -266,12 +297,58 @@ pub fn resume_invocation(
266
297
session_id: &str,
267
298
mcp: Option<&McpEndpoint>,
268
299
mcp_config_directory: Option<&Path>,
300
) -> Result<RunPlan, InvocationError> {
301
resume_with_flag(
302
profile,
303
action,
304
prompt,
305
session_id,
306
RESUME_FLAG,
307
mcp,
308
mcp_config_directory,
309
)
310
}
311
312
pub fn fork_invocation(
313
profile: &AgentProfile,
314
action: &AgentAction,
315
prompt: &str,
316
original_session_id: &str,
317
fork_session_id: &str,
318
mcp: Option<&McpEndpoint>,
319
mcp_config_directory: Option<&Path>,
320
) -> Result<RunPlan, InvocationError> {
321
if !is_plain_session_id(original_session_id) {
322
return Err(InvocationError::InvalidSessionId);
323
}
324
resume_with_flag(
325
profile,
326
action,
327
prompt,
328
fork_session_id,
329
&format!("--resume {original_session_id} --fork-session {SESSION_FLAG}"),
330
mcp,
331
mcp_config_directory,
332
)
333
}
334
335
fn resume_with_flag(
336
profile: &AgentProfile,
337
action: &AgentAction,
338
prompt: &str,
339
session_id: &str,
340
flag: &str,
341
mcp: Option<&McpEndpoint>,
342
mcp_config_directory: Option<&Path>,
269
343
) -> Result<RunPlan, InvocationError> {
270
344
if !supports_resume(profile) {
271
345
return Err(InvocationError::CannotResume);
272
346
}
347
if !is_plain_session_id(session_id) {
348
return Err(InvocationError::InvalidSessionId);
349
}
273
350
let resuming_profile = AgentProfile {
274
command: profile.command.replace(SESSION_FLAG, RESUME_FLAG),
351
command: profile.command.replace(SESSION_FLAG, flag),
275
352
..profile.clone()
276
353
};
277
354
build_invocation(
@@ -381,7 +458,17 @@ mod tests {
381
458
assert_eq!(stop.program, "wsl.exe");
382
459
assert_eq!(
383
460
stop.args,
384
["-d", "Ubuntu", "-e", "pkill", "-f", "sid-1"].map(String::from)
461
[
462
"-d",
463
"Ubuntu",
464
"-e",
465
"sh",
466
"-c",
467
APP_STOP_SCRIPT,
468
"sh",
469
"sid-1"
470
]
471
.map(String::from)
385
472
);
386
473
}
387
474
@@ -641,7 +728,17 @@ mod tests {
641
728
assert_eq!(plan.run.stdin.as_deref(), Some("go on"));
642
729
assert_eq!(
643
730
plan.stop.unwrap().args,
644
["-d", "Ubuntu", "-e", "pkill", "-f", "sid-9"].map(String::from)
731
[
732
"-d",
733
"Ubuntu",
734
"-e",
735
"sh",
736
"-c",
737
APP_STOP_SCRIPT,
738
"sh",
739
"sid-9"
740
]
741
.map(String::from)
645
742
);
646
743
}
647
744
@@ -673,6 +770,80 @@ mod tests {
673
770
assert_eq!(plan.stop, None);
674
771
}
675
772
773
#[test]
774
fn fork_resumes_the_original_into_a_fresh_session_id_and_keeps_the_stop() {
775
let action = AgentAction::answer_this("claude");
776
let plan = fork_invocation(
777
&AgentProfile::claude_wsl(),
778
&action,
779
"go on",
780
"old-6",
781
"new-6",
782
None,
783
None,
784
)
785
.unwrap();
786
assert!(plan.run.args.windows(5).any(|window| window
787
== [
788
"--resume",
789
"old-6",
790
"--fork-session",
791
"--session-id",
792
"new-6"
793
]));
794
assert_eq!(plan.run.stdin.as_deref(), Some("go on"));
795
assert_eq!(
796
plan.stop.unwrap().args,
797
["-e", "sh", "-c", APP_STOP_SCRIPT, "sh", "new-6"].map(String::from)
798
);
799
assert!(
800
fork_invocation(
801
&AgentProfile::claude_wsl(),
802
&action,
803
"x",
804
"bad id; rm",
805
"new",
806
None,
807
None
808
)
809
.is_err()
810
);
811
}
812
813
#[test]
814
fn resume_rejects_a_session_id_that_is_not_plain() {
815
let action = AgentAction::answer_this("claude");
816
assert!(matches!(
817
resume_invocation(
818
&AgentProfile::claude_wsl(),
819
&action,
820
"x",
821
"a b; rm",
822
None,
823
None
824
),
825
Err(InvocationError::InvalidSessionId)
826
));
827
}
828
829
#[test]
830
fn linux_path_maps_drives_and_wsl_unc_paths() {
831
assert_eq!(linux_path(r"C:\Users\dd\repo"), "/mnt/c/Users/dd/repo");
832
assert_eq!(
833
linux_path(r"\\wsl.localhost\Ubuntu\home\daniel\repo"),
834
"/home/daniel/repo"
835
);
836
assert_eq!(linux_path(r"\\wsl$\Ubuntu\home"), "/home");
837
assert_eq!(linux_path(r"\\wsl.localhost\Ubuntu"), "/");
838
assert_eq!(
839
wsl_unc_distro(r"\\wsl.localhost\Ubuntu\home"),
840
Some("Ubuntu")
841
);
842
assert_eq!(wsl_unc_distro(r"\\wsl$\Debian"), Some("Debian"));
843
assert_eq!(wsl_unc_distro(r"C:\Users"), None);
844
assert_eq!(linux_path("/home/daniel"), "/home/daniel");
845
}
846
676
847
#[test]
677
848
fn copilot_resumes_with_the_prompt_in_its_args() {
678
849
let action = AgentAction::answer_this("copilot");
@@ -721,6 +892,81 @@ mod tests {
721
892
mod unix_kill {
722
893
use super::super::*;
723
894
895
fn spawn_agent_like(arguments: &[&str]) -> std::process::Child {
896
std::process::Command::new("sh")
897
.args(["-c", "sleep 30", "claude"])
898
.args(arguments)
899
.spawn()
900
.unwrap()
901
}
902
903
fn run_app_stop(session_id: &str) {
904
std::process::Command::new("sh")
905
.args(["-c", APP_STOP_SCRIPT, "sh", session_id])
906
.status()
907
.unwrap();
908
}
909
910
fn is_running(child: &mut std::process::Child) -> bool {
911
child.try_wait().unwrap().is_none()
912
}
913
914
#[test]
915
fn the_app_stop_matches_by_the_role_of_the_session_id() {
916
let session = uuid::Uuid::new_v4().to_string();
917
let fork_id = uuid::Uuid::new_v4().to_string();
918
let mut headless = spawn_agent_like(&[
919
"--print",
920
"--resume",
921
&session,
922
"--output-format",
923
"stream-json",
924
]);
925
let mut fork = spawn_agent_like(&[
926
"-p",
927
"--output-format",
928
"stream-json",
929
"--resume",
930
&session,
931
"--fork-session",
932
"--session-id",
933
&fork_id,
934
]);
935
let mut terminal = spawn_agent_like(&["--resume", &session]);
936
std::thread::sleep(std::time::Duration::from_millis(200));
937
run_app_stop(&session);
938
assert!(headless.wait().is_ok_and(|status| !status.success()));
939
assert!(is_running(&mut fork));
940
assert!(is_running(&mut terminal));
941
run_app_stop(&fork_id);
942
assert!(fork.wait().is_ok_and(|status| !status.success()));
943
assert!(is_running(&mut terminal));
944
terminal.kill().unwrap();
945
terminal.wait().unwrap();
946
}
947
948
#[test]
949
fn a_running_stop_script_is_never_killed_by_another() {
950
let session = uuid::Uuid::new_v4().to_string();
951
let mut lookalike = std::process::Command::new("sh")
952
.args([
953
"-c",
954
&format!("sleep 30 # {APP_STOP_SCRIPT}"),
955
"sh",
956
"-p",
957
"--output-format",
958
"--resume",
959
&session,
960
])
961
.spawn()
962
.unwrap();
963
std::thread::sleep(std::time::Duration::from_millis(200));
964
run_app_stop(&session);
965
assert!(is_running(&mut lookalike));
966
lookalike.kill().unwrap();
967
lookalike.wait().unwrap();
968
}
969
724
970
fn spawn_sleeper(label: &str) -> std::process::Child {
725
971
std::process::Command::new("sh")
726
972
.args(["-c", "sleep 30", label])
@@ -5,6 +5,7 @@ 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 APP_STOP_SCRIPT: &str = r#"for p in $(pgrep -f -- "$1"); do c=$(tr '\0' ' ' </proc/$p/cmdline 2>/dev/null) || continue; case "$c" in *app-stop-marker*) continue;; esac; case "$c" in *" -p "*|*" --print "*) ;; *) continue;; esac; case "$c" in *--output-format*) ;; *) continue;; esac; case "$c" in *"--session-id $1 "*) kill -9 "$p";; *"--resume $1 "*) case "$c" in *--fork-session*) ;; *) kill -9 "$p";; esac;; esac; done"#;8
const SESSION_FLAG: &str = "--session-id {session_id}";9
const SESSION_FLAG: &str = "--session-id {session_id}";9
const RESUME_FLAG: &str = "--resume {session_id}";10
const RESUME_FLAG: &str = "--resume {session_id}";10
const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;11
const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;@@ -40,6 +41,8 @@ pub enum InvocationError {40
McpConfig(String),41
McpConfig(String),41
#[error("the agent command has no \"{SESSION_FLAG}\" to resume with")]42
#[error("the agent command has no \"{SESSION_FLAG}\" to resume with")]42
CannotResume,43
CannotResume,44
#[error("the session id is not valid")]45
InvalidSessionId,43
}46
}44
47
45
fn expand_home(path: &str) -> String {48
fn expand_home(path: &str) -> String {@@ -66,6 +69,25 @@ fn mcp_config_json(endpoint: &McpEndpoint) -> String {66
.to_string()69
.to_string()67
}70
}68
71
72
fn wsl_unc_rest(path: &str) -> Option<&str> {73
path.strip_prefix(r"\\wsl.localhost\")74
.or_else(|| path.strip_prefix(r"\\wsl$\"))75
}76
77
pub fn wsl_unc_distro(path: &str) -> Option<&str> {78
wsl_unc_rest(path).map(|rest| rest.split('\\').next().unwrap_or(rest))79
}80
81
pub fn linux_path(path: &str) -> String {82
match wsl_unc_rest(path) {83
Some(rest) => match rest.split_once('\\') {84
Some((_, relative)) => format!("/{}", relative.replace('\\', "/")),85
None => "/".to_owned(),86
},87
None => wsl_path(path),88
}89
}90
69
pub fn wsl_path(path: &str) -> String {91
pub fn wsl_path(path: &str) -> String {70
let mut characters = path.chars();92
let mut characters = path.chars();71
match (characters.next(), characters.next(), characters.next()) {93
match (characters.next(), characters.next(), characters.next()) {@@ -187,7 +209,6 @@ pub fn build_invocation(187
}209
}188
Environment::Wsl { .. } => {210
Environment::Wsl { .. } => {189
let mut args = wsl_prefix(&profile.environment);211
let mut args = wsl_prefix(&profile.environment);190
let mut stop_args = args.clone();191
args.extend(212
args.extend(192
["-e", "sh", "-lc", WSL_SCRIPT, "sh"]213
["-e", "sh", "-lc", WSL_SCRIPT, "sh"]193
.into_iter()214
.into_iter()@@ -195,7 +216,6 @@ pub fn build_invocation(195
);216
);196
args.push(working_dir);217
args.push(working_dir);197
args.extend(tokens);218
args.extend(tokens);198
stop_args.extend(["-e", "pkill", "-f", session_id].map(String::from));199
Ok(RunPlan {219
Ok(RunPlan {200
run: Invocation {220
run: Invocation {201
program: WSL_PROGRAM.to_string(),221
program: WSL_PROGRAM.to_string(),@@ -203,18 +223,29 @@ pub fn build_invocation(203
cwd: None,223
cwd: None,204
stdin,224
stdin,205
},225
},206
stop: Some(Invocation {226
stop: Some(app_stop_invocation(&profile.environment, session_id)),207
program: WSL_PROGRAM.to_string(),208
args: stop_args,209
cwd: None,210
stdin: None,211
}),212
cleanup,227
cleanup,213
})228
})214
}229
}215
}230
}216
}231
}217
232
233
fn app_stop_invocation(environment: &Environment, session_id: &str) -> Invocation {234
let mut args = wsl_prefix(environment);235
args.extend(["-e", "sh", "-c", APP_STOP_SCRIPT, "sh", session_id].map(String::from));236
Invocation {237
program: WSL_PROGRAM.to_string(),238
args,239
cwd: None,240
stdin: None,241
}242
}243
244
pub fn wsl_stop_invocation(environment: &Environment, session_id: &str) -> Option<Invocation> {245
(matches!(environment, Environment::Wsl { .. }) && is_plain_session_id(session_id))246
.then(|| app_stop_invocation(environment, session_id))247
}248
218
fn is_plain_session_id(session_id: &str) -> bool {249
fn is_plain_session_id(session_id: &str) -> bool {219
!session_id.is_empty()250
!session_id.is_empty()220
&& session_id251
&& session_id@@ -266,12 +297,58 @@ pub fn resume_invocation(266
session_id: &str,297
session_id: &str,267
mcp: Option<&McpEndpoint>,298
mcp: Option<&McpEndpoint>,268
mcp_config_directory: Option<&Path>,299
mcp_config_directory: Option<&Path>,300
) -> Result<RunPlan, InvocationError> {301
resume_with_flag(302
profile,303
action,304
prompt,305
session_id,306
RESUME_FLAG,307
mcp,308
mcp_config_directory,309
)310
}311
312
pub fn fork_invocation(313
profile: &AgentProfile,314
action: &AgentAction,315
prompt: &str,316
original_session_id: &str,317
fork_session_id: &str,318
mcp: Option<&McpEndpoint>,319
mcp_config_directory: Option<&Path>,320
) -> Result<RunPlan, InvocationError> {321
if !is_plain_session_id(original_session_id) {322
return Err(InvocationError::InvalidSessionId);323
}324
resume_with_flag(325
profile,326
action,327
prompt,328
fork_session_id,329
&format!("--resume {original_session_id} --fork-session {SESSION_FLAG}"),330
mcp,331
mcp_config_directory,332
)333
}334
335
fn resume_with_flag(336
profile: &AgentProfile,337
action: &AgentAction,338
prompt: &str,339
session_id: &str,340
flag: &str,341
mcp: Option<&McpEndpoint>,342
mcp_config_directory: Option<&Path>,269
) -> Result<RunPlan, InvocationError> {343
) -> Result<RunPlan, InvocationError> {270
if !supports_resume(profile) {344
if !supports_resume(profile) {271
return Err(InvocationError::CannotResume);345
return Err(InvocationError::CannotResume);272
}346
}347
if !is_plain_session_id(session_id) {348
return Err(InvocationError::InvalidSessionId);349
}273
let resuming_profile = AgentProfile {350
let resuming_profile = AgentProfile {274
command: profile.command.replace(SESSION_FLAG, RESUME_FLAG),351
command: profile.command.replace(SESSION_FLAG, flag),275
..profile.clone()352
..profile.clone()276
};353
};277
build_invocation(354
build_invocation(@@ -381,7 +458,17 @@ mod tests {381
assert_eq!(stop.program, "wsl.exe");458
assert_eq!(stop.program, "wsl.exe");382
assert_eq!(459
assert_eq!(383
stop.args,460
stop.args,384
["-d", "Ubuntu", "-e", "pkill", "-f", "sid-1"].map(String::from)461
[462
"-d",463
"Ubuntu",464
"-e",465
"sh",466
"-c",467
APP_STOP_SCRIPT,468
"sh",469
"sid-1"470
]471
.map(String::from)385
);472
);386
}473
}387
474
@@ -641,7 +728,17 @@ mod tests {641
assert_eq!(plan.run.stdin.as_deref(), Some("go on"));728
assert_eq!(plan.run.stdin.as_deref(), Some("go on"));642
assert_eq!(729
assert_eq!(643
plan.stop.unwrap().args,730
plan.stop.unwrap().args,644
["-d", "Ubuntu", "-e", "pkill", "-f", "sid-9"].map(String::from)731
[732
"-d",733
"Ubuntu",734
"-e",735
"sh",736
"-c",737
APP_STOP_SCRIPT,738
"sh",739
"sid-9"740
]741
.map(String::from)645
);742
);646
}743
}647
744
@@ -673,6 +770,80 @@ mod tests {673
assert_eq!(plan.stop, None);770
assert_eq!(plan.stop, None);674
}771
}675
772
773
#[test]774
fn fork_resumes_the_original_into_a_fresh_session_id_and_keeps_the_stop() {775
let action = AgentAction::answer_this("claude");776
let plan = fork_invocation(777
&AgentProfile::claude_wsl(),778
&action,779
"go on",780
"old-6",781
"new-6",782
None,783
None,784
)785
.unwrap();786
assert!(plan.run.args.windows(5).any(|window| window787
== [788
"--resume",789
"old-6",790
"--fork-session",791
"--session-id",792
"new-6"793
]));794
assert_eq!(plan.run.stdin.as_deref(), Some("go on"));795
assert_eq!(796
plan.stop.unwrap().args,797
["-e", "sh", "-c", APP_STOP_SCRIPT, "sh", "new-6"].map(String::from)798
);799
assert!(800
fork_invocation(801
&AgentProfile::claude_wsl(),802
&action,803
"x",804
"bad id; rm",805
"new",806
None,807
None808
)809
.is_err()810
);811
}812
813
#[test]814
fn resume_rejects_a_session_id_that_is_not_plain() {815
let action = AgentAction::answer_this("claude");816
assert!(matches!(817
resume_invocation(818
&AgentProfile::claude_wsl(),819
&action,820
"x",821
"a b; rm",822
None,823
None824
),825
Err(InvocationError::InvalidSessionId)826
));827
}828
829
#[test]830
fn linux_path_maps_drives_and_wsl_unc_paths() {831
assert_eq!(linux_path(r"C:\Users\dd\repo"), "/mnt/c/Users/dd/repo");832
assert_eq!(833
linux_path(r"\\wsl.localhost\Ubuntu\home\daniel\repo"),834
"/home/daniel/repo"835
);836
assert_eq!(linux_path(r"\\wsl$\Ubuntu\home"), "/home");837
assert_eq!(linux_path(r"\\wsl.localhost\Ubuntu"), "/");838
assert_eq!(839
wsl_unc_distro(r"\\wsl.localhost\Ubuntu\home"),840
Some("Ubuntu")841
);842
assert_eq!(wsl_unc_distro(r"\\wsl$\Debian"), Some("Debian"));843
assert_eq!(wsl_unc_distro(r"C:\Users"), None);844
assert_eq!(linux_path("/home/daniel"), "/home/daniel");845
}846
676
#[test]847
#[test]677
fn copilot_resumes_with_the_prompt_in_its_args() {848
fn copilot_resumes_with_the_prompt_in_its_args() {678
let action = AgentAction::answer_this("copilot");849
let action = AgentAction::answer_this("copilot");@@ -721,6 +892,81 @@ mod tests {721
mod unix_kill {892
mod unix_kill {722
use super::super::*;893
use super::super::*;723
894
895
fn spawn_agent_like(arguments: &[&str]) -> std::process::Child {896
std::process::Command::new("sh")897
.args(["-c", "sleep 30", "claude"])898
.args(arguments)899
.spawn()900
.unwrap()901
}902
903
fn run_app_stop(session_id: &str) {904
std::process::Command::new("sh")905
.args(["-c", APP_STOP_SCRIPT, "sh", session_id])906
.status()907
.unwrap();908
}909
910
fn is_running(child: &mut std::process::Child) -> bool {911
child.try_wait().unwrap().is_none()912
}913
914
#[test]915
fn the_app_stop_matches_by_the_role_of_the_session_id() {916
let session = uuid::Uuid::new_v4().to_string();917
let fork_id = uuid::Uuid::new_v4().to_string();918
let mut headless = spawn_agent_like(&[919
"--print",920
"--resume",921
&session,922
"--output-format",923
"stream-json",924
]);925
let mut fork = spawn_agent_like(&[926
"-p",927
"--output-format",928
"stream-json",929
"--resume",930
&session,931
"--fork-session",932
"--session-id",933
&fork_id,934
]);935
let mut terminal = spawn_agent_like(&["--resume", &session]);936
std::thread::sleep(std::time::Duration::from_millis(200));937
run_app_stop(&session);938
assert!(headless.wait().is_ok_and(|status| !status.success()));939
assert!(is_running(&mut fork));940
assert!(is_running(&mut terminal));941
run_app_stop(&fork_id);942
assert!(fork.wait().is_ok_and(|status| !status.success()));943
assert!(is_running(&mut terminal));944
terminal.kill().unwrap();945
terminal.wait().unwrap();946
}947
948
#[test]949
fn a_running_stop_script_is_never_killed_by_another() {950
let session = uuid::Uuid::new_v4().to_string();951
let mut lookalike = std::process::Command::new("sh")952
.args([953
"-c",954
&format!("sleep 30 # {APP_STOP_SCRIPT}"),955
"sh",956
"-p",957
"--output-format",958
"--resume",959
&session,960
])961
.spawn()962
.unwrap();963
std::thread::sleep(std::time::Duration::from_millis(200));964
run_app_stop(&session);965
assert!(is_running(&mut lookalike));966
lookalike.kill().unwrap();967
lookalike.wait().unwrap();968
}969
724
fn spawn_sleeper(label: &str) -> std::process::Child {970
fn spawn_sleeper(label: &str) -> std::process::Child {725
std::process::Command::new("sh")971
std::process::Command::new("sh")726
.args(["-c", "sleep 30", label])972
.args(["-c", "sleep 30", label])@@ -4,20 +4,27 @@ mod invocation;
4
4
mod parse;
5
5
mod profile;
6
6
mod runner;
7
mod sessions;
7
8
mod settings;
8
9
mod template;
9
10
10
11
pub use action::AgentAction;
11
pub use context::{MessageContext, ThreadMessage, build_prompt};
12
pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};
12
13
pub use invocation::{
13
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, kill_process_invocation,
14
open_session_invocation, resume_invocation, supports_resume, version_check_invocation,
15
wsl_path,
14
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, fork_invocation,
15
kill_process_invocation, linux_path, open_session_invocation, resume_invocation,
16
supports_resume, version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,
16
17
};
17
18
pub use parse::{OutputParser, RunEvent, parse_line};
18
19
pub use profile::{AgentProfile, Environment, OutputFormat};
19
pub use runner::{RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation};
20
pub use settings::{AgentSettings, SETTINGS_KEY, SettingsProblem};
20
pub use runner::{
21
RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,
22
};
23
pub use sessions::{
24
ExternalSession, encode_project_dir, live_session_names, resolve_project_dir,
25
scan_external_sessions,
26
};
27
pub use settings::{AgentSettings, RECENT_WORKING_DIR_LIMIT, SETTINGS_KEY, SettingsProblem};
21
28
pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};
22
29
23
30
pub fn new_session_id() -> String {
@@ -4,20 +4,27 @@ mod invocation;4
mod parse;4
mod parse;5
mod profile;5
mod profile;6
mod runner;6
mod runner;7
mod sessions;7
mod settings;8
mod settings;8
mod template;9
mod template;9
10
10
pub use action::AgentAction;11
pub use action::AgentAction;11
pub use context::{MessageContext, ThreadMessage, build_prompt};12
pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};12
pub use invocation::{13
pub use invocation::{13
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, kill_process_invocation,14
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, fork_invocation,14
open_session_invocation, resume_invocation, supports_resume, version_check_invocation,15
kill_process_invocation, linux_path, open_session_invocation, resume_invocation,15
wsl_path,16
supports_resume, version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,16
};17
};17
pub use parse::{OutputParser, RunEvent, parse_line};18
pub use parse::{OutputParser, RunEvent, parse_line};18
pub use profile::{AgentProfile, Environment, OutputFormat};19
pub use profile::{AgentProfile, Environment, OutputFormat};19
pub use runner::{RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation};20
pub use runner::{20
pub use settings::{AgentSettings, SETTINGS_KEY, SettingsProblem};21
RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,22
};23
pub use sessions::{24
ExternalSession, encode_project_dir, live_session_names, resolve_project_dir,25
scan_external_sessions,26
};27
pub use settings::{AgentSettings, RECENT_WORKING_DIR_LIMIT, SETTINGS_KEY, SettingsProblem};21
pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};28
pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};22
29
23
pub fn new_session_id() -> String {30
pub fn new_session_id() -> String {@@ -12,6 +12,7 @@ use crate::profile::OutputFormat;
12
12
13
13
const STDERR_TAIL_LINES: usize = 20;
14
14
const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
15
const STOP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
15
16
16
17
#[derive(Clone, Debug, PartialEq, Eq)]
17
18
pub enum RunUpdate {
@@ -50,6 +51,18 @@ fn command_for(invocation: &Invocation) -> Command {
50
51
command
51
52
}
52
53
54
#[cfg(windows)]
55
fn taskkill_tree(process_id: u32) -> Invocation {
56
Invocation {
57
program: "taskkill".to_string(),
58
args: ["/PID", &process_id.to_string(), "/T", "/F"]
59
.map(String::from)
60
.to_vec(),
61
cwd: None,
62
stdin: None,
63
}
64
}
65
53
66
fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) -> RunOutcome {
54
67
RunOutcome {
55
68
status: RunStatus::Failed {
@@ -61,13 +74,19 @@ fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) ->
61
74
}
62
75
63
76
pub async fn run_stop_invocation(invocation: &Invocation) {
77
run_stop_invocation_within(invocation, STOP_TIMEOUT).await;
78
}
79
80
pub async fn run_stop_invocation_within(invocation: &Invocation, limit: std::time::Duration) {
64
81
let mut command = command_for(invocation);
65
82
command
66
83
.stdin(Stdio::null())
67
84
.stdout(Stdio::null())
68
85
.stderr(Stdio::null());
69
if let Ok(mut child) = command.spawn() {
70
let _ = child.wait().await;
86
if let Ok(mut child) = command.spawn()
87
&& tokio::time::timeout(limit, child.wait()).await.is_err()
88
{
89
let _ = child.kill().await;
71
90
}
72
91
}
73
92
@@ -173,6 +192,10 @@ async fn run_plan(
173
192
tokio::select! {
174
193
stop_result = &mut stop, if stop_armed => {
175
194
if stop_result.is_ok() {
195
#[cfg(windows)]
196
if let Some(process_id) = child.id() {
197
run_stop_invocation(&taskkill_tree(process_id)).await;
198
}
176
199
let _ = child.kill().await;
177
200
if let Some(stop_invocation) = &plan.stop {
178
201
run_stop_invocation(stop_invocation).await;
@@ -12,6 +12,7 @@ use crate::profile::OutputFormat;12
12
13
const STDERR_TAIL_LINES: usize = 20;13
const STDERR_TAIL_LINES: usize = 20;14
const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);14
const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);15
const STOP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);15
16
16
#[derive(Clone, Debug, PartialEq, Eq)]17
#[derive(Clone, Debug, PartialEq, Eq)]17
pub enum RunUpdate {18
pub enum RunUpdate {@@ -50,6 +51,18 @@ fn command_for(invocation: &Invocation) -> Command {50
command51
command51
}52
}52
53
54
#[cfg(windows)]55
fn taskkill_tree(process_id: u32) -> Invocation {56
Invocation {57
program: "taskkill".to_string(),58
args: ["/PID", &process_id.to_string(), "/T", "/F"]59
.map(String::from)60
.to_vec(),61
cwd: None,62
stdin: None,63
}64
}65
53
fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) -> RunOutcome {66
fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) -> RunOutcome {54
RunOutcome {67
RunOutcome {55
status: RunStatus::Failed {68
status: RunStatus::Failed {@@ -61,13 +74,19 @@ fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) ->61
}74
}62
75
63
pub async fn run_stop_invocation(invocation: &Invocation) {76
pub async fn run_stop_invocation(invocation: &Invocation) {77
run_stop_invocation_within(invocation, STOP_TIMEOUT).await;78
}79
80
pub async fn run_stop_invocation_within(invocation: &Invocation, limit: std::time::Duration) {64
let mut command = command_for(invocation);81
let mut command = command_for(invocation);65
command82
command66
.stdin(Stdio::null())83
.stdin(Stdio::null())67
.stdout(Stdio::null())84
.stdout(Stdio::null())68
.stderr(Stdio::null());85
.stderr(Stdio::null());69
if let Ok(mut child) = command.spawn() {86
if let Ok(mut child) = command.spawn()70
let _ = child.wait().await;87
&& tokio::time::timeout(limit, child.wait()).await.is_err()88
{89
let _ = child.kill().await;71
}90
}72
}91
}73
92
@@ -173,6 +192,10 @@ async fn run_plan(173
tokio::select! {192
tokio::select! {174
stop_result = &mut stop, if stop_armed => {193
stop_result = &mut stop, if stop_armed => {175
if stop_result.is_ok() {194
if stop_result.is_ok() {195
#[cfg(windows)]196
if let Some(process_id) = child.id() {197
run_stop_invocation(&taskkill_tree(process_id)).await;198
}176
let _ = child.kill().await;199
let _ = child.kill().await;177
if let Some(stop_invocation) = &plan.stop {200
if let Some(stop_invocation) = &plan.stop {178
run_stop_invocation(stop_invocation).await;201
run_stop_invocation(stop_invocation).await;@@ -0,0 +1,538 @@
1
use std::collections::{HashMap, HashSet};
2
use std::fs::File;
3
use std::io::{BufRead, BufReader, Read};
4
use std::path::{Path, PathBuf};
5
use std::time::SystemTime;
6
7
const TITLE_READ_LIMIT: u64 = 1024 * 1024;
8
const PROJECT_DIR_NAME_LIMIT: usize = 200;
9
10
#[derive(Clone, Debug, PartialEq, Eq)]
11
pub struct ExternalSession {
12
pub session_id: String,
13
pub title: String,
14
pub modified: SystemTime,
15
pub live: bool,
16
}
17
18
pub fn encode_project_dir(working_dir: &str) -> String {
19
working_dir
20
.chars()
21
.map(|character| {
22
if character.is_ascii_alphanumeric() {
23
character
24
} else {
25
'-'
26
}
27
})
28
.collect()
29
}
30
31
pub fn resolve_project_dir(projects_dir: &Path, working_dir: &str) -> PathBuf {
32
let trimmed = working_dir.trim_end_matches(['/', '\\']);
33
let encoded = encode_project_dir(if trimmed.is_empty() {
34
working_dir
35
} else {
36
trimmed
37
});
38
let exact = projects_dir.join(&encoded);
39
if exact.exists() || encoded.len() <= PROJECT_DIR_NAME_LIMIT {
40
return exact;
41
}
42
let prefix = &encoded[..PROJECT_DIR_NAME_LIMIT];
43
std::fs::read_dir(projects_dir)
44
.into_iter()
45
.flatten()
46
.flatten()
47
.find(|entry| entry.file_name().to_string_lossy().starts_with(prefix))
48
.map_or(exact, |entry| entry.path())
49
}
50
51
fn proc_root(sessions_dir: &Path) -> Option<PathBuf> {
52
let text = sessions_dir.to_string_lossy();
53
let unc = text
54
.strip_prefix(r"\\wsl.localhost\")
55
.or_else(|| text.strip_prefix(r"\\wsl$\"));
56
match unc {
57
Some(rest) => {
58
let distro = rest.split('\\').next()?;
59
let prefix = &text[..text.len() - rest.len()];
60
Some(PathBuf::from(format!("{prefix}{distro}\\proc")))
61
}
62
None if cfg!(unix) => Some(PathBuf::from("/proc")),
63
None => None,
64
}
65
}
66
67
pub fn live_session_names(sessions_dir: &Path) -> HashMap<String, Option<String>> {
68
live_session_names_in(sessions_dir, proc_root(sessions_dir).as_deref())
69
}
70
71
fn live_session_names_in(
72
sessions_dir: &Path,
73
proc_root: Option<&Path>,
74
) -> HashMap<String, Option<String>> {
75
let Ok(entries) = std::fs::read_dir(sessions_dir) else {
76
return HashMap::new();
77
};
78
let checkable_root = proc_root.filter(|root| root.is_dir());
79
entries
80
.flatten()
81
.filter(|entry| {
82
let path = entry.path();
83
path.extension()
84
.is_some_and(|extension| extension == "json")
85
&& checkable_root
86
.is_none_or(|root| path.file_stem().is_some_and(|pid| root.join(pid).exists()))
87
})
88
.filter_map(|entry| {
89
let value: serde_json::Value =
90
serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;
91
let session_id = value["sessionId"].as_str()?.to_owned();
92
let name = value["name"]
93
.as_str()
94
.map(str::trim)
95
.filter(|name| !name.is_empty())
96
.map(str::to_owned);
97
Some((session_id, name))
98
})
99
.collect()
100
}
101
102
fn is_session_file_stem(stem: &str) -> bool {
103
stem.len() == 36
104
&& stem.char_indices().all(|(index, character)| {
105
if matches!(index, 8 | 13 | 18 | 23) {
106
character == '-'
107
} else {
108
character.is_ascii_hexdigit()
109
}
110
})
111
}
112
113
fn is_lone_tag(line: &str) -> bool {
114
let Some(inner) = line
115
.strip_prefix('<')
116
.and_then(|rest| rest.strip_suffix('>'))
117
else {
118
return false;
119
};
120
let inner = inner.strip_prefix('/').unwrap_or(inner);
121
let (name, attributes) = inner.split_once(' ').unwrap_or((inner, ""));
122
!name.is_empty()
123
&& name
124
.chars()
125
.all(|character| character.is_ascii_lowercase() || character == '_' || character == '-')
126
&& !attributes.contains('>')
127
}
128
129
fn open_tag_name(line: &str) -> Option<&str> {
130
let rest = line.strip_prefix('<')?;
131
let name_end = rest
132
.find(|character: char| {
133
!(character.is_ascii_lowercase() || character == '_' || character == '-')
134
})
135
.unwrap_or(rest.len());
136
let (name, after) = rest.split_at(name_end);
137
(!name.is_empty() && after.starts_with(['>', ' '])).then_some(name)
138
}
139
140
fn plain_line(text: &str) -> Option<String> {
141
let lines: Vec<&str> = text.lines().map(str::trim).collect();
142
let mut index = 0;
143
while index < lines.len() {
144
let line = lines[index];
145
if line.is_empty() {
146
index += 1;
147
continue;
148
}
149
let closing = open_tag_name(line).and_then(|name| {
150
let close = format!("</{name}>");
151
lines[index..]
152
.iter()
153
.enumerate()
154
.position(|(offset, later)| {
155
if offset == 0 {
156
later.ends_with(&close)
157
} else {
158
later.contains(&close)
159
}
160
})
161
});
162
if let Some(offset) = closing {
163
index += offset + 1;
164
} else if is_lone_tag(line) {
165
index += 1;
166
} else {
167
return Some(line.to_owned());
168
}
169
}
170
None
171
}
172
173
fn text_parts(content: &serde_json::Value) -> Vec<&str> {
174
match content {
175
serde_json::Value::String(text) => vec![text],
176
serde_json::Value::Array(parts) => parts
177
.iter()
178
.filter(|part| part["type"] == "text")
179
.filter_map(|part| part["text"].as_str())
180
.collect(),
181
_ => Vec::new(),
182
}
183
}
184
185
fn first_user_message(path: &Path) -> Option<String> {
186
let mut reader = BufReader::new(File::open(path).ok()?.take(TITLE_READ_LIMIT));
187
let mut line = Vec::new();
188
loop {
189
line.clear();
190
if reader.read_until(b'\n', &mut line).ok()? == 0 {
191
return None;
192
}
193
let Ok(entry) = serde_json::from_slice::<serde_json::Value>(&line) else {
194
continue;
195
};
196
if entry["type"] != "user" || entry["isMeta"] == true {
197
continue;
198
}
199
if let Some(title) = text_parts(&entry["message"]["content"])
200
.into_iter()
201
.find_map(plain_line)
202
{
203
return Some(title);
204
}
205
}
206
}
207
208
pub fn scan_external_sessions(
209
project_dir: &Path,
210
live_sessions: &HashMap<String, Option<String>>,
211
known_session_ids: &HashSet<String>,
212
limit: usize,
213
) -> Vec<ExternalSession> {
214
let Ok(entries) = std::fs::read_dir(project_dir) else {
215
return Vec::new();
216
};
217
let mut files: Vec<(String, SystemTime)> = entries
218
.flatten()
219
.filter_map(|entry| {
220
let path = entry.path();
221
if path.extension()? != "jsonl" {
222
return None;
223
}
224
let session_id = path.file_stem()?.to_str()?.to_owned();
225
if !is_session_file_stem(&session_id) {
226
return None;
227
}
228
let modified = entry.metadata().ok()?.modified().ok()?;
229
(!known_session_ids.contains(&session_id)).then_some((session_id, modified))
230
})
231
.collect();
232
files.sort_by(|left, right| right.1.cmp(&left.1));
233
files
234
.into_iter()
235
.filter_map(|(session_id, modified)| {
236
let live_name = live_sessions.get(&session_id);
237
let title = live_name
238
.cloned()
239
.flatten()
240
.or_else(|| first_user_message(&project_dir.join(format!("{session_id}.jsonl"))))?;
241
Some(ExternalSession {
242
live: live_name.is_some(),
243
session_id,
244
title,
245
modified,
246
})
247
})
248
.take(limit)
249
.collect()
250
}
251
252
#[cfg(test)]
253
mod tests {
254
use std::time::Duration;
255
256
use super::*;
257
258
const PLAIN: &str =
259
r#"{"type":"user","message":{"role":"user","content":"Fix the build\nplease"}}"#;
260
261
fn id(number: u32) -> String {
262
format!("00000000-0000-0000-0000-{number:012}")
263
}
264
265
fn user_line(content: &str) -> String {
266
serde_json::json!({"type": "user", "message": {"role": "user", "content": content}})
267
.to_string()
268
}
269
270
fn write_session(directory: &Path, session_id: &str, body: &str, age: Duration) {
271
let path = directory.join(format!("{session_id}.jsonl"));
272
std::fs::write(&path, body).unwrap();
273
File::options()
274
.write(true)
275
.open(&path)
276
.unwrap()
277
.set_modified(SystemTime::now() - age)
278
.unwrap();
279
}
280
281
fn scan(directory: &Path, limit: usize) -> Vec<ExternalSession> {
282
scan_external_sessions(directory, &HashMap::new(), &HashSet::new(), limit)
283
}
284
285
#[test]
286
fn encoding_replaces_every_non_alphanumeric_character() {
287
assert_eq!(
288
encode_project_dir("/home/daniel/Projects/ms-teams-linux"),
289
"-home-daniel-Projects-ms-teams-linux"
290
);
291
assert_eq!(
292
encode_project_dir("/home/daniel/repo/.claude/worktrees/x_y"),
293
"-home-daniel-repo--claude-worktrees-x-y"
294
);
295
assert_eq!(encode_project_dir(r"C:\Users\dd"), "C--Users-dd");
296
}
297
298
#[test]
299
fn trailing_separators_are_dropped_before_encoding() {
300
let projects = tempfile::tempdir().unwrap();
301
for working_dir in ["/home/x/repo/", "/home/x/repo", r"C:\x\repo\"] {
302
let resolved = resolve_project_dir(projects.path(), working_dir);
303
assert!(!resolved.to_string_lossy().ends_with("--"));
304
}
305
assert_eq!(
306
resolve_project_dir(projects.path(), "/home/x/repo/"),
307
projects.path().join("-home-x-repo")
308
);
309
assert_eq!(
310
resolve_project_dir(projects.path(), "/"),
311
projects.path().join("-")
312
);
313
}
314
315
#[test]
316
fn a_long_working_dir_falls_back_to_the_prefix_folder() {
317
let projects = tempfile::tempdir().unwrap();
318
let long_dir = format!("/home/daniel/{}", "deep/".repeat(45));
319
let encoded = encode_project_dir(long_dir.trim_end_matches('/'));
320
assert!(encoded.len() > PROJECT_DIR_NAME_LIMIT);
321
let truncated = projects
322
.path()
323
.join(format!("{}-abc123", &encoded[..PROJECT_DIR_NAME_LIMIT]));
324
std::fs::create_dir(&truncated).unwrap();
325
assert_eq!(resolve_project_dir(projects.path(), &long_dir), truncated);
326
std::fs::create_dir(projects.path().join(&encoded)).unwrap();
327
assert_eq!(
328
resolve_project_dir(projects.path(), &long_dir),
329
projects.path().join(&encoded)
330
);
331
assert_eq!(
332
resolve_project_dir(projects.path(), "/short"),
333
projects.path().join("-short")
334
);
335
}
336
337
#[test]
338
fn scan_takes_titles_from_the_first_plain_user_line_and_skips_known_ids() {
339
let directory = tempfile::tempdir().unwrap();
340
let meta = r#"{"type":"user","isMeta":true,"message":{"role":"user","content":"meta"}}"#;
341
let command = user_line("<command-name>/clear</command-name>");
342
let assistant = r#"{"type":"assistant","message":{"role":"assistant","content":"hi"}}"#;
343
let tagged = user_line("<pasted_content id=\"1\">\n<system-reminder>\nReal question here");
344
let parts = r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"x"},{"type":"text","text":"Parts title"}]}}"#;
345
write_session(
346
directory.path(),
347
&id(1),
348
&format!("{meta}\n{command}\n{assistant}\n{PLAIN}\n"),
349
Duration::from_secs(60),
350
);
351
write_session(
352
directory.path(),
353
&id(2),
354
&format!("{tagged}\n"),
355
Duration::from_secs(120),
356
);
357
write_session(
358
directory.path(),
359
&id(3),
360
&format!("not json\n{parts}\n"),
361
Duration::from_secs(3600),
362
);
363
write_session(directory.path(), &id(4), "", Duration::from_secs(7200));
364
write_session(
365
directory.path(),
366
&id(5),
367
assistant,
368
Duration::from_secs(7300),
369
);
370
write_session(directory.path(), &id(6), PLAIN, Duration::from_secs(10));
371
write_session(
372
directory.path(),
373
"agent-notes",
374
PLAIN,
375
Duration::from_secs(5),
376
);
377
std::fs::write(directory.path().join("notes.txt"), "x").unwrap();
378
let known = HashSet::from([id(6)]);
379
let sessions = scan_external_sessions(directory.path(), &HashMap::new(), &known, 10);
380
let summary: Vec<(String, &str)> = sessions
381
.iter()
382
.map(|session| (session.session_id.clone(), session.title.as_str()))
383
.collect();
384
assert_eq!(
385
summary,
386
[
387
(id(1), "Fix the build"),
388
(id(2), "Real question here"),
389
(id(3), "Parts title"),
390
]
391
);
392
assert!(sessions.iter().all(|session| !session.live));
393
let age = SystemTime::now()
394
.duration_since(sessions[0].modified)
395
.unwrap();
396
assert!(age >= Duration::from_secs(60) && age < Duration::from_secs(120));
397
}
398
399
#[test]
400
fn enclosed_blocks_are_skipped_across_lines_and_parts() {
401
assert_eq!(
402
plain_line("<system-reminder>\nIDE note\nmore\n</system-reminder>\nFix it").as_deref(),
403
Some("Fix it")
404
);
405
assert_eq!(
406
plain_line("<ide_opened_file>The user opened a.rs</ide_opened_file>"),
407
None
408
);
409
assert_eq!(
410
plain_line("<b>bold</b> text").as_deref(),
411
Some("<b>bold</b> text")
412
);
413
let directory = tempfile::tempdir().unwrap();
414
let body = serde_json::json!({"type": "user", "message": {"role": "user", "content": [
415
{"type": "text", "text": "<ide_opened_file>The user opened a.rs</ide_opened_file>"},
416
{"type": "text", "text": "<ide_selection>\nlet x = 1;\n</ide_selection>"},
417
{"type": "text", "text": "Refactor this"}
418
]}})
419
.to_string();
420
write_session(directory.path(), &id(1), &body, Duration::ZERO);
421
assert_eq!(scan(directory.path(), 1)[0].title, "Refactor this");
422
}
423
424
#[test]
425
fn lone_tags_are_recognised() {
426
assert!(is_lone_tag("<system-reminder>"));
427
assert!(is_lone_tag("</system-reminder>"));
428
assert!(is_lone_tag(r#"<pasted_content id="1" size="9">"#));
429
assert!(!is_lone_tag("<b>bold</b> text"));
430
assert!(!is_lone_tag("a < b > c"));
431
assert!(!is_lone_tag("<>"));
432
}
433
434
#[test]
435
fn a_title_past_the_first_user_line_is_still_found_and_the_read_is_capped() {
436
let directory = tempfile::tempdir().unwrap();
437
let filler = r#"{"type":"assistant","message":{"role":"assistant","content":"x"}}"#;
438
let body = format!("{}\n{PLAIN}\n", vec![filler; 2000].join("\n"));
439
assert!(body.len() as u64 > 64 * 1024);
440
write_session(directory.path(), &id(1), &body, Duration::ZERO);
441
assert_eq!(scan(directory.path(), 1)[0].title, "Fix the build");
442
let late = format!("{}\n{PLAIN}\n", " ".repeat(TITLE_READ_LIMIT as usize));
443
write_session(directory.path(), &id(2), &late, Duration::ZERO);
444
let found: Vec<String> = scan(directory.path(), 10)
445
.into_iter()
446
.map(|session| session.session_id)
447
.collect();
448
assert_eq!(found, [id(1)]);
449
}
450
451
#[test]
452
fn scan_keeps_the_newest_ten() {
453
let directory = tempfile::tempdir().unwrap();
454
for index in 0..12u32 {
455
write_session(
456
directory.path(),
457
&id(index),
458
PLAIN,
459
Duration::from_secs(u64::from(index) * 100),
460
);
461
}
462
let sessions = scan(directory.path(), 10);
463
assert_eq!(sessions.len(), 10);
464
assert_eq!(sessions[0].session_id, id(0));
465
assert_eq!(sessions[9].session_id, id(9));
466
}
467
468
#[test]
469
fn live_sessions_need_a_running_pid_and_use_their_name_as_title() {
470
let sessions_dir = tempfile::tempdir().unwrap();
471
let proc_root = tempfile::tempdir().unwrap();
472
std::fs::create_dir(proc_root.path().join("111")).unwrap();
473
std::fs::create_dir(proc_root.path().join("222")).unwrap();
474
let file = |pid: u32, session_id: &str, name: &str| {
475
std::fs::write(
476
sessions_dir.path().join(format!("{pid}.json")),
477
format!(r#"{{"pid":{pid},"sessionId":"{session_id}","name":"{name}"}}"#),
478
)
479
.unwrap();
480
};
481
file(111, &id(1), "Refactor auth");
482
file(222, &id(2), "");
483
file(333, &id(3), "Dead one");
484
std::fs::write(sessions_dir.path().join("444.json"), "garbage").unwrap();
485
let live = live_session_names_in(sessions_dir.path(), Some(proc_root.path()));
486
assert_eq!(live.len(), 2);
487
assert!(!live.contains_key(&id(3)));
488
assert_eq!(
489
live_session_names_in(sessions_dir.path(), Some(Path::new("/nonexistent"))).len(),
490
3
491
);
492
let directory = tempfile::tempdir().unwrap();
493
write_session(directory.path(), &id(1), PLAIN, Duration::from_secs(5000));
494
write_session(directory.path(), &id(2), PLAIN, Duration::from_secs(6000));
495
write_session(directory.path(), &id(7), PLAIN, Duration::from_secs(7000));
496
let sessions = scan_external_sessions(directory.path(), &live, &HashSet::new(), 10);
497
let summary: Vec<(String, &str, bool)> = sessions
498
.iter()
499
.map(|session| {
500
(
501
session.session_id.clone(),
502
session.title.as_str(),
503
session.live,
504
)
505
})
506
.collect();
507
assert_eq!(
508
summary,
509
[
510
(id(1), "Refactor auth", true),
511
(id(2), "Fix the build", true),
512
(id(7), "Fix the build", false),
513
]
514
);
515
assert!(live_session_names(Path::new("/nonexistent")).is_empty());
516
}
517
518
#[test]
519
fn the_proc_root_follows_the_environment_of_the_sessions_dir() {
520
assert_eq!(
521
proc_root(Path::new(r"\\wsl.localhost\Ubuntu\home\x\.claude\sessions")),
522
Some(PathBuf::from(r"\\wsl.localhost\Ubuntu\proc"))
523
);
524
assert_eq!(
525
proc_root(Path::new(r"\\wsl$\Debian\home\x")),
526
Some(PathBuf::from(r"\\wsl$\Debian\proc"))
527
);
528
assert_eq!(
529
proc_root(Path::new("/home/x/.claude/sessions")),
530
cfg!(unix).then(|| PathBuf::from("/proc"))
531
);
532
}
533
534
#[test]
535
fn a_missing_directory_yields_no_sessions() {
536
assert!(scan(Path::new("/nonexistent/projects"), 10).is_empty());
537
}
538
}
@@ -0,0 +1,538 @@1
use std::collections::{HashMap, HashSet};2
use std::fs::File;3
use std::io::{BufRead, BufReader, Read};4
use std::path::{Path, PathBuf};5
use std::time::SystemTime;6
7
const TITLE_READ_LIMIT: u64 = 1024 * 1024;8
const PROJECT_DIR_NAME_LIMIT: usize = 200;9
10
#[derive(Clone, Debug, PartialEq, Eq)]11
pub struct ExternalSession {12
pub session_id: String,13
pub title: String,14
pub modified: SystemTime,15
pub live: bool,16
}17
18
pub fn encode_project_dir(working_dir: &str) -> String {19
working_dir20
.chars()21
.map(|character| {22
if character.is_ascii_alphanumeric() {23
character24
} else {25
'-'26
}27
})28
.collect()29
}30
31
pub fn resolve_project_dir(projects_dir: &Path, working_dir: &str) -> PathBuf {32
let trimmed = working_dir.trim_end_matches(['/', '\\']);33
let encoded = encode_project_dir(if trimmed.is_empty() {34
working_dir35
} else {36
trimmed37
});38
let exact = projects_dir.join(&encoded);39
if exact.exists() || encoded.len() <= PROJECT_DIR_NAME_LIMIT {40
return exact;41
}42
let prefix = &encoded[..PROJECT_DIR_NAME_LIMIT];43
std::fs::read_dir(projects_dir)44
.into_iter()45
.flatten()46
.flatten()47
.find(|entry| entry.file_name().to_string_lossy().starts_with(prefix))48
.map_or(exact, |entry| entry.path())49
}50
51
fn proc_root(sessions_dir: &Path) -> Option<PathBuf> {52
let text = sessions_dir.to_string_lossy();53
let unc = text54
.strip_prefix(r"\\wsl.localhost\")55
.or_else(|| text.strip_prefix(r"\\wsl$\"));56
match unc {57
Some(rest) => {58
let distro = rest.split('\\').next()?;59
let prefix = &text[..text.len() - rest.len()];60
Some(PathBuf::from(format!("{prefix}{distro}\\proc")))61
}62
None if cfg!(unix) => Some(PathBuf::from("/proc")),63
None => None,64
}65
}66
67
pub fn live_session_names(sessions_dir: &Path) -> HashMap<String, Option<String>> {68
live_session_names_in(sessions_dir, proc_root(sessions_dir).as_deref())69
}70
71
fn live_session_names_in(72
sessions_dir: &Path,73
proc_root: Option<&Path>,74
) -> HashMap<String, Option<String>> {75
let Ok(entries) = std::fs::read_dir(sessions_dir) else {76
return HashMap::new();77
};78
let checkable_root = proc_root.filter(|root| root.is_dir());79
entries80
.flatten()81
.filter(|entry| {82
let path = entry.path();83
path.extension()84
.is_some_and(|extension| extension == "json")85
&& checkable_root86
.is_none_or(|root| path.file_stem().is_some_and(|pid| root.join(pid).exists()))87
})88
.filter_map(|entry| {89
let value: serde_json::Value =90
serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;91
let session_id = value["sessionId"].as_str()?.to_owned();92
let name = value["name"]93
.as_str()94
.map(str::trim)95
.filter(|name| !name.is_empty())96
.map(str::to_owned);97
Some((session_id, name))98
})99
.collect()100
}101
102
fn is_session_file_stem(stem: &str) -> bool {103
stem.len() == 36104
&& stem.char_indices().all(|(index, character)| {105
if matches!(index, 8 | 13 | 18 | 23) {106
character == '-'107
} else {108
character.is_ascii_hexdigit()109
}110
})111
}112
113
fn is_lone_tag(line: &str) -> bool {114
let Some(inner) = line115
.strip_prefix('<')116
.and_then(|rest| rest.strip_suffix('>'))117
else {118
return false;119
};120
let inner = inner.strip_prefix('/').unwrap_or(inner);121
let (name, attributes) = inner.split_once(' ').unwrap_or((inner, ""));122
!name.is_empty()123
&& name124
.chars()125
.all(|character| character.is_ascii_lowercase() || character == '_' || character == '-')126
&& !attributes.contains('>')127
}128
129
fn open_tag_name(line: &str) -> Option<&str> {130
let rest = line.strip_prefix('<')?;131
let name_end = rest132
.find(|character: char| {133
!(character.is_ascii_lowercase() || character == '_' || character == '-')134
})135
.unwrap_or(rest.len());136
let (name, after) = rest.split_at(name_end);137
(!name.is_empty() && after.starts_with(['>', ' '])).then_some(name)138
}139
140
fn plain_line(text: &str) -> Option<String> {141
let lines: Vec<&str> = text.lines().map(str::trim).collect();142
let mut index = 0;143
while index < lines.len() {144
let line = lines[index];145
if line.is_empty() {146
index += 1;147
continue;148
}149
let closing = open_tag_name(line).and_then(|name| {150
let close = format!("</{name}>");151
lines[index..]152
.iter()153
.enumerate()154
.position(|(offset, later)| {155
if offset == 0 {156
later.ends_with(&close)157
} else {158
later.contains(&close)159
}160
})161
});162
if let Some(offset) = closing {163
index += offset + 1;164
} else if is_lone_tag(line) {165
index += 1;166
} else {167
return Some(line.to_owned());168
}169
}170
None171
}172
173
fn text_parts(content: &serde_json::Value) -> Vec<&str> {174
match content {175
serde_json::Value::String(text) => vec![text],176
serde_json::Value::Array(parts) => parts177
.iter()178
.filter(|part| part["type"] == "text")179
.filter_map(|part| part["text"].as_str())180
.collect(),181
_ => Vec::new(),182
}183
}184
185
fn first_user_message(path: &Path) -> Option<String> {186
let mut reader = BufReader::new(File::open(path).ok()?.take(TITLE_READ_LIMIT));187
let mut line = Vec::new();188
loop {189
line.clear();190
if reader.read_until(b'\n', &mut line).ok()? == 0 {191
return None;192
}193
let Ok(entry) = serde_json::from_slice::<serde_json::Value>(&line) else {194
continue;195
};196
if entry["type"] != "user" || entry["isMeta"] == true {197
continue;198
}199
if let Some(title) = text_parts(&entry["message"]["content"])200
.into_iter()201
.find_map(plain_line)202
{203
return Some(title);204
}205
}206
}207
208
pub fn scan_external_sessions(209
project_dir: &Path,210
live_sessions: &HashMap<String, Option<String>>,211
known_session_ids: &HashSet<String>,212
limit: usize,213
) -> Vec<ExternalSession> {214
let Ok(entries) = std::fs::read_dir(project_dir) else {215
return Vec::new();216
};217
let mut files: Vec<(String, SystemTime)> = entries218
.flatten()219
.filter_map(|entry| {220
let path = entry.path();221
if path.extension()? != "jsonl" {222
return None;223
}224
let session_id = path.file_stem()?.to_str()?.to_owned();225
if !is_session_file_stem(&session_id) {226
return None;227
}228
let modified = entry.metadata().ok()?.modified().ok()?;229
(!known_session_ids.contains(&session_id)).then_some((session_id, modified))230
})231
.collect();232
files.sort_by(|left, right| right.1.cmp(&left.1));233
files234
.into_iter()235
.filter_map(|(session_id, modified)| {236
let live_name = live_sessions.get(&session_id);237
let title = live_name238
.cloned()239
.flatten()240
.or_else(|| first_user_message(&project_dir.join(format!("{session_id}.jsonl"))))?;241
Some(ExternalSession {242
live: live_name.is_some(),243
session_id,244
title,245
modified,246
})247
})248
.take(limit)249
.collect()250
}251
252
#[cfg(test)]253
mod tests {254
use std::time::Duration;255
256
use super::*;257
258
const PLAIN: &str =259
r#"{"type":"user","message":{"role":"user","content":"Fix the build\nplease"}}"#;260
261
fn id(number: u32) -> String {262
format!("00000000-0000-0000-0000-{number:012}")263
}264
265
fn user_line(content: &str) -> String {266
serde_json::json!({"type": "user", "message": {"role": "user", "content": content}})267
.to_string()268
}269
270
fn write_session(directory: &Path, session_id: &str, body: &str, age: Duration) {271
let path = directory.join(format!("{session_id}.jsonl"));272
std::fs::write(&path, body).unwrap();273
File::options()274
.write(true)275
.open(&path)276
.unwrap()277
.set_modified(SystemTime::now() - age)278
.unwrap();279
}280
281
fn scan(directory: &Path, limit: usize) -> Vec<ExternalSession> {282
scan_external_sessions(directory, &HashMap::new(), &HashSet::new(), limit)283
}284
285
#[test]286
fn encoding_replaces_every_non_alphanumeric_character() {287
assert_eq!(288
encode_project_dir("/home/daniel/Projects/ms-teams-linux"),289
"-home-daniel-Projects-ms-teams-linux"290
);291
assert_eq!(292
encode_project_dir("/home/daniel/repo/.claude/worktrees/x_y"),293
"-home-daniel-repo--claude-worktrees-x-y"294
);295
assert_eq!(encode_project_dir(r"C:\Users\dd"), "C--Users-dd");296
}297
298
#[test]299
fn trailing_separators_are_dropped_before_encoding() {300
let projects = tempfile::tempdir().unwrap();301
for working_dir in ["/home/x/repo/", "/home/x/repo", r"C:\x\repo\"] {302
let resolved = resolve_project_dir(projects.path(), working_dir);303
assert!(!resolved.to_string_lossy().ends_with("--"));304
}305
assert_eq!(306
resolve_project_dir(projects.path(), "/home/x/repo/"),307
projects.path().join("-home-x-repo")308
);309
assert_eq!(310
resolve_project_dir(projects.path(), "/"),311
projects.path().join("-")312
);313
}314
315
#[test]316
fn a_long_working_dir_falls_back_to_the_prefix_folder() {317
let projects = tempfile::tempdir().unwrap();318
let long_dir = format!("/home/daniel/{}", "deep/".repeat(45));319
let encoded = encode_project_dir(long_dir.trim_end_matches('/'));320
assert!(encoded.len() > PROJECT_DIR_NAME_LIMIT);321
let truncated = projects322
.path()323
.join(format!("{}-abc123", &encoded[..PROJECT_DIR_NAME_LIMIT]));324
std::fs::create_dir(&truncated).unwrap();325
assert_eq!(resolve_project_dir(projects.path(), &long_dir), truncated);326
std::fs::create_dir(projects.path().join(&encoded)).unwrap();327
assert_eq!(328
resolve_project_dir(projects.path(), &long_dir),329
projects.path().join(&encoded)330
);331
assert_eq!(332
resolve_project_dir(projects.path(), "/short"),333
projects.path().join("-short")334
);335
}336
337
#[test]338
fn scan_takes_titles_from_the_first_plain_user_line_and_skips_known_ids() {339
let directory = tempfile::tempdir().unwrap();340
let meta = r#"{"type":"user","isMeta":true,"message":{"role":"user","content":"meta"}}"#;341
let command = user_line("<command-name>/clear</command-name>");342
let assistant = r#"{"type":"assistant","message":{"role":"assistant","content":"hi"}}"#;343
let tagged = user_line("<pasted_content id=\"1\">\n<system-reminder>\nReal question here");344
let parts = r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"x"},{"type":"text","text":"Parts title"}]}}"#;345
write_session(346
directory.path(),347
&id(1),348
&format!("{meta}\n{command}\n{assistant}\n{PLAIN}\n"),349
Duration::from_secs(60),350
);351
write_session(352
directory.path(),353
&id(2),354
&format!("{tagged}\n"),355
Duration::from_secs(120),356
);357
write_session(358
directory.path(),359
&id(3),360
&format!("not json\n{parts}\n"),361
Duration::from_secs(3600),362
);363
write_session(directory.path(), &id(4), "", Duration::from_secs(7200));364
write_session(365
directory.path(),366
&id(5),367
assistant,368
Duration::from_secs(7300),369
);370
write_session(directory.path(), &id(6), PLAIN, Duration::from_secs(10));371
write_session(372
directory.path(),373
"agent-notes",374
PLAIN,375
Duration::from_secs(5),376
);377
std::fs::write(directory.path().join("notes.txt"), "x").unwrap();378
let known = HashSet::from([id(6)]);379
let sessions = scan_external_sessions(directory.path(), &HashMap::new(), &known, 10);380
let summary: Vec<(String, &str)> = sessions381
.iter()382
.map(|session| (session.session_id.clone(), session.title.as_str()))383
.collect();384
assert_eq!(385
summary,386
[387
(id(1), "Fix the build"),388
(id(2), "Real question here"),389
(id(3), "Parts title"),390
]391
);392
assert!(sessions.iter().all(|session| !session.live));393
let age = SystemTime::now()394
.duration_since(sessions[0].modified)395
.unwrap();396
assert!(age >= Duration::from_secs(60) && age < Duration::from_secs(120));397
}398
399
#[test]400
fn enclosed_blocks_are_skipped_across_lines_and_parts() {401
assert_eq!(402
plain_line("<system-reminder>\nIDE note\nmore\n</system-reminder>\nFix it").as_deref(),403
Some("Fix it")404
);405
assert_eq!(406
plain_line("<ide_opened_file>The user opened a.rs</ide_opened_file>"),407
None408
);409
assert_eq!(410
plain_line("<b>bold</b> text").as_deref(),411
Some("<b>bold</b> text")412
);413
let directory = tempfile::tempdir().unwrap();414
let body = serde_json::json!({"type": "user", "message": {"role": "user", "content": [415
{"type": "text", "text": "<ide_opened_file>The user opened a.rs</ide_opened_file>"},416
{"type": "text", "text": "<ide_selection>\nlet x = 1;\n</ide_selection>"},417
{"type": "text", "text": "Refactor this"}418
]}})419
.to_string();420
write_session(directory.path(), &id(1), &body, Duration::ZERO);421
assert_eq!(scan(directory.path(), 1)[0].title, "Refactor this");422
}423
424
#[test]425
fn lone_tags_are_recognised() {426
assert!(is_lone_tag("<system-reminder>"));427
assert!(is_lone_tag("</system-reminder>"));428
assert!(is_lone_tag(r#"<pasted_content id="1" size="9">"#));429
assert!(!is_lone_tag("<b>bold</b> text"));430
assert!(!is_lone_tag("a < b > c"));431
assert!(!is_lone_tag("<>"));432
}433
434
#[test]435
fn a_title_past_the_first_user_line_is_still_found_and_the_read_is_capped() {436
let directory = tempfile::tempdir().unwrap();437
let filler = r#"{"type":"assistant","message":{"role":"assistant","content":"x"}}"#;438
let body = format!("{}\n{PLAIN}\n", vec![filler; 2000].join("\n"));439
assert!(body.len() as u64 > 64 * 1024);440
write_session(directory.path(), &id(1), &body, Duration::ZERO);441
assert_eq!(scan(directory.path(), 1)[0].title, "Fix the build");442
let late = format!("{}\n{PLAIN}\n", " ".repeat(TITLE_READ_LIMIT as usize));443
write_session(directory.path(), &id(2), &late, Duration::ZERO);444
let found: Vec<String> = scan(directory.path(), 10)445
.into_iter()446
.map(|session| session.session_id)447
.collect();448
assert_eq!(found, [id(1)]);449
}450
451
#[test]452
fn scan_keeps_the_newest_ten() {453
let directory = tempfile::tempdir().unwrap();454
for index in 0..12u32 {455
write_session(456
directory.path(),457
&id(index),458
PLAIN,459
Duration::from_secs(u64::from(index) * 100),460
);461
}462
let sessions = scan(directory.path(), 10);463
assert_eq!(sessions.len(), 10);464
assert_eq!(sessions[0].session_id, id(0));465
assert_eq!(sessions[9].session_id, id(9));466
}467
468
#[test]469
fn live_sessions_need_a_running_pid_and_use_their_name_as_title() {470
let sessions_dir = tempfile::tempdir().unwrap();471
let proc_root = tempfile::tempdir().unwrap();472
std::fs::create_dir(proc_root.path().join("111")).unwrap();473
std::fs::create_dir(proc_root.path().join("222")).unwrap();474
let file = |pid: u32, session_id: &str, name: &str| {475
std::fs::write(476
sessions_dir.path().join(format!("{pid}.json")),477
format!(r#"{{"pid":{pid},"sessionId":"{session_id}","name":"{name}"}}"#),478
)479
.unwrap();480
};481
file(111, &id(1), "Refactor auth");482
file(222, &id(2), "");483
file(333, &id(3), "Dead one");484
std::fs::write(sessions_dir.path().join("444.json"), "garbage").unwrap();485
let live = live_session_names_in(sessions_dir.path(), Some(proc_root.path()));486
assert_eq!(live.len(), 2);487
assert!(!live.contains_key(&id(3)));488
assert_eq!(489
live_session_names_in(sessions_dir.path(), Some(Path::new("/nonexistent"))).len(),490
3491
);492
let directory = tempfile::tempdir().unwrap();493
write_session(directory.path(), &id(1), PLAIN, Duration::from_secs(5000));494
write_session(directory.path(), &id(2), PLAIN, Duration::from_secs(6000));495
write_session(directory.path(), &id(7), PLAIN, Duration::from_secs(7000));496
let sessions = scan_external_sessions(directory.path(), &live, &HashSet::new(), 10);497
let summary: Vec<(String, &str, bool)> = sessions498
.iter()499
.map(|session| {500
(501
session.session_id.clone(),502
session.title.as_str(),503
session.live,504
)505
})506
.collect();507
assert_eq!(508
summary,509
[510
(id(1), "Refactor auth", true),511
(id(2), "Fix the build", true),512
(id(7), "Fix the build", false),513
]514
);515
assert!(live_session_names(Path::new("/nonexistent")).is_empty());516
}517
518
#[test]519
fn the_proc_root_follows_the_environment_of_the_sessions_dir() {520
assert_eq!(521
proc_root(Path::new(r"\\wsl.localhost\Ubuntu\home\x\.claude\sessions")),522
Some(PathBuf::from(r"\\wsl.localhost\Ubuntu\proc"))523
);524
assert_eq!(525
proc_root(Path::new(r"\\wsl$\Debian\home\x")),526
Some(PathBuf::from(r"\\wsl$\Debian\proc"))527
);528
assert_eq!(529
proc_root(Path::new("/home/x/.claude/sessions")),530
cfg!(unix).then(|| PathBuf::from("/proc"))531
);532
}533
534
#[test]535
fn a_missing_directory_yields_no_sessions() {536
assert!(scan(Path::new("/nonexistent/projects"), 10).is_empty());537
}538
}@@ -1,3 +1,5 @@
1
use std::collections::HashMap;
2
1
3
use serde::{Deserialize, Serialize};
2
4
3
5
use crate::action::AgentAction;
@@ -5,6 +7,7 @@ use crate::profile::AgentProfile;
5
7
use crate::template::{is_known_placeholder, placeholders_in};
6
8
7
9
pub const SETTINGS_KEY: &str = "agents.settings";
10
pub const RECENT_WORKING_DIR_LIMIT: usize = 5;
8
11
9
12
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
10
13
pub enum SettingsProblem {
@@ -25,6 +28,7 @@ pub struct AgentSettings {
25
28
pub agents: Vec<AgentProfile>,
26
29
pub actions: Vec<AgentAction>,
27
30
pub resume_interrupted_runs: bool,
31
pub recent_working_dirs: HashMap<String, Vec<String>>,
28
32
}
29
33
30
34
impl Default for AgentSettings {
@@ -36,6 +40,7 @@ impl Default for AgentSettings {
36
40
AgentAction::build_this("claude"),
37
41
],
38
42
resume_interrupted_runs: true,
43
recent_working_dirs: HashMap::new(),
39
44
}
40
45
}
41
46
}
@@ -66,6 +71,22 @@ impl AgentSettings {
66
71
Ok(settings)
67
72
}
68
73
74
pub fn recent_working_dirs_of(&self, agent_id: &str) -> &[String] {
75
self.recent_working_dirs
76
.get(agent_id)
77
.map_or(&[], Vec::as_slice)
78
}
79
80
pub fn remember_working_dir(&mut self, agent_id: &str, working_dir: &str) {
81
let recent = self
82
.recent_working_dirs
83
.entry(agent_id.to_owned())
84
.or_default();
85
recent.retain(|existing| existing != working_dir);
86
recent.insert(0, working_dir.to_owned());
87
recent.truncate(RECENT_WORKING_DIR_LIMIT);
88
}
89
69
90
pub fn validate(&self) -> Vec<SettingsProblem> {
70
91
let mut problems = Vec::new();
71
92
for agent in &self.agents {
@@ -131,6 +152,30 @@ mod tests {
131
152
);
132
153
}
133
154
155
#[test]
156
fn recent_working_dirs_are_newest_first_deduped_limited_and_per_agent() {
157
let mut settings = AgentSettings::default();
158
assert!(settings.recent_working_dirs_of("claude").is_empty());
159
for index in 0..7 {
160
settings.remember_working_dir("claude", &format!("/repo/{index}"));
161
}
162
settings.remember_working_dir("claude", "/repo/4");
163
settings.remember_working_dir("copilot", "/other");
164
assert_eq!(
165
settings.recent_working_dirs_of("claude"),
166
["/repo/4", "/repo/6", "/repo/5", "/repo/3", "/repo/2"]
167
);
168
assert_eq!(settings.recent_working_dirs_of("copilot"), ["/other"]);
169
let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
170
assert_eq!(loaded, settings);
171
assert!(
172
AgentSettings::from_json("{}")
173
.unwrap()
174
.recent_working_dirs
175
.is_empty()
176
);
177
}
178
134
179
#[test]
135
180
fn empty_object_loads_defaults() {
136
181
assert_eq!(
@@ -1,3 +1,5 @@1
use std::collections::HashMap;2
1
use serde::{Deserialize, Serialize};3
use serde::{Deserialize, Serialize};2
4
3
use crate::action::AgentAction;5
use crate::action::AgentAction;@@ -5,6 +7,7 @@ use crate::profile::AgentProfile;5
use crate::template::{is_known_placeholder, placeholders_in};7
use crate::template::{is_known_placeholder, placeholders_in};6
8
7
pub const SETTINGS_KEY: &str = "agents.settings";9
pub const SETTINGS_KEY: &str = "agents.settings";10
pub const RECENT_WORKING_DIR_LIMIT: usize = 5;8
11
9
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]12
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]10
pub enum SettingsProblem {13
pub enum SettingsProblem {@@ -25,6 +28,7 @@ pub struct AgentSettings {25
pub agents: Vec<AgentProfile>,28
pub agents: Vec<AgentProfile>,26
pub actions: Vec<AgentAction>,29
pub actions: Vec<AgentAction>,27
pub resume_interrupted_runs: bool,30
pub resume_interrupted_runs: bool,31
pub recent_working_dirs: HashMap<String, Vec<String>>,28
}32
}29
33
30
impl Default for AgentSettings {34
impl Default for AgentSettings {@@ -36,6 +40,7 @@ impl Default for AgentSettings {36
AgentAction::build_this("claude"),40
AgentAction::build_this("claude"),37
],41
],38
resume_interrupted_runs: true,42
resume_interrupted_runs: true,43
recent_working_dirs: HashMap::new(),39
}44
}40
}45
}41
}46
}@@ -66,6 +71,22 @@ impl AgentSettings {66
Ok(settings)71
Ok(settings)67
}72
}68
73
74
pub fn recent_working_dirs_of(&self, agent_id: &str) -> &[String] {75
self.recent_working_dirs76
.get(agent_id)77
.map_or(&[], Vec::as_slice)78
}79
80
pub fn remember_working_dir(&mut self, agent_id: &str, working_dir: &str) {81
let recent = self82
.recent_working_dirs83
.entry(agent_id.to_owned())84
.or_default();85
recent.retain(|existing| existing != working_dir);86
recent.insert(0, working_dir.to_owned());87
recent.truncate(RECENT_WORKING_DIR_LIMIT);88
}89
69
pub fn validate(&self) -> Vec<SettingsProblem> {90
pub fn validate(&self) -> Vec<SettingsProblem> {70
let mut problems = Vec::new();91
let mut problems = Vec::new();71
for agent in &self.agents {92
for agent in &self.agents {@@ -131,6 +152,30 @@ mod tests {131
);152
);132
}153
}133
154
155
#[test]156
fn recent_working_dirs_are_newest_first_deduped_limited_and_per_agent() {157
let mut settings = AgentSettings::default();158
assert!(settings.recent_working_dirs_of("claude").is_empty());159
for index in 0..7 {160
settings.remember_working_dir("claude", &format!("/repo/{index}"));161
}162
settings.remember_working_dir("claude", "/repo/4");163
settings.remember_working_dir("copilot", "/other");164
assert_eq!(165
settings.recent_working_dirs_of("claude"),166
["/repo/4", "/repo/6", "/repo/5", "/repo/3", "/repo/2"]167
);168
assert_eq!(settings.recent_working_dirs_of("copilot"), ["/other"]);169
let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();170
assert_eq!(loaded, settings);171
assert!(172
AgentSettings::from_json("{}")173
.unwrap()174
.recent_working_dirs175
.is_empty()176
);177
}178
134
#[test]179
#[test]135
fn empty_object_loads_defaults() {180
fn empty_object_loads_defaults() {136
assert_eq!(181
assert_eq!(@@ -172,3 +172,16 @@ async fn cleanup_files_are_removed_when_the_run_ends() {
172
172
run(stopped_plan, OutputFormat::ClaudeStreamJson, sender, stop).await;
173
173
assert!(!config.exists());
174
174
}
175
176
#[tokio::test]
177
async fn a_hanging_stop_command_is_killed_after_the_limit() {
178
let invocation = Invocation {
179
program: "sleep".to_string(),
180
args: vec!["30".to_string()],
181
cwd: None,
182
stdin: None,
183
};
184
let started = std::time::Instant::now();
185
agents::run_stop_invocation_within(&invocation, std::time::Duration::from_millis(200)).await;
186
assert!(started.elapsed() < std::time::Duration::from_secs(5));
187
}
@@ -172,3 +172,16 @@ async fn cleanup_files_are_removed_when_the_run_ends() {172
run(stopped_plan, OutputFormat::ClaudeStreamJson, sender, stop).await;172
run(stopped_plan, OutputFormat::ClaudeStreamJson, sender, stop).await;173
assert!(!config.exists());173
assert!(!config.exists());174
}174
}175
176
#[tokio::test]177
async fn a_hanging_stop_command_is_killed_after_the_limit() {178
let invocation = Invocation {179
program: "sleep".to_string(),180
args: vec!["30".to_string()],181
cwd: None,182
stdin: None,183
};184
let started = std::time::Instant::now();185
agents::run_stop_invocation_within(&invocation, std::time::Duration::from_millis(200)).await;186
assert!(started.elapsed() < std::time::Duration::from_secs(5));187
}@@ -52,6 +52,10 @@ fn run_for(
52
52
expanded: false,
53
53
dismissed: false,
54
54
process_id: None,
55
pending_prompt: None,
56
launched: true,
57
sent_to: None,
58
launch_session_id: None,
55
59
}
56
60
}
57
61
@@ -52,6 +52,10 @@ fn run_for(52
expanded: false,52
expanded: false,53
dismissed: false,53
dismissed: false,54
process_id: None,54
process_id: None,55
pending_prompt: None,56
launched: true,57
sent_to: None,58
launch_session_id: None,55
}59
}56
}60
}57
61
@@ -0,0 +1,62 @@
1
use agents::{AgentSettings, Invocation, RunPlan};
2
3
use super::runs::AgentRun;
4
use crate::runtime;
5
6
pub fn orphan_stop(run: &AgentRun, plan: &RunPlan) -> Option<Invocation> {
7
plan.stop.clone().or_else(|| pid_kill(run))
8
}
9
10
pub fn pid_kill(run: &AgentRun) -> Option<Invocation> {
11
let launched_as = run.launch_session_id.as_ref().unwrap_or(&run.session_id);
12
run.process_id
13
.and_then(|process_id| agents::kill_process_invocation(process_id, launched_as))
14
}
15
16
pub fn startup_kill(settings: &AgentSettings, run: &AgentRun) -> Option<Invocation> {
17
let launched_as = run.launch_session_id.as_ref().unwrap_or(&run.session_id);
18
settings
19
.agents
20
.iter()
21
.find(|agent| agent.id == run.agent_id)
22
.and_then(|agent| agents::wsl_stop_invocation(&agent.environment, launched_as))
23
.or_else(|| pid_kill(run))
24
}
25
26
pub fn kill_for(
27
run: &AgentRun,
28
plan: &RunPlan,
29
plan_for_launch_id: impl Fn(&AgentRun) -> Option<RunPlan>,
30
) -> Option<Invocation> {
31
let Some(launch_session_id) = run
32
.launch_session_id
33
.clone()
34
.filter(|launch| *launch != run.session_id)
35
else {
36
return orphan_stop(run, plan);
37
};
38
let launched = AgentRun {
39
session_id: launch_session_id,
40
..run.clone()
41
};
42
let launched_plan = plan_for_launch_id(&launched)?;
43
for path in &launched_plan.cleanup {
44
let _ = std::fs::remove_file(path);
45
}
46
orphan_stop(&launched, &launched_plan)
47
}
48
49
pub fn orphan_kill(
50
run: &AgentRun,
51
plan_for_run: impl Fn(&AgentRun) -> Option<RunPlan>,
52
) -> Option<Invocation> {
53
let plan = plan_for_run(run)?;
54
for path in &plan.cleanup {
55
let _ = std::fs::remove_file(path);
56
}
57
kill_for(run, &plan, plan_for_run)
58
}
59
60
pub async fn execute(stop: Invocation) {
61
let _ = runtime::spawn(async move { agents::run_stop_invocation(&stop).await }).await;
62
}
@@ -0,0 +1,62 @@1
use agents::{AgentSettings, Invocation, RunPlan};2
3
use super::runs::AgentRun;4
use crate::runtime;5
6
pub fn orphan_stop(run: &AgentRun, plan: &RunPlan) -> Option<Invocation> {7
plan.stop.clone().or_else(|| pid_kill(run))8
}9
10
pub fn pid_kill(run: &AgentRun) -> Option<Invocation> {11
let launched_as = run.launch_session_id.as_ref().unwrap_or(&run.session_id);12
run.process_id13
.and_then(|process_id| agents::kill_process_invocation(process_id, launched_as))14
}15
16
pub fn startup_kill(settings: &AgentSettings, run: &AgentRun) -> Option<Invocation> {17
let launched_as = run.launch_session_id.as_ref().unwrap_or(&run.session_id);18
settings19
.agents20
.iter()21
.find(|agent| agent.id == run.agent_id)22
.and_then(|agent| agents::wsl_stop_invocation(&agent.environment, launched_as))23
.or_else(|| pid_kill(run))24
}25
26
pub fn kill_for(27
run: &AgentRun,28
plan: &RunPlan,29
plan_for_launch_id: impl Fn(&AgentRun) -> Option<RunPlan>,30
) -> Option<Invocation> {31
let Some(launch_session_id) = run32
.launch_session_id33
.clone()34
.filter(|launch| *launch != run.session_id)35
else {36
return orphan_stop(run, plan);37
};38
let launched = AgentRun {39
session_id: launch_session_id,40
..run.clone()41
};42
let launched_plan = plan_for_launch_id(&launched)?;43
for path in &launched_plan.cleanup {44
let _ = std::fs::remove_file(path);45
}46
orphan_stop(&launched, &launched_plan)47
}48
49
pub fn orphan_kill(50
run: &AgentRun,51
plan_for_run: impl Fn(&AgentRun) -> Option<RunPlan>,52
) -> Option<Invocation> {53
let plan = plan_for_run(run)?;54
for path in &plan.cleanup {55
let _ = std::fs::remove_file(path);56
}57
kill_for(run, &plan, plan_for_run)58
}59
60
pub async fn execute(stop: Invocation) {61
let _ = runtime::spawn(async move { agents::run_stop_invocation(&stop).await }).await;62
}@@ -0,0 +1,374 @@
1
use std::collections::{HashMap, VecDeque};
2
3
use agents::Invocation;
4
5
#[derive(Debug, Default, PartialEq, Eq)]
6
pub struct Lane {
7
pub active: Vec<u64>,
8
pub kills_pending: u32,
9
pub waiting: VecDeque<u64>,
10
}
11
12
impl Lane {
13
fn is_idle(&self) -> bool {
14
self.active.is_empty() && self.kills_pending == 0
15
}
16
}
17
18
#[derive(Debug, PartialEq, Eq)]
19
pub enum Admit {
20
Launch,
21
Queued,
22
}
23
24
pub struct RestoreInfo {
25
pub id: u64,
26
pub session_id: String,
27
pub queued: bool,
28
pub kill: Option<Invocation>,
29
}
30
31
pub struct Restored {
32
pub lanes: Lanes,
33
pub resume_queue: Vec<u64>,
34
pub interrupted: Vec<u64>,
35
pub kills: Vec<(String, Invocation)>,
36
}
37
38
#[derive(Debug, Default)]
39
pub struct Lanes {
40
lanes: HashMap<String, Lane>,
41
renamed: HashMap<String, String>,
42
}
43
44
impl Lanes {
45
pub fn get(&self, session_id: &str) -> Option<&Lane> {
46
self.lanes.get(session_id)
47
}
48
49
pub fn is_empty(&self) -> bool {
50
self.lanes.is_empty()
51
}
52
53
pub fn idle_sessions(&self) -> Vec<String> {
54
self.lanes
55
.iter()
56
.filter(|(_, lane)| lane.is_idle())
57
.map(|(session_id, _)| session_id.clone())
58
.collect()
59
}
60
61
pub fn has_kills_pending(&self, session_id: &str) -> bool {
62
self.lanes
63
.get(session_id)
64
.is_some_and(|lane| lane.kills_pending > 0)
65
}
66
67
pub fn admit(&mut self, session_id: &str, run_id: u64) -> Admit {
68
let lane = self.lanes.entry(session_id.to_owned()).or_default();
69
if lane.is_idle() && lane.waiting.is_empty() {
70
lane.active.push(run_id);
71
Admit::Launch
72
} else {
73
lane.waiting.push_back(run_id);
74
Admit::Queued
75
}
76
}
77
78
pub fn finished(&mut self, session_id: &str, run_id: u64) -> bool {
79
let Some(lane) = self.lanes.get_mut(session_id) else {
80
return false;
81
};
82
let before = lane.active.len();
83
lane.active.retain(|active| *active != run_id);
84
lane.active.len() != before
85
}
86
87
pub fn next(&mut self, session_id: &str, is_queued: impl Fn(u64) -> bool) -> Option<u64> {
88
let lane = self.lanes.get_mut(session_id)?;
89
if !lane.is_idle() {
90
return None;
91
}
92
while let Some(candidate) = lane.waiting.pop_front() {
93
if is_queued(candidate) {
94
lane.active.push(candidate);
95
return Some(candidate);
96
}
97
}
98
self.lanes.remove(session_id);
99
None
100
}
101
102
pub fn kill_started(&mut self, session_id: &str) {
103
self.lanes
104
.entry(session_id.to_owned())
105
.or_default()
106
.kills_pending += 1;
107
}
108
109
pub fn resolve(&self, session_id: &str) -> String {
110
let mut current = session_id;
111
for _ in 0..=self.renamed.len() {
112
match self.renamed.get(current) {
113
Some(next) => current = next,
114
None => break,
115
}
116
}
117
current.to_owned()
118
}
119
120
pub fn kill_done(&mut self, session_id: &str) {
121
let session_id = self.resolve(session_id);
122
if let Some(lane) = self.lanes.get_mut(&session_id) {
123
lane.kills_pending = lane.kills_pending.saturating_sub(1);
124
}
125
}
126
127
pub fn remove_waiting(&mut self, session_id: &str, run_id: u64) {
128
if let Some(lane) = self.lanes.get_mut(session_id) {
129
lane.waiting.retain(|waiting| *waiting != run_id);
130
}
131
}
132
133
pub fn drain_waiting(&mut self, session_id: &str) -> Vec<u64> {
134
self.lanes
135
.get_mut(session_id)
136
.map(|lane| lane.waiting.drain(..).collect())
137
.unwrap_or_default()
138
}
139
140
pub fn rename(&mut self, from: &str, to: &str) -> Vec<u64> {
141
let Some(lane) = self.lanes.remove(from) else {
142
return Vec::new();
143
};
144
self.renamed.insert(from.to_owned(), to.to_owned());
145
let moved: Vec<u64> = lane.waiting.iter().copied().collect();
146
let target = self.lanes.entry(to.to_owned()).or_default();
147
target.active.extend(lane.active);
148
target.kills_pending += lane.kills_pending;
149
target.waiting.extend(lane.waiting);
150
moved
151
}
152
153
pub fn restore(infos: &[RestoreInfo], can_resume: impl Fn(u64) -> bool) -> Restored {
154
let mut lanes = Lanes::default();
155
let mut resume_queue = Vec::new();
156
let mut interrupted = Vec::new();
157
let mut kills = Vec::new();
158
for info in infos.iter().filter(|info| !info.queued) {
159
let has_active = lanes
160
.get(&info.session_id)
161
.is_some_and(|lane| !lane.active.is_empty());
162
if !has_active && can_resume(info.id) {
163
lanes.admit(&info.session_id, info.id);
164
lanes.kill_started(&info.session_id);
165
resume_queue.push(info.id);
166
} else {
167
interrupted.push(info.id);
168
if let Some(kill) = &info.kill {
169
lanes.kill_started(&info.session_id);
170
kills.push((info.session_id.clone(), kill.clone()));
171
}
172
}
173
}
174
for info in infos.iter().filter(|info| info.queued) {
175
lanes
176
.lanes
177
.entry(info.session_id.clone())
178
.or_default()
179
.waiting
180
.push_back(info.id);
181
}
182
Restored {
183
lanes,
184
resume_queue,
185
interrupted,
186
kills,
187
}
188
}
189
}
190
191
#[cfg(test)]
192
mod tests {
193
use super::*;
194
195
fn info(id: u64, session_id: &str, queued: bool, kill: bool) -> RestoreInfo {
196
RestoreInfo {
197
id,
198
session_id: session_id.to_owned(),
199
queued,
200
kill: kill.then(|| Invocation {
201
program: "kill".to_owned(),
202
args: Vec::new(),
203
cwd: None,
204
stdin: None,
205
}),
206
}
207
}
208
209
fn waiting(lanes: &Lanes, session_id: &str) -> Vec<u64> {
210
lanes
211
.get(session_id)
212
.unwrap()
213
.waiting
214
.iter()
215
.copied()
216
.collect()
217
}
218
219
#[test]
220
fn admit_launches_on_an_idle_lane_and_queues_while_busy() {
221
let mut lanes = Lanes::default();
222
assert_eq!(lanes.admit("s", 1), Admit::Launch);
223
assert_eq!(lanes.admit("s", 2), Admit::Queued);
224
assert_eq!(lanes.admit("s", 3), Admit::Queued);
225
assert_eq!(lanes.admit("other", 4), Admit::Launch);
226
assert_eq!(lanes.get("s").unwrap().active, [1]);
227
assert_eq!(waiting(&lanes, "s"), [2, 3]);
228
}
229
230
#[test]
231
fn a_pending_kill_blocks_admission_and_release() {
232
let mut lanes = Lanes::default();
233
lanes.kill_started("s");
234
assert_eq!(lanes.admit("s", 1), Admit::Queued);
235
assert_eq!(lanes.next("s", |_| true), None);
236
lanes.kill_done("s");
237
assert_eq!(lanes.next("s", |_| true), Some(1));
238
}
239
240
#[test]
241
fn waiting_runs_are_released_in_order_one_at_a_time() {
242
let mut lanes = Lanes::default();
243
lanes.admit("s", 1);
244
lanes.admit("s", 2);
245
lanes.admit("s", 3);
246
assert_eq!(lanes.next("s", |_| true), None);
247
assert!(lanes.finished("s", 1));
248
assert!(!lanes.finished("s", 1));
249
assert_eq!(lanes.next("s", |_| true), Some(2));
250
assert_eq!(lanes.next("s", |_| true), None);
251
assert!(lanes.finished("s", 2));
252
assert_eq!(lanes.next("s", |_| true), Some(3));
253
assert!(lanes.finished("s", 3));
254
assert_eq!(lanes.next("s", |_| true), None);
255
assert!(lanes.is_empty());
256
}
257
258
#[test]
259
fn release_skips_runs_that_are_no_longer_queued() {
260
let mut lanes = Lanes::default();
261
lanes.admit("s", 1);
262
lanes.admit("s", 2);
263
lanes.admit("s", 3);
264
lanes.finished("s", 1);
265
assert_eq!(lanes.next("s", |id| id == 3), Some(3));
266
}
267
268
#[test]
269
fn kills_are_counted_not_flagged() {
270
let mut lanes = Lanes::default();
271
lanes.kill_started("s");
272
lanes.kill_started("s");
273
lanes.admit("s", 1);
274
lanes.kill_done("s");
275
assert!(lanes.has_kills_pending("s"));
276
assert_eq!(lanes.next("s", |_| true), None);
277
lanes.kill_done("s");
278
lanes.kill_done("s");
279
assert!(!lanes.has_kills_pending("s"));
280
assert_eq!(lanes.next("s", |_| true), Some(1));
281
}
282
283
#[test]
284
fn removing_and_draining_waiting_runs() {
285
let mut lanes = Lanes::default();
286
for id in 1..=4 {
287
lanes.admit("s", id);
288
}
289
lanes.remove_waiting("s", 3);
290
assert_eq!(waiting(&lanes, "s"), [2, 4]);
291
assert_eq!(lanes.drain_waiting("s"), [2, 4]);
292
assert!(waiting(&lanes, "s").is_empty());
293
assert!(lanes.drain_waiting("none").is_empty());
294
}
295
296
#[test]
297
fn renaming_moves_active_and_waiting_runs() {
298
let mut lanes = Lanes::default();
299
lanes.admit("x", 1);
300
lanes.admit("x", 2);
301
assert_eq!(lanes.rename("x", "y"), [2]);
302
assert!(lanes.get("x").is_none());
303
assert_eq!(lanes.get("y").unwrap().active, [1]);
304
assert_eq!(waiting(&lanes, "y"), [2]);
305
assert!(lanes.rename("missing", "z").is_empty());
306
}
307
308
#[test]
309
fn a_rename_collision_keeps_both_active_runs_blocking() {
310
let mut lanes = Lanes::default();
311
lanes.admit("x", 1);
312
lanes.admit("x", 2);
313
lanes.admit("y", 3);
314
lanes.admit("y", 4);
315
lanes.kill_started("x");
316
assert_eq!(lanes.rename("x", "y"), [2]);
317
let lane = lanes.get("y").unwrap();
318
assert_eq!(lane.active, [3, 1]);
319
assert_eq!(lane.kills_pending, 1);
320
assert_eq!(waiting(&lanes, "y"), [4, 2]);
321
lanes.kill_done("y");
322
assert!(lanes.finished("y", 3));
323
assert_eq!(lanes.next("y", |_| true), None);
324
assert!(lanes.finished("y", 1));
325
assert_eq!(lanes.next("y", |_| true), Some(4));
326
}
327
328
#[test]
329
fn a_kill_pending_across_a_rename_is_released_under_the_old_id() {
330
let mut lanes = Lanes::default();
331
lanes.admit("x", 1);
332
lanes.kill_started("x");
333
lanes.rename("x", "y");
334
assert_eq!(lanes.resolve("x"), "y");
335
assert!(lanes.has_kills_pending("y"));
336
lanes.kill_done("x");
337
assert!(!lanes.has_kills_pending("y"));
338
}
339
340
#[test]
341
fn restore_builds_active_candidates_waiting_order_and_kills() {
342
let infos = [
343
info(5, "shared", false, false),
344
info(6, "shared", false, true),
345
info(7, "shared", true, false),
346
info(8, "shared", true, false),
347
info(9, "dead", false, true),
348
info(10, "other", false, false),
349
];
350
let restored = Lanes::restore(&infos, |id| id != 9);
351
assert_eq!(restored.resume_queue, [5, 10]);
352
assert_eq!(restored.interrupted, [6, 9]);
353
let sessions: Vec<&str> = restored
354
.kills
355
.iter()
356
.map(|(session, _)| session.as_str())
357
.collect();
358
assert_eq!(sessions, ["shared", "dead"]);
359
let lanes = restored.lanes;
360
let shared = lanes.get("shared").unwrap();
361
assert_eq!(shared.active, [5]);
362
assert_eq!(shared.kills_pending, 2);
363
assert_eq!(waiting(&lanes, "shared"), [7, 8]);
364
assert_eq!(lanes.get("dead").unwrap().kills_pending, 1);
365
assert_eq!(lanes.get("other").unwrap().kills_pending, 1);
366
assert!(lanes.idle_sessions().is_empty());
367
}
368
369
#[test]
370
fn a_restored_lane_with_only_waiting_runs_is_idle() {
371
let restored = Lanes::restore(&[info(7, "s", true, false)], |_| true);
372
assert_eq!(restored.lanes.idle_sessions(), ["s"]);
373
}
374
}
@@ -0,0 +1,374 @@1
use std::collections::{HashMap, VecDeque};2
3
use agents::Invocation;4
5
#[derive(Debug, Default, PartialEq, Eq)]6
pub struct Lane {7
pub active: Vec<u64>,8
pub kills_pending: u32,9
pub waiting: VecDeque<u64>,10
}11
12
impl Lane {13
fn is_idle(&self) -> bool {14
self.active.is_empty() && self.kills_pending == 015
}16
}17
18
#[derive(Debug, PartialEq, Eq)]19
pub enum Admit {20
Launch,21
Queued,22
}23
24
pub struct RestoreInfo {25
pub id: u64,26
pub session_id: String,27
pub queued: bool,28
pub kill: Option<Invocation>,29
}30
31
pub struct Restored {32
pub lanes: Lanes,33
pub resume_queue: Vec<u64>,34
pub interrupted: Vec<u64>,35
pub kills: Vec<(String, Invocation)>,36
}37
38
#[derive(Debug, Default)]39
pub struct Lanes {40
lanes: HashMap<String, Lane>,41
renamed: HashMap<String, String>,42
}43
44
impl Lanes {45
pub fn get(&self, session_id: &str) -> Option<&Lane> {46
self.lanes.get(session_id)47
}48
49
pub fn is_empty(&self) -> bool {50
self.lanes.is_empty()51
}52
53
pub fn idle_sessions(&self) -> Vec<String> {54
self.lanes55
.iter()56
.filter(|(_, lane)| lane.is_idle())57
.map(|(session_id, _)| session_id.clone())58
.collect()59
}60
61
pub fn has_kills_pending(&self, session_id: &str) -> bool {62
self.lanes63
.get(session_id)64
.is_some_and(|lane| lane.kills_pending > 0)65
}66
67
pub fn admit(&mut self, session_id: &str, run_id: u64) -> Admit {68
let lane = self.lanes.entry(session_id.to_owned()).or_default();69
if lane.is_idle() && lane.waiting.is_empty() {70
lane.active.push(run_id);71
Admit::Launch72
} else {73
lane.waiting.push_back(run_id);74
Admit::Queued75
}76
}77
78
pub fn finished(&mut self, session_id: &str, run_id: u64) -> bool {79
let Some(lane) = self.lanes.get_mut(session_id) else {80
return false;81
};82
let before = lane.active.len();83
lane.active.retain(|active| *active != run_id);84
lane.active.len() != before85
}86
87
pub fn next(&mut self, session_id: &str, is_queued: impl Fn(u64) -> bool) -> Option<u64> {88
let lane = self.lanes.get_mut(session_id)?;89
if !lane.is_idle() {90
return None;91
}92
while let Some(candidate) = lane.waiting.pop_front() {93
if is_queued(candidate) {94
lane.active.push(candidate);95
return Some(candidate);96
}97
}98
self.lanes.remove(session_id);99
None100
}101
102
pub fn kill_started(&mut self, session_id: &str) {103
self.lanes104
.entry(session_id.to_owned())105
.or_default()106
.kills_pending += 1;107
}108
109
pub fn resolve(&self, session_id: &str) -> String {110
let mut current = session_id;111
for _ in 0..=self.renamed.len() {112
match self.renamed.get(current) {113
Some(next) => current = next,114
None => break,115
}116
}117
current.to_owned()118
}119
120
pub fn kill_done(&mut self, session_id: &str) {121
let session_id = self.resolve(session_id);122
if let Some(lane) = self.lanes.get_mut(&session_id) {123
lane.kills_pending = lane.kills_pending.saturating_sub(1);124
}125
}126
127
pub fn remove_waiting(&mut self, session_id: &str, run_id: u64) {128
if let Some(lane) = self.lanes.get_mut(session_id) {129
lane.waiting.retain(|waiting| *waiting != run_id);130
}131
}132
133
pub fn drain_waiting(&mut self, session_id: &str) -> Vec<u64> {134
self.lanes135
.get_mut(session_id)136
.map(|lane| lane.waiting.drain(..).collect())137
.unwrap_or_default()138
}139
140
pub fn rename(&mut self, from: &str, to: &str) -> Vec<u64> {141
let Some(lane) = self.lanes.remove(from) else {142
return Vec::new();143
};144
self.renamed.insert(from.to_owned(), to.to_owned());145
let moved: Vec<u64> = lane.waiting.iter().copied().collect();146
let target = self.lanes.entry(to.to_owned()).or_default();147
target.active.extend(lane.active);148
target.kills_pending += lane.kills_pending;149
target.waiting.extend(lane.waiting);150
moved151
}152
153
pub fn restore(infos: &[RestoreInfo], can_resume: impl Fn(u64) -> bool) -> Restored {154
let mut lanes = Lanes::default();155
let mut resume_queue = Vec::new();156
let mut interrupted = Vec::new();157
let mut kills = Vec::new();158
for info in infos.iter().filter(|info| !info.queued) {159
let has_active = lanes160
.get(&info.session_id)161
.is_some_and(|lane| !lane.active.is_empty());162
if !has_active && can_resume(info.id) {163
lanes.admit(&info.session_id, info.id);164
lanes.kill_started(&info.session_id);165
resume_queue.push(info.id);166
} else {167
interrupted.push(info.id);168
if let Some(kill) = &info.kill {169
lanes.kill_started(&info.session_id);170
kills.push((info.session_id.clone(), kill.clone()));171
}172
}173
}174
for info in infos.iter().filter(|info| info.queued) {175
lanes176
.lanes177
.entry(info.session_id.clone())178
.or_default()179
.waiting180
.push_back(info.id);181
}182
Restored {183
lanes,184
resume_queue,185
interrupted,186
kills,187
}188
}189
}190
191
#[cfg(test)]192
mod tests {193
use super::*;194
195
fn info(id: u64, session_id: &str, queued: bool, kill: bool) -> RestoreInfo {196
RestoreInfo {197
id,198
session_id: session_id.to_owned(),199
queued,200
kill: kill.then(|| Invocation {201
program: "kill".to_owned(),202
args: Vec::new(),203
cwd: None,204
stdin: None,205
}),206
}207
}208
209
fn waiting(lanes: &Lanes, session_id: &str) -> Vec<u64> {210
lanes211
.get(session_id)212
.unwrap()213
.waiting214
.iter()215
.copied()216
.collect()217
}218
219
#[test]220
fn admit_launches_on_an_idle_lane_and_queues_while_busy() {221
let mut lanes = Lanes::default();222
assert_eq!(lanes.admit("s", 1), Admit::Launch);223
assert_eq!(lanes.admit("s", 2), Admit::Queued);224
assert_eq!(lanes.admit("s", 3), Admit::Queued);225
assert_eq!(lanes.admit("other", 4), Admit::Launch);226
assert_eq!(lanes.get("s").unwrap().active, [1]);227
assert_eq!(waiting(&lanes, "s"), [2, 3]);228
}229
230
#[test]231
fn a_pending_kill_blocks_admission_and_release() {232
let mut lanes = Lanes::default();233
lanes.kill_started("s");234
assert_eq!(lanes.admit("s", 1), Admit::Queued);235
assert_eq!(lanes.next("s", |_| true), None);236
lanes.kill_done("s");237
assert_eq!(lanes.next("s", |_| true), Some(1));238
}239
240
#[test]241
fn waiting_runs_are_released_in_order_one_at_a_time() {242
let mut lanes = Lanes::default();243
lanes.admit("s", 1);244
lanes.admit("s", 2);245
lanes.admit("s", 3);246
assert_eq!(lanes.next("s", |_| true), None);247
assert!(lanes.finished("s", 1));248
assert!(!lanes.finished("s", 1));249
assert_eq!(lanes.next("s", |_| true), Some(2));250
assert_eq!(lanes.next("s", |_| true), None);251
assert!(lanes.finished("s", 2));252
assert_eq!(lanes.next("s", |_| true), Some(3));253
assert!(lanes.finished("s", 3));254
assert_eq!(lanes.next("s", |_| true), None);255
assert!(lanes.is_empty());256
}257
258
#[test]259
fn release_skips_runs_that_are_no_longer_queued() {260
let mut lanes = Lanes::default();261
lanes.admit("s", 1);262
lanes.admit("s", 2);263
lanes.admit("s", 3);264
lanes.finished("s", 1);265
assert_eq!(lanes.next("s", |id| id == 3), Some(3));266
}267
268
#[test]269
fn kills_are_counted_not_flagged() {270
let mut lanes = Lanes::default();271
lanes.kill_started("s");272
lanes.kill_started("s");273
lanes.admit("s", 1);274
lanes.kill_done("s");275
assert!(lanes.has_kills_pending("s"));276
assert_eq!(lanes.next("s", |_| true), None);277
lanes.kill_done("s");278
lanes.kill_done("s");279
assert!(!lanes.has_kills_pending("s"));280
assert_eq!(lanes.next("s", |_| true), Some(1));281
}282
283
#[test]284
fn removing_and_draining_waiting_runs() {285
let mut lanes = Lanes::default();286
for id in 1..=4 {287
lanes.admit("s", id);288
}289
lanes.remove_waiting("s", 3);290
assert_eq!(waiting(&lanes, "s"), [2, 4]);291
assert_eq!(lanes.drain_waiting("s"), [2, 4]);292
assert!(waiting(&lanes, "s").is_empty());293
assert!(lanes.drain_waiting("none").is_empty());294
}295
296
#[test]297
fn renaming_moves_active_and_waiting_runs() {298
let mut lanes = Lanes::default();299
lanes.admit("x", 1);300
lanes.admit("x", 2);301
assert_eq!(lanes.rename("x", "y"), [2]);302
assert!(lanes.get("x").is_none());303
assert_eq!(lanes.get("y").unwrap().active, [1]);304
assert_eq!(waiting(&lanes, "y"), [2]);305
assert!(lanes.rename("missing", "z").is_empty());306
}307
308
#[test]309
fn a_rename_collision_keeps_both_active_runs_blocking() {310
let mut lanes = Lanes::default();311
lanes.admit("x", 1);312
lanes.admit("x", 2);313
lanes.admit("y", 3);314
lanes.admit("y", 4);315
lanes.kill_started("x");316
assert_eq!(lanes.rename("x", "y"), [2]);317
let lane = lanes.get("y").unwrap();318
assert_eq!(lane.active, [3, 1]);319
assert_eq!(lane.kills_pending, 1);320
assert_eq!(waiting(&lanes, "y"), [4, 2]);321
lanes.kill_done("y");322
assert!(lanes.finished("y", 3));323
assert_eq!(lanes.next("y", |_| true), None);324
assert!(lanes.finished("y", 1));325
assert_eq!(lanes.next("y", |_| true), Some(4));326
}327
328
#[test]329
fn a_kill_pending_across_a_rename_is_released_under_the_old_id() {330
let mut lanes = Lanes::default();331
lanes.admit("x", 1);332
lanes.kill_started("x");333
lanes.rename("x", "y");334
assert_eq!(lanes.resolve("x"), "y");335
assert!(lanes.has_kills_pending("y"));336
lanes.kill_done("x");337
assert!(!lanes.has_kills_pending("y"));338
}339
340
#[test]341
fn restore_builds_active_candidates_waiting_order_and_kills() {342
let infos = [343
info(5, "shared", false, false),344
info(6, "shared", false, true),345
info(7, "shared", true, false),346
info(8, "shared", true, false),347
info(9, "dead", false, true),348
info(10, "other", false, false),349
];350
let restored = Lanes::restore(&infos, |id| id != 9);351
assert_eq!(restored.resume_queue, [5, 10]);352
assert_eq!(restored.interrupted, [6, 9]);353
let sessions: Vec<&str> = restored354
.kills355
.iter()356
.map(|(session, _)| session.as_str())357
.collect();358
assert_eq!(sessions, ["shared", "dead"]);359
let lanes = restored.lanes;360
let shared = lanes.get("shared").unwrap();361
assert_eq!(shared.active, [5]);362
assert_eq!(shared.kills_pending, 2);363
assert_eq!(waiting(&lanes, "shared"), [7, 8]);364
assert_eq!(lanes.get("dead").unwrap().kills_pending, 1);365
assert_eq!(lanes.get("other").unwrap().kills_pending, 1);366
assert!(lanes.idle_sessions().is_empty());367
}368
369
#[test]370
fn a_restored_lane_with_only_waiting_runs_is_idle() {371
let restored = Lanes::restore(&[info(7, "s", true, false)], |_| true);372
assert_eq!(restored.lanes.idle_sessions(), ["s"]);373
}374
}@@ -41,6 +41,19 @@ fn earlier_records(
41
41
earlier.split_off(skipped)
42
42
}
43
43
44
pub fn message_line(state: &AppState, conversation_id: &str, message_id: &str) -> Option<String> {
45
let record = state
46
.store
47
.messages_by_id(conversation_id, &[message_id.to_owned()])
48
.ok()?
49
.remove(message_id)?;
50
message_text(&record)
51
.lines()
52
.map(str::trim)
53
.find(|line| !line.is_empty())
54
.map(str::to_owned)
55
}
56
44
57
pub fn build(state: &AppState, conversation_id: &str, message_id: &str) -> Option<MessageContext> {
45
58
let record = state
46
59
.store
@@ -41,6 +41,19 @@ fn earlier_records(41
earlier.split_off(skipped)41
earlier.split_off(skipped)42
}42
}43
43
44
pub fn message_line(state: &AppState, conversation_id: &str, message_id: &str) -> Option<String> {45
let record = state46
.store47
.messages_by_id(conversation_id, &[message_id.to_owned()])48
.ok()?49
.remove(message_id)?;50
message_text(&record)51
.lines()52
.map(str::trim)53
.find(|line| !line.is_empty())54
.map(str::to_owned)55
}56
44
pub fn build(state: &AppState, conversation_id: &str, message_id: &str) -> Option<MessageContext> {57
pub fn build(state: &AppState, conversation_id: &str, message_id: &str) -> Option<MessageContext> {45
let record = state58
let record = state46
.store59
.store@@ -1,15 +1,19 @@
1
1
mod demo;
2
mod kills;
3
mod lanes;
2
4
mod mcp_bridge;
3
5
mod message_context;
4
6
mod run_chip;
5
7
mod runs;
6
8
mod runs_popover;
9
mod session_options;
7
10
mod settings_controls;
8
11
mod settings_forms;
9
12
mod settings_problems;
10
13
mod settings_section;
11
14
mod spinner;
12
15
mod start_dialog;
16
mod start_dialog_pickers;
13
17
mod store;
14
18
15
19
use std::path::PathBuf;
@@ -20,7 +24,7 @@ use directories::ProjectDirs;
20
24
use gpui_kit::*;
21
25
22
26
pub use run_chip::run_chip;
23
pub use runs::{AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState};
27
pub use runs::{AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions};
24
28
pub use runs_popover::RunsPopover;
25
29
pub use settings_section::AgentsSettings;
26
30
pub use start_dialog::{StartDialog, StartDialogEvent, StartRequest};
@@ -61,13 +65,14 @@ pub fn start_run(
61
65
conversation_id: &str,
62
66
message_id: &str,
63
67
extra: &str,
68
options: StartOptions,
64
69
cx: &mut App,
65
70
) {
66
71
let Some(runs) = runs_handle(cx) else {
67
72
return;
68
73
};
69
74
let started = runs.update(cx, |runs, cx| {
70
runs.start(action_id, conversation_id, message_id, extra, cx)
75
runs.start_with(action_id, conversation_id, message_id, extra, options, cx)
71
76
});
72
77
if let Err(error) = started {
73
78
raise_notice(format!("Agent could not start: {error}"), cx);
@@ -79,6 +84,7 @@ pub fn start_run_when_mcp_ready(
79
84
conversation_id: String,
80
85
message_id: String,
81
86
extra: String,
87
options: StartOptions,
82
88
cx: &mut App,
83
89
) {
84
90
cx.spawn(async move |cx| {
@@ -94,7 +100,14 @@ pub fn start_run_when_mcp_ready(
94
100
cx,
95
101
);
96
102
}
97
start_run(&action_id, &conversation_id, &message_id, &extra, cx);
103
start_run(
104
&action_id,
105
&conversation_id,
106
&message_id,
107
&extra,
108
options,
109
cx,
110
);
98
111
});
99
112
})
100
113
.detach();
@@ -133,6 +146,7 @@ pub fn delegate(request: StartRequest, cx: &mut App) {
133
146
&request.conversation_id,
134
147
&request.message_id,
135
148
"",
149
StartOptions::default(),
136
150
cx,
137
151
);
138
152
}
@@ -1,15 +1,19 @@1
mod demo;1
mod demo;2
mod kills;3
mod lanes;2
mod mcp_bridge;4
mod mcp_bridge;3
mod message_context;5
mod message_context;4
mod run_chip;6
mod run_chip;5
mod runs;7
mod runs;6
mod runs_popover;8
mod runs_popover;9
mod session_options;7
mod settings_controls;10
mod settings_controls;8
mod settings_forms;11
mod settings_forms;9
mod settings_problems;12
mod settings_problems;10
mod settings_section;13
mod settings_section;11
mod spinner;14
mod spinner;12
mod start_dialog;15
mod start_dialog;16
mod start_dialog_pickers;13
mod store;17
mod store;14
18
15
use std::path::PathBuf;19
use std::path::PathBuf;@@ -20,7 +24,7 @@ use directories::ProjectDirs;20
use gpui_kit::*;24
use gpui_kit::*;21
25
22
pub use run_chip::run_chip;26
pub use run_chip::run_chip;23
pub use runs::{AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState};27
pub use runs::{AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions};24
pub use runs_popover::RunsPopover;28
pub use runs_popover::RunsPopover;25
pub use settings_section::AgentsSettings;29
pub use settings_section::AgentsSettings;26
pub use start_dialog::{StartDialog, StartDialogEvent, StartRequest};30
pub use start_dialog::{StartDialog, StartDialogEvent, StartRequest};@@ -61,13 +65,14 @@ pub fn start_run(61
conversation_id: &str,65
conversation_id: &str,62
message_id: &str,66
message_id: &str,63
extra: &str,67
extra: &str,68
options: StartOptions,64
cx: &mut App,69
cx: &mut App,65
) {70
) {66
let Some(runs) = runs_handle(cx) else {71
let Some(runs) = runs_handle(cx) else {67
return;72
return;68
};73
};69
let started = runs.update(cx, |runs, cx| {74
let started = runs.update(cx, |runs, cx| {70
runs.start(action_id, conversation_id, message_id, extra, cx)75
runs.start_with(action_id, conversation_id, message_id, extra, options, cx)71
});76
});72
if let Err(error) = started {77
if let Err(error) = started {73
raise_notice(format!("Agent could not start: {error}"), cx);78
raise_notice(format!("Agent could not start: {error}"), cx);@@ -79,6 +84,7 @@ pub fn start_run_when_mcp_ready(79
conversation_id: String,84
conversation_id: String,80
message_id: String,85
message_id: String,81
extra: String,86
extra: String,87
options: StartOptions,82
cx: &mut App,88
cx: &mut App,83
) {89
) {84
cx.spawn(async move |cx| {90
cx.spawn(async move |cx| {@@ -94,7 +100,14 @@ pub fn start_run_when_mcp_ready(94
cx,100
cx,95
);101
);96
}102
}97
start_run(&action_id, &conversation_id, &message_id, &extra, cx);103
start_run(104
&action_id,105
&conversation_id,106
&message_id,107
&extra,108
options,109
cx,110
);98
});111
});99
})112
})100
.detach();113
.detach();@@ -133,6 +146,7 @@ pub fn delegate(request: StartRequest, cx: &mut App) {133
&request.conversation_id,146
&request.conversation_id,134
&request.message_id,147
&request.message_id,135
"",148
"",149
StartOptions::default(),136
cx,150
cx,137
);151
);138
}152
}@@ -1,15 +1,19 @@
1
1
use std::collections::{HashMap, HashSet, VecDeque};
2
2
use std::time::Duration;
3
3
4
use agents::{AgentAction, AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate};
4
use agents::{
5
AgentAction, AgentProfile, AgentSettings, McpEndpoint, RunEvent, RunOutcome, RunStatus,
6
RunUpdate,
7
};
5
8
use chrono::{DateTime, Utc};
6
9
use gpui_kit::*;
7
10
use serde::{Deserialize, Serialize};
8
11
use tokio::sync::{mpsc, oneshot};
9
12
13
use super::lanes::{Admit, Lanes, RestoreInfo};
10
14
use super::{
11
MCP_POLL_INTERVAL, MCP_WAIT_LIMIT, StartRequest, demo, mcp_bridge, mcp_config_directory,
12
message_context, open_run_session, store as run_store,
15
MCP_POLL_INTERVAL, MCP_WAIT_LIMIT, StartRequest, demo, kills, mcp_bridge, mcp_config_directory,
16
message_context, open_run_session, raise_notice, store as run_store,
13
17
};
14
18
use crate::app_state::AppState;
15
19
use crate::notice::truncated;
@@ -22,6 +26,8 @@ const TEXT_STEP_CHARS: usize = 80;
22
26
const DONE_STEP_CHARS: usize = 60;
23
27
const TICK: Duration = Duration::from_secs(1);
24
28
const RESUME_PARALLEL_LIMIT: usize = 3;
29
const QUEUED_STEP: &str = "Queued";
30
const OPENED_NOTICE: &str = "Session opened in a terminal - send cancelled";
25
31
const RESUMED_STEP: &str = "Resumed after restart";
26
32
const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";
27
33
@@ -58,6 +64,18 @@ pub struct AgentRun {
58
64
pub dismissed: bool,
59
65
#[serde(default)]
60
66
pub process_id: Option<u32>,
67
#[serde(default)]
68
pub pending_prompt: Option<String>,
69
#[serde(default)]
70
pub sent_to: Option<SessionTarget>,
71
#[serde(default)]
72
pub launch_session_id: Option<String>,
73
#[serde(default = "launched_by_default")]
74
pub launched: bool,
75
}
76
77
fn launched_by_default() -> bool {
78
true
61
79
}
62
80
63
81
impl AgentRun {
@@ -65,6 +83,10 @@ impl AgentRun {
65
83
self.state == RunState::Running
66
84
}
67
85
86
pub fn is_queued(&self) -> bool {
87
self.pending_prompt.is_some()
88
}
89
68
90
pub fn is_finished(&self) -> bool {
69
91
!self.is_running()
70
92
}
@@ -122,15 +144,9 @@ impl AgentRun {
122
144
}
123
145
}
124
146
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
147
fn can_resume(settings: &AgentSettings, run: &AgentRun) -> bool {
133
148
settings.resume_interrupted_runs
149
&& run.launched
134
150
&& !run.session_id.is_empty()
135
151
&& settings
136
152
.agents
@@ -163,6 +179,58 @@ fn first_line(text: &str) -> &str {
163
179
.trim()
164
180
}
165
181
182
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
183
pub struct SessionTarget {
184
pub session_id: String,
185
pub working_dir: String,
186
pub fork: bool,
187
}
188
189
#[derive(Clone, Debug, Default, PartialEq, Eq)]
190
pub struct StartOptions {
191
pub working_dir: Option<String>,
192
pub remember_working_dir: bool,
193
pub session: Option<SessionTarget>,
194
}
195
196
fn plan_for(
197
profile: &AgentProfile,
198
action: &AgentAction,
199
prompt: &str,
200
session_id: &str,
201
target: Option<&SessionTarget>,
202
endpoint: Option<&McpEndpoint>,
203
) -> Result<agents::RunPlan, agents::InvocationError> {
204
let directory = mcp_config_directory();
205
match target {
206
None => agents::build_invocation(
207
profile,
208
action,
209
prompt,
210
session_id,
211
endpoint,
212
directory.as_deref(),
213
),
214
Some(target) if target.fork => agents::fork_invocation(
215
profile,
216
action,
217
prompt,
218
&target.session_id,
219
session_id,
220
endpoint,
221
directory.as_deref(),
222
),
223
Some(_) => agents::resume_invocation(
224
profile,
225
action,
226
prompt,
227
session_id,
228
endpoint,
229
directory.as_deref(),
230
),
231
}
232
}
233
166
234
pub struct AgentRunsHandle(pub Entity<AgentRuns>);
167
235
168
236
impl Global for AgentRunsHandle {}
@@ -179,9 +247,12 @@ pub struct AgentRuns {
179
247
runs: Vec<AgentRun>,
180
248
stops: HashMap<u64, oneshot::Sender<()>>,
181
249
resume_queue: VecDeque<u64>,
250
lanes: Lanes,
251
startup_kills: Vec<(String, agents::Invocation)>,
182
252
resuming: HashSet<u64>,
183
253
stopping: HashSet<u64>,
184
254
open_after_stop: HashSet<u64>,
255
open_deferred: HashSet<u64>,
185
256
next_id: u64,
186
257
ticking: bool,
187
258
}
@@ -194,15 +265,33 @@ impl AgentRuns {
194
265
let settings = run_store::load_settings(&store);
195
266
let mut runs = run_store::load_runs(&store);
196
267
let interrupted = runs.iter().any(AgentRun::is_running);
197
let mut resume_queue = VecDeque::new();
198
for run in runs.iter_mut().filter(|run| run.is_running()) {
199
if can_resume(&settings, run) {
268
let infos: Vec<RestoreInfo> = runs
269
.iter()
270
.filter(|run| run.is_running())
271
.map(|run| RestoreInfo {
272
id: run.id,
273
session_id: run.session_id.clone(),
274
queued: run.is_queued(),
275
kill: kills::startup_kill(&settings, run),
276
})
277
.collect();
278
let restored = Lanes::restore(&infos, |run_id| {
279
runs.iter()
280
.find(|run| run.id == run_id)
281
.is_some_and(|run| can_resume(&settings, run))
282
});
283
for run in runs.iter_mut() {
284
if restored.resume_queue.contains(&run.id) {
200
285
run.push_step(RESUMED_STEP.to_owned());
201
resume_queue.push_back(run.id);
202
} else {
286
} else if restored.interrupted.contains(&run.id) {
203
287
run.mark_interrupted();
204
288
}
205
289
}
290
let (lanes, resume_queue, startup_kills) = (
291
restored.lanes,
292
VecDeque::from(restored.resume_queue),
293
restored.kills,
294
);
206
295
if interrupted {
207
296
run_store::save_runs(&store, &runs);
208
297
}
@@ -217,9 +306,12 @@ impl AgentRuns {
217
306
runs,
218
307
stops: HashMap::new(),
219
308
resume_queue,
309
lanes,
310
startup_kills,
220
311
resuming: HashSet::new(),
221
312
stopping: HashSet::new(),
222
313
open_after_stop: HashSet::new(),
314
open_deferred: HashSet::new(),
223
315
next_id,
224
316
ticking: false,
225
317
};
@@ -229,18 +321,18 @@ impl AgentRuns {
229
321
}
230
322
231
323
fn start_resumes(&mut self, cx: &mut Context<Self>) {
232
if self.resume_queue.is_empty() {
324
if self.lanes.is_empty() {
233
325
return;
234
326
}
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())
327
let needs_mcp = self.runs.iter().any(|run| {
328
run.is_running()
329
&& (self.resume_queue.contains(&run.id) || run.is_queued())
330
&& self
331
.settings
332
.agents
333
.iter()
334
.find(|agent| agent.id == run.agent_id)
335
.is_some_and(|agent| !agent.mcp_config_flag.is_empty())
244
336
});
245
337
cx.spawn(async move |this, cx| {
246
338
let mut waited = Duration::ZERO;
@@ -251,7 +343,16 @@ impl AgentRuns {
251
343
cx.background_executor().timer(MCP_POLL_INTERVAL).await;
252
344
waited += MCP_POLL_INTERVAL;
253
345
}
254
this.update(cx, |runs, cx| runs.resume_next(cx)).ok();
346
this.update(cx, |runs, cx| {
347
runs.resume_next(cx);
348
for (session_id, kill) in std::mem::take(&mut runs.startup_kills) {
349
runs.run_kill(&session_id, Some(kill), cx);
350
}
351
for session_id in runs.lanes.idle_sessions() {
352
runs.release(&session_id, cx);
353
}
354
})
355
.ok();
255
356
})
256
357
.detach();
257
358
}
@@ -300,22 +401,28 @@ impl AgentRuns {
300
401
}
301
402
302
403
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 {
404
let Some(run) = self.get(run_id).cloned() else {
304
405
return;
305
406
};
407
if !run.is_running() {
408
self.finish_kill(&run.session_id, cx);
409
return;
410
}
306
411
self.resuming.insert(run_id);
412
let session_id = run.session_id.clone();
307
413
match self.resume_plan(&run, cx) {
308
414
Ok((plan, format)) => {
309
let stop = orphan_stop(&run, &plan);
415
let stop = kills::kill_for(&run, &plan, |launched| {
416
self.resume_plan(launched, cx).ok().map(|(plan, _)| plan)
417
});
310
418
cx.spawn(async move |this, cx| {
311
419
if let Some(stop) = stop {
312
let _ =
313
runtime::spawn(async move { agents::run_stop_invocation(&stop).await })
314
.await;
420
kills::execute(stop).await;
315
421
}
316
422
this.update(cx, |runs, cx| {
317
423
let still_resuming = runs.resuming.contains(&run_id)
318
424
&& runs.get(run_id).is_some_and(AgentRun::is_running);
425
runs.finish_kill(&session_id, cx);
319
426
if still_resuming {
320
427
runs.spawn(run_id, plan, format, cx);
321
428
} else {
@@ -328,17 +435,21 @@ impl AgentRuns {
328
435
})
329
436
.detach();
330
437
}
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
),
438
Err(reason) => {
439
let stop = kills::startup_kill(&self.settings, &run);
440
self.finish(
441
run_id,
442
Some(RunOutcome {
443
status: RunStatus::Failed {
444
message: format!("Could not resume - {reason}"),
445
stderr_tail: Vec::new(),
446
},
447
exit_code: None,
448
}),
449
cx,
450
);
451
self.run_kill(&session_id, stop, cx);
452
}
342
453
}
343
454
}
344
455
@@ -376,6 +487,18 @@ impl AgentRuns {
376
487
.filter(move |run| run.conversation_id == conversation_id && !run.dismissed)
377
488
}
378
489
490
pub fn for_agent(&self, agent_id: &str) -> Vec<&AgentRun> {
491
self.runs
492
.iter()
493
.rev()
494
.filter(|run| run.agent_id == agent_id)
495
.collect()
496
}
497
498
pub fn session_ids(&self) -> HashSet<String> {
499
self.runs.iter().map(|run| run.session_id.clone()).collect()
500
}
501
379
502
pub fn running_count(&self) -> usize {
380
503
self.runs.iter().filter(|run| run.is_running()).count()
381
504
}
@@ -405,7 +528,26 @@ impl AgentRuns {
405
528
extra: &str,
406
529
cx: &mut Context<Self>,
407
530
) -> Result<u64, String> {
408
let action = self
531
self.start_with(
532
action_id,
533
conversation_id,
534
message_id,
535
extra,
536
StartOptions::default(),
537
cx,
538
)
539
}
540
541
pub fn start_with(
542
&mut self,
543
action_id: &str,
544
conversation_id: &str,
545
message_id: &str,
546
extra: &str,
547
options: StartOptions,
548
cx: &mut Context<Self>,
549
) -> Result<u64, String> {
550
let mut action = self
409
551
.settings
410
552
.actions
411
553
.iter()
@@ -421,17 +563,33 @@ impl AgentRuns {
421
563
.ok_or("The agent of this action no longer exists")?;
422
564
let context = message_context::build(self.app.read(cx), conversation_id, message_id)
423
565
.ok_or("The message is no longer available")?;
424
let session_id = agents::new_session_id();
425
let prompt = agents::build_prompt(&action, &context, extra, &session_id, &profile.id);
426
let endpoint = mcp_bridge::endpoint(cx);
427
let plan = agents::build_invocation(
428
&profile,
429
&action,
430
&prompt,
431
&session_id,
432
endpoint.as_ref(),
433
mcp_config_directory().as_deref(),
434
);
566
let chosen_working_dir = options
567
.working_dir
568
.clone()
569
.filter(|_| options.session.is_none() && options.remember_working_dir);
570
if let Some(target) = &options.session {
571
action.working_dir = target.working_dir.clone();
572
} else if let Some(working_dir) = &options.working_dir {
573
action.working_dir = working_dir.clone();
574
}
575
let (session_id, prompt) = match &options.session {
576
Some(target) => {
577
let session_id = if target.fork {
578
agents::new_session_id()
579
} else {
580
target.session_id.clone()
581
};
582
let prompt =
583
agents::build_session_prompt(&context, extra, &session_id, &profile.id);
584
(session_id, prompt)
585
}
586
None => {
587
let session_id = agents::new_session_id();
588
let prompt =
589
agents::build_prompt(&action, &context, extra, &session_id, &profile.id);
590
(session_id, prompt)
591
}
592
};
435
593
let run_id = self.next_id;
436
594
self.next_id += 1;
437
595
self.runs.push(AgentRun {
@@ -456,19 +614,146 @@ impl AgentRuns {
456
614
expanded: false,
457
615
dismissed: false,
458
616
process_id: None,
617
pending_prompt: Some(prompt),
618
sent_to: options.session.clone(),
619
launch_session_id: None,
620
launched: false,
459
621
});
460
if endpoint.is_none()
622
if mcp_bridge::endpoint(cx).is_none()
461
623
&& let Some(run) = self.run_mut(run_id)
462
624
{
463
625
run.push_step("MCP server is off - no reply proposal possible".to_owned());
464
626
}
465
match plan {
466
Ok(plan) => self.spawn(run_id, plan, profile.output, cx),
467
Err(error) => self.finish(
627
self.dispatch(run_id, cx);
628
if let Some(working_dir) = chosen_working_dir {
629
self.update_settings(
630
|settings| settings.remember_working_dir(&profile.id, &working_dir),
631
cx,
632
);
633
}
634
self.persist(cx);
635
self.ensure_ticking(cx);
636
cx.notify();
637
Ok(run_id)
638
}
639
640
fn dispatch(&mut self, run_id: u64, cx: &mut Context<Self>) {
641
let Some(session_id) = self.get(run_id).map(|run| run.session_id.clone()) else {
642
return;
643
};
644
match self.lanes.admit(&session_id, run_id) {
645
Admit::Launch => self.launch(run_id, cx),
646
Admit::Queued => {
647
if let Some(run) = self.run_mut(run_id) {
648
run.push_step(QUEUED_STEP.to_owned());
649
}
650
}
651
}
652
}
653
654
fn release(&mut self, session_id: &str, cx: &mut Context<Self>) {
655
let runs = &self.runs;
656
let next = self.lanes.next(session_id, |run_id| {
657
runs.iter().any(|run| run.id == run_id && run.is_queued())
658
});
659
if let Some(next) = next {
660
self.launch(next, cx);
661
}
662
}
663
664
fn finish_kill(&mut self, session_id: &str, cx: &mut Context<Self>) {
665
let session_id = &self.lanes.resolve(session_id);
666
self.lanes.kill_done(session_id);
667
self.open_deferred_for(session_id, cx);
668
self.release(session_id, cx);
669
}
670
671
fn open_deferred_for(&mut self, session_id: &str, cx: &mut Context<Self>) {
672
if self.lanes.has_kills_pending(session_id) {
673
return;
674
}
675
let ready: Vec<u64> = self
676
.open_deferred
677
.iter()
678
.copied()
679
.filter(|run_id| {
680
self.get(*run_id)
681
.is_some_and(|run| run.session_id == session_id)
682
})
683
.collect();
684
for run_id in ready {
685
self.open_deferred.remove(&run_id);
686
if let Some(run) = self.get(run_id).cloned() {
687
self.open_and_cancel(&run, cx);
688
}
689
}
690
}
691
692
fn run_kill(
693
&mut self,
694
session_id: &str,
695
stop: Option<agents::Invocation>,
696
cx: &mut Context<Self>,
697
) {
698
let Some(stop) = stop else {
699
self.finish_kill(session_id, cx);
700
return;
701
};
702
let session_id = session_id.to_owned();
703
cx.spawn(async move |this, cx| {
704
kills::execute(stop).await;
705
this.update(cx, |runs, cx| runs.finish_kill(&session_id, cx))
706
.ok();
707
})
708
.detach();
709
}
710
711
fn open_and_cancel(&mut self, run: &AgentRun, cx: &mut Context<Self>) {
712
open_run_session(run, cx);
713
let waiting = self.lanes.drain_waiting(&run.session_id);
714
for run_id in &waiting {
715
if let Some(waiting_run) = self.run_mut(*run_id) {
716
waiting_run.pending_prompt = None;
717
}
718
self.finish(
719
*run_id,
720
Some(RunOutcome {
721
status: RunStatus::Stopped,
722
exit_code: None,
723
}),
724
cx,
725
);
726
if let Some(waiting_run) = self.run_mut(*run_id) {
727
waiting_run.current_step = OPENED_NOTICE.to_owned();
728
}
729
}
730
if !waiting.is_empty() {
731
self.persist(cx);
732
raise_notice(OPENED_NOTICE.to_owned(), cx);
733
}
734
self.release(&run.session_id, cx);
735
}
736
737
fn launch(&mut self, run_id: u64, cx: &mut Context<Self>) {
738
let Some(run) = self.get(run_id).cloned() else {
739
return;
740
};
741
let prompt = run.pending_prompt.clone().unwrap_or_default();
742
let planned = self.launch_plan(&run, &prompt, cx);
743
if let Some(run) = self.run_mut(run_id) {
744
run.pending_prompt = None;
745
if run.current_step == QUEUED_STEP {
746
run.started_at = Utc::now();
747
run.push_step("Starting".to_owned());
748
}
749
}
750
match planned {
751
Ok((plan, format)) => self.spawn(run_id, plan, format, cx),
752
Err(message) => self.finish(
468
753
run_id,
469
754
Some(RunOutcome {
470
755
status: RunStatus::Failed {
471
message: error.to_string(),
756
message,
472
757
stderr_tail: Vec::new(),
473
758
},
474
759
exit_code: None,
@@ -477,9 +762,41 @@ impl AgentRuns {
477
762
),
478
763
}
479
764
self.persist(cx);
480
self.ensure_ticking(cx);
481
cx.notify();
482
Ok(run_id)
765
}
766
767
fn launch_plan(
768
&self,
769
run: &AgentRun,
770
prompt: &str,
771
cx: &App,
772
) -> Result<(agents::RunPlan, agents::OutputFormat), String> {
773
let action = self
774
.settings
775
.actions
776
.iter()
777
.find(|action| action.id == run.action_id)
778
.cloned()
779
.ok_or("the action no longer exists")?;
780
let profile = self
781
.settings
782
.agents
783
.iter()
784
.find(|profile| profile.id == run.agent_id)
785
.ok_or("the agent no longer exists")?;
786
let action = AgentAction {
787
working_dir: run.working_dir.clone(),
788
..action
789
};
790
plan_for(
791
profile,
792
&action,
793
prompt,
794
&run.session_id,
795
run.sent_to.as_ref(),
796
mcp_bridge::endpoint(cx).as_ref(),
797
)
798
.map(|plan| (plan, profile.output))
799
.map_err(|error| error.to_string())
483
800
}
484
801
485
802
fn spawn(
@@ -492,6 +809,9 @@ impl AgentRuns {
492
809
let (updates_sender, mut updates) = mpsc::unbounded_channel();
493
810
let (stop_sender, stop_receiver) = oneshot::channel();
494
811
self.stops.insert(run_id, stop_sender);
812
if let Some(run) = self.run_mut(run_id) {
813
run.launch_session_id = Some(run.session_id.clone());
814
}
495
815
let outcome = runtime::spawn(agents::run(plan, format, updates_sender, stop_receiver));
496
816
cx.spawn(async move |this, cx| {
497
817
while let Some(update) = updates.recv().await {
@@ -515,6 +835,7 @@ impl AgentRuns {
515
835
RunUpdate::Started(process_id) => {
516
836
if let Some(run) = self.run_mut(run_id) {
517
837
run.process_id = Some(process_id);
838
run.launched = true;
518
839
self.persist(cx);
519
840
}
520
841
return;
@@ -529,11 +850,27 @@ impl AgentRuns {
529
850
RunEvent::Text(text) => {
530
851
run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)
531
852
}
853
RunEvent::SessionId(session_id) if session_id != run.session_id => {
854
let previous = std::mem::replace(&mut run.session_id, session_id.clone());
855
self.move_lane(&previous, &session_id);
856
self.persist(cx);
857
}
532
858
_ => return,
533
859
}
534
860
cx.notify();
535
861
}
536
862
863
fn move_lane(&mut self, from: &str, to: &str) {
864
for run_id in self.lanes.rename(from, to) {
865
if let Some(run) = self.run_mut(run_id) {
866
run.session_id = to.to_owned();
867
if let Some(target) = run.sent_to.as_mut().filter(|target| !target.fork) {
868
target.session_id = to.to_owned();
869
}
870
}
871
}
872
}
873
537
874
fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {
538
875
self.stops.remove(&run_id);
539
876
self.stopping.remove(&run_id);
@@ -590,12 +927,21 @@ impl AgentRuns {
590
927
if failed_or_done {
591
928
cx.emit(AgentRunsEvent::Finished(run_id));
592
929
}
593
if self.open_after_stop.remove(&run_id) && stopped {
594
open_run_session(&snapshot, cx);
930
let session_id = snapshot.session_id.clone();
931
let was_active = self.lanes.finished(&session_id, run_id);
932
if self.open_after_stop.remove(&run_id) {
933
if self.lanes.has_kills_pending(&session_id) {
934
self.open_deferred.insert(run_id);
935
} else {
936
self.open_and_cancel(&snapshot, cx);
937
}
595
938
}
596
939
if was_resuming {
597
940
self.resume_next(cx);
598
941
}
942
if was_active {
943
self.release(&session_id, cx);
944
}
599
945
cx.notify();
600
946
}
601
947
@@ -647,10 +993,36 @@ impl AgentRuns {
647
993
run.current_step = "Stopping".to_owned();
648
994
}
649
995
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);
996
} else if self.get(run_id).is_some_and(AgentRun::is_queued) {
997
let session_id = self.get(run_id).map(|run| run.session_id.clone());
998
if let Some(session_id) = session_id {
999
self.lanes.remove_waiting(&session_id, run_id);
1000
}
1001
if let Some(run) = self.run_mut(run_id) {
1002
run.pending_prompt = None;
653
1003
}
1004
self.finish(
1005
run_id,
1006
Some(RunOutcome {
1007
status: RunStatus::Stopped,
1008
exit_code: None,
1009
}),
1010
cx,
1011
);
1012
} else if self.resuming.contains(&run_id) || self.resume_queue.contains(&run_id) {
1013
let orphan_stop = self
1014
.resume_queue
1015
.contains(&run_id)
1016
.then(|| {
1017
self.get(run_id).and_then(|run| {
1018
kills::orphan_kill(run, |candidate| {
1019
self.resume_plan(candidate, cx).ok().map(|(plan, _)| plan)
1020
})
1021
})
1022
})
1023
.flatten();
1024
let was_queued_for_resume = self.resume_queue.contains(&run_id);
1025
let session_id = self.get(run_id).map(|run| run.session_id.clone());
654
1026
self.resume_queue.retain(|queued| *queued != run_id);
655
1027
self.finish(
656
1028
run_id,
@@ -660,28 +1032,27 @@ impl AgentRuns {
660
1032
}),
661
1033
cx,
662
1034
);
1035
if let (true, Some(session_id)) = (was_queued_for_resume, session_id) {
1036
self.run_kill(&session_id, orphan_stop, cx);
1037
}
663
1038
}
664
1039
}
665
1040
666
fn stop_orphan(&self, run_id: u64, cx: &App) {
667
let Some(run) = self.get(run_id) else {
1041
pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) {
1042
let Some(run) = self.get(run_id).cloned() else {
668
1043
return;
669
1044
};
670
let Ok((plan, _)) = self.resume_plan(run, cx) else {
1045
if run.is_finished() {
1046
if self.lanes.has_kills_pending(&run.session_id) {
1047
self.open_deferred.insert(run_id);
1048
} else {
1049
self.open_and_cancel(&run, cx);
1050
}
671
1051
return;
672
};
673
for path in &plan.cleanup {
674
let _ = std::fs::remove_file(path);
675
1052
}
676
if let Some(stop) = orphan_stop(run, &plan) {
677
drop(runtime::spawn(async move {
678
agents::run_stop_invocation(&stop).await
679
}));
1053
if !run.is_queued() {
1054
self.open_after_stop.insert(run_id);
680
1055
}
681
}
682
683
pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) {
684
self.open_after_stop.insert(run_id);
685
1056
self.stop(run_id, cx);
686
1057
}
687
1058
@@ -690,11 +1061,24 @@ impl AgentRuns {
690
1061
.get(run_id)
691
1062
.cloned()
692
1063
.ok_or("This run no longer exists")?;
693
let started = self.start(
1064
let options = StartOptions {
1065
working_dir: run.sent_to.is_none().then(|| run.working_dir.clone()),
1066
remember_working_dir: false,
1067
session: run.sent_to.clone().map(|target| SessionTarget {
1068
session_id: if target.fork {
1069
target.session_id
1070
} else {
1071
run.session_id.clone()
1072
},
1073
..target
1074
}),
1075
};
1076
let started = self.start_with(
694
1077
&run.action_id,
695
1078
&run.conversation_id,
696
1079
&run.message_id,
697
1080
&run.extra,
1081
options,
698
1082
cx,
699
1083
)?;
700
1084
self.dismiss(run_id, cx);
@@ -729,7 +1113,9 @@ pub(super) mod tests {
729
1113
730
1114
use gpui_kit::{AppContext as _, Entity, TestAppContext};
731
1115
732
use super::{AgentRun, AgentRuns, RunState, Utc, format_elapsed, run_store};
1116
use super::{
1117
AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, format_elapsed, run_store,
1118
};
733
1119
use crate::app_state::{AppState, Mode};
734
1120
735
1121
pub fn finished_run(id: u64) -> AgentRun {
@@ -755,6 +1141,10 @@ pub(super) mod tests {
755
1141
expanded: false,
756
1142
dismissed: false,
757
1143
process_id: None,
1144
pending_prompt: None,
1145
sent_to: None,
1146
launch_session_id: None,
1147
launched: true,
758
1148
}
759
1149
}
760
1150
@@ -781,6 +1171,7 @@ pub(super) mod tests {
781
1171
agents: vec![profile],
782
1172
actions: vec![action],
783
1173
resume_interrupted_runs: true,
1174
..AgentSettings::default()
784
1175
}
785
1176
}
786
1177
@@ -827,9 +1218,531 @@ pub(super) mod tests {
827
1218
828
1219
#[cfg(unix)]
829
1220
mod shell_runs {
1221
use std::time::Duration;
1222
830
1223
use gpui_kit::AppContext as _;
831
1224
832
use super::{AgentRuns, RunState, TestAppContext, run_store, setup, wait_until_finished};
1225
use super::{
1226
AgentRun, AgentRuns, Entity, RunState, SessionTarget, StartOptions, TestAppContext,
1227
run_store, setup, wait_until_finished,
1228
};
1229
1230
const SESSION_COMMAND: &str = "sh -c 'sleep 1' --session-id {session_id}";
1231
1232
fn target_of(session_id: String) -> StartOptions {
1233
StartOptions {
1234
working_dir: None,
1235
remember_working_dir: false,
1236
session: Some(SessionTarget {
1237
session_id,
1238
working_dir: std::env::temp_dir().to_string_lossy().into_owned(),
1239
fork: false,
1240
}),
1241
}
1242
}
1243
1244
type LaneView = Option<(Option<u64>, Vec<u64>)>;
1245
1246
fn lane_of(
1247
cx: &mut TestAppContext,
1248
runs: &Entity<AgentRuns>,
1249
session_id: &str,
1250
) -> LaneView {
1251
cx.update(|cx| {
1252
runs.read(cx).lanes.get(session_id).map(|lane| {
1253
(
1254
lane.active.first().copied(),
1255
lane.waiting.iter().copied().collect::<Vec<u64>>(),
1256
)
1257
})
1258
})
1259
}
1260
1261
fn send_chain(
1262
cx: &mut TestAppContext,
1263
runs: &Entity<AgentRuns>,
1264
) -> (u64, u64, u64, String) {
1265
cx.update(|cx| {
1266
runs.update(cx, |runs, cx| {
1267
let first = runs.start("ask", "19:chat", "m1", "", cx).unwrap();
1268
let session_id = runs.get(first).unwrap().session_id.clone();
1269
let second = runs
1270
.start_with(
1271
"ask",
1272
"19:chat",
1273
"m1",
1274
"two",
1275
target_of(session_id.clone()),
1276
cx,
1277
)
1278
.unwrap();
1279
let third = runs
1280
.start_with(
1281
"ask",
1282
"19:chat",
1283
"m1",
1284
"three",
1285
target_of(session_id.clone()),
1286
cx,
1287
)
1288
.unwrap();
1289
(first, second, third, session_id)
1290
})
1291
})
1292
}
1293
1294
fn started_and_ended(
1295
cx: &mut TestAppContext,
1296
runs: &Entity<AgentRuns>,
1297
run_id: u64,
1298
) -> (chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>) {
1299
cx.update(|cx| {
1300
let run = runs.read(cx).get(run_id).unwrap();
1301
(run.started_at, run.ended_at.unwrap())
1302
})
1303
}
1304
1305
#[gpui_kit::test]
1306
fn two_sends_to_one_session_run_strictly_one_after_another(cx: &mut TestAppContext) {
1307
let (_, runs) = setup(cx, SESSION_COMMAND);
1308
let (first, second, third, session_id) = send_chain(cx, &runs);
1309
assert_eq!(
1310
lane_of(cx, &runs, &session_id),
1311
Some((Some(first), vec![second, third]))
1312
);
1313
cx.update(|cx| {
1314
let queued = runs.read(cx).get(second).unwrap();
1315
assert_eq!(queued.current_step, "Queued");
1316
let prompt = queued.pending_prompt.clone().unwrap();
1317
assert!(prompt.contains("propose_message") && prompt.contains("m1"));
1318
assert!(prompt.ends_with("\n\ntwo"));
1319
assert_eq!(queued.extra, "two");
1320
assert_eq!(queued.session_id, session_id);
1321
});
1322
wait_until_finished(cx, &runs, first);
1323
assert_eq!(
1324
lane_of(cx, &runs, &session_id),
1325
Some((Some(second), vec![third]))
1326
);
1327
cx.update(|cx| {
1328
assert!(!runs.read(cx).get(second).unwrap().is_queued());
1329
assert!(runs.read(cx).get(third).unwrap().is_queued());
1330
});
1331
wait_until_finished(cx, &runs, second);
1332
assert_eq!(lane_of(cx, &runs, &session_id), Some((Some(third), vec![])));
1333
wait_until_finished(cx, &runs, third);
1334
assert_eq!(lane_of(cx, &runs, &session_id), None);
1335
let (_, first_ended) = started_and_ended(cx, &runs, first);
1336
let (second_started, second_ended) = started_and_ended(cx, &runs, second);
1337
let (third_started, _) = started_and_ended(cx, &runs, third);
1338
assert!(second_started >= first_ended);
1339
assert!(third_started >= second_ended);
1340
}
1341
1342
#[gpui_kit::test]
1343
fn a_reported_session_id_moves_the_whole_lane_and_its_waiting_runs(
1344
cx: &mut TestAppContext,
1345
) {
1346
let (_, runs) = setup(cx, SESSION_COMMAND);
1347
let (first, second, third, session_id) = send_chain(cx, &runs);
1348
cx.update(|cx| {
1349
runs.update(cx, |runs, cx| {
1350
runs.apply_update(
1351
first,
1352
agents::RunUpdate::Event(agents::RunEvent::SessionId("adopted".to_owned())),
1353
cx,
1354
)
1355
});
1356
let runs = runs.read(cx);
1357
assert_eq!(
1358
runs.get(first).unwrap().launch_session_id,
1359
Some(session_id.clone())
1360
);
1361
assert_eq!(runs.get(first).unwrap().session_id, "adopted");
1362
for run_id in [second, third] {
1363
assert_eq!(runs.get(run_id).unwrap().session_id, "adopted");
1364
}
1365
});
1366
assert_eq!(lane_of(cx, &runs, &session_id), None);
1367
assert_eq!(
1368
lane_of(cx, &runs, "adopted"),
1369
Some((Some(first), vec![second, third]))
1370
);
1371
wait_until_finished(cx, &runs, first);
1372
assert_eq!(
1373
lane_of(cx, &runs, "adopted"),
1374
Some((Some(second), vec![third]))
1375
);
1376
wait_until_finished(cx, &runs, second);
1377
wait_until_finished(cx, &runs, third);
1378
}
1379
1380
#[gpui_kit::test]
1381
fn stopping_a_waiting_send_only_removes_it_from_the_lane(cx: &mut TestAppContext) {
1382
let (_, runs) = setup(cx, SESSION_COMMAND);
1383
let (first, second, third, session_id) = send_chain(cx, &runs);
1384
cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(second, cx)));
1385
cx.update(|cx| {
1386
let stopped = runs.read(cx).get(second).unwrap();
1387
assert_eq!(stopped.state, RunState::Stopped);
1388
assert!(!stopped.is_queued());
1389
});
1390
assert_eq!(
1391
lane_of(cx, &runs, &session_id),
1392
Some((Some(first), vec![third]))
1393
);
1394
wait_until_finished(cx, &runs, first);
1395
assert_eq!(lane_of(cx, &runs, &session_id), Some((Some(third), vec![])));
1396
wait_until_finished(cx, &runs, third);
1397
}
1398
1399
#[gpui_kit::test]
1400
fn stop_and_open_cancels_every_waiting_send_of_the_lane(cx: &mut TestAppContext) {
1401
let (app, runs) = setup(cx, SESSION_COMMAND);
1402
let (first, second, third, session_id) = send_chain(cx, &runs);
1403
cx.update(|cx| runs.update(cx, |runs, cx| runs.stop_and_open_session(first, cx)));
1404
wait_until_finished(cx, &runs, first);
1405
cx.update(|cx| {
1406
for run_id in [second, third] {
1407
let run = runs.read(cx).get(run_id).unwrap();
1408
assert_eq!(run.state, RunState::Stopped);
1409
assert_eq!(
1410
run.current_step,
1411
"Session opened in a terminal - send cancelled"
1412
);
1413
assert!(!run.is_queued());
1414
}
1415
assert!(runs.read(cx).open_after_stop.is_empty());
1416
});
1417
assert_eq!(lane_of(cx, &runs, &session_id), None);
1418
cx.update(|cx| {
1419
let stored = run_store::load_runs(&app.read(cx).store);
1420
let notice = stored.iter().find(|run| run.id == second).unwrap();
1421
assert_eq!(
1422
notice.current_step,
1423
"Session opened in a terminal - send cancelled"
1424
);
1425
});
1426
}
1427
1428
#[gpui_kit::test]
1429
fn a_requested_open_fires_whatever_the_outcome_of_the_run(cx: &mut TestAppContext) {
1430
let (_, runs) = setup(cx, "sh -c 'sleep 1; exit 3' --session-id {session_id}");
1431
let (first, second, _, session_id) = send_chain(cx, &runs);
1432
cx.update(|cx| runs.update(cx, |runs, _| runs.open_after_stop.insert(first)));
1433
wait_until_finished(cx, &runs, first);
1434
cx.update(|cx| {
1435
assert!(matches!(
1436
runs.read(cx).get(first).unwrap().state,
1437
RunState::Failed { .. }
1438
));
1439
assert_eq!(runs.read(cx).get(second).unwrap().state, RunState::Stopped);
1440
assert!(runs.read(cx).open_after_stop.is_empty());
1441
});
1442
assert_eq!(lane_of(cx, &runs, &session_id), None);
1443
}
1444
1445
#[gpui_kit::test]
1446
fn a_run_that_never_launched_is_interrupted_not_resumed(cx: &mut TestAppContext) {
1447
let (app, _) = setup(cx, SESSION_COMMAND);
1448
let mut never_started = super::running_run(5);
1449
never_started.launched = false;
1450
let reloaded = reload(cx, &app, vec![never_started]);
1451
cx.update(|cx| {
1452
assert!(reloaded.read(cx).get(5).unwrap().is_finished());
1453
});
1454
assert_eq!(lane_of(cx, &reloaded, "session-5"), None);
1455
}
1456
1457
#[gpui_kit::test]
1458
fn stop_and_open_waits_for_the_orphan_kill_before_cancelling_the_lane(
1459
cx: &mut TestAppContext,
1460
) {
1461
let (app, _) = setup(cx, SESSION_COMMAND);
1462
let mut orphan = super::running_run(5);
1463
orphan.session_id = "shared".to_owned();
1464
orphan.process_id = Some(1);
1465
let reloaded = reload(cx, &app, vec![orphan, queued_run(7)]);
1466
cx.update(|cx| {
1467
reloaded.update(cx, |runs, cx| runs.stop_and_open_session(5, cx));
1468
let runs = reloaded.read(cx);
1469
assert!(runs.get(5).unwrap().is_finished());
1470
assert!(runs.open_deferred.contains(&5));
1471
assert!(runs.get(7).unwrap().is_queued());
1472
assert!(runs.lanes.has_kills_pending("shared"));
1473
});
1474
for _ in 0..200 {
1475
cx.run_until_parked();
1476
if lane_of(cx, &reloaded, "shared").is_none() {
1477
break;
1478
}
1479
std::thread::sleep(Duration::from_millis(10));
1480
}
1481
cx.update(|cx| {
1482
let runs = reloaded.read(cx);
1483
assert_eq!(runs.get(7).unwrap().state, RunState::Stopped);
1484
assert!(runs.open_after_stop.is_empty() && runs.open_deferred.is_empty());
1485
});
1486
}
1487
1488
#[gpui_kit::test]
1489
fn a_send_during_an_in_flight_kill_waits_for_the_resumed_run(cx: &mut TestAppContext) {
1490
let (app, _) = setup(cx, SESSION_COMMAND);
1491
let mut orphan = super::running_run(5);
1492
orphan.session_id = "shared".to_owned();
1493
orphan.process_id = Some(1);
1494
let reloaded = reload(cx, &app, vec![orphan]);
1495
let sent = cx.update(|cx| {
1496
reloaded.update(cx, |runs, cx| {
1497
runs.start_with(
1498
"ask",
1499
"19:chat",
1500
"m1",
1501
"hi",
1502
target_of("shared".to_owned()),
1503
cx,
1504
)
1505
.unwrap()
1506
})
1507
});
1508
assert_eq!(
1509
lane_of(cx, &reloaded, "shared"),
1510
Some((Some(5), vec![sent]))
1511
);
1512
wait_until_finished(cx, &reloaded, 5);
1513
wait_until_finished(cx, &reloaded, sent);
1514
let (_, resumed_ended) = started_and_ended(cx, &reloaded, 5);
1515
let (sent_started, _) = started_and_ended(cx, &reloaded, sent);
1516
assert!(sent_started >= resumed_ended);
1517
}
1518
1519
#[test]
1520
fn old_saved_runs_with_a_chain_id_still_load() {
1521
let mut value = serde_json::to_value(super::running_run(3)).unwrap();
1522
let object = value.as_object_mut().unwrap();
1523
for key in ["sent_to", "launch_session_id", "launched", "pending_prompt"] {
1524
object.remove(key);
1525
}
1526
object.insert("after_run_id".to_owned(), serde_json::json!(2));
1527
object.insert("pending_prompt".to_owned(), serde_json::json!("saved"));
1528
let run: AgentRun = serde_json::from_value(value).unwrap();
1529
assert!(run.is_queued());
1530
assert!(run.launched);
1531
assert_eq!(run.sent_to, None);
1532
}
1533
1534
#[gpui_kit::test]
1535
fn a_forked_send_gets_a_fresh_session_id_and_adopts_a_reported_one(
1536
cx: &mut TestAppContext,
1537
) {
1538
let (app, runs) = setup(cx, SESSION_COMMAND);
1539
let forked = cx.update(|cx| {
1540
runs.update(cx, |runs, cx| {
1541
let mut options = target_of("live-session".to_owned());
1542
options.session.as_mut().unwrap().fork = true;
1543
runs.start_with("ask", "19:chat", "m1", "hi", options, cx)
1544
.unwrap()
1545
})
1546
});
1547
cx.update(|cx| {
1548
let run = runs.read(cx).get(forked).unwrap().clone();
1549
assert_ne!(run.session_id, "live-session");
1550
assert!(run.sent_to.as_ref().unwrap().fork);
1551
assert!(!run.is_queued());
1552
runs.update(cx, |runs, cx| {
1553
runs.apply_update(
1554
forked,
1555
agents::RunUpdate::Event(agents::RunEvent::SessionId(
1556
"reported".to_owned(),
1557
)),
1558
cx,
1559
)
1560
});
1561
assert_eq!(runs.read(cx).get(forked).unwrap().session_id, "reported");
1562
let stored = run_store::load_runs(&app.read(cx).store);
1563
assert_eq!(stored[0].session_id, "reported");
1564
});
1565
wait_until_finished(cx, &runs, forked);
1566
}
1567
1568
#[gpui_kit::test]
1569
fn retrying_a_plain_run_keeps_its_chosen_working_dir_without_recording_it(
1570
cx: &mut TestAppContext,
1571
) {
1572
let (_, runs) = setup(cx, SESSION_COMMAND);
1573
let started = cx.update(|cx| {
1574
runs.update(cx, |runs, cx| {
1575
runs.start_with(
1576
"ask",
1577
"19:chat",
1578
"m1",
1579
"",
1580
StartOptions {
1581
working_dir: Some("/srv/chosen".to_owned()),
1582
remember_working_dir: false,
1583
session: None,
1584
},
1585
cx,
1586
)
1587
.unwrap()
1588
})
1589
});
1590
wait_until_finished(cx, &runs, started);
1591
let retried =
1592
cx.update(|cx| runs.update(cx, |runs, cx| runs.retry(started, cx)).unwrap());
1593
cx.update(|cx| {
1594
assert_eq!(
1595
runs.read(cx).get(retried).unwrap().working_dir,
1596
"/srv/chosen"
1597
);
1598
assert!(
1599
runs.read(cx)
1600
.settings()
1601
.recent_working_dirs_of("fake")
1602
.is_empty()
1603
);
1604
});
1605
wait_until_finished(cx, &runs, retried);
1606
}
1607
1608
#[gpui_kit::test]
1609
fn retrying_a_session_send_sends_to_the_same_session_again(cx: &mut TestAppContext) {
1610
let (_, runs) = setup(cx, SESSION_COMMAND);
1611
let sent = cx.update(|cx| {
1612
runs.update(cx, |runs, cx| {
1613
runs.start_with(
1614
"ask",
1615
"19:chat",
1616
"m1",
1617
"again please",
1618
target_of("old-session".to_owned()),
1619
cx,
1620
)
1621
.unwrap()
1622
})
1623
});
1624
wait_until_finished(cx, &runs, sent);
1625
let retried = cx.update(|cx| runs.update(cx, |runs, cx| runs.retry(sent, cx)).unwrap());
1626
cx.update(|cx| {
1627
let run = runs.read(cx).get(retried).unwrap();
1628
assert_eq!(run.session_id, "old-session");
1629
assert_eq!(run.extra, "again please");
1630
assert_eq!(run.sent_to.as_ref().unwrap().session_id, "old-session");
1631
});
1632
wait_until_finished(cx, &runs, retried);
1633
}
1634
1635
fn queued_run(id: u64) -> AgentRun {
1636
let mut run = super::running_run(id);
1637
run.session_id = "shared".to_owned();
1638
run.current_step = "Queued".to_owned();
1639
run.pending_prompt = Some("saved prompt".to_owned());
1640
run
1641
}
1642
1643
fn reload(
1644
cx: &mut TestAppContext,
1645
app: &Entity<crate::app_state::AppState>,
1646
stored: Vec<AgentRun>,
1647
) -> Entity<AgentRuns> {
1648
cx.update(|cx| {
1649
run_store::save_runs(&app.read(cx).store, &stored);
1650
cx.new(|cx| AgentRuns::new(app.clone(), cx))
1651
})
1652
}
1653
1654
#[gpui_kit::test]
1655
fn a_restart_rebuilds_the_lane_and_never_runs_two_processes_on_one_session(
1656
cx: &mut TestAppContext,
1657
) {
1658
let (app, _) = setup(cx, SESSION_COMMAND);
1659
let mut active = super::running_run(5);
1660
active.session_id = "shared".to_owned();
1661
let mut duplicate = super::running_run(6);
1662
duplicate.session_id = "shared".to_owned();
1663
let reloaded = reload(
1664
cx,
1665
&app,
1666
vec![active, duplicate, queued_run(7), queued_run(8)],
1667
);
1668
cx.update(|cx| {
1669
let runs = reloaded.read(cx);
1670
assert!(runs.get(6).unwrap().is_finished());
1671
assert!(runs.get(7).unwrap().is_queued() && runs.get(8).unwrap().is_queued());
1672
});
1673
assert_eq!(
1674
lane_of(cx, &reloaded, "shared"),
1675
Some((Some(5), vec![7, 8]))
1676
);
1677
wait_until_finished(cx, &reloaded, 5);
1678
assert_eq!(lane_of(cx, &reloaded, "shared"), Some((Some(7), vec![8])));
1679
wait_until_finished(cx, &reloaded, 7);
1680
wait_until_finished(cx, &reloaded, 8);
1681
let (_, ended_5) = started_and_ended(cx, &reloaded, 5);
1682
let (started_7, ended_7) = started_and_ended(cx, &reloaded, 7);
1683
let (started_8, _) = started_and_ended(cx, &reloaded, 8);
1684
assert!(started_7 >= ended_5 && started_8 >= ended_7);
1685
}
1686
1687
#[gpui_kit::test]
1688
fn a_waiting_send_without_a_predecessor_runs_after_a_restart(cx: &mut TestAppContext) {
1689
let (app, _) = setup(cx, SESSION_COMMAND);
1690
let reloaded = reload(cx, &app, vec![queued_run(7), queued_run(8)]);
1691
assert_eq!(lane_of(cx, &reloaded, "shared"), Some((None, vec![7, 8])));
1692
cx.run_until_parked();
1693
assert_eq!(lane_of(cx, &reloaded, "shared"), Some((Some(7), vec![8])));
1694
wait_until_finished(cx, &reloaded, 7);
1695
wait_until_finished(cx, &reloaded, 8);
1696
assert_eq!(lane_of(cx, &reloaded, "shared"), None);
1697
}
1698
1699
#[gpui_kit::test]
1700
fn a_message_to_an_idle_session_resumes_it_and_a_chosen_dir_becomes_recent(
1701
cx: &mut TestAppContext,
1702
) {
1703
let (_, runs) = setup(cx, SESSION_COMMAND);
1704
let (resumed, other) = cx.update(|cx| {
1705
runs.update(cx, |runs, cx| {
1706
let resumed = runs
1707
.start_with(
1708
"ask",
1709
"19:chat",
1710
"m1",
1711
"hello",
1712
target_of("old-session".to_owned()),
1713
cx,
1714
)
1715
.unwrap();
1716
let other = runs
1717
.start_with(
1718
"ask",
1719
"19:chat",
1720
"m1",
1721
"",
1722
StartOptions {
1723
working_dir: Some("/srv/other".to_owned()),
1724
remember_working_dir: true,
1725
session: None,
1726
},
1727
cx,
1728
)
1729
.unwrap();
1730
(resumed, other)
1731
})
1732
});
1733
cx.update(|cx| {
1734
let resumed = runs.read(cx).get(resumed).unwrap().clone();
1735
assert_eq!(resumed.session_id, "old-session");
1736
assert_ne!(resumed.current_step, "Queued");
1737
let other = runs.read(cx).get(other).unwrap().clone();
1738
assert_eq!(other.working_dir, "/srv/other");
1739
assert_eq!(
1740
runs.read(cx).settings().recent_working_dirs_of("fake"),
1741
["/srv/other"]
1742
);
1743
});
1744
wait_until_finished(cx, &runs, resumed);
1745
}
833
1746
834
1747
#[gpui_kit::test]
835
1748
fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {
@@ -885,7 +1798,7 @@ pub(super) mod tests {
885
1798
cx.update(|cx| {
886
1799
let run = reloaded.read(cx).get(5).unwrap().clone();
887
1800
assert_eq!(run.state, RunState::Done);
888
assert_eq!(run.session_id, "session-5");
1801
assert_eq!(run.session_id, "3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11");
889
1802
assert!(
890
1803
run.steps
891
1804
.iter()
@@ -1,15 +1,19 @@1
use std::collections::{HashMap, HashSet, VecDeque};1
use std::collections::{HashMap, HashSet, VecDeque};2
use std::time::Duration;2
use std::time::Duration;3
3
4
use agents::{AgentAction, AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate};4
use agents::{5
AgentAction, AgentProfile, AgentSettings, McpEndpoint, RunEvent, RunOutcome, RunStatus,6
RunUpdate,7
};5
use chrono::{DateTime, Utc};8
use chrono::{DateTime, Utc};6
use gpui_kit::*;9
use gpui_kit::*;7
use serde::{Deserialize, Serialize};10
use serde::{Deserialize, Serialize};8
use tokio::sync::{mpsc, oneshot};11
use tokio::sync::{mpsc, oneshot};9
12
13
use super::lanes::{Admit, Lanes, RestoreInfo};10
use super::{14
use super::{11
MCP_POLL_INTERVAL, MCP_WAIT_LIMIT, StartRequest, demo, mcp_bridge, mcp_config_directory,15
MCP_POLL_INTERVAL, MCP_WAIT_LIMIT, StartRequest, demo, kills, mcp_bridge, mcp_config_directory,12
message_context, open_run_session, store as run_store,16
message_context, open_run_session, raise_notice, store as run_store,13
};17
};14
use crate::app_state::AppState;18
use crate::app_state::AppState;15
use crate::notice::truncated;19
use crate::notice::truncated;@@ -22,6 +26,8 @@ const TEXT_STEP_CHARS: usize = 80;22
const DONE_STEP_CHARS: usize = 60;26
const DONE_STEP_CHARS: usize = 60;23
const TICK: Duration = Duration::from_secs(1);27
const TICK: Duration = Duration::from_secs(1);24
const RESUME_PARALLEL_LIMIT: usize = 3;28
const RESUME_PARALLEL_LIMIT: usize = 3;29
const QUEUED_STEP: &str = "Queued";30
const OPENED_NOTICE: &str = "Session opened in a terminal - send cancelled";25
const RESUMED_STEP: &str = "Resumed after restart";31
const RESUMED_STEP: &str = "Resumed after restart";26
const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";32
const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";27
33
@@ -58,6 +64,18 @@ pub struct AgentRun {58
pub dismissed: bool,64
pub dismissed: bool,59
#[serde(default)]65
#[serde(default)]60
pub process_id: Option<u32>,66
pub process_id: Option<u32>,67
#[serde(default)]68
pub pending_prompt: Option<String>,69
#[serde(default)]70
pub sent_to: Option<SessionTarget>,71
#[serde(default)]72
pub launch_session_id: Option<String>,73
#[serde(default = "launched_by_default")]74
pub launched: bool,75
}76
77
fn launched_by_default() -> bool {78
true61
}79
}62
80
63
impl AgentRun {81
impl AgentRun {@@ -65,6 +83,10 @@ impl AgentRun {65
self.state == RunState::Running83
self.state == RunState::Running66
}84
}67
85
86
pub fn is_queued(&self) -> bool {87
self.pending_prompt.is_some()88
}89
68
pub fn is_finished(&self) -> bool {90
pub fn is_finished(&self) -> bool {69
!self.is_running()91
!self.is_running()70
}92
}@@ -122,15 +144,9 @@ impl AgentRun {122
}144
}123
}145
}124
146
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 {147
fn can_resume(settings: &AgentSettings, run: &AgentRun) -> bool {133
settings.resume_interrupted_runs148
settings.resume_interrupted_runs149
&& run.launched134
&& !run.session_id.is_empty()150
&& !run.session_id.is_empty()135
&& settings151
&& settings136
.agents152
.agents@@ -163,6 +179,58 @@ fn first_line(text: &str) -> &str {163
.trim()179
.trim()164
}180
}165
181
182
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]183
pub struct SessionTarget {184
pub session_id: String,185
pub working_dir: String,186
pub fork: bool,187
}188
189
#[derive(Clone, Debug, Default, PartialEq, Eq)]190
pub struct StartOptions {191
pub working_dir: Option<String>,192
pub remember_working_dir: bool,193
pub session: Option<SessionTarget>,194
}195
196
fn plan_for(197
profile: &AgentProfile,198
action: &AgentAction,199
prompt: &str,200
session_id: &str,201
target: Option<&SessionTarget>,202
endpoint: Option<&McpEndpoint>,203
) -> Result<agents::RunPlan, agents::InvocationError> {204
let directory = mcp_config_directory();205
match target {206
None => agents::build_invocation(207
profile,208
action,209
prompt,210
session_id,211
endpoint,212
directory.as_deref(),213
),214
Some(target) if target.fork => agents::fork_invocation(215
profile,216
action,217
prompt,218
&target.session_id,219
session_id,220
endpoint,221
directory.as_deref(),222
),223
Some(_) => agents::resume_invocation(224
profile,225
action,226
prompt,227
session_id,228
endpoint,229
directory.as_deref(),230
),231
}232
}233
166
pub struct AgentRunsHandle(pub Entity<AgentRuns>);234
pub struct AgentRunsHandle(pub Entity<AgentRuns>);167
235
168
impl Global for AgentRunsHandle {}236
impl Global for AgentRunsHandle {}@@ -179,9 +247,12 @@ pub struct AgentRuns {179
runs: Vec<AgentRun>,247
runs: Vec<AgentRun>,180
stops: HashMap<u64, oneshot::Sender<()>>,248
stops: HashMap<u64, oneshot::Sender<()>>,181
resume_queue: VecDeque<u64>,249
resume_queue: VecDeque<u64>,250
lanes: Lanes,251
startup_kills: Vec<(String, agents::Invocation)>,182
resuming: HashSet<u64>,252
resuming: HashSet<u64>,183
stopping: HashSet<u64>,253
stopping: HashSet<u64>,184
open_after_stop: HashSet<u64>,254
open_after_stop: HashSet<u64>,255
open_deferred: HashSet<u64>,185
next_id: u64,256
next_id: u64,186
ticking: bool,257
ticking: bool,187
}258
}@@ -194,15 +265,33 @@ impl AgentRuns {194
let settings = run_store::load_settings(&store);265
let settings = run_store::load_settings(&store);195
let mut runs = run_store::load_runs(&store);266
let mut runs = run_store::load_runs(&store);196
let interrupted = runs.iter().any(AgentRun::is_running);267
let interrupted = runs.iter().any(AgentRun::is_running);197
let mut resume_queue = VecDeque::new();268
let infos: Vec<RestoreInfo> = runs198
for run in runs.iter_mut().filter(|run| run.is_running()) {269
.iter()199
if can_resume(&settings, run) {270
.filter(|run| run.is_running())271
.map(|run| RestoreInfo {272
id: run.id,273
session_id: run.session_id.clone(),274
queued: run.is_queued(),275
kill: kills::startup_kill(&settings, run),276
})277
.collect();278
let restored = Lanes::restore(&infos, |run_id| {279
runs.iter()280
.find(|run| run.id == run_id)281
.is_some_and(|run| can_resume(&settings, run))282
});283
for run in runs.iter_mut() {284
if restored.resume_queue.contains(&run.id) {200
run.push_step(RESUMED_STEP.to_owned());285
run.push_step(RESUMED_STEP.to_owned());201
resume_queue.push_back(run.id);286
} else if restored.interrupted.contains(&run.id) {202
} else {203
run.mark_interrupted();287
run.mark_interrupted();204
}288
}205
}289
}290
let (lanes, resume_queue, startup_kills) = (291
restored.lanes,292
VecDeque::from(restored.resume_queue),293
restored.kills,294
);206
if interrupted {295
if interrupted {207
run_store::save_runs(&store, &runs);296
run_store::save_runs(&store, &runs);208
}297
}@@ -217,9 +306,12 @@ impl AgentRuns {217
runs,306
runs,218
stops: HashMap::new(),307
stops: HashMap::new(),219
resume_queue,308
resume_queue,309
lanes,310
startup_kills,220
resuming: HashSet::new(),311
resuming: HashSet::new(),221
stopping: HashSet::new(),312
stopping: HashSet::new(),222
open_after_stop: HashSet::new(),313
open_after_stop: HashSet::new(),314
open_deferred: HashSet::new(),223
next_id,315
next_id,224
ticking: false,316
ticking: false,225
};317
};@@ -229,18 +321,18 @@ impl AgentRuns {229
}321
}230
322
231
fn start_resumes(&mut self, cx: &mut Context<Self>) {323
fn start_resumes(&mut self, cx: &mut Context<Self>) {232
if self.resume_queue.is_empty() {324
if self.lanes.is_empty() {233
return;325
return;234
}326
}235
let needs_mcp = self.resume_queue.iter().any(|run_id| {327
let needs_mcp = self.runs.iter().any(|run| {236
self.get(*run_id)328
run.is_running()237
.and_then(|run| {329
&& (self.resume_queue.contains(&run.id) || run.is_queued())238
self.settings330
&& self239
.agents331
.settings240
.iter()332
.agents241
.find(|agent| agent.id == run.agent_id)333
.iter()242
})334
.find(|agent| agent.id == run.agent_id)243
.is_some_and(|agent| !agent.mcp_config_flag.is_empty())335
.is_some_and(|agent| !agent.mcp_config_flag.is_empty())244
});336
});245
cx.spawn(async move |this, cx| {337
cx.spawn(async move |this, cx| {246
let mut waited = Duration::ZERO;338
let mut waited = Duration::ZERO;@@ -251,7 +343,16 @@ impl AgentRuns {251
cx.background_executor().timer(MCP_POLL_INTERVAL).await;343
cx.background_executor().timer(MCP_POLL_INTERVAL).await;252
waited += MCP_POLL_INTERVAL;344
waited += MCP_POLL_INTERVAL;253
}345
}254
this.update(cx, |runs, cx| runs.resume_next(cx)).ok();346
this.update(cx, |runs, cx| {347
runs.resume_next(cx);348
for (session_id, kill) in std::mem::take(&mut runs.startup_kills) {349
runs.run_kill(&session_id, Some(kill), cx);350
}351
for session_id in runs.lanes.idle_sessions() {352
runs.release(&session_id, cx);353
}354
})355
.ok();255
})356
})256
.detach();357
.detach();257
}358
}@@ -300,22 +401,28 @@ impl AgentRuns {300
}401
}301
402
302
fn begin_resume(&mut self, run_id: u64, cx: &mut Context<Self>) {403
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 {404
let Some(run) = self.get(run_id).cloned() else {304
return;405
return;305
};406
};407
if !run.is_running() {408
self.finish_kill(&run.session_id, cx);409
return;410
}306
self.resuming.insert(run_id);411
self.resuming.insert(run_id);412
let session_id = run.session_id.clone();307
match self.resume_plan(&run, cx) {413
match self.resume_plan(&run, cx) {308
Ok((plan, format)) => {414
Ok((plan, format)) => {309
let stop = orphan_stop(&run, &plan);415
let stop = kills::kill_for(&run, &plan, |launched| {416
self.resume_plan(launched, cx).ok().map(|(plan, _)| plan)417
});310
cx.spawn(async move |this, cx| {418
cx.spawn(async move |this, cx| {311
if let Some(stop) = stop {419
if let Some(stop) = stop {312
let _ =420
kills::execute(stop).await;313
runtime::spawn(async move { agents::run_stop_invocation(&stop).await })314
.await;315
}421
}316
this.update(cx, |runs, cx| {422
this.update(cx, |runs, cx| {317
let still_resuming = runs.resuming.contains(&run_id)423
let still_resuming = runs.resuming.contains(&run_id)318
&& runs.get(run_id).is_some_and(AgentRun::is_running);424
&& runs.get(run_id).is_some_and(AgentRun::is_running);425
runs.finish_kill(&session_id, cx);319
if still_resuming {426
if still_resuming {320
runs.spawn(run_id, plan, format, cx);427
runs.spawn(run_id, plan, format, cx);321
} else {428
} else {@@ -328,17 +435,21 @@ impl AgentRuns {328
})435
})329
.detach();436
.detach();330
}437
}331
Err(reason) => self.finish(438
Err(reason) => {332
run_id,439
let stop = kills::startup_kill(&self.settings, &run);333
Some(RunOutcome {440
self.finish(334
status: RunStatus::Failed {441
run_id,335
message: format!("Could not resume - {reason}"),442
Some(RunOutcome {336
stderr_tail: Vec::new(),443
status: RunStatus::Failed {337
},444
message: format!("Could not resume - {reason}"),338
exit_code: None,445
stderr_tail: Vec::new(),339
}),446
},340
cx,447
exit_code: None,341
),448
}),449
cx,450
);451
self.run_kill(&session_id, stop, cx);452
}342
}453
}343
}454
}344
455
@@ -376,6 +487,18 @@ impl AgentRuns {376
.filter(move |run| run.conversation_id == conversation_id && !run.dismissed)487
.filter(move |run| run.conversation_id == conversation_id && !run.dismissed)377
}488
}378
489
490
pub fn for_agent(&self, agent_id: &str) -> Vec<&AgentRun> {491
self.runs492
.iter()493
.rev()494
.filter(|run| run.agent_id == agent_id)495
.collect()496
}497
498
pub fn session_ids(&self) -> HashSet<String> {499
self.runs.iter().map(|run| run.session_id.clone()).collect()500
}501
379
pub fn running_count(&self) -> usize {502
pub fn running_count(&self) -> usize {380
self.runs.iter().filter(|run| run.is_running()).count()503
self.runs.iter().filter(|run| run.is_running()).count()381
}504
}@@ -405,7 +528,26 @@ impl AgentRuns {405
extra: &str,528
extra: &str,406
cx: &mut Context<Self>,529
cx: &mut Context<Self>,407
) -> Result<u64, String> {530
) -> Result<u64, String> {408
let action = self531
self.start_with(532
action_id,533
conversation_id,534
message_id,535
extra,536
StartOptions::default(),537
cx,538
)539
}540
541
pub fn start_with(542
&mut self,543
action_id: &str,544
conversation_id: &str,545
message_id: &str,546
extra: &str,547
options: StartOptions,548
cx: &mut Context<Self>,549
) -> Result<u64, String> {550
let mut action = self409
.settings551
.settings410
.actions552
.actions411
.iter()553
.iter()@@ -421,17 +563,33 @@ impl AgentRuns {421
.ok_or("The agent of this action no longer exists")?;563
.ok_or("The agent of this action no longer exists")?;422
let context = message_context::build(self.app.read(cx), conversation_id, message_id)564
let context = message_context::build(self.app.read(cx), conversation_id, message_id)423
.ok_or("The message is no longer available")?;565
.ok_or("The message is no longer available")?;424
let session_id = agents::new_session_id();566
let chosen_working_dir = options425
let prompt = agents::build_prompt(&action, &context, extra, &session_id, &profile.id);567
.working_dir426
let endpoint = mcp_bridge::endpoint(cx);568
.clone()427
let plan = agents::build_invocation(569
.filter(|_| options.session.is_none() && options.remember_working_dir);428
&profile,570
if let Some(target) = &options.session {429
&action,571
action.working_dir = target.working_dir.clone();430
&prompt,572
} else if let Some(working_dir) = &options.working_dir {431
&session_id,573
action.working_dir = working_dir.clone();432
endpoint.as_ref(),574
}433
mcp_config_directory().as_deref(),575
let (session_id, prompt) = match &options.session {434
);576
Some(target) => {577
let session_id = if target.fork {578
agents::new_session_id()579
} else {580
target.session_id.clone()581
};582
let prompt =583
agents::build_session_prompt(&context, extra, &session_id, &profile.id);584
(session_id, prompt)585
}586
None => {587
let session_id = agents::new_session_id();588
let prompt =589
agents::build_prompt(&action, &context, extra, &session_id, &profile.id);590
(session_id, prompt)591
}592
};435
let run_id = self.next_id;593
let run_id = self.next_id;436
self.next_id += 1;594
self.next_id += 1;437
self.runs.push(AgentRun {595
self.runs.push(AgentRun {@@ -456,19 +614,146 @@ impl AgentRuns {456
expanded: false,614
expanded: false,457
dismissed: false,615
dismissed: false,458
process_id: None,616
process_id: None,617
pending_prompt: Some(prompt),618
sent_to: options.session.clone(),619
launch_session_id: None,620
launched: false,459
});621
});460
if endpoint.is_none()622
if mcp_bridge::endpoint(cx).is_none()461
&& let Some(run) = self.run_mut(run_id)623
&& let Some(run) = self.run_mut(run_id)462
{624
{463
run.push_step("MCP server is off - no reply proposal possible".to_owned());625
run.push_step("MCP server is off - no reply proposal possible".to_owned());464
}626
}465
match plan {627
self.dispatch(run_id, cx);466
Ok(plan) => self.spawn(run_id, plan, profile.output, cx),628
if let Some(working_dir) = chosen_working_dir {467
Err(error) => self.finish(629
self.update_settings(630
|settings| settings.remember_working_dir(&profile.id, &working_dir),631
cx,632
);633
}634
self.persist(cx);635
self.ensure_ticking(cx);636
cx.notify();637
Ok(run_id)638
}639
640
fn dispatch(&mut self, run_id: u64, cx: &mut Context<Self>) {641
let Some(session_id) = self.get(run_id).map(|run| run.session_id.clone()) else {642
return;643
};644
match self.lanes.admit(&session_id, run_id) {645
Admit::Launch => self.launch(run_id, cx),646
Admit::Queued => {647
if let Some(run) = self.run_mut(run_id) {648
run.push_step(QUEUED_STEP.to_owned());649
}650
}651
}652
}653
654
fn release(&mut self, session_id: &str, cx: &mut Context<Self>) {655
let runs = &self.runs;656
let next = self.lanes.next(session_id, |run_id| {657
runs.iter().any(|run| run.id == run_id && run.is_queued())658
});659
if let Some(next) = next {660
self.launch(next, cx);661
}662
}663
664
fn finish_kill(&mut self, session_id: &str, cx: &mut Context<Self>) {665
let session_id = &self.lanes.resolve(session_id);666
self.lanes.kill_done(session_id);667
self.open_deferred_for(session_id, cx);668
self.release(session_id, cx);669
}670
671
fn open_deferred_for(&mut self, session_id: &str, cx: &mut Context<Self>) {672
if self.lanes.has_kills_pending(session_id) {673
return;674
}675
let ready: Vec<u64> = self676
.open_deferred677
.iter()678
.copied()679
.filter(|run_id| {680
self.get(*run_id)681
.is_some_and(|run| run.session_id == session_id)682
})683
.collect();684
for run_id in ready {685
self.open_deferred.remove(&run_id);686
if let Some(run) = self.get(run_id).cloned() {687
self.open_and_cancel(&run, cx);688
}689
}690
}691
692
fn run_kill(693
&mut self,694
session_id: &str,695
stop: Option<agents::Invocation>,696
cx: &mut Context<Self>,697
) {698
let Some(stop) = stop else {699
self.finish_kill(session_id, cx);700
return;701
};702
let session_id = session_id.to_owned();703
cx.spawn(async move |this, cx| {704
kills::execute(stop).await;705
this.update(cx, |runs, cx| runs.finish_kill(&session_id, cx))706
.ok();707
})708
.detach();709
}710
711
fn open_and_cancel(&mut self, run: &AgentRun, cx: &mut Context<Self>) {712
open_run_session(run, cx);713
let waiting = self.lanes.drain_waiting(&run.session_id);714
for run_id in &waiting {715
if let Some(waiting_run) = self.run_mut(*run_id) {716
waiting_run.pending_prompt = None;717
}718
self.finish(719
*run_id,720
Some(RunOutcome {721
status: RunStatus::Stopped,722
exit_code: None,723
}),724
cx,725
);726
if let Some(waiting_run) = self.run_mut(*run_id) {727
waiting_run.current_step = OPENED_NOTICE.to_owned();728
}729
}730
if !waiting.is_empty() {731
self.persist(cx);732
raise_notice(OPENED_NOTICE.to_owned(), cx);733
}734
self.release(&run.session_id, cx);735
}736
737
fn launch(&mut self, run_id: u64, cx: &mut Context<Self>) {738
let Some(run) = self.get(run_id).cloned() else {739
return;740
};741
let prompt = run.pending_prompt.clone().unwrap_or_default();742
let planned = self.launch_plan(&run, &prompt, cx);743
if let Some(run) = self.run_mut(run_id) {744
run.pending_prompt = None;745
if run.current_step == QUEUED_STEP {746
run.started_at = Utc::now();747
run.push_step("Starting".to_owned());748
}749
}750
match planned {751
Ok((plan, format)) => self.spawn(run_id, plan, format, cx),752
Err(message) => self.finish(468
run_id,753
run_id,469
Some(RunOutcome {754
Some(RunOutcome {470
status: RunStatus::Failed {755
status: RunStatus::Failed {471
message: error.to_string(),756
message,472
stderr_tail: Vec::new(),757
stderr_tail: Vec::new(),473
},758
},474
exit_code: None,759
exit_code: None,@@ -477,9 +762,41 @@ impl AgentRuns {477
),762
),478
}763
}479
self.persist(cx);764
self.persist(cx);480
self.ensure_ticking(cx);765
}481
cx.notify();766
482
Ok(run_id)767
fn launch_plan(768
&self,769
run: &AgentRun,770
prompt: &str,771
cx: &App,772
) -> Result<(agents::RunPlan, agents::OutputFormat), String> {773
let action = self774
.settings775
.actions776
.iter()777
.find(|action| action.id == run.action_id)778
.cloned()779
.ok_or("the action no longer exists")?;780
let profile = self781
.settings782
.agents783
.iter()784
.find(|profile| profile.id == run.agent_id)785
.ok_or("the agent no longer exists")?;786
let action = AgentAction {787
working_dir: run.working_dir.clone(),788
..action789
};790
plan_for(791
profile,792
&action,793
prompt,794
&run.session_id,795
run.sent_to.as_ref(),796
mcp_bridge::endpoint(cx).as_ref(),797
)798
.map(|plan| (plan, profile.output))799
.map_err(|error| error.to_string())483
}800
}484
801
485
fn spawn(802
fn spawn(@@ -492,6 +809,9 @@ impl AgentRuns {492
let (updates_sender, mut updates) = mpsc::unbounded_channel();809
let (updates_sender, mut updates) = mpsc::unbounded_channel();493
let (stop_sender, stop_receiver) = oneshot::channel();810
let (stop_sender, stop_receiver) = oneshot::channel();494
self.stops.insert(run_id, stop_sender);811
self.stops.insert(run_id, stop_sender);812
if let Some(run) = self.run_mut(run_id) {813
run.launch_session_id = Some(run.session_id.clone());814
}495
let outcome = runtime::spawn(agents::run(plan, format, updates_sender, stop_receiver));815
let outcome = runtime::spawn(agents::run(plan, format, updates_sender, stop_receiver));496
cx.spawn(async move |this, cx| {816
cx.spawn(async move |this, cx| {497
while let Some(update) = updates.recv().await {817
while let Some(update) = updates.recv().await {@@ -515,6 +835,7 @@ impl AgentRuns {515
RunUpdate::Started(process_id) => {835
RunUpdate::Started(process_id) => {516
if let Some(run) = self.run_mut(run_id) {836
if let Some(run) = self.run_mut(run_id) {517
run.process_id = Some(process_id);837
run.process_id = Some(process_id);838
run.launched = true;518
self.persist(cx);839
self.persist(cx);519
}840
}520
return;841
return;@@ -529,11 +850,27 @@ impl AgentRuns {529
RunEvent::Text(text) => {850
RunEvent::Text(text) => {530
run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)851
run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)531
}852
}853
RunEvent::SessionId(session_id) if session_id != run.session_id => {854
let previous = std::mem::replace(&mut run.session_id, session_id.clone());855
self.move_lane(&previous, &session_id);856
self.persist(cx);857
}532
_ => return,858
_ => return,533
}859
}534
cx.notify();860
cx.notify();535
}861
}536
862
863
fn move_lane(&mut self, from: &str, to: &str) {864
for run_id in self.lanes.rename(from, to) {865
if let Some(run) = self.run_mut(run_id) {866
run.session_id = to.to_owned();867
if let Some(target) = run.sent_to.as_mut().filter(|target| !target.fork) {868
target.session_id = to.to_owned();869
}870
}871
}872
}873
537
fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {874
fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {538
self.stops.remove(&run_id);875
self.stops.remove(&run_id);539
self.stopping.remove(&run_id);876
self.stopping.remove(&run_id);@@ -590,12 +927,21 @@ impl AgentRuns {590
if failed_or_done {927
if failed_or_done {591
cx.emit(AgentRunsEvent::Finished(run_id));928
cx.emit(AgentRunsEvent::Finished(run_id));592
}929
}593
if self.open_after_stop.remove(&run_id) && stopped {930
let session_id = snapshot.session_id.clone();594
open_run_session(&snapshot, cx);931
let was_active = self.lanes.finished(&session_id, run_id);932
if self.open_after_stop.remove(&run_id) {933
if self.lanes.has_kills_pending(&session_id) {934
self.open_deferred.insert(run_id);935
} else {936
self.open_and_cancel(&snapshot, cx);937
}595
}938
}596
if was_resuming {939
if was_resuming {597
self.resume_next(cx);940
self.resume_next(cx);598
}941
}942
if was_active {943
self.release(&session_id, cx);944
}599
cx.notify();945
cx.notify();600
}946
}601
947
@@ -647,10 +993,36 @@ impl AgentRuns {647
run.current_step = "Stopping".to_owned();993
run.current_step = "Stopping".to_owned();648
}994
}649
cx.notify();995
cx.notify();650
} else if self.resuming.contains(&run_id) || self.resume_queue.contains(&run_id) {996
} else if self.get(run_id).is_some_and(AgentRun::is_queued) {651
if self.resume_queue.contains(&run_id) {997
let session_id = self.get(run_id).map(|run| run.session_id.clone());652
self.stop_orphan(run_id, cx);998
if let Some(session_id) = session_id {999
self.lanes.remove_waiting(&session_id, run_id);1000
}1001
if let Some(run) = self.run_mut(run_id) {1002
run.pending_prompt = None;653
}1003
}1004
self.finish(1005
run_id,1006
Some(RunOutcome {1007
status: RunStatus::Stopped,1008
exit_code: None,1009
}),1010
cx,1011
);1012
} else if self.resuming.contains(&run_id) || self.resume_queue.contains(&run_id) {1013
let orphan_stop = self1014
.resume_queue1015
.contains(&run_id)1016
.then(|| {1017
self.get(run_id).and_then(|run| {1018
kills::orphan_kill(run, |candidate| {1019
self.resume_plan(candidate, cx).ok().map(|(plan, _)| plan)1020
})1021
})1022
})1023
.flatten();1024
let was_queued_for_resume = self.resume_queue.contains(&run_id);1025
let session_id = self.get(run_id).map(|run| run.session_id.clone());654
self.resume_queue.retain(|queued| *queued != run_id);1026
self.resume_queue.retain(|queued| *queued != run_id);655
self.finish(1027
self.finish(656
run_id,1028
run_id,@@ -660,28 +1032,27 @@ impl AgentRuns {660
}),1032
}),661
cx,1033
cx,662
);1034
);1035
if let (true, Some(session_id)) = (was_queued_for_resume, session_id) {1036
self.run_kill(&session_id, orphan_stop, cx);1037
}663
}1038
}664
}1039
}665
1040
666
fn stop_orphan(&self, run_id: u64, cx: &App) {1041
pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) {667
let Some(run) = self.get(run_id) else {1042
let Some(run) = self.get(run_id).cloned() else {668
return;1043
return;669
};1044
};670
let Ok((plan, _)) = self.resume_plan(run, cx) else {1045
if run.is_finished() {1046
if self.lanes.has_kills_pending(&run.session_id) {1047
self.open_deferred.insert(run_id);1048
} else {1049
self.open_and_cancel(&run, cx);1050
}671
return;1051
return;672
};673
for path in &plan.cleanup {674
let _ = std::fs::remove_file(path);675
}1052
}676
if let Some(stop) = orphan_stop(run, &plan) {1053
if !run.is_queued() {677
drop(runtime::spawn(async move {1054
self.open_after_stop.insert(run_id);678
agents::run_stop_invocation(&stop).await679
}));680
}1055
}681
}682
683
pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) {684
self.open_after_stop.insert(run_id);685
self.stop(run_id, cx);1056
self.stop(run_id, cx);686
}1057
}687
1058
@@ -690,11 +1061,24 @@ impl AgentRuns {690
.get(run_id)1061
.get(run_id)691
.cloned()1062
.cloned()692
.ok_or("This run no longer exists")?;1063
.ok_or("This run no longer exists")?;693
let started = self.start(1064
let options = StartOptions {1065
working_dir: run.sent_to.is_none().then(|| run.working_dir.clone()),1066
remember_working_dir: false,1067
session: run.sent_to.clone().map(|target| SessionTarget {1068
session_id: if target.fork {1069
target.session_id1070
} else {1071
run.session_id.clone()1072
},1073
..target1074
}),1075
};1076
let started = self.start_with(694
&run.action_id,1077
&run.action_id,695
&run.conversation_id,1078
&run.conversation_id,696
&run.message_id,1079
&run.message_id,697
&run.extra,1080
&run.extra,1081
options,698
cx,1082
cx,699
)?;1083
)?;700
self.dismiss(run_id, cx);1084
self.dismiss(run_id, cx);@@ -729,7 +1113,9 @@ pub(super) mod tests {729
1113
730
use gpui_kit::{AppContext as _, Entity, TestAppContext};1114
use gpui_kit::{AppContext as _, Entity, TestAppContext};731
1115
732
use super::{AgentRun, AgentRuns, RunState, Utc, format_elapsed, run_store};1116
use super::{1117
AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, format_elapsed, run_store,1118
};733
use crate::app_state::{AppState, Mode};1119
use crate::app_state::{AppState, Mode};734
1120
735
pub fn finished_run(id: u64) -> AgentRun {1121
pub fn finished_run(id: u64) -> AgentRun {@@ -755,6 +1141,10 @@ pub(super) mod tests {755
expanded: false,1141
expanded: false,756
dismissed: false,1142
dismissed: false,757
process_id: None,1143
process_id: None,1144
pending_prompt: None,1145
sent_to: None,1146
launch_session_id: None,1147
launched: true,758
}1148
}759
}1149
}760
1150
@@ -781,6 +1171,7 @@ pub(super) mod tests {781
agents: vec![profile],1171
agents: vec![profile],782
actions: vec![action],1172
actions: vec![action],783
resume_interrupted_runs: true,1173
resume_interrupted_runs: true,1174
..AgentSettings::default()784
}1175
}785
}1176
}786
1177
@@ -827,9 +1218,531 @@ pub(super) mod tests {827
1218
828
#[cfg(unix)]1219
#[cfg(unix)]829
mod shell_runs {1220
mod shell_runs {1221
use std::time::Duration;1222
830
use gpui_kit::AppContext as _;1223
use gpui_kit::AppContext as _;831
1224
832
use super::{AgentRuns, RunState, TestAppContext, run_store, setup, wait_until_finished};1225
use super::{1226
AgentRun, AgentRuns, Entity, RunState, SessionTarget, StartOptions, TestAppContext,1227
run_store, setup, wait_until_finished,1228
};1229
1230
const SESSION_COMMAND: &str = "sh -c 'sleep 1' --session-id {session_id}";1231
1232
fn target_of(session_id: String) -> StartOptions {1233
StartOptions {1234
working_dir: None,1235
remember_working_dir: false,1236
session: Some(SessionTarget {1237
session_id,1238
working_dir: std::env::temp_dir().to_string_lossy().into_owned(),1239
fork: false,1240
}),1241
}1242
}1243
1244
type LaneView = Option<(Option<u64>, Vec<u64>)>;1245
1246
fn lane_of(1247
cx: &mut TestAppContext,1248
runs: &Entity<AgentRuns>,1249
session_id: &str,1250
) -> LaneView {1251
cx.update(|cx| {1252
runs.read(cx).lanes.get(session_id).map(|lane| {1253
(1254
lane.active.first().copied(),1255
lane.waiting.iter().copied().collect::<Vec<u64>>(),1256
)1257
})1258
})1259
}1260
1261
fn send_chain(1262
cx: &mut TestAppContext,1263
runs: &Entity<AgentRuns>,1264
) -> (u64, u64, u64, String) {1265
cx.update(|cx| {1266
runs.update(cx, |runs, cx| {1267
let first = runs.start("ask", "19:chat", "m1", "", cx).unwrap();1268
let session_id = runs.get(first).unwrap().session_id.clone();1269
let second = runs1270
.start_with(1271
"ask",1272
"19:chat",1273
"m1",1274
"two",1275
target_of(session_id.clone()),1276
cx,1277
)1278
.unwrap();1279
let third = runs1280
.start_with(1281
"ask",1282
"19:chat",1283
"m1",1284
"three",1285
target_of(session_id.clone()),1286
cx,1287
)1288
.unwrap();1289
(first, second, third, session_id)1290
})1291
})1292
}1293
1294
fn started_and_ended(1295
cx: &mut TestAppContext,1296
runs: &Entity<AgentRuns>,1297
run_id: u64,1298
) -> (chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>) {1299
cx.update(|cx| {1300
let run = runs.read(cx).get(run_id).unwrap();1301
(run.started_at, run.ended_at.unwrap())1302
})1303
}1304
1305
#[gpui_kit::test]1306
fn two_sends_to_one_session_run_strictly_one_after_another(cx: &mut TestAppContext) {1307
let (_, runs) = setup(cx, SESSION_COMMAND);1308
let (first, second, third, session_id) = send_chain(cx, &runs);1309
assert_eq!(1310
lane_of(cx, &runs, &session_id),1311
Some((Some(first), vec![second, third]))1312
);1313
cx.update(|cx| {1314
let queued = runs.read(cx).get(second).unwrap();1315
assert_eq!(queued.current_step, "Queued");1316
let prompt = queued.pending_prompt.clone().unwrap();1317
assert!(prompt.contains("propose_message") && prompt.contains("m1"));1318
assert!(prompt.ends_with("\n\ntwo"));1319
assert_eq!(queued.extra, "two");1320
assert_eq!(queued.session_id, session_id);1321
});1322
wait_until_finished(cx, &runs, first);1323
assert_eq!(1324
lane_of(cx, &runs, &session_id),1325
Some((Some(second), vec![third]))1326
);1327
cx.update(|cx| {1328
assert!(!runs.read(cx).get(second).unwrap().is_queued());1329
assert!(runs.read(cx).get(third).unwrap().is_queued());1330
});1331
wait_until_finished(cx, &runs, second);1332
assert_eq!(lane_of(cx, &runs, &session_id), Some((Some(third), vec![])));1333
wait_until_finished(cx, &runs, third);1334
assert_eq!(lane_of(cx, &runs, &session_id), None);1335
let (_, first_ended) = started_and_ended(cx, &runs, first);1336
let (second_started, second_ended) = started_and_ended(cx, &runs, second);1337
let (third_started, _) = started_and_ended(cx, &runs, third);1338
assert!(second_started >= first_ended);1339
assert!(third_started >= second_ended);1340
}1341
1342
#[gpui_kit::test]1343
fn a_reported_session_id_moves_the_whole_lane_and_its_waiting_runs(1344
cx: &mut TestAppContext,1345
) {1346
let (_, runs) = setup(cx, SESSION_COMMAND);1347
let (first, second, third, session_id) = send_chain(cx, &runs);1348
cx.update(|cx| {1349
runs.update(cx, |runs, cx| {1350
runs.apply_update(1351
first,1352
agents::RunUpdate::Event(agents::RunEvent::SessionId("adopted".to_owned())),1353
cx,1354
)1355
});1356
let runs = runs.read(cx);1357
assert_eq!(1358
runs.get(first).unwrap().launch_session_id,1359
Some(session_id.clone())1360
);1361
assert_eq!(runs.get(first).unwrap().session_id, "adopted");1362
for run_id in [second, third] {1363
assert_eq!(runs.get(run_id).unwrap().session_id, "adopted");1364
}1365
});1366
assert_eq!(lane_of(cx, &runs, &session_id), None);1367
assert_eq!(1368
lane_of(cx, &runs, "adopted"),1369
Some((Some(first), vec![second, third]))1370
);1371
wait_until_finished(cx, &runs, first);1372
assert_eq!(1373
lane_of(cx, &runs, "adopted"),1374
Some((Some(second), vec![third]))1375
);1376
wait_until_finished(cx, &runs, second);1377
wait_until_finished(cx, &runs, third);1378
}1379
1380
#[gpui_kit::test]1381
fn stopping_a_waiting_send_only_removes_it_from_the_lane(cx: &mut TestAppContext) {1382
let (_, runs) = setup(cx, SESSION_COMMAND);1383
let (first, second, third, session_id) = send_chain(cx, &runs);1384
cx.update(|cx| runs.update(cx, |runs, cx| runs.stop(second, cx)));1385
cx.update(|cx| {1386
let stopped = runs.read(cx).get(second).unwrap();1387
assert_eq!(stopped.state, RunState::Stopped);1388
assert!(!stopped.is_queued());1389
});1390
assert_eq!(1391
lane_of(cx, &runs, &session_id),1392
Some((Some(first), vec![third]))1393
);1394
wait_until_finished(cx, &runs, first);1395
assert_eq!(lane_of(cx, &runs, &session_id), Some((Some(third), vec![])));1396
wait_until_finished(cx, &runs, third);1397
}1398
1399
#[gpui_kit::test]1400
fn stop_and_open_cancels_every_waiting_send_of_the_lane(cx: &mut TestAppContext) {1401
let (app, runs) = setup(cx, SESSION_COMMAND);1402
let (first, second, third, session_id) = send_chain(cx, &runs);1403
cx.update(|cx| runs.update(cx, |runs, cx| runs.stop_and_open_session(first, cx)));1404
wait_until_finished(cx, &runs, first);1405
cx.update(|cx| {1406
for run_id in [second, third] {1407
let run = runs.read(cx).get(run_id).unwrap();1408
assert_eq!(run.state, RunState::Stopped);1409
assert_eq!(1410
run.current_step,1411
"Session opened in a terminal - send cancelled"1412
);1413
assert!(!run.is_queued());1414
}1415
assert!(runs.read(cx).open_after_stop.is_empty());1416
});1417
assert_eq!(lane_of(cx, &runs, &session_id), None);1418
cx.update(|cx| {1419
let stored = run_store::load_runs(&app.read(cx).store);1420
let notice = stored.iter().find(|run| run.id == second).unwrap();1421
assert_eq!(1422
notice.current_step,1423
"Session opened in a terminal - send cancelled"1424
);1425
});1426
}1427
1428
#[gpui_kit::test]1429
fn a_requested_open_fires_whatever_the_outcome_of_the_run(cx: &mut TestAppContext) {1430
let (_, runs) = setup(cx, "sh -c 'sleep 1; exit 3' --session-id {session_id}");1431
let (first, second, _, session_id) = send_chain(cx, &runs);1432
cx.update(|cx| runs.update(cx, |runs, _| runs.open_after_stop.insert(first)));1433
wait_until_finished(cx, &runs, first);1434
cx.update(|cx| {1435
assert!(matches!(1436
runs.read(cx).get(first).unwrap().state,1437
RunState::Failed { .. }1438
));1439
assert_eq!(runs.read(cx).get(second).unwrap().state, RunState::Stopped);1440
assert!(runs.read(cx).open_after_stop.is_empty());1441
});1442
assert_eq!(lane_of(cx, &runs, &session_id), None);1443
}1444
1445
#[gpui_kit::test]1446
fn a_run_that_never_launched_is_interrupted_not_resumed(cx: &mut TestAppContext) {1447
let (app, _) = setup(cx, SESSION_COMMAND);1448
let mut never_started = super::running_run(5);1449
never_started.launched = false;1450
let reloaded = reload(cx, &app, vec![never_started]);1451
cx.update(|cx| {1452
assert!(reloaded.read(cx).get(5).unwrap().is_finished());1453
});1454
assert_eq!(lane_of(cx, &reloaded, "session-5"), None);1455
}1456
1457
#[gpui_kit::test]1458
fn stop_and_open_waits_for_the_orphan_kill_before_cancelling_the_lane(1459
cx: &mut TestAppContext,1460
) {1461
let (app, _) = setup(cx, SESSION_COMMAND);1462
let mut orphan = super::running_run(5);1463
orphan.session_id = "shared".to_owned();1464
orphan.process_id = Some(1);1465
let reloaded = reload(cx, &app, vec![orphan, queued_run(7)]);1466
cx.update(|cx| {1467
reloaded.update(cx, |runs, cx| runs.stop_and_open_session(5, cx));1468
let runs = reloaded.read(cx);1469
assert!(runs.get(5).unwrap().is_finished());1470
assert!(runs.open_deferred.contains(&5));1471
assert!(runs.get(7).unwrap().is_queued());1472
assert!(runs.lanes.has_kills_pending("shared"));1473
});1474
for _ in 0..200 {1475
cx.run_until_parked();1476
if lane_of(cx, &reloaded, "shared").is_none() {1477
break;1478
}1479
std::thread::sleep(Duration::from_millis(10));1480
}1481
cx.update(|cx| {1482
let runs = reloaded.read(cx);1483
assert_eq!(runs.get(7).unwrap().state, RunState::Stopped);1484
assert!(runs.open_after_stop.is_empty() && runs.open_deferred.is_empty());1485
});1486
}1487
1488
#[gpui_kit::test]1489
fn a_send_during_an_in_flight_kill_waits_for_the_resumed_run(cx: &mut TestAppContext) {1490
let (app, _) = setup(cx, SESSION_COMMAND);1491
let mut orphan = super::running_run(5);1492
orphan.session_id = "shared".to_owned();1493
orphan.process_id = Some(1);1494
let reloaded = reload(cx, &app, vec![orphan]);1495
let sent = cx.update(|cx| {1496
reloaded.update(cx, |runs, cx| {1497
runs.start_with(1498
"ask",1499
"19:chat",1500
"m1",1501
"hi",1502
target_of("shared".to_owned()),1503
cx,1504
)1505
.unwrap()1506
})1507
});1508
assert_eq!(1509
lane_of(cx, &reloaded, "shared"),1510
Some((Some(5), vec![sent]))1511
);1512
wait_until_finished(cx, &reloaded, 5);1513
wait_until_finished(cx, &reloaded, sent);1514
let (_, resumed_ended) = started_and_ended(cx, &reloaded, 5);1515
let (sent_started, _) = started_and_ended(cx, &reloaded, sent);1516
assert!(sent_started >= resumed_ended);1517
}1518
1519
#[test]1520
fn old_saved_runs_with_a_chain_id_still_load() {1521
let mut value = serde_json::to_value(super::running_run(3)).unwrap();1522
let object = value.as_object_mut().unwrap();1523
for key in ["sent_to", "launch_session_id", "launched", "pending_prompt"] {1524
object.remove(key);1525
}1526
object.insert("after_run_id".to_owned(), serde_json::json!(2));1527
object.insert("pending_prompt".to_owned(), serde_json::json!("saved"));1528
let run: AgentRun = serde_json::from_value(value).unwrap();1529
assert!(run.is_queued());1530
assert!(run.launched);1531
assert_eq!(run.sent_to, None);1532
}1533
1534
#[gpui_kit::test]1535
fn a_forked_send_gets_a_fresh_session_id_and_adopts_a_reported_one(1536
cx: &mut TestAppContext,1537
) {1538
let (app, runs) = setup(cx, SESSION_COMMAND);1539
let forked = cx.update(|cx| {1540
runs.update(cx, |runs, cx| {1541
let mut options = target_of("live-session".to_owned());1542
options.session.as_mut().unwrap().fork = true;1543
runs.start_with("ask", "19:chat", "m1", "hi", options, cx)1544
.unwrap()1545
})1546
});1547
cx.update(|cx| {1548
let run = runs.read(cx).get(forked).unwrap().clone();1549
assert_ne!(run.session_id, "live-session");1550
assert!(run.sent_to.as_ref().unwrap().fork);1551
assert!(!run.is_queued());1552
runs.update(cx, |runs, cx| {1553
runs.apply_update(1554
forked,1555
agents::RunUpdate::Event(agents::RunEvent::SessionId(1556
"reported".to_owned(),1557
)),1558
cx,1559
)1560
});1561
assert_eq!(runs.read(cx).get(forked).unwrap().session_id, "reported");1562
let stored = run_store::load_runs(&app.read(cx).store);1563
assert_eq!(stored[0].session_id, "reported");1564
});1565
wait_until_finished(cx, &runs, forked);1566
}1567
1568
#[gpui_kit::test]1569
fn retrying_a_plain_run_keeps_its_chosen_working_dir_without_recording_it(1570
cx: &mut TestAppContext,1571
) {1572
let (_, runs) = setup(cx, SESSION_COMMAND);1573
let started = cx.update(|cx| {1574
runs.update(cx, |runs, cx| {1575
runs.start_with(1576
"ask",1577
"19:chat",1578
"m1",1579
"",1580
StartOptions {1581
working_dir: Some("/srv/chosen".to_owned()),1582
remember_working_dir: false,1583
session: None,1584
},1585
cx,1586
)1587
.unwrap()1588
})1589
});1590
wait_until_finished(cx, &runs, started);1591
let retried =1592
cx.update(|cx| runs.update(cx, |runs, cx| runs.retry(started, cx)).unwrap());1593
cx.update(|cx| {1594
assert_eq!(1595
runs.read(cx).get(retried).unwrap().working_dir,1596
"/srv/chosen"1597
);1598
assert!(1599
runs.read(cx)1600
.settings()1601
.recent_working_dirs_of("fake")1602
.is_empty()1603
);1604
});1605
wait_until_finished(cx, &runs, retried);1606
}1607
1608
#[gpui_kit::test]1609
fn retrying_a_session_send_sends_to_the_same_session_again(cx: &mut TestAppContext) {1610
let (_, runs) = setup(cx, SESSION_COMMAND);1611
let sent = cx.update(|cx| {1612
runs.update(cx, |runs, cx| {1613
runs.start_with(1614
"ask",1615
"19:chat",1616
"m1",1617
"again please",1618
target_of("old-session".to_owned()),1619
cx,1620
)1621
.unwrap()1622
})1623
});1624
wait_until_finished(cx, &runs, sent);1625
let retried = cx.update(|cx| runs.update(cx, |runs, cx| runs.retry(sent, cx)).unwrap());1626
cx.update(|cx| {1627
let run = runs.read(cx).get(retried).unwrap();1628
assert_eq!(run.session_id, "old-session");1629
assert_eq!(run.extra, "again please");1630
assert_eq!(run.sent_to.as_ref().unwrap().session_id, "old-session");1631
});1632
wait_until_finished(cx, &runs, retried);1633
}1634
1635
fn queued_run(id: u64) -> AgentRun {1636
let mut run = super::running_run(id);1637
run.session_id = "shared".to_owned();1638
run.current_step = "Queued".to_owned();1639
run.pending_prompt = Some("saved prompt".to_owned());1640
run1641
}1642
1643
fn reload(1644
cx: &mut TestAppContext,1645
app: &Entity<crate::app_state::AppState>,1646
stored: Vec<AgentRun>,1647
) -> Entity<AgentRuns> {1648
cx.update(|cx| {1649
run_store::save_runs(&app.read(cx).store, &stored);1650
cx.new(|cx| AgentRuns::new(app.clone(), cx))1651
})1652
}1653
1654
#[gpui_kit::test]1655
fn a_restart_rebuilds_the_lane_and_never_runs_two_processes_on_one_session(1656
cx: &mut TestAppContext,1657
) {1658
let (app, _) = setup(cx, SESSION_COMMAND);1659
let mut active = super::running_run(5);1660
active.session_id = "shared".to_owned();1661
let mut duplicate = super::running_run(6);1662
duplicate.session_id = "shared".to_owned();1663
let reloaded = reload(1664
cx,1665
&app,1666
vec![active, duplicate, queued_run(7), queued_run(8)],1667
);1668
cx.update(|cx| {1669
let runs = reloaded.read(cx);1670
assert!(runs.get(6).unwrap().is_finished());1671
assert!(runs.get(7).unwrap().is_queued() && runs.get(8).unwrap().is_queued());1672
});1673
assert_eq!(1674
lane_of(cx, &reloaded, "shared"),1675
Some((Some(5), vec![7, 8]))1676
);1677
wait_until_finished(cx, &reloaded, 5);1678
assert_eq!(lane_of(cx, &reloaded, "shared"), Some((Some(7), vec![8])));1679
wait_until_finished(cx, &reloaded, 7);1680
wait_until_finished(cx, &reloaded, 8);1681
let (_, ended_5) = started_and_ended(cx, &reloaded, 5);1682
let (started_7, ended_7) = started_and_ended(cx, &reloaded, 7);1683
let (started_8, _) = started_and_ended(cx, &reloaded, 8);1684
assert!(started_7 >= ended_5 && started_8 >= ended_7);1685
}1686
1687
#[gpui_kit::test]1688
fn a_waiting_send_without_a_predecessor_runs_after_a_restart(cx: &mut TestAppContext) {1689
let (app, _) = setup(cx, SESSION_COMMAND);1690
let reloaded = reload(cx, &app, vec![queued_run(7), queued_run(8)]);1691
assert_eq!(lane_of(cx, &reloaded, "shared"), Some((None, vec![7, 8])));1692
cx.run_until_parked();1693
assert_eq!(lane_of(cx, &reloaded, "shared"), Some((Some(7), vec![8])));1694
wait_until_finished(cx, &reloaded, 7);1695
wait_until_finished(cx, &reloaded, 8);1696
assert_eq!(lane_of(cx, &reloaded, "shared"), None);1697
}1698
1699
#[gpui_kit::test]1700
fn a_message_to_an_idle_session_resumes_it_and_a_chosen_dir_becomes_recent(1701
cx: &mut TestAppContext,1702
) {1703
let (_, runs) = setup(cx, SESSION_COMMAND);1704
let (resumed, other) = cx.update(|cx| {1705
runs.update(cx, |runs, cx| {1706
let resumed = runs1707
.start_with(1708
"ask",1709
"19:chat",1710
"m1",1711
"hello",1712
target_of("old-session".to_owned()),1713
cx,1714
)1715
.unwrap();1716
let other = runs1717
.start_with(1718
"ask",1719
"19:chat",1720
"m1",1721
"",1722
StartOptions {1723
working_dir: Some("/srv/other".to_owned()),1724
remember_working_dir: true,1725
session: None,1726
},1727
cx,1728
)1729
.unwrap();1730
(resumed, other)1731
})1732
});1733
cx.update(|cx| {1734
let resumed = runs.read(cx).get(resumed).unwrap().clone();1735
assert_eq!(resumed.session_id, "old-session");1736
assert_ne!(resumed.current_step, "Queued");1737
let other = runs.read(cx).get(other).unwrap().clone();1738
assert_eq!(other.working_dir, "/srv/other");1739
assert_eq!(1740
runs.read(cx).settings().recent_working_dirs_of("fake"),1741
["/srv/other"]1742
);1743
});1744
wait_until_finished(cx, &runs, resumed);1745
}833
1746
834
#[gpui_kit::test]1747
#[gpui_kit::test]835
fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {1748
fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {@@ -885,7 +1798,7 @@ pub(super) mod tests {885
cx.update(|cx| {1798
cx.update(|cx| {886
let run = reloaded.read(cx).get(5).unwrap().clone();1799
let run = reloaded.read(cx).get(5).unwrap().clone();887
assert_eq!(run.state, RunState::Done);1800
assert_eq!(run.state, RunState::Done);888
assert_eq!(run.session_id, "session-5");1801
assert_eq!(run.session_id, "3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11");889
assert!(1802
assert!(890
run.steps1803
run.steps891
.iter()1804
.iter()@@ -0,0 +1,360 @@
1
use std::collections::HashSet;
2
use std::path::{Path, PathBuf};
3
use std::time::Duration;
4
5
use agents::{Environment, ExternalSession};
6
use chrono::{DateTime, Local, Utc};
7
use mcp::install::{Homes, Location};
8
9
use super::message_context;
10
use super::runs::{AgentRun, RunState};
11
use crate::agent_api::agent_homes;
12
use crate::app_state::AppState;
13
use crate::notice::truncated;
14
15
pub const SESSION_LIMIT: usize = 10;
16
const ACTIVE_WINDOW: Duration = Duration::from_secs(120);
17
const LABEL_CHARS: usize = 60;
18
const WEEK_DAYS: i64 = 7;
19
20
#[derive(Clone, Debug, PartialEq, Eq)]
21
pub struct SessionOption {
22
pub session_id: String,
23
pub working_dir: String,
24
pub label: String,
25
pub meta: String,
26
pub running: bool,
27
pub fork: bool,
28
}
29
30
pub fn relative_age(now: DateTime<Utc>, then: DateTime<Utc>) -> String {
31
let age = now - then;
32
if age.num_minutes() < 1 {
33
"now".to_owned()
34
} else if age.num_hours() < 1 {
35
format!("{}m", age.num_minutes())
36
} else if age.num_days() < 1 {
37
format!("{}h", age.num_hours())
38
} else if age.num_days() < WEEK_DAYS {
39
then.with_timezone(&Local).format("%a").to_string()
40
} else {
41
then.with_timezone(&Local).format("%b %-d").to_string()
42
}
43
}
44
45
fn run_meta(run: &AgentRun, now: DateTime<Utc>) -> String {
46
let age = relative_age(now, run.ended_at.unwrap_or(run.started_at));
47
match run.state {
48
RunState::Running => "Running".to_owned(),
49
RunState::Done => format!("Done - {age}"),
50
RunState::Failed { .. } => format!("Failed - {age}"),
51
RunState::Stopped => format!("Stopped - {age}"),
52
}
53
}
54
55
pub fn run_options(runs: &[&AgentRun], state: &AppState, now: DateTime<Utc>) -> Vec<SessionOption> {
56
let mut seen = HashSet::new();
57
runs.iter()
58
.filter(|run| {
59
!run.session_id.is_empty()
60
&& (run.launched || run.sent_to.is_some())
61
&& seen.insert(run.session_id.clone())
62
})
63
.take(SESSION_LIMIT)
64
.map(|run| {
65
let message =
66
message_context::message_line(state, &run.conversation_id, &run.message_id)
67
.unwrap_or_else(|| run.chat_title.clone());
68
SessionOption {
69
session_id: run.session_id.clone(),
70
working_dir: run.working_dir.clone(),
71
label: format!(
72
"{} - {}",
73
run.action_label,
74
truncated(&message, LABEL_CHARS)
75
),
76
meta: run_meta(run, now),
77
running: run.is_running(),
78
fork: false,
79
}
80
})
81
.collect()
82
}
83
84
pub fn external_options(
85
sessions: &[ExternalSession],
86
working_dir: &str,
87
now: DateTime<Utc>,
88
) -> Vec<SessionOption> {
89
sessions
90
.iter()
91
.map(|session| {
92
let modified = DateTime::<Utc>::from(session.modified);
93
let active = session.live
94
|| modified > now
95
|| (now - modified)
96
.to_std()
97
.is_ok_and(|age| age < ACTIVE_WINDOW);
98
SessionOption {
99
session_id: session.session_id.clone(),
100
working_dir: working_dir.to_owned(),
101
label: truncated(&session.title, LABEL_CHARS),
102
meta: if active {
103
"Active elsewhere - sends to a copy".to_owned()
104
} else {
105
format!("Idle - {}", relative_age(now, modified))
106
},
107
running: false,
108
fork: active,
109
}
110
})
111
.collect()
112
}
113
114
fn pick_home<'a>(environment: &Environment, homes: &'a Homes) -> Option<&'a PathBuf> {
115
homes
116
.entries
117
.iter()
118
.find(|(location, _)| match (environment, location) {
119
(Environment::Host, Location::Windows | Location::Native) => true,
120
(
121
Environment::Wsl {
122
distro: Some(wanted),
123
},
124
Location::Wsl { distro },
125
) => wanted == distro,
126
(Environment::Wsl { distro: None }, Location::Wsl { .. }) => true,
127
(Environment::Wsl { .. }, Location::Native) => true,
128
_ => false,
129
})
130
.map(|(_, home)| home)
131
}
132
133
fn resolve_working_dir(environment: &Environment, working_dir: &str, home: &Path) -> String {
134
let home_text = home.to_string_lossy();
135
let home_text = match environment {
136
Environment::Host => home_text.into_owned(),
137
Environment::Wsl { .. } => agents::linux_path(&home_text),
138
};
139
match working_dir.strip_prefix('~') {
140
Some(rest) if rest.is_empty() || rest.starts_with(['/', '\\']) => {
141
format!("{home_text}{rest}")
142
}
143
_ => working_dir.to_owned(),
144
}
145
}
146
147
fn claude_dirs(
148
environment: &Environment,
149
working_dir: &str,
150
homes: &Homes,
151
) -> Option<(PathBuf, PathBuf)> {
152
let home = pick_home(environment, homes)?;
153
let resolved = resolve_working_dir(environment, working_dir, home);
154
let claude = home.join(".claude");
155
Some((
156
agents::resolve_project_dir(&claude.join("projects"), &resolved),
157
claude.join("sessions"),
158
))
159
}
160
161
#[derive(Default)]
162
pub struct ExternalLoad {
163
pub sessions: Vec<ExternalSession>,
164
pub live_session_ids: HashSet<String>,
165
}
166
167
pub fn load_external(
168
environment: &Environment,
169
working_dir: &str,
170
known_session_ids: &HashSet<String>,
171
demo: bool,
172
) -> ExternalLoad {
173
let Some((project_dir, sessions_dir)) =
174
claude_dirs(environment, working_dir, &agent_homes(demo))
175
else {
176
return ExternalLoad::default();
177
};
178
let live = agents::live_session_names(&sessions_dir);
179
ExternalLoad {
180
sessions: agents::scan_external_sessions(
181
&project_dir,
182
&live,
183
known_session_ids,
184
SESSION_LIMIT,
185
),
186
live_session_ids: live.into_keys().collect(),
187
}
188
}
189
190
pub fn mark_live_runs(options: &mut [SessionOption], live_session_ids: &HashSet<String>) {
191
for option in options {
192
option.fork = !option.running && live_session_ids.contains(&option.session_id);
193
}
194
}
195
196
pub fn default_wsl_distro(demo: bool) -> Option<String> {
197
agent_homes(demo)
198
.entries
199
.into_iter()
200
.find_map(|(location, _)| match location {
201
Location::Wsl { distro } => Some(distro),
202
_ => None,
203
})
204
}
205
206
#[cfg(test)]
207
mod tests {
208
use std::time::SystemTime;
209
210
use chrono::TimeZone;
211
212
use super::*;
213
214
fn external(age: Duration) -> ExternalSession {
215
ExternalSession {
216
session_id: "abc".to_owned(),
217
title: "Fix the build".to_owned(),
218
modified: SystemTime::now() - age,
219
live: false,
220
}
221
}
222
223
#[test]
224
fn relative_age_uses_minutes_hours_weekday_and_date() {
225
let now = Utc.with_ymd_and_hms(2026, 10, 13, 12, 0, 0).unwrap();
226
let ago = |seconds: i64| relative_age(now, now - chrono::Duration::seconds(seconds));
227
assert_eq!(ago(20), "now");
228
assert_eq!(ago(5 * 60), "5m");
229
assert_eq!(ago(3 * 3600), "3h");
230
assert_eq!(ago(2 * 86400).len(), 3);
231
assert!(ago(10 * 86400).contains(char::is_whitespace));
232
}
233
234
#[test]
235
fn external_sessions_are_active_under_two_minutes_and_fork() {
236
let now = Utc::now();
237
let options = external_options(
238
&[
239
external(Duration::from_secs(30)),
240
external(Duration::from_secs(3 * 3600 + 30)),
241
],
242
"/repo",
243
now,
244
);
245
assert_eq!(options[0].meta, "Active elsewhere - sends to a copy");
246
assert!(options[0].fork);
247
assert_eq!(options[1].meta, "Idle - 3h");
248
assert!(!options[1].fork);
249
assert_eq!(options[1].label, "Fix the build");
250
assert_eq!(options[1].working_dir, "/repo");
251
let live = ExternalSession {
252
live: true,
253
..external(Duration::from_secs(3 * 3600))
254
};
255
let options = external_options(&[live], "/repo", now);
256
assert_eq!(options[0].meta, "Active elsewhere - sends to a copy");
257
assert!(options[0].fork);
258
}
259
260
#[test]
261
fn app_sessions_open_in_a_terminal_are_forked_unless_running_here() {
262
let option = |session_id: &str, running: bool| SessionOption {
263
session_id: session_id.to_owned(),
264
working_dir: "/repo".to_owned(),
265
label: String::new(),
266
meta: String::new(),
267
running,
268
fork: false,
269
};
270
let mut options = vec![option("a", false), option("b", false), option("c", true)];
271
mark_live_runs(
272
&mut options,
273
&HashSet::from(["a".to_owned(), "c".to_owned()]),
274
);
275
let forks: Vec<bool> = options.iter().map(|option| option.fork).collect();
276
assert_eq!(forks, [true, false, false]);
277
}
278
279
#[test]
280
fn runs_that_never_created_a_session_are_left_out() {
281
let state = AppState::new(
282
std::sync::Arc::new(store::Store::open_in_memory().unwrap()),
283
crate::app_state::Mode::default(),
284
);
285
let mut created = crate::agents::runs::tests::finished_run(1);
286
created.launched = true;
287
let mut never_started = crate::agents::runs::tests::finished_run(2);
288
never_started.launched = false;
289
let mut sent = crate::agents::runs::tests::finished_run(3);
290
sent.launched = false;
291
sent.sent_to = Some(crate::agents::runs::SessionTarget {
292
session_id: sent.session_id.clone(),
293
working_dir: "~".to_owned(),
294
fork: false,
295
});
296
let options = run_options(&[&created, &never_started, &sent], &state, Utc::now());
297
let ids: Vec<&str> = options
298
.iter()
299
.map(|option| option.session_id.as_str())
300
.collect();
301
assert_eq!(ids, ["session-1", "session-3"]);
302
}
303
304
#[test]
305
fn the_home_matches_the_agent_environment() {
306
let homes = Homes {
307
entries: vec![
308
(Location::Windows, PathBuf::from(r"C:\Users\dd")),
309
(
310
Location::Wsl {
311
distro: "Ubuntu".to_owned(),
312
},
313
PathBuf::from(r"\\wsl.localhost\Ubuntu\home\daniel"),
314
),
315
],
316
};
317
let wsl = |distro: Option<&str>| Environment::Wsl {
318
distro: distro.map(str::to_owned),
319
};
320
assert_eq!(
321
pick_home(&Environment::Host, &homes),
322
Some(&PathBuf::from(r"C:\Users\dd"))
323
);
324
assert!(pick_home(&wsl(None), &homes).is_some());
325
assert!(pick_home(&wsl(Some("Ubuntu")), &homes).is_some());
326
assert_eq!(pick_home(&wsl(Some("Debian")), &homes), None);
327
}
328
329
#[test]
330
fn a_wsl_home_encodes_the_linux_path_of_the_working_dir() {
331
let homes = Homes {
332
entries: vec![(
333
Location::Wsl {
334
distro: "Ubuntu".to_owned(),
335
},
336
PathBuf::from(r"\\wsl.localhost\Ubuntu\home\daniel"),
337
)],
338
};
339
let environment = Environment::Wsl { distro: None };
340
let (directory, sessions) = claude_dirs(&environment, "~/Projects/x", &homes).unwrap();
341
assert!(sessions.ends_with(".claude/sessions"));
342
assert_eq!(
343
directory.file_name().unwrap().to_string_lossy(),
344
"-home-daniel-Projects-x"
345
);
346
assert_eq!(
347
resolve_working_dir(&environment, "/srv/app", Path::new("/home/daniel")),
348
"/srv/app"
349
);
350
}
351
352
#[test]
353
fn a_host_home_expands_the_tilde_before_encoding() {
354
let homes = Homes {
355
entries: vec![(Location::Native, PathBuf::from("/home/daniel"))],
356
};
357
let (directory, _) = claude_dirs(&Environment::Host, "~", &homes).unwrap();
358
assert!(directory.ends_with(".claude/projects/-home-daniel"));
359
}
360
}
@@ -0,0 +1,360 @@1
use std::collections::HashSet;2
use std::path::{Path, PathBuf};3
use std::time::Duration;4
5
use agents::{Environment, ExternalSession};6
use chrono::{DateTime, Local, Utc};7
use mcp::install::{Homes, Location};8
9
use super::message_context;10
use super::runs::{AgentRun, RunState};11
use crate::agent_api::agent_homes;12
use crate::app_state::AppState;13
use crate::notice::truncated;14
15
pub const SESSION_LIMIT: usize = 10;16
const ACTIVE_WINDOW: Duration = Duration::from_secs(120);17
const LABEL_CHARS: usize = 60;18
const WEEK_DAYS: i64 = 7;19
20
#[derive(Clone, Debug, PartialEq, Eq)]21
pub struct SessionOption {22
pub session_id: String,23
pub working_dir: String,24
pub label: String,25
pub meta: String,26
pub running: bool,27
pub fork: bool,28
}29
30
pub fn relative_age(now: DateTime<Utc>, then: DateTime<Utc>) -> String {31
let age = now - then;32
if age.num_minutes() < 1 {33
"now".to_owned()34
} else if age.num_hours() < 1 {35
format!("{}m", age.num_minutes())36
} else if age.num_days() < 1 {37
format!("{}h", age.num_hours())38
} else if age.num_days() < WEEK_DAYS {39
then.with_timezone(&Local).format("%a").to_string()40
} else {41
then.with_timezone(&Local).format("%b %-d").to_string()42
}43
}44
45
fn run_meta(run: &AgentRun, now: DateTime<Utc>) -> String {46
let age = relative_age(now, run.ended_at.unwrap_or(run.started_at));47
match run.state {48
RunState::Running => "Running".to_owned(),49
RunState::Done => format!("Done - {age}"),50
RunState::Failed { .. } => format!("Failed - {age}"),51
RunState::Stopped => format!("Stopped - {age}"),52
}53
}54
55
pub fn run_options(runs: &[&AgentRun], state: &AppState, now: DateTime<Utc>) -> Vec<SessionOption> {56
let mut seen = HashSet::new();57
runs.iter()58
.filter(|run| {59
!run.session_id.is_empty()60
&& (run.launched || run.sent_to.is_some())61
&& seen.insert(run.session_id.clone())62
})63
.take(SESSION_LIMIT)64
.map(|run| {65
let message =66
message_context::message_line(state, &run.conversation_id, &run.message_id)67
.unwrap_or_else(|| run.chat_title.clone());68
SessionOption {69
session_id: run.session_id.clone(),70
working_dir: run.working_dir.clone(),71
label: format!(72
"{} - {}",73
run.action_label,74
truncated(&message, LABEL_CHARS)75
),76
meta: run_meta(run, now),77
running: run.is_running(),78
fork: false,79
}80
})81
.collect()82
}83
84
pub fn external_options(85
sessions: &[ExternalSession],86
working_dir: &str,87
now: DateTime<Utc>,88
) -> Vec<SessionOption> {89
sessions90
.iter()91
.map(|session| {92
let modified = DateTime::<Utc>::from(session.modified);93
let active = session.live94
|| modified > now95
|| (now - modified)96
.to_std()97
.is_ok_and(|age| age < ACTIVE_WINDOW);98
SessionOption {99
session_id: session.session_id.clone(),100
working_dir: working_dir.to_owned(),101
label: truncated(&session.title, LABEL_CHARS),102
meta: if active {103
"Active elsewhere - sends to a copy".to_owned()104
} else {105
format!("Idle - {}", relative_age(now, modified))106
},107
running: false,108
fork: active,109
}110
})111
.collect()112
}113
114
fn pick_home<'a>(environment: &Environment, homes: &'a Homes) -> Option<&'a PathBuf> {115
homes116
.entries117
.iter()118
.find(|(location, _)| match (environment, location) {119
(Environment::Host, Location::Windows | Location::Native) => true,120
(121
Environment::Wsl {122
distro: Some(wanted),123
},124
Location::Wsl { distro },125
) => wanted == distro,126
(Environment::Wsl { distro: None }, Location::Wsl { .. }) => true,127
(Environment::Wsl { .. }, Location::Native) => true,128
_ => false,129
})130
.map(|(_, home)| home)131
}132
133
fn resolve_working_dir(environment: &Environment, working_dir: &str, home: &Path) -> String {134
let home_text = home.to_string_lossy();135
let home_text = match environment {136
Environment::Host => home_text.into_owned(),137
Environment::Wsl { .. } => agents::linux_path(&home_text),138
};139
match working_dir.strip_prefix('~') {140
Some(rest) if rest.is_empty() || rest.starts_with(['/', '\\']) => {141
format!("{home_text}{rest}")142
}143
_ => working_dir.to_owned(),144
}145
}146
147
fn claude_dirs(148
environment: &Environment,149
working_dir: &str,150
homes: &Homes,151
) -> Option<(PathBuf, PathBuf)> {152
let home = pick_home(environment, homes)?;153
let resolved = resolve_working_dir(environment, working_dir, home);154
let claude = home.join(".claude");155
Some((156
agents::resolve_project_dir(&claude.join("projects"), &resolved),157
claude.join("sessions"),158
))159
}160
161
#[derive(Default)]162
pub struct ExternalLoad {163
pub sessions: Vec<ExternalSession>,164
pub live_session_ids: HashSet<String>,165
}166
167
pub fn load_external(168
environment: &Environment,169
working_dir: &str,170
known_session_ids: &HashSet<String>,171
demo: bool,172
) -> ExternalLoad {173
let Some((project_dir, sessions_dir)) =174
claude_dirs(environment, working_dir, &agent_homes(demo))175
else {176
return ExternalLoad::default();177
};178
let live = agents::live_session_names(&sessions_dir);179
ExternalLoad {180
sessions: agents::scan_external_sessions(181
&project_dir,182
&live,183
known_session_ids,184
SESSION_LIMIT,185
),186
live_session_ids: live.into_keys().collect(),187
}188
}189
190
pub fn mark_live_runs(options: &mut [SessionOption], live_session_ids: &HashSet<String>) {191
for option in options {192
option.fork = !option.running && live_session_ids.contains(&option.session_id);193
}194
}195
196
pub fn default_wsl_distro(demo: bool) -> Option<String> {197
agent_homes(demo)198
.entries199
.into_iter()200
.find_map(|(location, _)| match location {201
Location::Wsl { distro } => Some(distro),202
_ => None,203
})204
}205
206
#[cfg(test)]207
mod tests {208
use std::time::SystemTime;209
210
use chrono::TimeZone;211
212
use super::*;213
214
fn external(age: Duration) -> ExternalSession {215
ExternalSession {216
session_id: "abc".to_owned(),217
title: "Fix the build".to_owned(),218
modified: SystemTime::now() - age,219
live: false,220
}221
}222
223
#[test]224
fn relative_age_uses_minutes_hours_weekday_and_date() {225
let now = Utc.with_ymd_and_hms(2026, 10, 13, 12, 0, 0).unwrap();226
let ago = |seconds: i64| relative_age(now, now - chrono::Duration::seconds(seconds));227
assert_eq!(ago(20), "now");228
assert_eq!(ago(5 * 60), "5m");229
assert_eq!(ago(3 * 3600), "3h");230
assert_eq!(ago(2 * 86400).len(), 3);231
assert!(ago(10 * 86400).contains(char::is_whitespace));232
}233
234
#[test]235
fn external_sessions_are_active_under_two_minutes_and_fork() {236
let now = Utc::now();237
let options = external_options(238
&[239
external(Duration::from_secs(30)),240
external(Duration::from_secs(3 * 3600 + 30)),241
],242
"/repo",243
now,244
);245
assert_eq!(options[0].meta, "Active elsewhere - sends to a copy");246
assert!(options[0].fork);247
assert_eq!(options[1].meta, "Idle - 3h");248
assert!(!options[1].fork);249
assert_eq!(options[1].label, "Fix the build");250
assert_eq!(options[1].working_dir, "/repo");251
let live = ExternalSession {252
live: true,253
..external(Duration::from_secs(3 * 3600))254
};255
let options = external_options(&[live], "/repo", now);256
assert_eq!(options[0].meta, "Active elsewhere - sends to a copy");257
assert!(options[0].fork);258
}259
260
#[test]261
fn app_sessions_open_in_a_terminal_are_forked_unless_running_here() {262
let option = |session_id: &str, running: bool| SessionOption {263
session_id: session_id.to_owned(),264
working_dir: "/repo".to_owned(),265
label: String::new(),266
meta: String::new(),267
running,268
fork: false,269
};270
let mut options = vec![option("a", false), option("b", false), option("c", true)];271
mark_live_runs(272
&mut options,273
&HashSet::from(["a".to_owned(), "c".to_owned()]),274
);275
let forks: Vec<bool> = options.iter().map(|option| option.fork).collect();276
assert_eq!(forks, [true, false, false]);277
}278
279
#[test]280
fn runs_that_never_created_a_session_are_left_out() {281
let state = AppState::new(282
std::sync::Arc::new(store::Store::open_in_memory().unwrap()),283
crate::app_state::Mode::default(),284
);285
let mut created = crate::agents::runs::tests::finished_run(1);286
created.launched = true;287
let mut never_started = crate::agents::runs::tests::finished_run(2);288
never_started.launched = false;289
let mut sent = crate::agents::runs::tests::finished_run(3);290
sent.launched = false;291
sent.sent_to = Some(crate::agents::runs::SessionTarget {292
session_id: sent.session_id.clone(),293
working_dir: "~".to_owned(),294
fork: false,295
});296
let options = run_options(&[&created, &never_started, &sent], &state, Utc::now());297
let ids: Vec<&str> = options298
.iter()299
.map(|option| option.session_id.as_str())300
.collect();301
assert_eq!(ids, ["session-1", "session-3"]);302
}303
304
#[test]305
fn the_home_matches_the_agent_environment() {306
let homes = Homes {307
entries: vec![308
(Location::Windows, PathBuf::from(r"C:\Users\dd")),309
(310
Location::Wsl {311
distro: "Ubuntu".to_owned(),312
},313
PathBuf::from(r"\\wsl.localhost\Ubuntu\home\daniel"),314
),315
],316
};317
let wsl = |distro: Option<&str>| Environment::Wsl {318
distro: distro.map(str::to_owned),319
};320
assert_eq!(321
pick_home(&Environment::Host, &homes),322
Some(&PathBuf::from(r"C:\Users\dd"))323
);324
assert!(pick_home(&wsl(None), &homes).is_some());325
assert!(pick_home(&wsl(Some("Ubuntu")), &homes).is_some());326
assert_eq!(pick_home(&wsl(Some("Debian")), &homes), None);327
}328
329
#[test]330
fn a_wsl_home_encodes_the_linux_path_of_the_working_dir() {331
let homes = Homes {332
entries: vec![(333
Location::Wsl {334
distro: "Ubuntu".to_owned(),335
},336
PathBuf::from(r"\\wsl.localhost\Ubuntu\home\daniel"),337
)],338
};339
let environment = Environment::Wsl { distro: None };340
let (directory, sessions) = claude_dirs(&environment, "~/Projects/x", &homes).unwrap();341
assert!(sessions.ends_with(".claude/sessions"));342
assert_eq!(343
directory.file_name().unwrap().to_string_lossy(),344
"-home-daniel-Projects-x"345
);346
assert_eq!(347
resolve_working_dir(&environment, "/srv/app", Path::new("/home/daniel")),348
"/srv/app"349
);350
}351
352
#[test]353
fn a_host_home_expands_the_tilde_before_encoding() {354
let homes = Homes {355
entries: vec![(Location::Native, PathBuf::from("/home/daniel"))],356
};357
let (directory, _) = claude_dirs(&Environment::Host, "~", &homes).unwrap();358
assert!(directory.ends_with(".claude/projects/-home-daniel"));359
}360
}@@ -1,14 +1,24 @@
1
use agents::AgentAction;
1
use std::rc::Rc;
2
3
use agents::{AgentAction, Environment};
4
use chrono::Utc;
2
5
use gpui_kit::assets::IconName;
3
6
use gpui_kit::component::{
4
7
ActiveTheme as _, h_flex,
5
input::{Textarea, TextareaState},
8
input::{InputEvent, Textarea, TextareaState},
6
9
v_flex,
7
10
};
8
11
use gpui_kit::prelude::FluentBuilder as _;
9
12
use gpui_kit::*;
10
13
11
use super::{mcp_bridge, message_context, start_run, start_run_when_mcp_ready};
14
use super::runs::{SessionTarget, StartOptions};
15
use super::session_options::{
16
SessionOption, default_wsl_distro, external_options, load_external, mark_live_runs, run_options,
17
};
18
use super::start_dialog_pickers::{MenuPart, MenuRow, locked_select, picker_row, select};
19
use super::{
20
mcp_bridge, message_context, raise_notice, runs_handle, start_run, start_run_when_mcp_ready,
21
};
12
22
use crate::app_state::AppState;
13
23
use crate::theme;
14
24
use crate::views::widgets::{icon, symbol};
@@ -25,6 +35,9 @@ const QUOTE_LINES: usize = 3;
25
35
const FIELD_MIN_ROWS: usize = 3;
26
36
const FIELD_MAX_ROWS: usize = 6;
27
37
const PROMPT_SIZE: f32 = 12.;
38
const DISABLED_OPACITY: f32 = 0.5;
39
const DEFAULT_PLACEHOLDER: &str = "e.g. only the backend, open a PR when done";
40
const SESSION_PLACEHOLDER: &str = "Type the message to send";
28
41
29
42
#[derive(Clone, Debug, PartialEq, Eq)]
30
43
pub struct StartRequest {
@@ -47,6 +60,16 @@ pub struct StartDialog {
47
60
needs_allow: bool,
48
61
input: Entity<TextareaState>,
49
62
show_prompt: bool,
63
environment: Environment,
64
default_working_dir: String,
65
working_dir: String,
66
recent_working_dirs: Vec<String>,
67
offers_sessions: bool,
68
scans_external: bool,
69
run_sessions: Vec<SessionOption>,
70
external_sessions: Vec<SessionOption>,
71
selected_session: Option<SessionOption>,
72
external_generation: u64,
50
73
}
51
74
52
75
impl EventEmitter<StartDialogEvent> for StartDialog {}
@@ -72,24 +95,202 @@ impl StartDialog {
72
95
let input = cx.new(|cx| {
73
96
TextareaState::new(window, cx)
74
97
.auto_grow(FIELD_MIN_ROWS, FIELD_MAX_ROWS)
75
.placeholder("e.g. only the backend, open a PR when done")
98
.placeholder(DEFAULT_PLACEHOLDER)
76
99
});
77
100
input.update(cx, |input, cx| input.focus(window, cx));
78
StartDialog {
101
cx.subscribe(&input, |_, _, event: &InputEvent, cx| {
102
if matches!(event, InputEvent::Change) {
103
cx.notify();
104
}
105
})
106
.detach();
107
let runs = runs_handle(cx).map(|runs| runs.read(cx));
108
let profile = runs.and_then(|runs| {
109
runs.settings()
110
.agents
111
.iter()
112
.find(|profile| profile.id == action.agent_id)
113
.cloned()
114
});
115
let recent_working_dirs = runs
116
.map(|runs| {
117
runs.settings()
118
.recent_working_dirs_of(&action.agent_id)
119
.to_vec()
120
})
121
.unwrap_or_default();
122
let offers_sessions = profile.as_ref().is_some_and(agents::supports_resume);
123
let run_sessions = match runs {
124
Some(runs) if offers_sessions => {
125
run_options(&runs.for_agent(&action.agent_id), app.read(cx), Utc::now())
126
}
127
_ => Vec::new(),
128
};
129
let mut dialog = StartDialog {
79
130
app,
80
subtitle: format!("{agent_name} - {}", action.working_dir),
131
subtitle: agent_name.to_owned(),
81
132
needs_allow: !mcp_bridge::chat_allowed(&request.conversation_id, cx),
82
133
request,
83
action,
84
134
sender,
85
135
quote,
86
136
input,
87
137
show_prompt: false,
138
environment: profile
139
.as_ref()
140
.map(|profile| profile.environment.clone())
141
.unwrap_or_default(),
142
default_working_dir: action.working_dir.clone(),
143
working_dir: action.working_dir.clone(),
144
recent_working_dirs,
145
offers_sessions,
146
scans_external: profile
147
.is_some_and(|profile| profile.output == agents::OutputFormat::ClaudeStreamJson)
148
&& offers_sessions,
149
run_sessions,
150
external_sessions: Vec::new(),
151
selected_session: None,
152
external_generation: 0,
153
action,
154
};
155
dialog.reload_external(cx);
156
dialog
157
}
158
159
fn reload_external(&mut self, cx: &mut Context<Self>) {
160
self.external_sessions.clear();
161
if !self.scans_external {
162
return;
163
}
164
self.external_generation += 1;
165
let generation = self.external_generation;
166
let environment = self.environment.clone();
167
let working_dir = self.working_dir.clone();
168
let known_session_ids = runs_handle(cx)
169
.map(|runs| runs.read(cx).session_ids())
170
.unwrap_or_default();
171
let demo = crate::agent_api::is_demo(cx);
172
cx.spawn(async move |this, cx| {
173
let scanned_dir = working_dir.clone();
174
let loaded = cx
175
.background_executor()
176
.spawn(async move {
177
load_external(&environment, &scanned_dir, &known_session_ids, demo)
178
})
179
.await;
180
this.update(cx, |this, cx| {
181
if this.external_generation == generation {
182
this.external_sessions =
183
external_options(&loaded.sessions, &working_dir, Utc::now());
184
mark_live_runs(&mut this.run_sessions, &loaded.live_session_ids);
185
cx.notify();
186
}
187
})
188
.ok();
189
})
190
.detach();
191
}
192
193
fn choose_session(
194
&mut self,
195
session: Option<SessionOption>,
196
window: &mut Window,
197
cx: &mut Context<Self>,
198
) {
199
let placeholder = if session.is_some() {
200
SESSION_PLACEHOLDER
201
} else {
202
DEFAULT_PLACEHOLDER
203
};
204
self.input.update(cx, |input, cx| {
205
input.set_placeholder(placeholder, window, cx)
206
});
207
self.selected_session = session;
208
cx.notify();
209
}
210
211
fn choose_working_dir(&mut self, working_dir: String, cx: &mut Context<Self>) {
212
if self.working_dir != working_dir {
213
self.working_dir = working_dir;
214
self.reload_external(cx);
215
}
216
cx.notify();
217
}
218
219
fn browse(&mut self, cx: &mut Context<Self>) {
220
let receiver = cx.prompt_for_paths(PathPromptOptions {
221
files: false,
222
directories: true,
223
multiple: false,
224
prompt: None,
225
});
226
let environment = self.environment.clone();
227
cx.spawn(async move |this, cx| {
228
let Ok(Ok(Some(paths))) = receiver.await else {
229
return;
230
};
231
let Some(path) = paths.into_iter().next() else {
232
return;
233
};
234
let text = path.to_string_lossy().into_owned();
235
let working_dir = match &environment {
236
Environment::Host => text,
237
Environment::Wsl { distro } => {
238
let chosen = agents::wsl_unc_distro(&text).map(str::to_owned);
239
let wanted = match (&chosen, distro) {
240
(_, Some(distro)) => Some(distro.clone()),
241
(Some(_), None) => {
242
let demo = cx.update(|cx| crate::agent_api::is_demo(cx));
243
cx.background_executor()
244
.spawn(async move { default_wsl_distro(demo) })
245
.await
246
}
247
(None, None) => None,
248
};
249
if chosen.is_some() && wanted.is_some() && chosen != wanted {
250
cx.update(|cx| {
251
raise_notice(
252
"That folder is in a different WSL distro than the agent"
253
.to_owned(),
254
cx,
255
)
256
});
257
return;
258
}
259
agents::linux_path(&text)
260
}
261
};
262
this.update(cx, |this, cx| this.choose_working_dir(working_dir, cx))
263
.ok();
264
})
265
.detach();
266
}
267
268
fn start_options(&self) -> StartOptions {
269
match &self.selected_session {
270
Some(session) => StartOptions {
271
working_dir: None,
272
remember_working_dir: false,
273
session: Some(SessionTarget {
274
session_id: session.session_id.clone(),
275
working_dir: session.working_dir.clone(),
276
fork: session.fork,
277
}),
278
},
279
None => StartOptions {
280
working_dir: (self.working_dir != self.default_working_dir)
281
.then(|| self.working_dir.clone()),
282
remember_working_dir: true,
283
session: None,
284
},
88
285
}
89
286
}
90
287
91
288
fn start(&mut self, cx: &mut Context<Self>) {
92
289
let extra = self.input.read(cx).value().trim().to_owned();
290
if self.selected_session.is_some() && extra.is_empty() {
291
return;
292
}
293
let options = self.start_options();
93
294
if self.needs_allow {
94
295
mcp_bridge::allow_chat(&self.request.conversation_id, cx);
95
296
}
@@ -99,6 +300,7 @@ impl StartDialog {
99
300
self.request.conversation_id.clone(),
100
301
self.request.message_id.clone(),
101
302
extra,
303
options,
102
304
cx,
103
305
);
104
306
} else {
@@ -107,6 +309,7 @@ impl StartDialog {
107
309
&self.request.conversation_id,
108
310
&self.request.message_id,
109
311
&extra,
312
options,
110
313
cx,
111
314
);
112
315
}
@@ -182,6 +385,133 @@ impl StartDialog {
182
385
.child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
183
386
}
184
387
388
fn session_parts(&self, dialog: &Entity<Self>) -> Vec<MenuPart> {
389
let row = |session: &SessionOption| {
390
let dialog = dialog.clone();
391
let chosen = session.clone();
392
MenuPart::Row(MenuRow {
393
label: session.label.clone(),
394
meta: Some(session.meta.clone()),
395
running: session.running,
396
selected: self
397
.selected_session
398
.as_ref()
399
.is_some_and(|selected| selected.session_id == session.session_id),
400
choose: Rc::new(move |window, cx| {
401
let chosen = chosen.clone();
402
dialog.update(cx, |dialog, cx| {
403
dialog.choose_session(Some(chosen), window, cx)
404
});
405
}),
406
})
407
};
408
let new_dialog = dialog.clone();
409
let mut parts = vec![MenuPart::Row(MenuRow {
410
label: "New session".to_owned(),
411
meta: None,
412
running: false,
413
selected: self.selected_session.is_none(),
414
choose: Rc::new(move |window, cx| {
415
new_dialog.update(cx, |dialog, cx| dialog.choose_session(None, window, cx));
416
}),
417
})];
418
if !self.run_sessions.is_empty() {
419
parts.push(MenuPart::Separator);
420
parts.push(MenuPart::Header("Recent sessions".to_owned()));
421
parts.extend(self.run_sessions.iter().map(row));
422
}
423
if !self.external_sessions.is_empty() {
424
parts.push(MenuPart::Separator);
425
parts.push(MenuPart::Header(format!(
426
"Other sessions in {}",
427
self.working_dir
428
)));
429
parts.extend(self.external_sessions.iter().map(row));
430
}
431
parts
432
}
433
434
fn working_dir_parts(&self, dialog: &Entity<Self>) -> Vec<MenuPart> {
435
let row = |working_dir: &str, meta: Option<&str>| {
436
let dialog = dialog.clone();
437
let chosen = working_dir.to_owned();
438
MenuPart::Row(MenuRow {
439
label: working_dir.to_owned(),
440
meta: meta.map(str::to_owned),
441
running: false,
442
selected: self.working_dir == working_dir,
443
choose: Rc::new(move |_, cx| {
444
let chosen = chosen.clone();
445
dialog.update(cx, |dialog, cx| dialog.choose_working_dir(chosen, cx));
446
}),
447
})
448
};
449
let browse_dialog = dialog.clone();
450
let mut parts = vec![
451
MenuPart::Header("Recent".to_owned()),
452
row(&self.default_working_dir, Some("action default")),
453
];
454
parts.extend(
455
self.recent_working_dirs
456
.iter()
457
.filter(|working_dir| **working_dir != self.default_working_dir)
458
.map(|working_dir| row(working_dir, None)),
459
);
460
parts.push(MenuPart::Separator);
461
parts.push(MenuPart::Row(MenuRow {
462
label: "Browse...".to_owned(),
463
meta: None,
464
running: false,
465
selected: false,
466
choose: Rc::new(move |_, cx| {
467
browse_dialog.update(cx, |dialog, cx| dialog.browse(cx));
468
}),
469
}));
470
parts
471
}
472
473
fn pickers(&self, cx: &mut Context<Self>) -> Div {
474
let dialog = cx.entity();
475
let session_row = self.offers_sessions.then(|| {
476
let (value, meta, running) = match &self.selected_session {
477
Some(session) => (
478
session.label.clone(),
479
Some(session.meta.clone()),
480
session.running,
481
),
482
None => ("New session".to_owned(), None, false),
483
};
484
picker_row(
485
"Session",
486
select(
487
"agent-dialog-session",
488
value,
489
meta,
490
running,
491
self.session_parts(&dialog),
492
),
493
)
494
});
495
let working_dir_control = match &self.selected_session {
496
Some(session) => {
497
locked_select(session.working_dir.clone(), "from session").into_any_element()
498
}
499
None => select(
500
"agent-dialog-working-dir",
501
self.working_dir.clone(),
502
None,
503
false,
504
self.working_dir_parts(&dialog),
505
)
506
.into_any_element(),
507
};
508
v_flex()
509
.w_full()
510
.gap(px(8.))
511
.children(session_row)
512
.child(picker_row("Working dir", working_dir_control))
513
}
514
185
515
fn field(&self, window: &Window, cx: &App) -> Div {
186
516
let focused = self.input.focus_handle(cx).contains_focused(window, cx);
187
517
v_flex()
@@ -192,7 +522,11 @@ impl StartDialog {
192
522
.text_size(px(11.))
193
523
.font_weight(FontWeight::SEMIBOLD)
194
524
.text_color(theme::text_faint())
195
.child("Extra instructions (optional)"),
525
.child(if self.selected_session.is_some() {
526
"Message to the session"
527
} else {
528
"Extra instructions (optional)"
529
}),
196
530
)
197
531
.child(
198
532
div()
@@ -238,14 +572,18 @@ impl StartDialog {
238
572
239
573
fn prompt_box(&self, cx: &mut Context<Self>) -> Div {
240
574
let extra = self.input.read(cx).value().trim().to_owned();
241
let prompt = message_context::preview_prompt(
242
self.app.read(cx),
243
&self.action,
244
&self.request.conversation_id,
245
&self.request.message_id,
246
&extra,
247
)
248
.unwrap_or_default();
575
let prompt = if self.selected_session.is_some() {
576
extra
577
} else {
578
message_context::preview_prompt(
579
self.app.read(cx),
580
&self.action,
581
&self.request.conversation_id,
582
&self.request.message_id,
583
&extra,
584
)
585
.unwrap_or_default()
586
};
249
587
div()
250
588
.w_full()
251
589
.max_h(px(160.))
@@ -262,7 +600,11 @@ impl StartDialog {
262
600
}
263
601
264
602
fn buttons(&self, cx: &mut Context<Self>) -> Div {
265
let start_label = if self.needs_allow {
603
let blocked =
604
self.selected_session.is_some() && self.input.read(cx).value().trim().is_empty();
605
let start_label = if self.selected_session.is_some() {
606
"Send"
607
} else if self.needs_allow {
266
608
"Allow and start"
267
609
} else {
268
610
"Start"
@@ -294,14 +636,18 @@ impl StartDialog {
294
636
.px(px(12.))
295
637
.items_center()
296
638
.rounded(px(8.))
297
.cursor_pointer()
298
639
.bg(theme::accent())
299
.hover(|button| button.bg(theme::accent_text()))
300
640
.text_color(theme::on_accent())
301
641
.text_size(px(13.))
302
642
.font_weight(FontWeight::SEMIBOLD)
303
643
.child(start_label)
304
.on_click(cx.listener(|this, _, _, cx| this.start(cx))),
644
.when(blocked, |button| button.opacity(DISABLED_OPACITY))
645
.when(!blocked, |button| {
646
button
647
.cursor_pointer()
648
.hover(|button| button.bg(theme::accent_text()))
649
.on_click(cx.listener(|this, _, _, cx| this.start(cx)))
650
}),
305
651
)
306
652
}
307
653
}
@@ -352,6 +698,7 @@ impl Render for StartDialog {
352
698
.child("Agents can't see this chat yet."),
353
699
)
354
700
})
701
.child(self.pickers(cx))
355
702
.child(self.field(window, cx))
356
703
.when(self.show_prompt, |card| card.child(self.prompt_box(cx)))
357
704
.child(self.buttons(cx)),
@@ -1,14 +1,24 @@1
use agents::AgentAction;1
use std::rc::Rc;2
3
use agents::{AgentAction, Environment};4
use chrono::Utc;2
use gpui_kit::assets::IconName;5
use gpui_kit::assets::IconName;3
use gpui_kit::component::{6
use gpui_kit::component::{4
ActiveTheme as _, h_flex,7
ActiveTheme as _, h_flex,5
input::{Textarea, TextareaState},8
input::{InputEvent, Textarea, TextareaState},6
v_flex,9
v_flex,7
};10
};8
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::prelude::FluentBuilder as _;9
use gpui_kit::*;12
use gpui_kit::*;10
13
11
use super::{mcp_bridge, message_context, start_run, start_run_when_mcp_ready};14
use super::runs::{SessionTarget, StartOptions};15
use super::session_options::{16
SessionOption, default_wsl_distro, external_options, load_external, mark_live_runs, run_options,17
};18
use super::start_dialog_pickers::{MenuPart, MenuRow, locked_select, picker_row, select};19
use super::{20
mcp_bridge, message_context, raise_notice, runs_handle, start_run, start_run_when_mcp_ready,21
};12
use crate::app_state::AppState;22
use crate::app_state::AppState;13
use crate::theme;23
use crate::theme;14
use crate::views::widgets::{icon, symbol};24
use crate::views::widgets::{icon, symbol};@@ -25,6 +35,9 @@ const QUOTE_LINES: usize = 3;25
const FIELD_MIN_ROWS: usize = 3;35
const FIELD_MIN_ROWS: usize = 3;26
const FIELD_MAX_ROWS: usize = 6;36
const FIELD_MAX_ROWS: usize = 6;27
const PROMPT_SIZE: f32 = 12.;37
const PROMPT_SIZE: f32 = 12.;38
const DISABLED_OPACITY: f32 = 0.5;39
const DEFAULT_PLACEHOLDER: &str = "e.g. only the backend, open a PR when done";40
const SESSION_PLACEHOLDER: &str = "Type the message to send";28
41
29
#[derive(Clone, Debug, PartialEq, Eq)]42
#[derive(Clone, Debug, PartialEq, Eq)]30
pub struct StartRequest {43
pub struct StartRequest {@@ -47,6 +60,16 @@ pub struct StartDialog {47
needs_allow: bool,60
needs_allow: bool,48
input: Entity<TextareaState>,61
input: Entity<TextareaState>,49
show_prompt: bool,62
show_prompt: bool,63
environment: Environment,64
default_working_dir: String,65
working_dir: String,66
recent_working_dirs: Vec<String>,67
offers_sessions: bool,68
scans_external: bool,69
run_sessions: Vec<SessionOption>,70
external_sessions: Vec<SessionOption>,71
selected_session: Option<SessionOption>,72
external_generation: u64,50
}73
}51
74
52
impl EventEmitter<StartDialogEvent> for StartDialog {}75
impl EventEmitter<StartDialogEvent> for StartDialog {}@@ -72,24 +95,202 @@ impl StartDialog {72
let input = cx.new(|cx| {95
let input = cx.new(|cx| {73
TextareaState::new(window, cx)96
TextareaState::new(window, cx)74
.auto_grow(FIELD_MIN_ROWS, FIELD_MAX_ROWS)97
.auto_grow(FIELD_MIN_ROWS, FIELD_MAX_ROWS)75
.placeholder("e.g. only the backend, open a PR when done")98
.placeholder(DEFAULT_PLACEHOLDER)76
});99
});77
input.update(cx, |input, cx| input.focus(window, cx));100
input.update(cx, |input, cx| input.focus(window, cx));78
StartDialog {101
cx.subscribe(&input, |_, _, event: &InputEvent, cx| {102
if matches!(event, InputEvent::Change) {103
cx.notify();104
}105
})106
.detach();107
let runs = runs_handle(cx).map(|runs| runs.read(cx));108
let profile = runs.and_then(|runs| {109
runs.settings()110
.agents111
.iter()112
.find(|profile| profile.id == action.agent_id)113
.cloned()114
});115
let recent_working_dirs = runs116
.map(|runs| {117
runs.settings()118
.recent_working_dirs_of(&action.agent_id)119
.to_vec()120
})121
.unwrap_or_default();122
let offers_sessions = profile.as_ref().is_some_and(agents::supports_resume);123
let run_sessions = match runs {124
Some(runs) if offers_sessions => {125
run_options(&runs.for_agent(&action.agent_id), app.read(cx), Utc::now())126
}127
_ => Vec::new(),128
};129
let mut dialog = StartDialog {79
app,130
app,80
subtitle: format!("{agent_name} - {}", action.working_dir),131
subtitle: agent_name.to_owned(),81
needs_allow: !mcp_bridge::chat_allowed(&request.conversation_id, cx),132
needs_allow: !mcp_bridge::chat_allowed(&request.conversation_id, cx),82
request,133
request,83
action,84
sender,134
sender,85
quote,135
quote,86
input,136
input,87
show_prompt: false,137
show_prompt: false,138
environment: profile139
.as_ref()140
.map(|profile| profile.environment.clone())141
.unwrap_or_default(),142
default_working_dir: action.working_dir.clone(),143
working_dir: action.working_dir.clone(),144
recent_working_dirs,145
offers_sessions,146
scans_external: profile147
.is_some_and(|profile| profile.output == agents::OutputFormat::ClaudeStreamJson)148
&& offers_sessions,149
run_sessions,150
external_sessions: Vec::new(),151
selected_session: None,152
external_generation: 0,153
action,154
};155
dialog.reload_external(cx);156
dialog157
}158
159
fn reload_external(&mut self, cx: &mut Context<Self>) {160
self.external_sessions.clear();161
if !self.scans_external {162
return;163
}164
self.external_generation += 1;165
let generation = self.external_generation;166
let environment = self.environment.clone();167
let working_dir = self.working_dir.clone();168
let known_session_ids = runs_handle(cx)169
.map(|runs| runs.read(cx).session_ids())170
.unwrap_or_default();171
let demo = crate::agent_api::is_demo(cx);172
cx.spawn(async move |this, cx| {173
let scanned_dir = working_dir.clone();174
let loaded = cx175
.background_executor()176
.spawn(async move {177
load_external(&environment, &scanned_dir, &known_session_ids, demo)178
})179
.await;180
this.update(cx, |this, cx| {181
if this.external_generation == generation {182
this.external_sessions =183
external_options(&loaded.sessions, &working_dir, Utc::now());184
mark_live_runs(&mut this.run_sessions, &loaded.live_session_ids);185
cx.notify();186
}187
})188
.ok();189
})190
.detach();191
}192
193
fn choose_session(194
&mut self,195
session: Option<SessionOption>,196
window: &mut Window,197
cx: &mut Context<Self>,198
) {199
let placeholder = if session.is_some() {200
SESSION_PLACEHOLDER201
} else {202
DEFAULT_PLACEHOLDER203
};204
self.input.update(cx, |input, cx| {205
input.set_placeholder(placeholder, window, cx)206
});207
self.selected_session = session;208
cx.notify();209
}210
211
fn choose_working_dir(&mut self, working_dir: String, cx: &mut Context<Self>) {212
if self.working_dir != working_dir {213
self.working_dir = working_dir;214
self.reload_external(cx);215
}216
cx.notify();217
}218
219
fn browse(&mut self, cx: &mut Context<Self>) {220
let receiver = cx.prompt_for_paths(PathPromptOptions {221
files: false,222
directories: true,223
multiple: false,224
prompt: None,225
});226
let environment = self.environment.clone();227
cx.spawn(async move |this, cx| {228
let Ok(Ok(Some(paths))) = receiver.await else {229
return;230
};231
let Some(path) = paths.into_iter().next() else {232
return;233
};234
let text = path.to_string_lossy().into_owned();235
let working_dir = match &environment {236
Environment::Host => text,237
Environment::Wsl { distro } => {238
let chosen = agents::wsl_unc_distro(&text).map(str::to_owned);239
let wanted = match (&chosen, distro) {240
(_, Some(distro)) => Some(distro.clone()),241
(Some(_), None) => {242
let demo = cx.update(|cx| crate::agent_api::is_demo(cx));243
cx.background_executor()244
.spawn(async move { default_wsl_distro(demo) })245
.await246
}247
(None, None) => None,248
};249
if chosen.is_some() && wanted.is_some() && chosen != wanted {250
cx.update(|cx| {251
raise_notice(252
"That folder is in a different WSL distro than the agent"253
.to_owned(),254
cx,255
)256
});257
return;258
}259
agents::linux_path(&text)260
}261
};262
this.update(cx, |this, cx| this.choose_working_dir(working_dir, cx))263
.ok();264
})265
.detach();266
}267
268
fn start_options(&self) -> StartOptions {269
match &self.selected_session {270
Some(session) => StartOptions {271
working_dir: None,272
remember_working_dir: false,273
session: Some(SessionTarget {274
session_id: session.session_id.clone(),275
working_dir: session.working_dir.clone(),276
fork: session.fork,277
}),278
},279
None => StartOptions {280
working_dir: (self.working_dir != self.default_working_dir)281
.then(|| self.working_dir.clone()),282
remember_working_dir: true,283
session: None,284
},88
}285
}89
}286
}90
287
91
fn start(&mut self, cx: &mut Context<Self>) {288
fn start(&mut self, cx: &mut Context<Self>) {92
let extra = self.input.read(cx).value().trim().to_owned();289
let extra = self.input.read(cx).value().trim().to_owned();290
if self.selected_session.is_some() && extra.is_empty() {291
return;292
}293
let options = self.start_options();93
if self.needs_allow {294
if self.needs_allow {94
mcp_bridge::allow_chat(&self.request.conversation_id, cx);295
mcp_bridge::allow_chat(&self.request.conversation_id, cx);95
}296
}@@ -99,6 +300,7 @@ impl StartDialog {99
self.request.conversation_id.clone(),300
self.request.conversation_id.clone(),100
self.request.message_id.clone(),301
self.request.message_id.clone(),101
extra,302
extra,303
options,102
cx,304
cx,103
);305
);104
} else {306
} else {@@ -107,6 +309,7 @@ impl StartDialog {107
&self.request.conversation_id,309
&self.request.conversation_id,108
&self.request.message_id,310
&self.request.message_id,109
&extra,311
&extra,312
options,110
cx,313
cx,111
);314
);112
}315
}@@ -182,6 +385,133 @@ impl StartDialog {182
.child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))385
.child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))183
}386
}184
387
388
fn session_parts(&self, dialog: &Entity<Self>) -> Vec<MenuPart> {389
let row = |session: &SessionOption| {390
let dialog = dialog.clone();391
let chosen = session.clone();392
MenuPart::Row(MenuRow {393
label: session.label.clone(),394
meta: Some(session.meta.clone()),395
running: session.running,396
selected: self397
.selected_session398
.as_ref()399
.is_some_and(|selected| selected.session_id == session.session_id),400
choose: Rc::new(move |window, cx| {401
let chosen = chosen.clone();402
dialog.update(cx, |dialog, cx| {403
dialog.choose_session(Some(chosen), window, cx)404
});405
}),406
})407
};408
let new_dialog = dialog.clone();409
let mut parts = vec![MenuPart::Row(MenuRow {410
label: "New session".to_owned(),411
meta: None,412
running: false,413
selected: self.selected_session.is_none(),414
choose: Rc::new(move |window, cx| {415
new_dialog.update(cx, |dialog, cx| dialog.choose_session(None, window, cx));416
}),417
})];418
if !self.run_sessions.is_empty() {419
parts.push(MenuPart::Separator);420
parts.push(MenuPart::Header("Recent sessions".to_owned()));421
parts.extend(self.run_sessions.iter().map(row));422
}423
if !self.external_sessions.is_empty() {424
parts.push(MenuPart::Separator);425
parts.push(MenuPart::Header(format!(426
"Other sessions in {}",427
self.working_dir428
)));429
parts.extend(self.external_sessions.iter().map(row));430
}431
parts432
}433
434
fn working_dir_parts(&self, dialog: &Entity<Self>) -> Vec<MenuPart> {435
let row = |working_dir: &str, meta: Option<&str>| {436
let dialog = dialog.clone();437
let chosen = working_dir.to_owned();438
MenuPart::Row(MenuRow {439
label: working_dir.to_owned(),440
meta: meta.map(str::to_owned),441
running: false,442
selected: self.working_dir == working_dir,443
choose: Rc::new(move |_, cx| {444
let chosen = chosen.clone();445
dialog.update(cx, |dialog, cx| dialog.choose_working_dir(chosen, cx));446
}),447
})448
};449
let browse_dialog = dialog.clone();450
let mut parts = vec![451
MenuPart::Header("Recent".to_owned()),452
row(&self.default_working_dir, Some("action default")),453
];454
parts.extend(455
self.recent_working_dirs456
.iter()457
.filter(|working_dir| **working_dir != self.default_working_dir)458
.map(|working_dir| row(working_dir, None)),459
);460
parts.push(MenuPart::Separator);461
parts.push(MenuPart::Row(MenuRow {462
label: "Browse...".to_owned(),463
meta: None,464
running: false,465
selected: false,466
choose: Rc::new(move |_, cx| {467
browse_dialog.update(cx, |dialog, cx| dialog.browse(cx));468
}),469
}));470
parts471
}472
473
fn pickers(&self, cx: &mut Context<Self>) -> Div {474
let dialog = cx.entity();475
let session_row = self.offers_sessions.then(|| {476
let (value, meta, running) = match &self.selected_session {477
Some(session) => (478
session.label.clone(),479
Some(session.meta.clone()),480
session.running,481
),482
None => ("New session".to_owned(), None, false),483
};484
picker_row(485
"Session",486
select(487
"agent-dialog-session",488
value,489
meta,490
running,491
self.session_parts(&dialog),492
),493
)494
});495
let working_dir_control = match &self.selected_session {496
Some(session) => {497
locked_select(session.working_dir.clone(), "from session").into_any_element()498
}499
None => select(500
"agent-dialog-working-dir",501
self.working_dir.clone(),502
None,503
false,504
self.working_dir_parts(&dialog),505
)506
.into_any_element(),507
};508
v_flex()509
.w_full()510
.gap(px(8.))511
.children(session_row)512
.child(picker_row("Working dir", working_dir_control))513
}514
185
fn field(&self, window: &Window, cx: &App) -> Div {515
fn field(&self, window: &Window, cx: &App) -> Div {186
let focused = self.input.focus_handle(cx).contains_focused(window, cx);516
let focused = self.input.focus_handle(cx).contains_focused(window, cx);187
v_flex()517
v_flex()@@ -192,7 +522,11 @@ impl StartDialog {192
.text_size(px(11.))522
.text_size(px(11.))193
.font_weight(FontWeight::SEMIBOLD)523
.font_weight(FontWeight::SEMIBOLD)194
.text_color(theme::text_faint())524
.text_color(theme::text_faint())195
.child("Extra instructions (optional)"),525
.child(if self.selected_session.is_some() {526
"Message to the session"527
} else {528
"Extra instructions (optional)"529
}),196
)530
)197
.child(531
.child(198
div()532
div()@@ -238,14 +572,18 @@ impl StartDialog {238
572
239
fn prompt_box(&self, cx: &mut Context<Self>) -> Div {573
fn prompt_box(&self, cx: &mut Context<Self>) -> Div {240
let extra = self.input.read(cx).value().trim().to_owned();574
let extra = self.input.read(cx).value().trim().to_owned();241
let prompt = message_context::preview_prompt(575
let prompt = if self.selected_session.is_some() {242
self.app.read(cx),576
extra243
&self.action,577
} else {244
&self.request.conversation_id,578
message_context::preview_prompt(245
&self.request.message_id,579
self.app.read(cx),246
&extra,580
&self.action,247
)581
&self.request.conversation_id,248
.unwrap_or_default();582
&self.request.message_id,583
&extra,584
)585
.unwrap_or_default()586
};249
div()587
div()250
.w_full()588
.w_full()251
.max_h(px(160.))589
.max_h(px(160.))@@ -262,7 +600,11 @@ impl StartDialog {262
}600
}263
601
264
fn buttons(&self, cx: &mut Context<Self>) -> Div {602
fn buttons(&self, cx: &mut Context<Self>) -> Div {265
let start_label = if self.needs_allow {603
let blocked =604
self.selected_session.is_some() && self.input.read(cx).value().trim().is_empty();605
let start_label = if self.selected_session.is_some() {606
"Send"607
} else if self.needs_allow {266
"Allow and start"608
"Allow and start"267
} else {609
} else {268
"Start"610
"Start"@@ -294,14 +636,18 @@ impl StartDialog {294
.px(px(12.))636
.px(px(12.))295
.items_center()637
.items_center()296
.rounded(px(8.))638
.rounded(px(8.))297
.cursor_pointer()298
.bg(theme::accent())639
.bg(theme::accent())299
.hover(|button| button.bg(theme::accent_text()))300
.text_color(theme::on_accent())640
.text_color(theme::on_accent())301
.text_size(px(13.))641
.text_size(px(13.))302
.font_weight(FontWeight::SEMIBOLD)642
.font_weight(FontWeight::SEMIBOLD)303
.child(start_label)643
.child(start_label)304
.on_click(cx.listener(|this, _, _, cx| this.start(cx))),644
.when(blocked, |button| button.opacity(DISABLED_OPACITY))645
.when(!blocked, |button| {646
button647
.cursor_pointer()648
.hover(|button| button.bg(theme::accent_text()))649
.on_click(cx.listener(|this, _, _, cx| this.start(cx)))650
}),305
)651
)306
}652
}307
}653
}@@ -352,6 +698,7 @@ impl Render for StartDialog {352
.child("Agents can't see this chat yet."),698
.child("Agents can't see this chat yet."),353
)699
)354
})700
})701
.child(self.pickers(cx))355
.child(self.field(window, cx))702
.child(self.field(window, cx))356
.when(self.show_prompt, |card| card.child(self.prompt_box(cx)))703
.when(self.show_prompt, |card| card.child(self.prompt_box(cx)))357
.child(self.buttons(cx)),704
.child(self.buttons(cx)),@@ -0,0 +1,145 @@
1
use gpui_kit::assets::IconName;
2
use gpui_kit::component::{
3
button::{Button, ButtonVariants as _},
4
h_flex,
5
menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},
6
};
7
use gpui_kit::prelude::FluentBuilder as _;
8
use gpui_kit::*;
9
10
use super::settings_controls::Choice;
11
use crate::theme;
12
use crate::views::widgets::icon;
13
14
pub const LABEL_WIDTH: f32 = 92.;
15
const SELECT_HEIGHT: f32 = 32.;
16
const MENU_HEIGHT: f32 = 320.;
17
const MENU_WIDTH: f32 = 380.;
18
const ROW_WIDTH: f32 = MENU_WIDTH - 56.;
19
const DOT_SIZE: f32 = 6.;
20
21
#[derive(Clone)]
22
pub struct MenuRow {
23
pub label: String,
24
pub meta: Option<String>,
25
pub running: bool,
26
pub selected: bool,
27
pub choose: Choice,
28
}
29
30
#[derive(Clone)]
31
pub enum MenuPart {
32
Header(String),
33
Separator,
34
Row(MenuRow),
35
}
36
37
pub fn picker_row(label: &'static str, control: impl IntoElement) -> Div {
38
h_flex()
39
.w_full()
40
.items_center()
41
.gap(px(12.))
42
.child(
43
div()
44
.w(px(LABEL_WIDTH))
45
.flex_none()
46
.text_size(px(11.))
47
.font_weight(FontWeight::SEMIBOLD)
48
.text_color(theme::text_faint())
49
.child(label),
50
)
51
.child(div().flex_1().min_w(px(0.)).child(control))
52
}
53
54
fn meta_text(meta: String, running: bool) -> Div {
55
h_flex()
56
.flex_none()
57
.items_center()
58
.gap(px(4.))
59
.text_size(px(11.))
60
.text_color(theme::text_faint())
61
.when(running, |meta_row| {
62
meta_row.child(
63
div()
64
.size(px(DOT_SIZE))
65
.rounded_full()
66
.bg(theme::accent_text()),
67
)
68
})
69
.child(meta)
70
}
71
72
fn select_body(value: String, meta: Option<String>, running: bool, chevron: bool) -> Div {
73
h_flex()
74
.w_full()
75
.items_center()
76
.gap(px(8.))
77
.child(
78
div()
79
.flex_1()
80
.min_w(px(0.))
81
.truncate()
82
.text_size(px(13.))
83
.child(value),
84
)
85
.children(meta.map(|meta| meta_text(meta, running)))
86
.when(chevron, |body| {
87
body.child(icon(IconName::ChevronDown, 14., theme::text_muted()))
88
})
89
}
90
91
fn menu_from(menu: PopupMenu, parts: &[MenuPart]) -> PopupMenu {
92
parts.iter().fold(menu, |menu, part| match part {
93
MenuPart::Header(text) => menu.item(PopupMenuItem::label(text.clone())),
94
MenuPart::Separator => menu.item(PopupMenuItem::separator()),
95
MenuPart::Row(row) => {
96
let choose = row.choose.clone();
97
let (label, meta, running) = (row.label.clone(), row.meta.clone(), row.running);
98
menu.item(
99
PopupMenuItem::element(move |_, _| {
100
select_body(label.clone(), meta.clone(), running, false).w(px(ROW_WIDTH))
101
})
102
.checked(row.selected)
103
.on_click(move |_, window, cx| choose(window, cx)),
104
)
105
}
106
})
107
}
108
109
pub fn select(
110
id: &'static str,
111
value: String,
112
meta: Option<String>,
113
running: bool,
114
parts: Vec<MenuPart>,
115
) -> impl IntoElement {
116
Button::new(id)
117
.ghost()
118
.w_full()
119
.h(px(SELECT_HEIGHT))
120
.px(px(12.))
121
.rounded(px(8.))
122
.bg(theme::surface_raised())
123
.child(select_body(value, meta, running, true))
124
.dropdown_menu(move |menu, _, _| {
125
menu_from(
126
menu.min_w(px(MENU_WIDTH))
127
.max_w(px(MENU_WIDTH))
128
.max_h(px(MENU_HEIGHT))
129
.scrollable(true),
130
&parts,
131
)
132
})
133
}
134
135
pub fn locked_select(value: String, meta: &'static str) -> Div {
136
h_flex()
137
.w_full()
138
.h(px(SELECT_HEIGHT))
139
.px(px(12.))
140
.items_center()
141
.rounded(px(8.))
142
.bg(theme::surface_raised())
143
.text_color(theme::text_faint())
144
.child(select_body(value, Some(meta.to_owned()), false, false))
145
}
@@ -0,0 +1,145 @@1
use gpui_kit::assets::IconName;2
use gpui_kit::component::{3
button::{Button, ButtonVariants as _},4
h_flex,5
menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},6
};7
use gpui_kit::prelude::FluentBuilder as _;8
use gpui_kit::*;9
10
use super::settings_controls::Choice;11
use crate::theme;12
use crate::views::widgets::icon;13
14
pub const LABEL_WIDTH: f32 = 92.;15
const SELECT_HEIGHT: f32 = 32.;16
const MENU_HEIGHT: f32 = 320.;17
const MENU_WIDTH: f32 = 380.;18
const ROW_WIDTH: f32 = MENU_WIDTH - 56.;19
const DOT_SIZE: f32 = 6.;20
21
#[derive(Clone)]22
pub struct MenuRow {23
pub label: String,24
pub meta: Option<String>,25
pub running: bool,26
pub selected: bool,27
pub choose: Choice,28
}29
30
#[derive(Clone)]31
pub enum MenuPart {32
Header(String),33
Separator,34
Row(MenuRow),35
}36
37
pub fn picker_row(label: &'static str, control: impl IntoElement) -> Div {38
h_flex()39
.w_full()40
.items_center()41
.gap(px(12.))42
.child(43
div()44
.w(px(LABEL_WIDTH))45
.flex_none()46
.text_size(px(11.))47
.font_weight(FontWeight::SEMIBOLD)48
.text_color(theme::text_faint())49
.child(label),50
)51
.child(div().flex_1().min_w(px(0.)).child(control))52
}53
54
fn meta_text(meta: String, running: bool) -> Div {55
h_flex()56
.flex_none()57
.items_center()58
.gap(px(4.))59
.text_size(px(11.))60
.text_color(theme::text_faint())61
.when(running, |meta_row| {62
meta_row.child(63
div()64
.size(px(DOT_SIZE))65
.rounded_full()66
.bg(theme::accent_text()),67
)68
})69
.child(meta)70
}71
72
fn select_body(value: String, meta: Option<String>, running: bool, chevron: bool) -> Div {73
h_flex()74
.w_full()75
.items_center()76
.gap(px(8.))77
.child(78
div()79
.flex_1()80
.min_w(px(0.))81
.truncate()82
.text_size(px(13.))83
.child(value),84
)85
.children(meta.map(|meta| meta_text(meta, running)))86
.when(chevron, |body| {87
body.child(icon(IconName::ChevronDown, 14., theme::text_muted()))88
})89
}90
91
fn menu_from(menu: PopupMenu, parts: &[MenuPart]) -> PopupMenu {92
parts.iter().fold(menu, |menu, part| match part {93
MenuPart::Header(text) => menu.item(PopupMenuItem::label(text.clone())),94
MenuPart::Separator => menu.item(PopupMenuItem::separator()),95
MenuPart::Row(row) => {96
let choose = row.choose.clone();97
let (label, meta, running) = (row.label.clone(), row.meta.clone(), row.running);98
menu.item(99
PopupMenuItem::element(move |_, _| {100
select_body(label.clone(), meta.clone(), running, false).w(px(ROW_WIDTH))101
})102
.checked(row.selected)103
.on_click(move |_, window, cx| choose(window, cx)),104
)105
}106
})107
}108
109
pub fn select(110
id: &'static str,111
value: String,112
meta: Option<String>,113
running: bool,114
parts: Vec<MenuPart>,115
) -> impl IntoElement {116
Button::new(id)117
.ghost()118
.w_full()119
.h(px(SELECT_HEIGHT))120
.px(px(12.))121
.rounded(px(8.))122
.bg(theme::surface_raised())123
.child(select_body(value, meta, running, true))124
.dropdown_menu(move |menu, _, _| {125
menu_from(126
menu.min_w(px(MENU_WIDTH))127
.max_w(px(MENU_WIDTH))128
.max_h(px(MENU_HEIGHT))129
.scrollable(true),130
&parts,131
)132
})133
}134
135
pub fn locked_select(value: String, meta: &'static str) -> Div {136
h_flex()137
.w_full()138
.h(px(SELECT_HEIGHT))139
.px(px(12.))140
.items_center()141
.rounded(px(8.))142
.bg(theme::surface_raised())143
.text_color(theme::text_faint())144
.child(select_body(value, Some(meta.to_owned()), false, false))145
}