feat(agents): send Teams messages into running or ended agent sessions
- session picker lists running and Claude Desktop sessions across all folders - running session gets the message through its socket, no new process - ended session is resumed in place, fork sends removed - reply comes back as a propose_message draft - tests for socket delivery, resume fallback, failure and session list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,133 @@
1
use std::path::Path;
2
3
use serde::Deserialize;
4
5
#[derive(Clone, Debug, PartialEq, Eq)]
6
pub struct DesktopSession {
7
pub session_id: String,
8
pub working_dir: String,
9
pub title: String,
10
pub last_activity_millis: i64,
11
}
12
13
#[derive(Deserialize)]
14
struct DesktopConfig {
15
#[serde(rename = "lastKnownAccountUuid")]
16
account_uuid: Option<String>,
17
}
18
19
#[derive(Deserialize)]
20
struct DesktopSessionFile {
21
#[serde(rename = "cliSessionId")]
22
cli_session_id: Option<String>,
23
cwd: Option<String>,
24
title: Option<String>,
25
#[serde(rename = "isArchived", default)]
26
archived: bool,
27
#[serde(rename = "lastActivityAt", default)]
28
last_activity_millis: i64,
29
}
30
31
fn is_plain_account_uuid(text: &str) -> bool {
32
!text.is_empty()
33
&& text
34
.chars()
35
.all(|character| character.is_ascii_alphanumeric() || character == '-')
36
}
37
38
pub fn desktop_sessions(desktop_dir: &Path) -> Vec<DesktopSession> {
39
let Some(account_uuid) = std::fs::read_to_string(desktop_dir.join("config.json"))
40
.ok()
41
.and_then(|text| serde_json::from_str::<DesktopConfig>(&text).ok())
42
.and_then(|config| config.account_uuid)
43
.filter(|uuid| is_plain_account_uuid(uuid))
44
else {
45
return Vec::new();
46
};
47
let Ok(organizations) =
48
std::fs::read_dir(desktop_dir.join("claude-code-sessions").join(account_uuid))
49
else {
50
return Vec::new();
51
};
52
organizations
53
.flatten()
54
.filter_map(|organization| std::fs::read_dir(organization.path()).ok())
55
.flatten()
56
.flatten()
57
.filter(|entry| {
58
let name = entry.file_name();
59
let name = name.to_string_lossy();
60
name.starts_with("local_") && name.ends_with(".json")
61
})
62
.filter_map(|entry| {
63
let file: DesktopSessionFile =
64
serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;
65
if file.archived {
66
return None;
67
}
68
Some(DesktopSession {
69
session_id: file.cli_session_id.filter(|id| !id.is_empty())?,
70
working_dir: file.cwd.unwrap_or_default(),
71
title: file.title.unwrap_or_default(),
72
last_activity_millis: file.last_activity_millis,
73
})
74
})
75
.collect()
76
}
77
78
#[cfg(test)]
79
mod tests {
80
use super::*;
81
82
fn write(path: &Path, body: &str) {
83
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
84
std::fs::write(path, body).unwrap();
85
}
86
87
#[test]
88
fn only_active_sessions_of_the_signed_in_account_with_a_cli_id_are_listed() {
89
let root = tempfile::tempdir().unwrap();
90
write(
91
&root.path().join("config.json"),
92
r#"{"lastKnownAccountUuid":"acc-1","oauth:tokenCache":"secret"}"#,
93
);
94
let sessions = root.path().join("claude-code-sessions");
95
write(
96
&sessions.join("acc-1/org-1/local_a.json"),
97
r#"{"cliSessionId":"cli-a","cwd":"/srv/app","title":"Fix build","isArchived":false,"lastActivityAt":1700000000000,"wslConfig":{"distro":"Ubuntu"}}"#,
98
);
99
write(
100
&sessions.join("acc-1/org-2/local_b.json"),
101
r#"{"cliSessionId":"cli-b","cwd":"/srv/b","title":"Archived","isArchived":true,"lastActivityAt":1}"#,
102
);
103
write(
104
&sessions.join("acc-1/org-1/local_c.json"),
105
r#"{"cwd":"/srv/c","title":"No cli id","isArchived":false}"#,
106
);
107
write(
108
&sessions.join("acc-2/org-1/local_d.json"),
109
r#"{"cliSessionId":"cli-d","cwd":"/srv/d","title":"Other account","isArchived":false}"#,
110
);
111
write(&sessions.join("acc-1/org-1/notes.json"), "{}");
112
assert_eq!(
113
desktop_sessions(root.path()),
114
[DesktopSession {
115
session_id: "cli-a".to_owned(),
116
working_dir: "/srv/app".to_owned(),
117
title: "Fix build".to_owned(),
118
last_activity_millis: 1_700_000_000_000,
119
}]
120
);
121
}
122
123
#[test]
124
fn a_missing_config_or_an_unsafe_account_id_lists_nothing() {
125
let root = tempfile::tempdir().unwrap();
126
assert!(desktop_sessions(root.path()).is_empty());
127
write(
128
&root.path().join("config.json"),
129
r#"{"lastKnownAccountUuid":"../x"}"#,
130
);
131
assert!(desktop_sessions(root.path()).is_empty());
132
}
133
}
@@ -0,0 +1,133 @@1
use std::path::Path;2
3
use serde::Deserialize;4
5
#[derive(Clone, Debug, PartialEq, Eq)]6
pub struct DesktopSession {7
pub session_id: String,8
pub working_dir: String,9
pub title: String,10
pub last_activity_millis: i64,11
}12
13
#[derive(Deserialize)]14
struct DesktopConfig {15
#[serde(rename = "lastKnownAccountUuid")]16
account_uuid: Option<String>,17
}18
19
#[derive(Deserialize)]20
struct DesktopSessionFile {21
#[serde(rename = "cliSessionId")]22
cli_session_id: Option<String>,23
cwd: Option<String>,24
title: Option<String>,25
#[serde(rename = "isArchived", default)]26
archived: bool,27
#[serde(rename = "lastActivityAt", default)]28
last_activity_millis: i64,29
}30
31
fn is_plain_account_uuid(text: &str) -> bool {32
!text.is_empty()33
&& text34
.chars()35
.all(|character| character.is_ascii_alphanumeric() || character == '-')36
}37
38
pub fn desktop_sessions(desktop_dir: &Path) -> Vec<DesktopSession> {39
let Some(account_uuid) = std::fs::read_to_string(desktop_dir.join("config.json"))40
.ok()41
.and_then(|text| serde_json::from_str::<DesktopConfig>(&text).ok())42
.and_then(|config| config.account_uuid)43
.filter(|uuid| is_plain_account_uuid(uuid))44
else {45
return Vec::new();46
};47
let Ok(organizations) =48
std::fs::read_dir(desktop_dir.join("claude-code-sessions").join(account_uuid))49
else {50
return Vec::new();51
};52
organizations53
.flatten()54
.filter_map(|organization| std::fs::read_dir(organization.path()).ok())55
.flatten()56
.flatten()57
.filter(|entry| {58
let name = entry.file_name();59
let name = name.to_string_lossy();60
name.starts_with("local_") && name.ends_with(".json")61
})62
.filter_map(|entry| {63
let file: DesktopSessionFile =64
serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;65
if file.archived {66
return None;67
}68
Some(DesktopSession {69
session_id: file.cli_session_id.filter(|id| !id.is_empty())?,70
working_dir: file.cwd.unwrap_or_default(),71
title: file.title.unwrap_or_default(),72
last_activity_millis: file.last_activity_millis,73
})74
})75
.collect()76
}77
78
#[cfg(test)]79
mod tests {80
use super::*;81
82
fn write(path: &Path, body: &str) {83
std::fs::create_dir_all(path.parent().unwrap()).unwrap();84
std::fs::write(path, body).unwrap();85
}86
87
#[test]88
fn only_active_sessions_of_the_signed_in_account_with_a_cli_id_are_listed() {89
let root = tempfile::tempdir().unwrap();90
write(91
&root.path().join("config.json"),92
r#"{"lastKnownAccountUuid":"acc-1","oauth:tokenCache":"secret"}"#,93
);94
let sessions = root.path().join("claude-code-sessions");95
write(96
&sessions.join("acc-1/org-1/local_a.json"),97
r#"{"cliSessionId":"cli-a","cwd":"/srv/app","title":"Fix build","isArchived":false,"lastActivityAt":1700000000000,"wslConfig":{"distro":"Ubuntu"}}"#,98
);99
write(100
&sessions.join("acc-1/org-2/local_b.json"),101
r#"{"cliSessionId":"cli-b","cwd":"/srv/b","title":"Archived","isArchived":true,"lastActivityAt":1}"#,102
);103
write(104
&sessions.join("acc-1/org-1/local_c.json"),105
r#"{"cwd":"/srv/c","title":"No cli id","isArchived":false}"#,106
);107
write(108
&sessions.join("acc-2/org-1/local_d.json"),109
r#"{"cliSessionId":"cli-d","cwd":"/srv/d","title":"Other account","isArchived":false}"#,110
);111
write(&sessions.join("acc-1/org-1/notes.json"), "{}");112
assert_eq!(113
desktop_sessions(root.path()),114
[DesktopSession {115
session_id: "cli-a".to_owned(),116
working_dir: "/srv/app".to_owned(),117
title: "Fix build".to_owned(),118
last_activity_millis: 1_700_000_000_000,119
}]120
);121
}122
123
#[test]124
fn a_missing_config_or_an_unsafe_account_id_lists_nothing() {125
let root = tempfile::tempdir().unwrap();126
assert!(desktop_sessions(root.path()).is_empty());127
write(128
&root.path().join("config.json"),129
r#"{"lastKnownAccountUuid":"../x"}"#,130
);131
assert!(desktop_sessions(root.path()).is_empty());132
}133
}@@ -0,0 +1,298 @@
1
use std::fmt;
2
use std::io::Write;
3
use std::path::Path;
4
use std::process::{Command, Stdio};
5
use std::time::Duration;
6
7
use serde::Serialize;
8
9
use crate::profile::Environment;
10
use crate::sessions::RunningSession;
11
12
const SENDER: &str = "rusty-teams";
13
const SOCKET_TIMEOUT: Duration = Duration::from_secs(5);
14
const WSL_PROGRAM: &str = "wsl.exe";
15
const SOCKET_RELAY_SCRIPT: &str = "import socket,sys;s=socket.socket(socket.AF_UNIX);s.settimeout(5);s.connect(sys.argv[1]);s.sendall(sys.stdin.buffer.read());s.close()";
16
#[cfg(windows)]
17
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
18
19
#[derive(Debug, PartialEq, Eq)]
20
pub enum DeliveryError {
21
SessionGone,
22
Failed(String),
23
}
24
25
impl fmt::Display for DeliveryError {
26
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
27
match self {
28
DeliveryError::SessionGone => formatter.write_str("the session is no longer running"),
29
DeliveryError::Failed(message) => formatter.write_str(message),
30
}
31
}
32
}
33
34
impl std::error::Error for DeliveryError {}
35
36
struct PeerToken(String);
37
38
impl fmt::Debug for PeerToken {
39
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
40
formatter.write_str("PeerToken(..)")
41
}
42
}
43
44
#[derive(Serialize)]
45
struct AuthFrame<'a> {
46
#[serde(rename = "type")]
47
kind: &'a str,
48
token: &'a str,
49
}
50
51
#[derive(Serialize)]
52
struct UserFrame<'a> {
53
#[serde(rename = "type")]
54
kind: &'a str,
55
message: UserMessage<'a>,
56
from: &'a str,
57
msg_id: &'a str,
58
}
59
60
#[derive(Serialize)]
61
struct UserMessage<'a> {
62
content: &'a str,
63
}
64
65
pub fn inbox_frame(token: &str, content: &str, message_id: &str) -> String {
66
let auth = AuthFrame {
67
kind: "auth",
68
token,
69
};
70
let user = UserFrame {
71
kind: "user",
72
message: UserMessage { content },
73
from: SENDER,
74
msg_id: message_id,
75
};
76
format!(
77
"{}\n{}\n",
78
serde_json::to_string(&auth).unwrap_or_default(),
79
serde_json::to_string(&user).unwrap_or_default()
80
)
81
}
82
83
fn read_peer_token(sessions_dir: &Path, process_id: u32) -> Option<PeerToken> {
84
let prefix = format!("{process_id}.");
85
std::fs::read_dir(sessions_dir)
86
.ok()?
87
.flatten()
88
.filter(|entry| {
89
let name = entry.file_name();
90
let name = name.to_string_lossy();
91
name.starts_with(&prefix) && name.ends_with(".key")
92
})
93
.find_map(|entry| {
94
let value: serde_json::Value =
95
serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;
96
value["peerToken"]
97
.as_str()
98
.map(|token| PeerToken(token.to_owned()))
99
})
100
}
101
102
pub fn deliver(
103
environment: &Environment,
104
sessions_dir: &Path,
105
session: &RunningSession,
106
content: &str,
107
) -> Result<(), DeliveryError> {
108
let socket_path = session
109
.socket_path
110
.as_deref()
111
.ok_or_else(|| DeliveryError::Failed("the session does not accept messages".to_owned()))?;
112
let token = read_peer_token(sessions_dir, session.process_id).ok_or_else(|| {
113
DeliveryError::Failed("the session's message key is not readable".to_owned())
114
})?;
115
let frame = inbox_frame(&token.0, content, &uuid::Uuid::new_v4().to_string());
116
match environment {
117
Environment::Wsl { distro } => send_through_wsl(distro.as_deref(), socket_path, &frame),
118
Environment::Host => send_on_host(socket_path, &frame),
119
}
120
}
121
122
#[cfg(unix)]
123
fn send_on_host(socket_path: &str, frame: &str) -> Result<(), DeliveryError> {
124
use std::os::unix::net::UnixStream;
125
126
let mut stream = UnixStream::connect(socket_path).map_err(|error| match error.kind() {
127
std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused => {
128
DeliveryError::SessionGone
129
}
130
_ => DeliveryError::Failed(format!("cannot connect to the session: {error}")),
131
})?;
132
let failed = |error: std::io::Error| DeliveryError::Failed(format!("send failed: {error}"));
133
stream
134
.set_write_timeout(Some(SOCKET_TIMEOUT))
135
.map_err(failed)?;
136
stream.write_all(frame.as_bytes()).map_err(failed)
137
}
138
139
#[cfg(not(unix))]
140
fn send_on_host(_socket_path: &str, _frame: &str) -> Result<(), DeliveryError> {
141
Err(DeliveryError::Failed(
142
"delivery to Windows-native sessions is not supported".to_owned(),
143
))
144
}
145
146
fn send_through_wsl(
147
distro: Option<&str>,
148
socket_path: &str,
149
frame: &str,
150
) -> Result<(), DeliveryError> {
151
let mut command = Command::new(WSL_PROGRAM);
152
if let Some(distro) = distro {
153
command.args(["-d", distro]);
154
}
155
command
156
.args(["-e", "python3", "-c", SOCKET_RELAY_SCRIPT, socket_path])
157
.stdin(Stdio::piped())
158
.stdout(Stdio::null())
159
.stderr(Stdio::piped());
160
#[cfg(windows)]
161
{
162
use std::os::windows::process::CommandExt;
163
command.creation_flags(CREATE_NO_WINDOW);
164
}
165
let mut child = command
166
.spawn()
167
.map_err(|error| DeliveryError::Failed(format!("cannot start {WSL_PROGRAM}: {error}")))?;
168
let written = child
169
.stdin
170
.take()
171
.map(|mut stdin| stdin.write_all(frame.as_bytes()));
172
let output = child
173
.wait_with_output()
174
.map_err(|error| DeliveryError::Failed(format!("send failed: {error}")))?;
175
if output.status.success() {
176
return Ok(());
177
}
178
let stderr = String::from_utf8_lossy(&output.stderr);
179
if stderr.contains("ConnectionRefusedError") || stderr.contains("FileNotFoundError") {
180
return Err(DeliveryError::SessionGone);
181
}
182
let detail = stderr.lines().last().unwrap_or_default().trim();
183
let write_note = match written {
184
Some(Err(error)) => format!(" ({error})"),
185
_ => String::new(),
186
};
187
Err(DeliveryError::Failed(format!(
188
"delivery failed: {detail}{write_note}"
189
)))
190
}
191
192
#[cfg(test)]
193
mod tests {
194
use super::*;
195
196
#[test]
197
fn the_frame_is_an_auth_line_then_a_user_line() {
198
assert_eq!(
199
inbox_frame("tok", "Hi \"you\"\nbye", "id-1"),
200
"{\"type\":\"auth\",\"token\":\"tok\"}\n{\"type\":\"user\",\"message\":{\"content\":\"Hi \\\"you\\\"\\nbye\"},\"from\":\"rusty-teams\",\"msg_id\":\"id-1\"}\n"
201
);
202
}
203
204
#[test]
205
fn errors_and_the_token_wrapper_never_show_the_token() {
206
let token = PeerToken("s3cret".to_owned());
207
assert!(!format!("{token:?}").contains("s3cret"));
208
for error in [
209
DeliveryError::SessionGone,
210
DeliveryError::Failed("delivery failed: boom".to_owned()),
211
] {
212
assert!(!format!("{error:?} {error}").contains("s3cret"));
213
}
214
}
215
216
#[test]
217
fn a_session_without_a_socket_cannot_be_delivered_to() {
218
let directory = tempfile::tempdir().unwrap();
219
let session = RunningSession {
220
session_id: "abc".to_owned(),
221
name: None,
222
working_dir: String::new(),
223
socket_path: None,
224
process_id: 1,
225
};
226
assert!(matches!(
227
deliver(&Environment::Host, directory.path(), &session, "hi"),
228
Err(DeliveryError::Failed(_))
229
));
230
}
231
232
#[cfg(unix)]
233
mod unix {
234
use std::io::Read;
235
use std::os::unix::net::UnixListener;
236
237
use super::*;
238
239
fn session(socket_path: &Path, process_id: u32) -> RunningSession {
240
RunningSession {
241
session_id: "abc".to_owned(),
242
name: None,
243
working_dir: String::new(),
244
socket_path: Some(socket_path.to_string_lossy().into_owned()),
245
process_id,
246
}
247
}
248
249
#[test]
250
fn a_host_delivery_writes_both_lines_to_the_socket() {
251
let directory = tempfile::tempdir().unwrap();
252
let socket_path = directory.path().join("s.sock");
253
let listener = UnixListener::bind(&socket_path).unwrap();
254
std::fs::write(
255
directory.path().join("42.ab12.key"),
256
r#"{"peerToken":"tok"}"#,
257
)
258
.unwrap();
259
let reader = std::thread::spawn(move || {
260
let (mut stream, _) = listener.accept().unwrap();
261
let mut received = String::new();
262
stream.read_to_string(&mut received).unwrap();
263
received
264
});
265
deliver(
266
&Environment::Host,
267
directory.path(),
268
&session(&socket_path, 42),
269
"hello",
270
)
271
.unwrap();
272
let received = reader.join().unwrap();
273
let lines: Vec<&str> = received.lines().collect();
274
assert_eq!(lines.len(), 2);
275
assert_eq!(lines[0], r#"{"type":"auth","token":"tok"}"#);
276
assert!(lines[1].starts_with(
277
r#"{"type":"user","message":{"content":"hello"},"from":"rusty-teams","msg_id":""#
278
));
279
}
280
281
#[test]
282
fn a_missing_socket_means_the_session_is_gone() {
283
let directory = tempfile::tempdir().unwrap();
284
std::fs::write(
285
directory.path().join("42.ab12.key"),
286
r#"{"peerToken":"tok"}"#,
287
)
288
.unwrap();
289
let result = deliver(
290
&Environment::Host,
291
directory.path(),
292
&session(&directory.path().join("none.sock"), 42),
293
"hello",
294
);
295
assert_eq!(result, Err(DeliveryError::SessionGone));
296
}
297
}
298
}
@@ -0,0 +1,298 @@1
use std::fmt;2
use std::io::Write;3
use std::path::Path;4
use std::process::{Command, Stdio};5
use std::time::Duration;6
7
use serde::Serialize;8
9
use crate::profile::Environment;10
use crate::sessions::RunningSession;11
12
const SENDER: &str = "rusty-teams";13
const SOCKET_TIMEOUT: Duration = Duration::from_secs(5);14
const WSL_PROGRAM: &str = "wsl.exe";15
const SOCKET_RELAY_SCRIPT: &str = "import socket,sys;s=socket.socket(socket.AF_UNIX);s.settimeout(5);s.connect(sys.argv[1]);s.sendall(sys.stdin.buffer.read());s.close()";16
#[cfg(windows)]17
const CREATE_NO_WINDOW: u32 = 0x0800_0000;18
19
#[derive(Debug, PartialEq, Eq)]20
pub enum DeliveryError {21
SessionGone,22
Failed(String),23
}24
25
impl fmt::Display for DeliveryError {26
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {27
match self {28
DeliveryError::SessionGone => formatter.write_str("the session is no longer running"),29
DeliveryError::Failed(message) => formatter.write_str(message),30
}31
}32
}33
34
impl std::error::Error for DeliveryError {}35
36
struct PeerToken(String);37
38
impl fmt::Debug for PeerToken {39
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {40
formatter.write_str("PeerToken(..)")41
}42
}43
44
#[derive(Serialize)]45
struct AuthFrame<'a> {46
#[serde(rename = "type")]47
kind: &'a str,48
token: &'a str,49
}50
51
#[derive(Serialize)]52
struct UserFrame<'a> {53
#[serde(rename = "type")]54
kind: &'a str,55
message: UserMessage<'a>,56
from: &'a str,57
msg_id: &'a str,58
}59
60
#[derive(Serialize)]61
struct UserMessage<'a> {62
content: &'a str,63
}64
65
pub fn inbox_frame(token: &str, content: &str, message_id: &str) -> String {66
let auth = AuthFrame {67
kind: "auth",68
token,69
};70
let user = UserFrame {71
kind: "user",72
message: UserMessage { content },73
from: SENDER,74
msg_id: message_id,75
};76
format!(77
"{}\n{}\n",78
serde_json::to_string(&auth).unwrap_or_default(),79
serde_json::to_string(&user).unwrap_or_default()80
)81
}82
83
fn read_peer_token(sessions_dir: &Path, process_id: u32) -> Option<PeerToken> {84
let prefix = format!("{process_id}.");85
std::fs::read_dir(sessions_dir)86
.ok()?87
.flatten()88
.filter(|entry| {89
let name = entry.file_name();90
let name = name.to_string_lossy();91
name.starts_with(&prefix) && name.ends_with(".key")92
})93
.find_map(|entry| {94
let value: serde_json::Value =95
serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;96
value["peerToken"]97
.as_str()98
.map(|token| PeerToken(token.to_owned()))99
})100
}101
102
pub fn deliver(103
environment: &Environment,104
sessions_dir: &Path,105
session: &RunningSession,106
content: &str,107
) -> Result<(), DeliveryError> {108
let socket_path = session109
.socket_path110
.as_deref()111
.ok_or_else(|| DeliveryError::Failed("the session does not accept messages".to_owned()))?;112
let token = read_peer_token(sessions_dir, session.process_id).ok_or_else(|| {113
DeliveryError::Failed("the session's message key is not readable".to_owned())114
})?;115
let frame = inbox_frame(&token.0, content, &uuid::Uuid::new_v4().to_string());116
match environment {117
Environment::Wsl { distro } => send_through_wsl(distro.as_deref(), socket_path, &frame),118
Environment::Host => send_on_host(socket_path, &frame),119
}120
}121
122
#[cfg(unix)]123
fn send_on_host(socket_path: &str, frame: &str) -> Result<(), DeliveryError> {124
use std::os::unix::net::UnixStream;125
126
let mut stream = UnixStream::connect(socket_path).map_err(|error| match error.kind() {127
std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused => {128
DeliveryError::SessionGone129
}130
_ => DeliveryError::Failed(format!("cannot connect to the session: {error}")),131
})?;132
let failed = |error: std::io::Error| DeliveryError::Failed(format!("send failed: {error}"));133
stream134
.set_write_timeout(Some(SOCKET_TIMEOUT))135
.map_err(failed)?;136
stream.write_all(frame.as_bytes()).map_err(failed)137
}138
139
#[cfg(not(unix))]140
fn send_on_host(_socket_path: &str, _frame: &str) -> Result<(), DeliveryError> {141
Err(DeliveryError::Failed(142
"delivery to Windows-native sessions is not supported".to_owned(),143
))144
}145
146
fn send_through_wsl(147
distro: Option<&str>,148
socket_path: &str,149
frame: &str,150
) -> Result<(), DeliveryError> {151
let mut command = Command::new(WSL_PROGRAM);152
if let Some(distro) = distro {153
command.args(["-d", distro]);154
}155
command156
.args(["-e", "python3", "-c", SOCKET_RELAY_SCRIPT, socket_path])157
.stdin(Stdio::piped())158
.stdout(Stdio::null())159
.stderr(Stdio::piped());160
#[cfg(windows)]161
{162
use std::os::windows::process::CommandExt;163
command.creation_flags(CREATE_NO_WINDOW);164
}165
let mut child = command166
.spawn()167
.map_err(|error| DeliveryError::Failed(format!("cannot start {WSL_PROGRAM}: {error}")))?;168
let written = child169
.stdin170
.take()171
.map(|mut stdin| stdin.write_all(frame.as_bytes()));172
let output = child173
.wait_with_output()174
.map_err(|error| DeliveryError::Failed(format!("send failed: {error}")))?;175
if output.status.success() {176
return Ok(());177
}178
let stderr = String::from_utf8_lossy(&output.stderr);179
if stderr.contains("ConnectionRefusedError") || stderr.contains("FileNotFoundError") {180
return Err(DeliveryError::SessionGone);181
}182
let detail = stderr.lines().last().unwrap_or_default().trim();183
let write_note = match written {184
Some(Err(error)) => format!(" ({error})"),185
_ => String::new(),186
};187
Err(DeliveryError::Failed(format!(188
"delivery failed: {detail}{write_note}"189
)))190
}191
192
#[cfg(test)]193
mod tests {194
use super::*;195
196
#[test]197
fn the_frame_is_an_auth_line_then_a_user_line() {198
assert_eq!(199
inbox_frame("tok", "Hi \"you\"\nbye", "id-1"),200
"{\"type\":\"auth\",\"token\":\"tok\"}\n{\"type\":\"user\",\"message\":{\"content\":\"Hi \\\"you\\\"\\nbye\"},\"from\":\"rusty-teams\",\"msg_id\":\"id-1\"}\n"201
);202
}203
204
#[test]205
fn errors_and_the_token_wrapper_never_show_the_token() {206
let token = PeerToken("s3cret".to_owned());207
assert!(!format!("{token:?}").contains("s3cret"));208
for error in [209
DeliveryError::SessionGone,210
DeliveryError::Failed("delivery failed: boom".to_owned()),211
] {212
assert!(!format!("{error:?} {error}").contains("s3cret"));213
}214
}215
216
#[test]217
fn a_session_without_a_socket_cannot_be_delivered_to() {218
let directory = tempfile::tempdir().unwrap();219
let session = RunningSession {220
session_id: "abc".to_owned(),221
name: None,222
working_dir: String::new(),223
socket_path: None,224
process_id: 1,225
};226
assert!(matches!(227
deliver(&Environment::Host, directory.path(), &session, "hi"),228
Err(DeliveryError::Failed(_))229
));230
}231
232
#[cfg(unix)]233
mod unix {234
use std::io::Read;235
use std::os::unix::net::UnixListener;236
237
use super::*;238
239
fn session(socket_path: &Path, process_id: u32) -> RunningSession {240
RunningSession {241
session_id: "abc".to_owned(),242
name: None,243
working_dir: String::new(),244
socket_path: Some(socket_path.to_string_lossy().into_owned()),245
process_id,246
}247
}248
249
#[test]250
fn a_host_delivery_writes_both_lines_to_the_socket() {251
let directory = tempfile::tempdir().unwrap();252
let socket_path = directory.path().join("s.sock");253
let listener = UnixListener::bind(&socket_path).unwrap();254
std::fs::write(255
directory.path().join("42.ab12.key"),256
r#"{"peerToken":"tok"}"#,257
)258
.unwrap();259
let reader = std::thread::spawn(move || {260
let (mut stream, _) = listener.accept().unwrap();261
let mut received = String::new();262
stream.read_to_string(&mut received).unwrap();263
received264
});265
deliver(266
&Environment::Host,267
directory.path(),268
&session(&socket_path, 42),269
"hello",270
)271
.unwrap();272
let received = reader.join().unwrap();273
let lines: Vec<&str> = received.lines().collect();274
assert_eq!(lines.len(), 2);275
assert_eq!(lines[0], r#"{"type":"auth","token":"tok"}"#);276
assert!(lines[1].starts_with(277
r#"{"type":"user","message":{"content":"hello"},"from":"rusty-teams","msg_id":""#278
));279
}280
281
#[test]282
fn a_missing_socket_means_the_session_is_gone() {283
let directory = tempfile::tempdir().unwrap();284
std::fs::write(285
directory.path().join("42.ab12.key"),286
r#"{"peerToken":"tok"}"#,287
)288
.unwrap();289
let result = deliver(290
&Environment::Host,291
directory.path(),292
&session(&directory.path().join("none.sock"), 42),293
"hello",294
);295
assert_eq!(result, Err(DeliveryError::SessionGone));296
}297
}298
}@@ -309,29 +309,6 @@ pub fn resume_invocation(
309
309
)
310
310
}
311
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
312
fn resume_with_flag(
336
313
profile: &AgentProfile,
337
314
action: &AgentAction,
@@ -770,46 +747,6 @@ mod tests {
770
747
assert_eq!(plan.stop, None);
771
748
}
772
749
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
750
#[test]
814
751
fn resume_rejects_a_session_id_that_is_not_plain() {
815
752
let action = AgentAction::answer_this("claude");
@@ -309,29 +309,6 @@ pub fn resume_invocation(309
)309
)310
}310
}311
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(312
fn resume_with_flag(336
profile: &AgentProfile,313
profile: &AgentProfile,337
action: &AgentAction,314
action: &AgentAction,@@ -770,46 +747,6 @@ mod tests {770
assert_eq!(plan.stop, None);747
assert_eq!(plan.stop, None);771
}748
}772
749
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]750
#[test]814
fn resume_rejects_a_session_id_that_is_not_plain() {751
fn resume_rejects_a_session_id_that_is_not_plain() {815
let action = AgentAction::answer_this("claude");752
let action = AgentAction::answer_this("claude");@@ -1,5 +1,7 @@
1
1
mod action;
2
2
mod context;
3
mod desktop_sessions;
4
mod inbox;
3
5
mod invocation;
4
6
mod parse;
5
7
mod profile;
@@ -10,10 +12,12 @@ mod template;
10
12
11
13
pub use action::AgentAction;
12
14
pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};
15
pub use desktop_sessions::{DesktopSession, desktop_sessions};
16
pub use inbox::{DeliveryError, deliver, inbox_frame};
13
17
pub use invocation::{
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,
18
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, kill_process_invocation,
19
linux_path, open_session_invocation, resume_invocation, supports_resume,
20
version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,
17
21
};
18
22
pub use parse::{OutputParser, RunEvent, parse_line};
19
23
pub use profile::{AgentProfile, Environment, OutputFormat};
@@ -21,8 +25,8 @@ pub use runner::{
21
25
RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,
22
26
};
23
27
pub use sessions::{
24
ExternalSession, encode_project_dir, live_session_names, resolve_project_dir,
25
scan_external_sessions,
28
ExternalSession, RunningSession, encode_project_dir, live_session_names, resolve_project_dir,
29
running_sessions, scan_external_sessions,
26
30
};
27
31
pub use settings::{AgentSettings, RECENT_WORKING_DIR_LIMIT, SETTINGS_KEY, SettingsProblem};
28
32
pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};
@@ -1,5 +1,7 @@1
mod action;1
mod action;2
mod context;2
mod context;3
mod desktop_sessions;4
mod inbox;3
mod invocation;5
mod invocation;4
mod parse;6
mod parse;5
mod profile;7
mod profile;@@ -10,10 +12,12 @@ mod template;10
12
11
pub use action::AgentAction;13
pub use action::AgentAction;12
pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};14
pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};15
pub use desktop_sessions::{DesktopSession, desktop_sessions};16
pub use inbox::{DeliveryError, deliver, inbox_frame};13
pub use invocation::{17
pub use invocation::{14
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, fork_invocation,18
Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, kill_process_invocation,15
kill_process_invocation, linux_path, open_session_invocation, resume_invocation,19
linux_path, open_session_invocation, resume_invocation, supports_resume,16
supports_resume, version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,20
version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,17
};21
};18
pub use parse::{OutputParser, RunEvent, parse_line};22
pub use parse::{OutputParser, RunEvent, parse_line};19
pub use profile::{AgentProfile, Environment, OutputFormat};23
pub use profile::{AgentProfile, Environment, OutputFormat};@@ -21,8 +25,8 @@ pub use runner::{21
RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,25
RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,22
};26
};23
pub use sessions::{27
pub use sessions::{24
ExternalSession, encode_project_dir, live_session_names, resolve_project_dir,28
ExternalSession, RunningSession, encode_project_dir, live_session_names, resolve_project_dir,25
scan_external_sessions,29
running_sessions, scan_external_sessions,26
};30
};27
pub use settings::{AgentSettings, RECENT_WORKING_DIR_LIMIT, SETTINGS_KEY, SettingsProblem};31
pub use settings::{AgentSettings, RECENT_WORKING_DIR_LIMIT, SETTINGS_KEY, SettingsProblem};28
pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};32
pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};@@ -4,6 +4,8 @@ use std::io::{BufRead, BufReader, Read};
4
4
use std::path::{Path, PathBuf};
5
5
use std::time::SystemTime;
6
6
7
use serde::{Deserialize, Serialize};
8
7
9
const TITLE_READ_LIMIT: u64 = 1024 * 1024;
8
10
const PROJECT_DIR_NAME_LIMIT: usize = 200;
9
11
@@ -64,16 +66,29 @@ fn proc_root(sessions_dir: &Path) -> Option<PathBuf> {
64
66
}
65
67
}
66
68
69
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
70
pub struct RunningSession {
71
pub session_id: String,
72
pub name: Option<String>,
73
pub working_dir: String,
74
pub socket_path: Option<String>,
75
pub process_id: u32,
76
}
77
78
pub fn running_sessions(sessions_dir: &Path) -> Vec<RunningSession> {
79
running_sessions_in(sessions_dir, proc_root(sessions_dir).as_deref())
80
}
81
67
82
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())
83
running_sessions(sessions_dir)
84
.into_iter()
85
.map(|session| (session.session_id, session.name))
86
.collect()
69
87
}
70
88
71
fn live_session_names_in(
72
sessions_dir: &Path,
73
proc_root: Option<&Path>,
74
) -> HashMap<String, Option<String>> {
89
fn running_sessions_in(sessions_dir: &Path, proc_root: Option<&Path>) -> Vec<RunningSession> {
75
90
let Ok(entries) = std::fs::read_dir(sessions_dir) else {
76
return HashMap::new();
91
return Vec::new();
77
92
};
78
93
let checkable_root = proc_root.filter(|root| root.is_dir());
79
94
entries
@@ -88,13 +103,30 @@ fn live_session_names_in(
88
103
.filter_map(|entry| {
89
104
let value: serde_json::Value =
90
105
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))
106
let text = |key: &str| {
107
value[key]
108
.as_str()
109
.map(str::trim)
110
.filter(|text| !text.is_empty())
111
.map(str::to_owned)
112
};
113
let process_id = entry
114
.path()
115
.file_stem()
116
.and_then(|stem| stem.to_str())
117
.and_then(|stem| stem.parse().ok())
118
.or_else(|| {
119
value["pid"]
120
.as_u64()
121
.and_then(|pid| u32::try_from(pid).ok())
122
})?;
123
Some(RunningSession {
124
session_id: value["sessionId"].as_str()?.to_owned(),
125
name: text("name"),
126
working_dir: text("cwd").unwrap_or_default(),
127
socket_path: text("messagingSocketPath"),
128
process_id,
129
})
98
130
})
99
131
.collect()
100
132
}
@@ -465,6 +497,40 @@ mod tests {
465
497
assert_eq!(sessions[9].session_id, id(9));
466
498
}
467
499
500
fn names(sessions: Vec<RunningSession>) -> HashMap<String, Option<String>> {
501
sessions
502
.into_iter()
503
.map(|session| (session.session_id, session.name))
504
.collect()
505
}
506
507
#[test]
508
fn running_sessions_carry_their_socket_directory_and_process_id() {
509
let sessions_dir = tempfile::tempdir().unwrap();
510
let proc_root = tempfile::tempdir().unwrap();
511
std::fs::create_dir(proc_root.path().join("205357")).unwrap();
512
std::fs::write(
513
sessions_dir.path().join("205357.json"),
514
r#"{"pid":205357,"sessionId":"abc","name":" Review ","cwd":"/srv/app","status":"busy","messagingSocketPath":"/run/user/1000/cc-socks/205357.sock"}"#,
515
)
516
.unwrap();
517
std::fs::write(
518
sessions_dir.path().join("999.json"),
519
r#"{"pid":999,"sessionId":"dead","cwd":"/srv/gone"}"#,
520
)
521
.unwrap();
522
assert_eq!(
523
running_sessions_in(sessions_dir.path(), Some(proc_root.path())),
524
[RunningSession {
525
session_id: "abc".to_owned(),
526
name: Some("Review".to_owned()),
527
working_dir: "/srv/app".to_owned(),
528
socket_path: Some("/run/user/1000/cc-socks/205357.sock".to_owned()),
529
process_id: 205357,
530
}]
531
);
532
}
533
468
534
#[test]
469
535
fn live_sessions_need_a_running_pid_and_use_their_name_as_title() {
470
536
let sessions_dir = tempfile::tempdir().unwrap();
@@ -482,11 +548,14 @@ mod tests {
482
548
file(222, &id(2), "");
483
549
file(333, &id(3), "Dead one");
484
550
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()));
551
let live = names(running_sessions_in(
552
sessions_dir.path(),
553
Some(proc_root.path()),
554
));
486
555
assert_eq!(live.len(), 2);
487
556
assert!(!live.contains_key(&id(3)));
488
557
assert_eq!(
489
live_session_names_in(sessions_dir.path(), Some(Path::new("/nonexistent"))).len(),
558
running_sessions_in(sessions_dir.path(), Some(Path::new("/nonexistent"))).len(),
490
559
3
491
560
);
492
561
let directory = tempfile::tempdir().unwrap();
@@ -4,6 +4,8 @@ use std::io::{BufRead, BufReader, Read};4
use std::path::{Path, PathBuf};4
use std::path::{Path, PathBuf};5
use std::time::SystemTime;5
use std::time::SystemTime;6
6
7
use serde::{Deserialize, Serialize};8
7
const TITLE_READ_LIMIT: u64 = 1024 * 1024;9
const TITLE_READ_LIMIT: u64 = 1024 * 1024;8
const PROJECT_DIR_NAME_LIMIT: usize = 200;10
const PROJECT_DIR_NAME_LIMIT: usize = 200;9
11
@@ -64,16 +66,29 @@ fn proc_root(sessions_dir: &Path) -> Option<PathBuf> {64
}66
}65
}67
}66
68
69
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]70
pub struct RunningSession {71
pub session_id: String,72
pub name: Option<String>,73
pub working_dir: String,74
pub socket_path: Option<String>,75
pub process_id: u32,76
}77
78
pub fn running_sessions(sessions_dir: &Path) -> Vec<RunningSession> {79
running_sessions_in(sessions_dir, proc_root(sessions_dir).as_deref())80
}81
67
pub fn live_session_names(sessions_dir: &Path) -> HashMap<String, Option<String>> {82
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())83
running_sessions(sessions_dir)84
.into_iter()85
.map(|session| (session.session_id, session.name))86
.collect()69
}87
}70
88
71
fn live_session_names_in(89
fn running_sessions_in(sessions_dir: &Path, proc_root: Option<&Path>) -> Vec<RunningSession> {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 {90
let Ok(entries) = std::fs::read_dir(sessions_dir) else {76
return HashMap::new();91
return Vec::new();77
};92
};78
let checkable_root = proc_root.filter(|root| root.is_dir());93
let checkable_root = proc_root.filter(|root| root.is_dir());79
entries94
entries@@ -88,13 +103,30 @@ fn live_session_names_in(88
.filter_map(|entry| {103
.filter_map(|entry| {89
let value: serde_json::Value =104
let value: serde_json::Value =90
serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;105
serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;91
let session_id = value["sessionId"].as_str()?.to_owned();106
let text = |key: &str| {92
let name = value["name"]107
value[key]93
.as_str()108
.as_str()94
.map(str::trim)109
.map(str::trim)95
.filter(|name| !name.is_empty())110
.filter(|text| !text.is_empty())96
.map(str::to_owned);111
.map(str::to_owned)97
Some((session_id, name))112
};113
let process_id = entry114
.path()115
.file_stem()116
.and_then(|stem| stem.to_str())117
.and_then(|stem| stem.parse().ok())118
.or_else(|| {119
value["pid"]120
.as_u64()121
.and_then(|pid| u32::try_from(pid).ok())122
})?;123
Some(RunningSession {124
session_id: value["sessionId"].as_str()?.to_owned(),125
name: text("name"),126
working_dir: text("cwd").unwrap_or_default(),127
socket_path: text("messagingSocketPath"),128
process_id,129
})98
})130
})99
.collect()131
.collect()100
}132
}@@ -465,6 +497,40 @@ mod tests {465
assert_eq!(sessions[9].session_id, id(9));497
assert_eq!(sessions[9].session_id, id(9));466
}498
}467
499
500
fn names(sessions: Vec<RunningSession>) -> HashMap<String, Option<String>> {501
sessions502
.into_iter()503
.map(|session| (session.session_id, session.name))504
.collect()505
}506
507
#[test]508
fn running_sessions_carry_their_socket_directory_and_process_id() {509
let sessions_dir = tempfile::tempdir().unwrap();510
let proc_root = tempfile::tempdir().unwrap();511
std::fs::create_dir(proc_root.path().join("205357")).unwrap();512
std::fs::write(513
sessions_dir.path().join("205357.json"),514
r#"{"pid":205357,"sessionId":"abc","name":" Review ","cwd":"/srv/app","status":"busy","messagingSocketPath":"/run/user/1000/cc-socks/205357.sock"}"#,515
)516
.unwrap();517
std::fs::write(518
sessions_dir.path().join("999.json"),519
r#"{"pid":999,"sessionId":"dead","cwd":"/srv/gone"}"#,520
)521
.unwrap();522
assert_eq!(523
running_sessions_in(sessions_dir.path(), Some(proc_root.path())),524
[RunningSession {525
session_id: "abc".to_owned(),526
name: Some("Review".to_owned()),527
working_dir: "/srv/app".to_owned(),528
socket_path: Some("/run/user/1000/cc-socks/205357.sock".to_owned()),529
process_id: 205357,530
}]531
);532
}533
468
#[test]534
#[test]469
fn live_sessions_need_a_running_pid_and_use_their_name_as_title() {535
fn live_sessions_need_a_running_pid_and_use_their_name_as_title() {470
let sessions_dir = tempfile::tempdir().unwrap();536
let sessions_dir = tempfile::tempdir().unwrap();@@ -482,11 +548,14 @@ mod tests {482
file(222, &id(2), "");548
file(222, &id(2), "");483
file(333, &id(3), "Dead one");549
file(333, &id(3), "Dead one");484
std::fs::write(sessions_dir.path().join("444.json"), "garbage").unwrap();550
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()));551
let live = names(running_sessions_in(552
sessions_dir.path(),553
Some(proc_root.path()),554
));486
assert_eq!(live.len(), 2);555
assert_eq!(live.len(), 2);487
assert!(!live.contains_key(&id(3)));556
assert!(!live.contains_key(&id(3)));488
assert_eq!(557
assert_eq!(489
live_session_names_in(sessions_dir.path(), Some(Path::new("/nonexistent"))).len(),558
running_sessions_in(sessions_dir.path(), Some(Path::new("/nonexistent"))).len(),490
3559
3491
);560
);492
let directory = tempfile::tempdir().unwrap();561
let directory = tempfile::tempdir().unwrap();@@ -1,9 +1,10 @@
1
1
use std::collections::{HashMap, HashSet, VecDeque};
2
use std::path::PathBuf;
2
3
use std::time::{Duration, Instant};
3
4
4
5
use agents::{
5
6
AgentAction, AgentProfile, AgentSettings, McpEndpoint, RunEvent, RunOutcome, RunStatus,
6
RunUpdate,
7
RunUpdate, RunningSession,
7
8
};
8
9
use chrono::{DateTime, Utc};
9
10
use gpui_kit::*;
@@ -29,6 +30,8 @@ const PROGRESS_PERSIST_INTERVAL: Duration = Duration::from_secs(5);
29
30
const RESUME_PARALLEL_LIMIT: usize = 3;
30
31
const QUEUED_STEP: &str = "Queued";
31
32
const OPENED_NOTICE: &str = "Session opened in a terminal - send cancelled";
33
const DELIVERED_TEXT: &str = "The reply arrives as a Teams draft.";
34
const RESUMING_STEP: &str = "Session ended - resuming it";
32
35
const RESUMED_STEP: &str = "Resumed after restart";
33
36
const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";
34
37
@@ -197,7 +200,14 @@ fn first_line(text: &str) -> &str {
197
200
pub struct SessionTarget {
198
201
pub session_id: String,
199
202
pub working_dir: String,
200
pub fork: bool,
203
#[serde(default)]
204
pub inbox: Option<InboxTarget>,
205
}
206
207
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
208
pub struct InboxTarget {
209
pub session: RunningSession,
210
pub sessions_dir: PathBuf,
201
211
}
202
212
203
213
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -225,15 +235,6 @@ fn plan_for(
225
235
endpoint,
226
236
directory.as_deref(),
227
237
),
228
Some(target) if target.fork => agents::fork_invocation(
229
profile,
230
action,
231
prompt,
232
&target.session_id,
233
session_id,
234
endpoint,
235
directory.as_deref(),
236
),
237
238
Some(_) => agents::resume_invocation(
238
239
profile,
239
240
action,
@@ -598,11 +599,7 @@ impl AgentRuns {
598
599
}
599
600
let (session_id, prompt) = match &options.session {
600
601
Some(target) => {
601
let session_id = if target.fork {
602
agents::new_session_id()
603
} else {
604
target.session_id.clone()
605
};
602
let session_id = target.session_id.clone();
606
603
let prompt =
607
604
agents::build_session_prompt(&context, extra, &session_id, &profile.id);
608
605
(session_id, prompt)
@@ -614,6 +611,10 @@ impl AgentRuns {
614
611
(session_id, prompt)
615
612
}
616
613
};
614
let inbox = options
615
.session
616
.as_ref()
617
.and_then(|target| target.inbox.clone());
617
618
let run_id = self.next_id;
618
619
self.next_id += 1;
619
620
self.runs.push(AgentRun {
@@ -638,7 +639,7 @@ impl AgentRuns {
638
639
expanded: false,
639
640
dismissed: false,
640
641
process_id: None,
641
pending_prompt: Some(prompt),
642
pending_prompt: inbox.is_none().then(|| prompt.clone()),
642
643
sent_to: options.session.clone(),
643
644
launch_session_id: None,
644
645
launched: false,
@@ -648,7 +649,10 @@ impl AgentRuns {
648
649
{
649
650
run.push_step("MCP server is off - no reply proposal possible".to_owned());
650
651
}
651
self.dispatch(run_id, cx);
652
match inbox {
653
Some(inbox) => self.deliver(run_id, inbox, profile.environment.clone(), prompt, cx),
654
None => self.dispatch(run_id, cx),
655
}
652
656
if let Some(working_dir) = chosen_working_dir {
653
657
self.update_settings(
654
658
|settings| settings.remember_working_dir(&profile.id, &working_dir),
@@ -661,6 +665,77 @@ impl AgentRuns {
661
665
Ok(run_id)
662
666
}
663
667
668
fn deliver(
669
&mut self,
670
run_id: u64,
671
inbox: InboxTarget,
672
environment: agents::Environment,
673
prompt: String,
674
cx: &mut Context<Self>,
675
) {
676
let session_name = inbox
677
.session
678
.name
679
.clone()
680
.unwrap_or_else(|| inbox.session.session_id.clone());
681
cx.spawn(async move |this, cx| {
682
let fallback_prompt = prompt.clone();
683
let result = cx
684
.background_executor()
685
.spawn(async move {
686
agents::deliver(&environment, &inbox.sessions_dir, &inbox.session, &prompt)
687
})
688
.await;
689
this.update(cx, |runs, cx| {
690
runs.finish_delivery(run_id, &session_name, fallback_prompt, result, cx)
691
})
692
.ok();
693
})
694
.detach();
695
}
696
697
fn finish_delivery(
698
&mut self,
699
run_id: u64,
700
session_name: &str,
701
prompt: String,
702
result: Result<(), agents::DeliveryError>,
703
cx: &mut Context<Self>,
704
) {
705
let status = match result {
706
Ok(()) => RunStatus::Completed {
707
final_text: DELIVERED_TEXT.to_owned(),
708
},
709
Err(agents::DeliveryError::SessionGone) => {
710
if let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) {
711
run.pending_prompt = Some(prompt);
712
run.push_step(RESUMING_STEP.to_owned());
713
self.dispatch(run_id, cx);
714
self.persist(cx);
715
cx.notify();
716
}
717
return;
718
}
719
Err(error) => RunStatus::Failed {
720
message: error.to_string(),
721
stderr_tail: Vec::new(),
722
},
723
};
724
let delivered = matches!(status, RunStatus::Completed { .. });
725
self.finish(
726
run_id,
727
Some(RunOutcome {
728
status,
729
exit_code: None,
730
}),
731
cx,
732
);
733
if delivered && let Some(run) = self.run_mut(run_id) {
734
run.current_step = format!("Delivered to {session_name}");
735
self.persist(cx);
736
}
737
}
738
664
739
fn dispatch(&mut self, run_id: u64, cx: &mut Context<Self>) {
665
740
let Some(session_id) = self.get(run_id).map(|run| run.session_id.clone()) else {
666
741
return;
@@ -894,7 +969,7 @@ impl AgentRuns {
894
969
for run_id in self.lanes.rename(from, to) {
895
970
if let Some(run) = self.run_mut(run_id) {
896
971
run.session_id = to.to_owned();
897
if let Some(target) = run.sent_to.as_mut().filter(|target| !target.fork) {
972
if let Some(target) = run.sent_to.as_mut() {
898
973
target.session_id = to.to_owned();
899
974
}
900
975
}
@@ -1098,11 +1173,7 @@ impl AgentRuns {
1098
1173
working_dir: run.sent_to.is_none().then(|| run.working_dir.clone()),
1099
1174
remember_working_dir: false,
1100
1175
session: run.sent_to.clone().map(|target| SessionTarget {
1101
session_id: if target.fork {
1102
target.session_id
1103
} else {
1104
run.session_id.clone()
1105
},
1176
session_id: run.session_id.clone(),
1106
1177
..target
1107
1178
}),
1108
1179
};
@@ -1236,6 +1307,7 @@ pub(super) mod tests {
1236
1307
1237
1308
use gpui_kit::AppContext as _;
1238
1309
1310
use super::super::InboxTarget;
1239
1311
use super::{
1240
1312
AgentRun, AgentRuns, Entity, RunState, SessionTarget, StartOptions, TestAppContext,
1241
1313
run_store, setup, wait_until_finished,
@@ -1250,7 +1322,7 @@ pub(super) mod tests {
1250
1322
session: Some(SessionTarget {
1251
1323
session_id,
1252
1324
working_dir: std::env::temp_dir().to_string_lossy().into_owned(),
1253
fork: false,
1325
inbox: None,
1254
1326
}),
1255
1327
}
1256
1328
}
@@ -1547,38 +1619,117 @@ pub(super) mod tests {
1547
1619
assert_eq!(run.sent_to, None);
1548
1620
}
1549
1621
1622
fn inbox_options(
1623
socket_path: &std::path::Path,
1624
sessions_dir: &std::path::Path,
1625
) -> StartOptions {
1626
let mut options = target_of("live-session".to_owned());
1627
options.session.as_mut().unwrap().inbox = Some(InboxTarget {
1628
session: agents::RunningSession {
1629
session_id: "live-session".to_owned(),
1630
name: Some("Review".to_owned()),
1631
working_dir: "/srv".to_owned(),
1632
socket_path: Some(socket_path.to_string_lossy().into_owned()),
1633
process_id: 42,
1634
},
1635
sessions_dir: sessions_dir.to_path_buf(),
1636
});
1637
options
1638
}
1639
1550
1640
#[gpui_kit::test]
1551
fn a_forked_send_gets_a_fresh_session_id_and_adopts_a_reported_one(
1552
cx: &mut TestAppContext,
1553
) {
1554
let (app, runs) = setup(cx, SESSION_COMMAND);
1555
let forked = cx.update(|cx| {
1641
fn a_message_to_a_running_session_is_delivered_without_a_process(cx: &mut TestAppContext) {
1642
let (_, runs) = setup(cx, SESSION_COMMAND);
1643
let directory = tempfile::tempdir().unwrap();
1644
let socket_path = directory.path().join("s.sock");
1645
let listener = std::os::unix::net::UnixListener::bind(&socket_path).unwrap();
1646
std::fs::write(directory.path().join("42.ab.key"), r#"{"peerToken":"tok"}"#).unwrap();
1647
let reader = std::thread::spawn(move || {
1648
let (mut stream, _) = listener.accept().unwrap();
1649
let mut received = String::new();
1650
std::io::Read::read_to_string(&mut stream, &mut received).unwrap();
1651
received
1652
});
1653
let delivered = cx.update(|cx| {
1556
1654
runs.update(cx, |runs, cx| {
1557
let mut options = target_of("live-session".to_owned());
1558
options.session.as_mut().unwrap().fork = true;
1559
runs.start_with("ask", "19:chat", "m1", "hi", options, cx)
1560
.unwrap()
1655
runs.start_with(
1656
"ask",
1657
"19:chat",
1658
"m1",
1659
"hi",
1660
inbox_options(&socket_path, directory.path()),
1661
cx,
1662
)
1663
.unwrap()
1561
1664
})
1562
1665
});
1666
wait_until_finished(cx, &runs, delivered);
1563
1667
cx.update(|cx| {
1564
let run = runs.read(cx).get(forked).unwrap().clone();
1565
assert_ne!(run.session_id, "live-session");
1566
assert!(run.sent_to.as_ref().unwrap().fork);
1567
assert!(!run.is_queued());
1668
let run = runs.read(cx).get(delivered).unwrap();
1669
assert_eq!(run.state, RunState::Done);
1670
assert_eq!(run.current_step, "Delivered to Review");
1671
assert_eq!(run.session_id, "live-session");
1672
assert_eq!(run.process_id, None);
1673
assert!(run.final_text.contains("Teams draft"));
1674
});
1675
let received = reader.join().unwrap();
1676
assert!(received.contains("live-session"));
1677
assert!(received.contains("propose_message"));
1678
assert!(received.contains("19:chat"));
1679
assert!(received.starts_with(r#"{"type":"auth","token":"tok"}"#));
1680
}
1681
1682
#[gpui_kit::test]
1683
fn a_session_that_ended_before_delivery_is_resumed_in_place(cx: &mut TestAppContext) {
1684
let (_, runs) = setup(cx, SESSION_COMMAND);
1685
let directory = tempfile::tempdir().unwrap();
1686
std::fs::write(directory.path().join("42.ab.key"), r#"{"peerToken":"tok"}"#).unwrap();
1687
let resumed = cx.update(|cx| {
1568
1688
runs.update(cx, |runs, cx| {
1569
runs.apply_update(
1570
forked,
1571
agents::RunUpdate::Event(agents::RunEvent::SessionId(
1572
"reported".to_owned(),
1573
)),
1689
runs.start_with(
1690
"ask",
1691
"19:chat",
1692
"m1",
1693
"hi",
1694
inbox_options(&directory.path().join("gone.sock"), directory.path()),
1574
1695
cx,
1575
1696
)
1576
});
1577
assert_eq!(runs.read(cx).get(forked).unwrap().session_id, "reported");
1578
let stored = run_store::load_runs(&app.read(cx).store);
1579
assert_eq!(stored[0].session_id, "reported");
1697
.unwrap()
1698
})
1699
});
1700
wait_until_finished(cx, &runs, resumed);
1701
cx.update(|cx| {
1702
let run = runs.read(cx).get(resumed).unwrap();
1703
assert!(run.steps.iter().any(|(_, step)| step.contains("resuming")));
1704
assert!(run.launched);
1705
assert_eq!(run.session_id, "live-session");
1706
});
1707
}
1708
1709
#[gpui_kit::test]
1710
fn a_delivery_failure_marks_the_run_failed_without_the_token(cx: &mut TestAppContext) {
1711
let (_, runs) = setup(cx, SESSION_COMMAND);
1712
let directory = tempfile::tempdir().unwrap();
1713
let failed = cx.update(|cx| {
1714
runs.update(cx, |runs, cx| {
1715
runs.start_with(
1716
"ask",
1717
"19:chat",
1718
"m1",
1719
"hi",
1720
inbox_options(&directory.path().join("s.sock"), directory.path()),
1721
cx,
1722
)
1723
.unwrap()
1724
})
1725
});
1726
wait_until_finished(cx, &runs, failed);
1727
cx.update(|cx| {
1728
assert!(matches!(
1729
runs.read(cx).get(failed).unwrap().state,
1730
RunState::Failed { .. }
1731
));
1580
1732
});
1581
wait_until_finished(cx, &runs, forked);
1582
1733
}
1583
1734
1584
1735
#[gpui_kit::test]
@@ -1,9 +1,10 @@1
use std::collections::{HashMap, HashSet, VecDeque};1
use std::collections::{HashMap, HashSet, VecDeque};2
use std::path::PathBuf;2
use std::time::{Duration, Instant};3
use std::time::{Duration, Instant};3
4
4
use agents::{5
use agents::{5
AgentAction, AgentProfile, AgentSettings, McpEndpoint, RunEvent, RunOutcome, RunStatus,6
AgentAction, AgentProfile, AgentSettings, McpEndpoint, RunEvent, RunOutcome, RunStatus,6
RunUpdate,7
RunUpdate, RunningSession,7
};8
};8
use chrono::{DateTime, Utc};9
use chrono::{DateTime, Utc};9
use gpui_kit::*;10
use gpui_kit::*;@@ -29,6 +30,8 @@ const PROGRESS_PERSIST_INTERVAL: Duration = Duration::from_secs(5);29
const RESUME_PARALLEL_LIMIT: usize = 3;30
const RESUME_PARALLEL_LIMIT: usize = 3;30
const QUEUED_STEP: &str = "Queued";31
const QUEUED_STEP: &str = "Queued";31
const OPENED_NOTICE: &str = "Session opened in a terminal - send cancelled";32
const OPENED_NOTICE: &str = "Session opened in a terminal - send cancelled";33
const DELIVERED_TEXT: &str = "The reply arrives as a Teams draft.";34
const RESUMING_STEP: &str = "Session ended - resuming it";32
const RESUMED_STEP: &str = "Resumed after restart";35
const RESUMED_STEP: &str = "Resumed after restart";33
const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";36
const RESUME_PROMPT: &str = "The app was restarted. Continue where you stopped.";34
37
@@ -197,7 +200,14 @@ fn first_line(text: &str) -> &str {197
pub struct SessionTarget {200
pub struct SessionTarget {198
pub session_id: String,201
pub session_id: String,199
pub working_dir: String,202
pub working_dir: String,200
pub fork: bool,203
#[serde(default)]204
pub inbox: Option<InboxTarget>,205
}206
207
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]208
pub struct InboxTarget {209
pub session: RunningSession,210
pub sessions_dir: PathBuf,201
}211
}202
212
203
#[derive(Clone, Debug, Default, PartialEq, Eq)]213
#[derive(Clone, Debug, Default, PartialEq, Eq)]@@ -225,15 +235,6 @@ fn plan_for(225
endpoint,235
endpoint,226
directory.as_deref(),236
directory.as_deref(),227
),237
),228
Some(target) if target.fork => agents::fork_invocation(229
profile,230
action,231
prompt,232
&target.session_id,233
session_id,234
endpoint,235
directory.as_deref(),236
),237
Some(_) => agents::resume_invocation(238
Some(_) => agents::resume_invocation(238
profile,239
profile,239
action,240
action,@@ -598,11 +599,7 @@ impl AgentRuns {598
}599
}599
let (session_id, prompt) = match &options.session {600
let (session_id, prompt) = match &options.session {600
Some(target) => {601
Some(target) => {601
let session_id = if target.fork {602
let session_id = target.session_id.clone();602
agents::new_session_id()603
} else {604
target.session_id.clone()605
};606
let prompt =603
let prompt =607
agents::build_session_prompt(&context, extra, &session_id, &profile.id);604
agents::build_session_prompt(&context, extra, &session_id, &profile.id);608
(session_id, prompt)605
(session_id, prompt)@@ -614,6 +611,10 @@ impl AgentRuns {614
(session_id, prompt)611
(session_id, prompt)615
}612
}616
};613
};614
let inbox = options615
.session616
.as_ref()617
.and_then(|target| target.inbox.clone());617
let run_id = self.next_id;618
let run_id = self.next_id;618
self.next_id += 1;619
self.next_id += 1;619
self.runs.push(AgentRun {620
self.runs.push(AgentRun {@@ -638,7 +639,7 @@ impl AgentRuns {638
expanded: false,639
expanded: false,639
dismissed: false,640
dismissed: false,640
process_id: None,641
process_id: None,641
pending_prompt: Some(prompt),642
pending_prompt: inbox.is_none().then(|| prompt.clone()),642
sent_to: options.session.clone(),643
sent_to: options.session.clone(),643
launch_session_id: None,644
launch_session_id: None,644
launched: false,645
launched: false,@@ -648,7 +649,10 @@ impl AgentRuns {648
{649
{649
run.push_step("MCP server is off - no reply proposal possible".to_owned());650
run.push_step("MCP server is off - no reply proposal possible".to_owned());650
}651
}651
self.dispatch(run_id, cx);652
match inbox {653
Some(inbox) => self.deliver(run_id, inbox, profile.environment.clone(), prompt, cx),654
None => self.dispatch(run_id, cx),655
}652
if let Some(working_dir) = chosen_working_dir {656
if let Some(working_dir) = chosen_working_dir {653
self.update_settings(657
self.update_settings(654
|settings| settings.remember_working_dir(&profile.id, &working_dir),658
|settings| settings.remember_working_dir(&profile.id, &working_dir),@@ -661,6 +665,77 @@ impl AgentRuns {661
Ok(run_id)665
Ok(run_id)662
}666
}663
667
668
fn deliver(669
&mut self,670
run_id: u64,671
inbox: InboxTarget,672
environment: agents::Environment,673
prompt: String,674
cx: &mut Context<Self>,675
) {676
let session_name = inbox677
.session678
.name679
.clone()680
.unwrap_or_else(|| inbox.session.session_id.clone());681
cx.spawn(async move |this, cx| {682
let fallback_prompt = prompt.clone();683
let result = cx684
.background_executor()685
.spawn(async move {686
agents::deliver(&environment, &inbox.sessions_dir, &inbox.session, &prompt)687
})688
.await;689
this.update(cx, |runs, cx| {690
runs.finish_delivery(run_id, &session_name, fallback_prompt, result, cx)691
})692
.ok();693
})694
.detach();695
}696
697
fn finish_delivery(698
&mut self,699
run_id: u64,700
session_name: &str,701
prompt: String,702
result: Result<(), agents::DeliveryError>,703
cx: &mut Context<Self>,704
) {705
let status = match result {706
Ok(()) => RunStatus::Completed {707
final_text: DELIVERED_TEXT.to_owned(),708
},709
Err(agents::DeliveryError::SessionGone) => {710
if let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) {711
run.pending_prompt = Some(prompt);712
run.push_step(RESUMING_STEP.to_owned());713
self.dispatch(run_id, cx);714
self.persist(cx);715
cx.notify();716
}717
return;718
}719
Err(error) => RunStatus::Failed {720
message: error.to_string(),721
stderr_tail: Vec::new(),722
},723
};724
let delivered = matches!(status, RunStatus::Completed { .. });725
self.finish(726
run_id,727
Some(RunOutcome {728
status,729
exit_code: None,730
}),731
cx,732
);733
if delivered && let Some(run) = self.run_mut(run_id) {734
run.current_step = format!("Delivered to {session_name}");735
self.persist(cx);736
}737
}738
664
fn dispatch(&mut self, run_id: u64, cx: &mut Context<Self>) {739
fn dispatch(&mut self, run_id: u64, cx: &mut Context<Self>) {665
let Some(session_id) = self.get(run_id).map(|run| run.session_id.clone()) else {740
let Some(session_id) = self.get(run_id).map(|run| run.session_id.clone()) else {666
return;741
return;@@ -894,7 +969,7 @@ impl AgentRuns {894
for run_id in self.lanes.rename(from, to) {969
for run_id in self.lanes.rename(from, to) {895
if let Some(run) = self.run_mut(run_id) {970
if let Some(run) = self.run_mut(run_id) {896
run.session_id = to.to_owned();971
run.session_id = to.to_owned();897
if let Some(target) = run.sent_to.as_mut().filter(|target| !target.fork) {972
if let Some(target) = run.sent_to.as_mut() {898
target.session_id = to.to_owned();973
target.session_id = to.to_owned();899
}974
}900
}975
}@@ -1098,11 +1173,7 @@ impl AgentRuns {1098
working_dir: run.sent_to.is_none().then(|| run.working_dir.clone()),1173
working_dir: run.sent_to.is_none().then(|| run.working_dir.clone()),1099
remember_working_dir: false,1174
remember_working_dir: false,1100
session: run.sent_to.clone().map(|target| SessionTarget {1175
session: run.sent_to.clone().map(|target| SessionTarget {1101
session_id: if target.fork {1176
session_id: run.session_id.clone(),1102
target.session_id1103
} else {1104
run.session_id.clone()1105
},1106
..target1177
..target1107
}),1178
}),1108
};1179
};@@ -1236,6 +1307,7 @@ pub(super) mod tests {1236
1307
1237
use gpui_kit::AppContext as _;1308
use gpui_kit::AppContext as _;1238
1309
1310
use super::super::InboxTarget;1239
use super::{1311
use super::{1240
AgentRun, AgentRuns, Entity, RunState, SessionTarget, StartOptions, TestAppContext,1312
AgentRun, AgentRuns, Entity, RunState, SessionTarget, StartOptions, TestAppContext,1241
run_store, setup, wait_until_finished,1313
run_store, setup, wait_until_finished,@@ -1250,7 +1322,7 @@ pub(super) mod tests {1250
session: Some(SessionTarget {1322
session: Some(SessionTarget {1251
session_id,1323
session_id,1252
working_dir: std::env::temp_dir().to_string_lossy().into_owned(),1324
working_dir: std::env::temp_dir().to_string_lossy().into_owned(),1253
fork: false,1325
inbox: None,1254
}),1326
}),1255
}1327
}1256
}1328
}@@ -1547,38 +1619,117 @@ pub(super) mod tests {1547
assert_eq!(run.sent_to, None);1619
assert_eq!(run.sent_to, None);1548
}1620
}1549
1621
1622
fn inbox_options(1623
socket_path: &std::path::Path,1624
sessions_dir: &std::path::Path,1625
) -> StartOptions {1626
let mut options = target_of("live-session".to_owned());1627
options.session.as_mut().unwrap().inbox = Some(InboxTarget {1628
session: agents::RunningSession {1629
session_id: "live-session".to_owned(),1630
name: Some("Review".to_owned()),1631
working_dir: "/srv".to_owned(),1632
socket_path: Some(socket_path.to_string_lossy().into_owned()),1633
process_id: 42,1634
},1635
sessions_dir: sessions_dir.to_path_buf(),1636
});1637
options1638
}1639
1550
#[gpui_kit::test]1640
#[gpui_kit::test]1551
fn a_forked_send_gets_a_fresh_session_id_and_adopts_a_reported_one(1641
fn a_message_to_a_running_session_is_delivered_without_a_process(cx: &mut TestAppContext) {1552
cx: &mut TestAppContext,1642
let (_, runs) = setup(cx, SESSION_COMMAND);1553
) {1643
let directory = tempfile::tempdir().unwrap();1554
let (app, runs) = setup(cx, SESSION_COMMAND);1644
let socket_path = directory.path().join("s.sock");1555
let forked = cx.update(|cx| {1645
let listener = std::os::unix::net::UnixListener::bind(&socket_path).unwrap();1646
std::fs::write(directory.path().join("42.ab.key"), r#"{"peerToken":"tok"}"#).unwrap();1647
let reader = std::thread::spawn(move || {1648
let (mut stream, _) = listener.accept().unwrap();1649
let mut received = String::new();1650
std::io::Read::read_to_string(&mut stream, &mut received).unwrap();1651
received1652
});1653
let delivered = cx.update(|cx| {1556
runs.update(cx, |runs, cx| {1654
runs.update(cx, |runs, cx| {1557
let mut options = target_of("live-session".to_owned());1655
runs.start_with(1558
options.session.as_mut().unwrap().fork = true;1656
"ask",1559
runs.start_with("ask", "19:chat", "m1", "hi", options, cx)1657
"19:chat",1560
.unwrap()1658
"m1",1659
"hi",1660
inbox_options(&socket_path, directory.path()),1661
cx,1662
)1663
.unwrap()1561
})1664
})1562
});1665
});1666
wait_until_finished(cx, &runs, delivered);1563
cx.update(|cx| {1667
cx.update(|cx| {1564
let run = runs.read(cx).get(forked).unwrap().clone();1668
let run = runs.read(cx).get(delivered).unwrap();1565
assert_ne!(run.session_id, "live-session");1669
assert_eq!(run.state, RunState::Done);1566
assert!(run.sent_to.as_ref().unwrap().fork);1670
assert_eq!(run.current_step, "Delivered to Review");1567
assert!(!run.is_queued());1671
assert_eq!(run.session_id, "live-session");1672
assert_eq!(run.process_id, None);1673
assert!(run.final_text.contains("Teams draft"));1674
});1675
let received = reader.join().unwrap();1676
assert!(received.contains("live-session"));1677
assert!(received.contains("propose_message"));1678
assert!(received.contains("19:chat"));1679
assert!(received.starts_with(r#"{"type":"auth","token":"tok"}"#));1680
}1681
1682
#[gpui_kit::test]1683
fn a_session_that_ended_before_delivery_is_resumed_in_place(cx: &mut TestAppContext) {1684
let (_, runs) = setup(cx, SESSION_COMMAND);1685
let directory = tempfile::tempdir().unwrap();1686
std::fs::write(directory.path().join("42.ab.key"), r#"{"peerToken":"tok"}"#).unwrap();1687
let resumed = cx.update(|cx| {1568
runs.update(cx, |runs, cx| {1688
runs.update(cx, |runs, cx| {1569
runs.apply_update(1689
runs.start_with(1570
forked,1690
"ask",1571
agents::RunUpdate::Event(agents::RunEvent::SessionId(1691
"19:chat",1572
"reported".to_owned(),1692
"m1",1573
)),1693
"hi",1694
inbox_options(&directory.path().join("gone.sock"), directory.path()),1574
cx,1695
cx,1575
)1696
)1576
});1697
.unwrap()1577
assert_eq!(runs.read(cx).get(forked).unwrap().session_id, "reported");1698
})1578
let stored = run_store::load_runs(&app.read(cx).store);1699
});1579
assert_eq!(stored[0].session_id, "reported");1700
wait_until_finished(cx, &runs, resumed);1701
cx.update(|cx| {1702
let run = runs.read(cx).get(resumed).unwrap();1703
assert!(run.steps.iter().any(|(_, step)| step.contains("resuming")));1704
assert!(run.launched);1705
assert_eq!(run.session_id, "live-session");1706
});1707
}1708
1709
#[gpui_kit::test]1710
fn a_delivery_failure_marks_the_run_failed_without_the_token(cx: &mut TestAppContext) {1711
let (_, runs) = setup(cx, SESSION_COMMAND);1712
let directory = tempfile::tempdir().unwrap();1713
let failed = cx.update(|cx| {1714
runs.update(cx, |runs, cx| {1715
runs.start_with(1716
"ask",1717
"19:chat",1718
"m1",1719
"hi",1720
inbox_options(&directory.path().join("s.sock"), directory.path()),1721
cx,1722
)1723
.unwrap()1724
})1725
});1726
wait_until_finished(cx, &runs, failed);1727
cx.update(|cx| {1728
assert!(matches!(1729
runs.read(cx).get(failed).unwrap().state,1730
RunState::Failed { .. }1731
));1580
});1732
});1581
wait_until_finished(cx, &runs, forked);1582
}1733
}1583
1734
1584
#[gpui_kit::test]1735
#[gpui_kit::test]@@ -1,19 +1,17 @@
1
1
use std::collections::HashSet;
2
2
use std::path::{Path, PathBuf};
3
use std::time::Duration;
4
3
5
use agents::{Environment, ExternalSession};
4
use agents::{DesktopSession, Environment, RunningSession};
6
5
use chrono::{DateTime, Local, Utc};
7
6
use mcp::install::{Homes, Location};
8
7
9
8
use super::message_context;
10
use super::runs::{AgentRun, RunState};
9
use super::runs::{AgentRun, InboxTarget, RunState};
11
10
use crate::agent_api::agent_homes;
12
11
use crate::app_state::AppState;
13
12
use crate::notice::truncated;
14
13
15
14
pub const SESSION_LIMIT: usize = 10;
16
const ACTIVE_WINDOW: Duration = Duration::from_secs(120);
17
15
const LABEL_CHARS: usize = 60;
18
16
const WEEK_DAYS: i64 = 7;
19
17
@@ -24,7 +22,7 @@ pub struct SessionOption {
24
22
pub label: String,
25
23
pub meta: String,
26
24
pub running: bool,
27
pub fork: bool,
25
pub inbox: Option<InboxTarget>,
28
26
}
29
27
30
28
pub fn relative_age(now: DateTime<Utc>, then: DateTime<Utc>) -> String {
@@ -75,39 +73,83 @@ pub fn run_options(runs: &[&AgentRun], state: &AppState, now: DateTime<Utc>) ->
75
73
),
76
74
meta: run_meta(run, now),
77
75
running: run.is_running(),
78
fork: false,
76
inbox: None,
79
77
}
80
78
})
81
79
.collect()
82
80
}
83
81
84
pub fn external_options(
85
sessions: &[ExternalSession],
86
working_dir: &str,
82
pub fn merged_options(
83
desktop: &[DesktopSession],
84
running: &[RunningSession],
85
sessions_dir: &Path,
86
known_session_ids: &HashSet<String>,
87
87
now: DateTime<Utc>,
88
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);
89
let mut seen = known_session_ids.clone();
90
let mut entries: Vec<(SessionOption, i64)> = Vec::new();
91
for session in running {
92
if !seen.insert(session.session_id.clone()) {
93
continue;
94
}
95
let desktop_session = desktop
96
.iter()
97
.find(|candidate| candidate.session_id == session.session_id);
98
let title = desktop_session
99
.map(|candidate| candidate.title.clone())
100
.filter(|title| !title.is_empty())
101
.or_else(|| session.name.clone())
102
.unwrap_or_else(|| session.session_id.clone());
103
let working_dir = desktop_session
104
.map(|candidate| candidate.working_dir.clone())
105
.filter(|working_dir| !working_dir.is_empty())
106
.unwrap_or_else(|| session.working_dir.clone());
107
entries.push((
108
SessionOption {
109
session_id: session.session_id.clone(),
110
working_dir,
111
label: truncated(&title, LABEL_CHARS),
112
meta: "Running".to_owned(),
113
running: true,
114
inbox: Some(InboxTarget {
115
session: session.clone(),
116
sessions_dir: sessions_dir.to_path_buf(),
117
}),
118
},
119
desktop_session.map_or(0, |candidate| candidate.last_activity_millis),
120
));
121
}
122
for session in desktop {
123
if !seen.insert(session.session_id.clone()) {
124
continue;
125
}
126
let activity = DateTime::<Utc>::from_timestamp_millis(session.last_activity_millis);
127
entries.push((
98
128
SessionOption {
99
129
session_id: session.session_id.clone(),
100
working_dir: working_dir.to_owned(),
130
working_dir: session.working_dir.clone(),
101
131
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
},
132
meta: activity.map_or_else(
133
|| "Idle".to_owned(),
134
|activity| format!("Idle - {}", relative_age(now, activity)),
135
),
107
136
running: false,
108
fork: active,
109
}
110
})
137
inbox: None,
138
},
139
session.last_activity_millis,
140
));
141
}
142
entries.sort_by(|left, right| {
143
right
144
.0
145
.running
146
.cmp(&left.0.running)
147
.then(right.1.cmp(&left.1))
148
});
149
entries
150
.into_iter()
151
.take(SESSION_LIMIT)
152
.map(|(option, _)| option)
111
153
.collect()
112
154
}
113
155
@@ -130,66 +172,56 @@ fn pick_home<'a>(environment: &Environment, homes: &'a Homes) -> Option<&'a Path
130
172
.map(|(_, home)| home)
131
173
}
132
174
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
}
175
fn registry_dir(environment: &Environment, homes: &Homes) -> Option<PathBuf> {
176
Some(
177
pick_home(environment, homes)?
178
.join(".claude")
179
.join("sessions"),
180
)
145
181
}
146
182
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
))
183
fn desktop_dir() -> Option<PathBuf> {
184
std::env::var_os("APPDATA").map(|appdata| PathBuf::from(appdata).join("Claude"))
159
185
}
160
186
161
187
#[derive(Default)]
162
pub struct ExternalLoad {
163
pub sessions: Vec<ExternalSession>,
164
pub live_session_ids: HashSet<String>,
188
pub struct SessionLoad {
189
pub desktop: Vec<DesktopSession>,
190
pub running: Vec<RunningSession>,
191
pub sessions_dir: PathBuf,
165
192
}
166
193
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();
194
pub fn load_sessions(environment: &Environment, demo: bool) -> SessionLoad {
195
let Some(sessions_dir) = registry_dir(environment, &agent_homes(demo)) else {
196
return SessionLoad::default();
177
197
};
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(),
198
SessionLoad {
199
desktop: if demo {
200
Vec::new()
201
} else {
202
desktop_dir()
203
.map(|directory| agents::desktop_sessions(&directory))
204
.unwrap_or_default()
205
},
206
running: agents::running_sessions(&sessions_dir),
207
sessions_dir,
187
208
}
188
209
}
189
210
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);
211
pub fn attach_inboxes(options: &mut [SessionOption], load: &SessionLoad) {
212
for option in options.iter_mut().filter(|option| !option.running) {
213
if let Some(session) = load
214
.running
215
.iter()
216
.find(|session| session.session_id == option.session_id)
217
{
218
option.running = true;
219
option.meta = "Running".to_owned();
220
option.inbox = Some(InboxTarget {
221
session: session.clone(),
222
sessions_dir: load.sessions_dir.clone(),
223
});
224
}
193
225
}
194
226
}
195
227
@@ -205,21 +237,10 @@ pub fn default_wsl_distro(demo: bool) -> Option<String> {
205
237
206
238
#[cfg(test)]
207
239
mod tests {
208
use std::time::SystemTime;
209
210
240
use chrono::TimeZone;
211
241
212
242
use super::*;
213
243
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
244
#[test]
224
245
fn relative_age_uses_minutes_hours_weekday_and_date() {
225
246
let now = Utc.with_ymd_and_hms(2026, 10, 13, 12, 0, 0).unwrap();
@@ -231,51 +252,6 @@ mod tests {
231
252
assert!(ago(10 * 86400).contains(char::is_whitespace));
232
253
}
233
254
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
255
#[test]
280
256
fn runs_that_never_created_a_session_are_left_out() {
281
257
let state = AppState::new(
@@ -291,7 +267,7 @@ mod tests {
291
267
sent.sent_to = Some(crate::agents::runs::SessionTarget {
292
268
session_id: sent.session_id.clone(),
293
269
working_dir: "~".to_owned(),
294
fork: false,
270
inbox: None,
295
271
});
296
272
let options = run_options(&[&created, &never_started, &sent], &state, Utc::now());
297
273
let ids: Vec<&str> = options
@@ -326,35 +302,94 @@ mod tests {
326
302
assert_eq!(pick_home(&wsl(Some("Debian")), &homes), None);
327
303
}
328
304
305
fn desktop(session_id: &str, last_activity_millis: i64) -> DesktopSession {
306
DesktopSession {
307
session_id: session_id.to_owned(),
308
working_dir: format!("/srv/{session_id}"),
309
title: format!("Title {session_id}"),
310
last_activity_millis,
311
}
312
}
313
314
fn running(session_id: &str) -> RunningSession {
315
RunningSession {
316
session_id: session_id.to_owned(),
317
name: Some(format!("Name {session_id}")),
318
working_dir: "/registry".to_owned(),
319
socket_path: Some("/run/s.sock".to_owned()),
320
process_id: 7,
321
}
322
}
323
324
fn ids(options: &[SessionOption]) -> Vec<&str> {
325
options
326
.iter()
327
.map(|option| option.session_id.as_str())
328
.collect()
329
}
330
329
331
#[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"
332
fn running_sessions_come_first_then_the_newest_activity() {
333
let options = merged_options(
334
&[
335
desktop("old", 1_000),
336
desktop("live", 500),
337
desktop("new", 9_000),
338
],
339
&[running("live"), running("registry-only")],
340
Path::new("/sessions"),
341
&HashSet::new(),
342
Utc::now(),
345
343
);
346
assert_eq!(
347
resolve_working_dir(&environment, "/srv/app", Path::new("/home/daniel")),
348
"/srv/app"
344
assert_eq!(ids(&options), ["live", "registry-only", "new", "old"]);
345
assert!(options[0].running && options[0].inbox.is_some());
346
assert_eq!(options[0].label, "Title live");
347
assert_eq!(options[0].working_dir, "/srv/live");
348
assert_eq!(options[1].label, "Name registry-only");
349
assert_eq!(options[1].working_dir, "/registry");
350
assert!(!options[2].running && options[2].inbox.is_none());
351
}
352
353
#[test]
354
fn known_run_ids_are_excluded_and_the_limit_applies() {
355
let sessions: Vec<DesktopSession> = (0..15)
356
.map(|index| desktop(&format!("s{index}"), index))
357
.collect();
358
let known = HashSet::from(["s14".to_owned(), "live".to_owned()]);
359
let options = merged_options(
360
&sessions,
361
&[running("live")],
362
Path::new("/sessions"),
363
&known,
364
Utc::now(),
349
365
);
366
assert_eq!(options.len(), SESSION_LIMIT);
367
assert_eq!(options[0].session_id, "s13");
368
assert!(!ids(&options).contains(&"live"));
350
369
}
351
370
352
371
#[test]
353
fn a_host_home_expands_the_tilde_before_encoding() {
354
let homes = Homes {
355
entries: vec![(Location::Native, PathBuf::from("/home/daniel"))],
372
fn a_session_known_to_the_registry_gets_an_inbox_on_a_run_option() {
373
let option = |session_id: &str, running: bool| SessionOption {
374
session_id: session_id.to_owned(),
375
working_dir: "/repo".to_owned(),
376
label: String::new(),
377
meta: String::new(),
378
running,
379
inbox: None,
356
380
};
357
let (directory, _) = claude_dirs(&Environment::Host, "~", &homes).unwrap();
358
assert!(directory.ends_with(".claude/projects/-home-daniel"));
381
let mut options = vec![option("a", false), option("b", false), option("c", true)];
382
let load = SessionLoad {
383
desktop: Vec::new(),
384
running: vec![running("a"), running("c")],
385
sessions_dir: PathBuf::from("/sessions"),
386
};
387
attach_inboxes(&mut options, &load);
388
let inboxes: Vec<bool> = options
389
.iter()
390
.map(|option| option.inbox.is_some())
391
.collect();
392
assert_eq!(inboxes, [true, false, false]);
393
assert!(options[0].running);
359
394
}
360
395
}
@@ -1,19 +1,17 @@1
use std::collections::HashSet;1
use std::collections::HashSet;2
use std::path::{Path, PathBuf};2
use std::path::{Path, PathBuf};3
use std::time::Duration;4
3
5
use agents::{Environment, ExternalSession};4
use agents::{DesktopSession, Environment, RunningSession};6
use chrono::{DateTime, Local, Utc};5
use chrono::{DateTime, Local, Utc};7
use mcp::install::{Homes, Location};6
use mcp::install::{Homes, Location};8
7
9
use super::message_context;8
use super::message_context;10
use super::runs::{AgentRun, RunState};9
use super::runs::{AgentRun, InboxTarget, RunState};11
use crate::agent_api::agent_homes;10
use crate::agent_api::agent_homes;12
use crate::app_state::AppState;11
use crate::app_state::AppState;13
use crate::notice::truncated;12
use crate::notice::truncated;14
13
15
pub const SESSION_LIMIT: usize = 10;14
pub const SESSION_LIMIT: usize = 10;16
const ACTIVE_WINDOW: Duration = Duration::from_secs(120);17
const LABEL_CHARS: usize = 60;15
const LABEL_CHARS: usize = 60;18
const WEEK_DAYS: i64 = 7;16
const WEEK_DAYS: i64 = 7;19
17
@@ -24,7 +22,7 @@ pub struct SessionOption {24
pub label: String,22
pub label: String,25
pub meta: String,23
pub meta: String,26
pub running: bool,24
pub running: bool,27
pub fork: bool,25
pub inbox: Option<InboxTarget>,28
}26
}29
27
30
pub fn relative_age(now: DateTime<Utc>, then: DateTime<Utc>) -> String {28
pub fn relative_age(now: DateTime<Utc>, then: DateTime<Utc>) -> String {@@ -75,39 +73,83 @@ pub fn run_options(runs: &[&AgentRun], state: &AppState, now: DateTime<Utc>) ->75
),73
),76
meta: run_meta(run, now),74
meta: run_meta(run, now),77
running: run.is_running(),75
running: run.is_running(),78
fork: false,76
inbox: None,79
}77
}80
})78
})81
.collect()79
.collect()82
}80
}83
81
84
pub fn external_options(82
pub fn merged_options(85
sessions: &[ExternalSession],83
desktop: &[DesktopSession],86
working_dir: &str,84
running: &[RunningSession],85
sessions_dir: &Path,86
known_session_ids: &HashSet<String>,87
now: DateTime<Utc>,87
now: DateTime<Utc>,88
) -> Vec<SessionOption> {88
) -> Vec<SessionOption> {89
sessions89
let mut seen = known_session_ids.clone();90
.iter()90
let mut entries: Vec<(SessionOption, i64)> = Vec::new();91
.map(|session| {91
for session in running {92
let modified = DateTime::<Utc>::from(session.modified);92
if !seen.insert(session.session_id.clone()) {93
let active = session.live93
continue;94
|| modified > now94
}95
|| (now - modified)95
let desktop_session = desktop96
.to_std()96
.iter()97
.is_ok_and(|age| age < ACTIVE_WINDOW);97
.find(|candidate| candidate.session_id == session.session_id);98
let title = desktop_session99
.map(|candidate| candidate.title.clone())100
.filter(|title| !title.is_empty())101
.or_else(|| session.name.clone())102
.unwrap_or_else(|| session.session_id.clone());103
let working_dir = desktop_session104
.map(|candidate| candidate.working_dir.clone())105
.filter(|working_dir| !working_dir.is_empty())106
.unwrap_or_else(|| session.working_dir.clone());107
entries.push((108
SessionOption {109
session_id: session.session_id.clone(),110
working_dir,111
label: truncated(&title, LABEL_CHARS),112
meta: "Running".to_owned(),113
running: true,114
inbox: Some(InboxTarget {115
session: session.clone(),116
sessions_dir: sessions_dir.to_path_buf(),117
}),118
},119
desktop_session.map_or(0, |candidate| candidate.last_activity_millis),120
));121
}122
for session in desktop {123
if !seen.insert(session.session_id.clone()) {124
continue;125
}126
let activity = DateTime::<Utc>::from_timestamp_millis(session.last_activity_millis);127
entries.push((98
SessionOption {128
SessionOption {99
session_id: session.session_id.clone(),129
session_id: session.session_id.clone(),100
working_dir: working_dir.to_owned(),130
working_dir: session.working_dir.clone(),101
label: truncated(&session.title, LABEL_CHARS),131
label: truncated(&session.title, LABEL_CHARS),102
meta: if active {132
meta: activity.map_or_else(103
"Active elsewhere - sends to a copy".to_owned()133
|| "Idle".to_owned(),104
} else {134
|activity| format!("Idle - {}", relative_age(now, activity)),105
format!("Idle - {}", relative_age(now, modified))135
),106
},107
running: false,136
running: false,108
fork: active,137
inbox: None,109
}138
},110
})139
session.last_activity_millis,140
));141
}142
entries.sort_by(|left, right| {143
right144
.0145
.running146
.cmp(&left.0.running)147
.then(right.1.cmp(&left.1))148
});149
entries150
.into_iter()151
.take(SESSION_LIMIT)152
.map(|(option, _)| option)111
.collect()153
.collect()112
}154
}113
155
@@ -130,66 +172,56 @@ fn pick_home<'a>(environment: &Environment, homes: &'a Homes) -> Option<&'a Path130
.map(|(_, home)| home)172
.map(|(_, home)| home)131
}173
}132
174
133
fn resolve_working_dir(environment: &Environment, working_dir: &str, home: &Path) -> String {175
fn registry_dir(environment: &Environment, homes: &Homes) -> Option<PathBuf> {134
let home_text = home.to_string_lossy();176
Some(135
let home_text = match environment {177
pick_home(environment, homes)?136
Environment::Host => home_text.into_owned(),178
.join(".claude")137
Environment::Wsl { .. } => agents::linux_path(&home_text),179
.join("sessions"),138
};180
)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
}181
}146
182
147
fn claude_dirs(183
fn desktop_dir() -> Option<PathBuf> {148
environment: &Environment,184
std::env::var_os("APPDATA").map(|appdata| PathBuf::from(appdata).join("Claude"))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
}185
}160
186
161
#[derive(Default)]187
#[derive(Default)]162
pub struct ExternalLoad {188
pub struct SessionLoad {163
pub sessions: Vec<ExternalSession>,189
pub desktop: Vec<DesktopSession>,164
pub live_session_ids: HashSet<String>,190
pub running: Vec<RunningSession>,191
pub sessions_dir: PathBuf,165
}192
}166
193
167
pub fn load_external(194
pub fn load_sessions(environment: &Environment, demo: bool) -> SessionLoad {168
environment: &Environment,195
let Some(sessions_dir) = registry_dir(environment, &agent_homes(demo)) else {169
working_dir: &str,196
return SessionLoad::default();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
};197
};178
let live = agents::live_session_names(&sessions_dir);198
SessionLoad {179
ExternalLoad {199
desktop: if demo {180
sessions: agents::scan_external_sessions(200
Vec::new()181
&project_dir,201
} else {182
&live,202
desktop_dir()183
known_session_ids,203
.map(|directory| agents::desktop_sessions(&directory))184
SESSION_LIMIT,204
.unwrap_or_default()185
),205
},186
live_session_ids: live.into_keys().collect(),206
running: agents::running_sessions(&sessions_dir),207
sessions_dir,187
}208
}188
}209
}189
210
190
pub fn mark_live_runs(options: &mut [SessionOption], live_session_ids: &HashSet<String>) {211
pub fn attach_inboxes(options: &mut [SessionOption], load: &SessionLoad) {191
for option in options {212
for option in options.iter_mut().filter(|option| !option.running) {192
option.fork = !option.running && live_session_ids.contains(&option.session_id);213
if let Some(session) = load214
.running215
.iter()216
.find(|session| session.session_id == option.session_id)217
{218
option.running = true;219
option.meta = "Running".to_owned();220
option.inbox = Some(InboxTarget {221
session: session.clone(),222
sessions_dir: load.sessions_dir.clone(),223
});224
}193
}225
}194
}226
}195
227
@@ -205,21 +237,10 @@ pub fn default_wsl_distro(demo: bool) -> Option<String> {205
237
206
#[cfg(test)]238
#[cfg(test)]207
mod tests {239
mod tests {208
use std::time::SystemTime;209
210
use chrono::TimeZone;240
use chrono::TimeZone;211
241
212
use super::*;242
use super::*;213
243
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]244
#[test]224
fn relative_age_uses_minutes_hours_weekday_and_date() {245
fn relative_age_uses_minutes_hours_weekday_and_date() {225
let now = Utc.with_ymd_and_hms(2026, 10, 13, 12, 0, 0).unwrap();246
let now = Utc.with_ymd_and_hms(2026, 10, 13, 12, 0, 0).unwrap();@@ -231,51 +252,6 @@ mod tests {231
assert!(ago(10 * 86400).contains(char::is_whitespace));252
assert!(ago(10 * 86400).contains(char::is_whitespace));232
}253
}233
254
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]255
#[test]280
fn runs_that_never_created_a_session_are_left_out() {256
fn runs_that_never_created_a_session_are_left_out() {281
let state = AppState::new(257
let state = AppState::new(@@ -291,7 +267,7 @@ mod tests {291
sent.sent_to = Some(crate::agents::runs::SessionTarget {267
sent.sent_to = Some(crate::agents::runs::SessionTarget {292
session_id: sent.session_id.clone(),268
session_id: sent.session_id.clone(),293
working_dir: "~".to_owned(),269
working_dir: "~".to_owned(),294
fork: false,270
inbox: None,295
});271
});296
let options = run_options(&[&created, &never_started, &sent], &state, Utc::now());272
let options = run_options(&[&created, &never_started, &sent], &state, Utc::now());297
let ids: Vec<&str> = options273
let ids: Vec<&str> = options@@ -326,35 +302,94 @@ mod tests {326
assert_eq!(pick_home(&wsl(Some("Debian")), &homes), None);302
assert_eq!(pick_home(&wsl(Some("Debian")), &homes), None);327
}303
}328
304
305
fn desktop(session_id: &str, last_activity_millis: i64) -> DesktopSession {306
DesktopSession {307
session_id: session_id.to_owned(),308
working_dir: format!("/srv/{session_id}"),309
title: format!("Title {session_id}"),310
last_activity_millis,311
}312
}313
314
fn running(session_id: &str) -> RunningSession {315
RunningSession {316
session_id: session_id.to_owned(),317
name: Some(format!("Name {session_id}")),318
working_dir: "/registry".to_owned(),319
socket_path: Some("/run/s.sock".to_owned()),320
process_id: 7,321
}322
}323
324
fn ids(options: &[SessionOption]) -> Vec<&str> {325
options326
.iter()327
.map(|option| option.session_id.as_str())328
.collect()329
}330
329
#[test]331
#[test]330
fn a_wsl_home_encodes_the_linux_path_of_the_working_dir() {332
fn running_sessions_come_first_then_the_newest_activity() {331
let homes = Homes {333
let options = merged_options(332
entries: vec![(334
&[333
Location::Wsl {335
desktop("old", 1_000),334
distro: "Ubuntu".to_owned(),336
desktop("live", 500),335
},337
desktop("new", 9_000),336
PathBuf::from(r"\\wsl.localhost\Ubuntu\home\daniel"),338
],337
)],339
&[running("live"), running("registry-only")],338
};340
Path::new("/sessions"),339
let environment = Environment::Wsl { distro: None };341
&HashSet::new(),340
let (directory, sessions) = claude_dirs(&environment, "~/Projects/x", &homes).unwrap();342
Utc::now(),341
assert!(sessions.ends_with(".claude/sessions"));342
assert_eq!(343
directory.file_name().unwrap().to_string_lossy(),344
"-home-daniel-Projects-x"345
);343
);346
assert_eq!(344
assert_eq!(ids(&options), ["live", "registry-only", "new", "old"]);347
resolve_working_dir(&environment, "/srv/app", Path::new("/home/daniel")),345
assert!(options[0].running && options[0].inbox.is_some());348
"/srv/app"346
assert_eq!(options[0].label, "Title live");347
assert_eq!(options[0].working_dir, "/srv/live");348
assert_eq!(options[1].label, "Name registry-only");349
assert_eq!(options[1].working_dir, "/registry");350
assert!(!options[2].running && options[2].inbox.is_none());351
}352
353
#[test]354
fn known_run_ids_are_excluded_and_the_limit_applies() {355
let sessions: Vec<DesktopSession> = (0..15)356
.map(|index| desktop(&format!("s{index}"), index))357
.collect();358
let known = HashSet::from(["s14".to_owned(), "live".to_owned()]);359
let options = merged_options(360
&sessions,361
&[running("live")],362
Path::new("/sessions"),363
&known,364
Utc::now(),349
);365
);366
assert_eq!(options.len(), SESSION_LIMIT);367
assert_eq!(options[0].session_id, "s13");368
assert!(!ids(&options).contains(&"live"));350
}369
}351
370
352
#[test]371
#[test]353
fn a_host_home_expands_the_tilde_before_encoding() {372
fn a_session_known_to_the_registry_gets_an_inbox_on_a_run_option() {354
let homes = Homes {373
let option = |session_id: &str, running: bool| SessionOption {355
entries: vec![(Location::Native, PathBuf::from("/home/daniel"))],374
session_id: session_id.to_owned(),375
working_dir: "/repo".to_owned(),376
label: String::new(),377
meta: String::new(),378
running,379
inbox: None,356
};380
};357
let (directory, _) = claude_dirs(&Environment::Host, "~", &homes).unwrap();381
let mut options = vec![option("a", false), option("b", false), option("c", true)];358
assert!(directory.ends_with(".claude/projects/-home-daniel"));382
let load = SessionLoad {383
desktop: Vec::new(),384
running: vec![running("a"), running("c")],385
sessions_dir: PathBuf::from("/sessions"),386
};387
attach_inboxes(&mut options, &load);388
let inboxes: Vec<bool> = options389
.iter()390
.map(|option| option.inbox.is_some())391
.collect();392
assert_eq!(inboxes, [true, false, false]);393
assert!(options[0].running);359
}394
}360
}395
}@@ -13,7 +13,7 @@ use gpui_kit::*;
13
13
14
14
use super::runs::{SessionTarget, StartOptions, StartRequest};
15
15
use super::session_options::{
16
SessionOption, default_wsl_distro, external_options, load_external, mark_live_runs, run_options,
16
SessionOption, attach_inboxes, default_wsl_distro, load_sessions, merged_options, run_options,
17
17
};
18
18
use super::start_dialog_pickers::{MenuPart, MenuRow, locked_select, picker_row, select};
19
19
use super::{
@@ -62,7 +62,6 @@ pub struct StartDialog {
62
62
run_sessions: Vec<SessionOption>,
63
63
external_sessions: Vec<SessionOption>,
64
64
selected_session: Option<SessionOption>,
65
external_generation: u64,
66
65
}
67
66
68
67
impl EventEmitter<StartDialogEvent> for StartDialog {}
@@ -138,41 +137,36 @@ impl StartDialog {
138
137
run_sessions,
139
138
external_sessions: Vec::new(),
140
139
selected_session: None,
141
external_generation: 0,
142
140
action,
143
141
};
144
dialog.reload_external(cx);
142
dialog.load_external(cx);
145
143
dialog
146
144
}
147
145
148
fn reload_external(&mut self, cx: &mut Context<Self>) {
149
self.external_sessions.clear();
146
fn load_external(&mut self, cx: &mut Context<Self>) {
150
147
if !self.scans_external {
151
148
return;
152
149
}
153
self.external_generation += 1;
154
let generation = self.external_generation;
155
150
let environment = self.environment.clone();
156
let working_dir = self.working_dir.clone();
157
151
let known_session_ids = runs_handle(cx)
158
152
.map(|runs| runs.read(cx).session_ids())
159
153
.unwrap_or_default();
160
154
let demo = crate::agent_api::is_demo(cx);
161
155
cx.spawn(async move |this, cx| {
162
let scanned_dir = working_dir.clone();
163
156
let loaded = cx
164
157
.background_executor()
165
.spawn(async move {
166
load_external(&environment, &scanned_dir, &known_session_ids, demo)
167
})
158
.spawn(async move { load_sessions(&environment, demo) })
168
159
.await;
169
160
this.update(cx, |this, cx| {
170
if this.external_generation == generation {
171
this.external_sessions =
172
external_options(&loaded.sessions, &working_dir, Utc::now());
173
mark_live_runs(&mut this.run_sessions, &loaded.live_session_ids);
174
cx.notify();
175
}
161
this.external_sessions = merged_options(
162
&loaded.desktop,
163
&loaded.running,
164
&loaded.sessions_dir,
165
&known_session_ids,
166
Utc::now(),
167
);
168
attach_inboxes(&mut this.run_sessions, &loaded);
169
cx.notify();
176
170
})
177
171
.ok();
178
172
})
@@ -198,10 +192,7 @@ impl StartDialog {
198
192
}
199
193
200
194
fn choose_working_dir(&mut self, working_dir: String, cx: &mut Context<Self>) {
201
if self.working_dir != working_dir {
202
self.working_dir = working_dir;
203
self.reload_external(cx);
204
}
195
self.working_dir = working_dir;
205
196
cx.notify();
206
197
}
207
198
@@ -262,7 +253,7 @@ impl StartDialog {
262
253
session: Some(SessionTarget {
263
254
session_id: session.session_id.clone(),
264
255
working_dir: session.working_dir.clone(),
265
fork: session.fork,
256
inbox: session.inbox.clone(),
266
257
}),
267
258
},
268
259
None => StartOptions {
@@ -411,10 +402,7 @@ impl StartDialog {
411
402
}
412
403
if !self.external_sessions.is_empty() {
413
404
parts.push(MenuPart::Separator);
414
parts.push(MenuPart::Header(format!(
415
"Other sessions in {}",
416
self.working_dir
417
)));
405
parts.push(MenuPart::Header("Other sessions".to_owned()));
418
406
parts.extend(self.external_sessions.iter().map(row));
419
407
}
420
408
parts
@@ -13,7 +13,7 @@ use gpui_kit::*;13
13
14
use super::runs::{SessionTarget, StartOptions, StartRequest};14
use super::runs::{SessionTarget, StartOptions, StartRequest};15
use super::session_options::{15
use super::session_options::{16
SessionOption, default_wsl_distro, external_options, load_external, mark_live_runs, run_options,16
SessionOption, attach_inboxes, default_wsl_distro, load_sessions, merged_options, run_options,17
};17
};18
use super::start_dialog_pickers::{MenuPart, MenuRow, locked_select, picker_row, select};18
use super::start_dialog_pickers::{MenuPart, MenuRow, locked_select, picker_row, select};19
use super::{19
use super::{@@ -62,7 +62,6 @@ pub struct StartDialog {62
run_sessions: Vec<SessionOption>,62
run_sessions: Vec<SessionOption>,63
external_sessions: Vec<SessionOption>,63
external_sessions: Vec<SessionOption>,64
selected_session: Option<SessionOption>,64
selected_session: Option<SessionOption>,65
external_generation: u64,66
}65
}67
66
68
impl EventEmitter<StartDialogEvent> for StartDialog {}67
impl EventEmitter<StartDialogEvent> for StartDialog {}@@ -138,41 +137,36 @@ impl StartDialog {138
run_sessions,137
run_sessions,139
external_sessions: Vec::new(),138
external_sessions: Vec::new(),140
selected_session: None,139
selected_session: None,141
external_generation: 0,142
action,140
action,143
};141
};144
dialog.reload_external(cx);142
dialog.load_external(cx);145
dialog143
dialog146
}144
}147
145
148
fn reload_external(&mut self, cx: &mut Context<Self>) {146
fn load_external(&mut self, cx: &mut Context<Self>) {149
self.external_sessions.clear();150
if !self.scans_external {147
if !self.scans_external {151
return;148
return;152
}149
}153
self.external_generation += 1;154
let generation = self.external_generation;155
let environment = self.environment.clone();150
let environment = self.environment.clone();156
let working_dir = self.working_dir.clone();157
let known_session_ids = runs_handle(cx)151
let known_session_ids = runs_handle(cx)158
.map(|runs| runs.read(cx).session_ids())152
.map(|runs| runs.read(cx).session_ids())159
.unwrap_or_default();153
.unwrap_or_default();160
let demo = crate::agent_api::is_demo(cx);154
let demo = crate::agent_api::is_demo(cx);161
cx.spawn(async move |this, cx| {155
cx.spawn(async move |this, cx| {162
let scanned_dir = working_dir.clone();163
let loaded = cx156
let loaded = cx164
.background_executor()157
.background_executor()165
.spawn(async move {158
.spawn(async move { load_sessions(&environment, demo) })166
load_external(&environment, &scanned_dir, &known_session_ids, demo)167
})168
.await;159
.await;169
this.update(cx, |this, cx| {160
this.update(cx, |this, cx| {170
if this.external_generation == generation {161
this.external_sessions = merged_options(171
this.external_sessions =162
&loaded.desktop,172
external_options(&loaded.sessions, &working_dir, Utc::now());163
&loaded.running,173
mark_live_runs(&mut this.run_sessions, &loaded.live_session_ids);164
&loaded.sessions_dir,174
cx.notify();165
&known_session_ids,175
}166
Utc::now(),167
);168
attach_inboxes(&mut this.run_sessions, &loaded);169
cx.notify();176
})170
})177
.ok();171
.ok();178
})172
})@@ -198,10 +192,7 @@ impl StartDialog {198
}192
}199
193
200
fn choose_working_dir(&mut self, working_dir: String, cx: &mut Context<Self>) {194
fn choose_working_dir(&mut self, working_dir: String, cx: &mut Context<Self>) {201
if self.working_dir != working_dir {195
self.working_dir = working_dir;202
self.working_dir = working_dir;203
self.reload_external(cx);204
}205
cx.notify();196
cx.notify();206
}197
}207
198
@@ -262,7 +253,7 @@ impl StartDialog {262
session: Some(SessionTarget {253
session: Some(SessionTarget {263
session_id: session.session_id.clone(),254
session_id: session.session_id.clone(),264
working_dir: session.working_dir.clone(),255
working_dir: session.working_dir.clone(),265
fork: session.fork,256
inbox: session.inbox.clone(),266
}),257
}),267
},258
},268
None => StartOptions {259
None => StartOptions {@@ -411,10 +402,7 @@ impl StartDialog {411
}402
}412
if !self.external_sessions.is_empty() {403
if !self.external_sessions.is_empty() {413
parts.push(MenuPart::Separator);404
parts.push(MenuPart::Separator);414
parts.push(MenuPart::Header(format!(405
parts.push(MenuPart::Header("Other sessions".to_owned()));415
"Other sessions in {}",416
self.working_dir417
)));418
parts.extend(self.external_sessions.iter().map(row));406
parts.extend(self.external_sessions.iter().map(row));419
}407
}420
parts408
parts