BlueGit

ict rusty-teams

Files

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

session_options.rs

session_options.rs 13.1 KiB Download Raw
1use std::collections::HashSet;
2use std::path::{Path, PathBuf};
3
4use agents::{DesktopSession, Environment, RunningSession};
5use chrono::{DateTime, Local, Utc};
6use mcp::install::{Homes, Location};
7
8use super::message_context;
9use super::runs::{AgentRun, InboxTarget, RunState};
10use crate::agent_api::agent_homes;
11use crate::app_state::AppState;
12use crate::notice::truncated;
13
14pub const SESSION_LIMIT: usize = 10;
15const LABEL_CHARS: usize = 60;
16const WEEK_DAYS: i64 = 7;
17
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct SessionOption {
20 pub session_id: String,
21 pub working_dir: String,
22 pub label: String,
23 pub meta: String,
24 pub running: bool,
25 pub inbox: Option<InboxTarget>,
26}
27
28pub fn relative_age(now: DateTime<Utc>, then: DateTime<Utc>) -> String {
29 let age = now - then;
30 if age.num_minutes() < 1 {
31 "now".to_owned()
32 } else if age.num_hours() < 1 {
33 format!("{}m", age.num_minutes())
34 } else if age.num_days() < 1 {
35 format!("{}h", age.num_hours())
36 } else if age.num_days() < WEEK_DAYS {
37 then.with_timezone(&Local).format("%a").to_string()
38 } else {
39 then.with_timezone(&Local).format("%b %-d").to_string()
40 }
41}
42
43fn run_meta(run: &AgentRun, now: DateTime<Utc>) -> String {
44 let age = relative_age(now, run.ended_at.unwrap_or(run.started_at));
45 match run.state {
46 RunState::Running => "Running".to_owned(),
47 RunState::Done => format!("Done - {age}"),
48 RunState::Failed { .. } => format!("Failed - {age}"),
49 RunState::Stopped => format!("Stopped - {age}"),
50 }
51}
52
53pub fn run_options(runs: &[&AgentRun], state: &AppState, now: DateTime<Utc>) -> Vec<SessionOption> {
54 let mut seen = HashSet::new();
55 runs.iter()
56 .filter(|run| {
57 !run.session_id.is_empty()
58 && (run.launched || run.sent_to.is_some())
59 && seen.insert(run.session_id.clone())
60 })
61 .take(SESSION_LIMIT)
62 .map(|run| {
63 let message =
64 message_context::message_line(state, &run.conversation_id, &run.message_id)
65 .unwrap_or_else(|| run.chat_title.clone());
66 SessionOption {
67 session_id: run.session_id.clone(),
68 working_dir: run.working_dir.clone(),
69 label: format!(
70 "{} - {}",
71 run.action_label,
72 truncated(&message, LABEL_CHARS)
73 ),
74 meta: run_meta(run, now),
75 running: run.is_running(),
76 inbox: None,
77 }
78 })
79 .collect()
80}
81
82pub fn merged_options(
83 desktop: &[DesktopSession],
84 running: &[RunningSession],
85 sessions_dir: &Path,
86 known_session_ids: &HashSet<String>,
87 now: DateTime<Utc>,
88) -> Vec<SessionOption> {
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((
128 SessionOption {
129 session_id: session.session_id.clone(),
130 working_dir: session.working_dir.clone(),
131 label: truncated(&session.title, LABEL_CHARS),
132 meta: activity.map_or_else(
133 || "Idle".to_owned(),
134 |activity| format!("Idle - {}", relative_age(now, activity)),
135 ),
136 running: false,
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)
153 .collect()
154}
155
156fn pick_home<'a>(environment: &Environment, homes: &'a Homes) -> Option<&'a PathBuf> {
157 homes
158 .entries
159 .iter()
160 .find(|(location, _)| match (environment, location) {
161 (Environment::Host, Location::Windows | Location::Native) => true,
162 (
163 Environment::Wsl {
164 distro: Some(wanted),
165 },
166 Location::Wsl { distro },
167 ) => wanted == distro,
168 (Environment::Wsl { distro: None }, Location::Wsl { .. }) => true,
169 (Environment::Wsl { .. }, Location::Native) => true,
170 _ => false,
171 })
172 .map(|(_, home)| home)
173}
174
175fn registry_dir(environment: &Environment, homes: &Homes) -> Option<PathBuf> {
176 Some(
177 pick_home(environment, homes)?
178 .join(".claude")
179 .join("sessions"),
180 )
181}
182
183fn desktop_dir() -> Option<PathBuf> {
184 std::env::var_os("APPDATA").map(|appdata| PathBuf::from(appdata).join("Claude"))
185}
186
187#[derive(Default)]
188pub struct SessionLoad {
189 pub desktop: Vec<DesktopSession>,
190 pub running: Vec<RunningSession>,
191 pub sessions_dir: PathBuf,
192}
193
194pub fn load_sessions(environment: &Environment, demo: bool) -> SessionLoad {
195 let Some(sessions_dir) = registry_dir(environment, &agent_homes(demo)) else {
196 return SessionLoad::default();
197 };
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,
208 }
209}
210
211pub 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 }
225 }
226}
227
228pub fn default_wsl_distro(demo: bool) -> Option<String> {
229 agent_homes(demo)
230 .entries
231 .into_iter()
232 .find_map(|(location, _)| match location {
233 Location::Wsl { distro } => Some(distro),
234 _ => None,
235 })
236}
237
238#[cfg(test)]
239mod tests {
240 use chrono::TimeZone;
241
242 use super::*;
243
244 #[test]
245 fn relative_age_uses_minutes_hours_weekday_and_date() {
246 let now = Utc.with_ymd_and_hms(2026, 10, 13, 12, 0, 0).unwrap();
247 let ago = |seconds: i64| relative_age(now, now - chrono::Duration::seconds(seconds));
248 assert_eq!(ago(20), "now");
249 assert_eq!(ago(5 * 60), "5m");
250 assert_eq!(ago(3 * 3600), "3h");
251 assert_eq!(ago(2 * 86400).len(), 3);
252 assert!(ago(10 * 86400).contains(char::is_whitespace));
253 }
254
255 #[test]
256 fn runs_that_never_created_a_session_are_left_out() {
257 let state = AppState::new(
258 std::sync::Arc::new(store::Store::open_in_memory().unwrap()),
259 crate::app_state::Mode::default(),
260 );
261 let mut created = crate::agents::fixtures::finished_run(1);
262 created.launched = true;
263 let mut never_started = crate::agents::fixtures::finished_run(2);
264 never_started.launched = false;
265 let mut sent = crate::agents::fixtures::finished_run(3);
266 sent.launched = false;
267 sent.sent_to = Some(crate::agents::runs::SessionTarget {
268 session_id: sent.session_id.clone(),
269 working_dir: "~".to_owned(),
270 inbox: None,
271 });
272 let options = run_options(&[&created, &never_started, &sent], &state, Utc::now());
273 let ids: Vec<&str> = options
274 .iter()
275 .map(|option| option.session_id.as_str())
276 .collect();
277 assert_eq!(ids, ["session-1", "session-3"]);
278 }
279
280 #[test]
281 fn the_home_matches_the_agent_environment() {
282 let homes = Homes {
283 entries: vec![
284 (Location::Windows, PathBuf::from(r"C:\Users\dd")),
285 (
286 Location::Wsl {
287 distro: "Ubuntu".to_owned(),
288 },
289 PathBuf::from(r"\\wsl.localhost\Ubuntu\home\daniel"),
290 ),
291 ],
292 };
293 let wsl = |distro: Option<&str>| Environment::Wsl {
294 distro: distro.map(str::to_owned),
295 };
296 assert_eq!(
297 pick_home(&Environment::Host, &homes),
298 Some(&PathBuf::from(r"C:\Users\dd"))
299 );
300 assert!(pick_home(&wsl(None), &homes).is_some());
301 assert!(pick_home(&wsl(Some("Ubuntu")), &homes).is_some());
302 assert_eq!(pick_home(&wsl(Some("Debian")), &homes), None);
303 }
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
331 #[test]
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(),
343 );
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(),
365 );
366 assert_eq!(options.len(), SESSION_LIMIT);
367 assert_eq!(options[0].session_id, "s13");
368 assert!(!ids(&options).contains(&"live"));
369 }
370
371 #[test]
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,
380 };
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);
394 }
395}