| 1 | use std::collections::HashSet; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | |
| 4 | use agents::{DesktopSession, Environment, RunningSession}; |
| 5 | use chrono::{DateTime, Datelike, Local, Utc}; |
| 6 | use mcp::install::{Homes, Location}; |
| 7 | |
| 8 | use super::message_context; |
| 9 | use super::runs::{AgentRun, InboxTarget, RunState}; |
| 10 | use crate::agent_api::agent_homes; |
| 11 | use crate::app_state::AppState; |
| 12 | use crate::notice::truncated; |
| 13 | |
| 14 | pub const SESSION_LIMIT: usize = 10; |
| 15 | const LABEL_CHARS: usize = 60; |
| 16 | const WEEK_DAYS: i64 = 7; |
| 17 | |
| 18 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 19 | pub 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 | |
| 28 | pub 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 | let weekday = then.with_timezone(&Local).weekday(); |
| 38 | crate::format::weekday_name(weekday, crate::format::WeekdayWidth::Short) |
| 39 | } else { |
| 40 | crate::format::day_month_label(then.with_timezone(&Local).date_naive()) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | fn run_meta(run: &AgentRun, now: DateTime<Utc>) -> String { |
| 45 | let age = relative_age(now, run.ended_at.unwrap_or(run.started_at)); |
| 46 | match run.state { |
| 47 | RunState::Running => "Running".to_owned(), |
| 48 | RunState::Done => format!("Done - {age}"), |
| 49 | RunState::Failed { .. } => format!("Failed - {age}"), |
| 50 | RunState::Stopped => format!("Stopped - {age}"), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | pub fn run_options(runs: &[&AgentRun], state: &AppState, now: DateTime<Utc>) -> Vec<SessionOption> { |
| 55 | let mut seen = HashSet::new(); |
| 56 | runs.iter() |
| 57 | .filter(|run| { |
| 58 | !run.session_id.is_empty() |
| 59 | && (run.launched || run.sent_to.is_some()) |
| 60 | && seen.insert(run.session_id.clone()) |
| 61 | }) |
| 62 | .take(SESSION_LIMIT) |
| 63 | .map(|run| { |
| 64 | let message = |
| 65 | message_context::message_line(state, &run.conversation_id, &run.message_id) |
| 66 | .unwrap_or_else(|| run.chat_title.clone()); |
| 67 | SessionOption { |
| 68 | session_id: run.session_id.clone(), |
| 69 | working_dir: run.working_dir.clone(), |
| 70 | label: format!( |
| 71 | "{} - {}", |
| 72 | run.action_label, |
| 73 | truncated(&message, LABEL_CHARS) |
| 74 | ), |
| 75 | meta: run_meta(run, now), |
| 76 | running: run.is_running(), |
| 77 | inbox: None, |
| 78 | } |
| 79 | }) |
| 80 | .collect() |
| 81 | } |
| 82 | |
| 83 | pub fn merged_options( |
| 84 | desktop: &[DesktopSession], |
| 85 | running: &[RunningSession], |
| 86 | sessions_dir: &Path, |
| 87 | known_session_ids: &HashSet<String>, |
| 88 | now: DateTime<Utc>, |
| 89 | ) -> Vec<SessionOption> { |
| 90 | let mut seen = known_session_ids.clone(); |
| 91 | let mut entries: Vec<(SessionOption, i64)> = Vec::new(); |
| 92 | for session in running { |
| 93 | if !seen.insert(session.session_id.clone()) { |
| 94 | continue; |
| 95 | } |
| 96 | let desktop_session = desktop |
| 97 | .iter() |
| 98 | .find(|candidate| candidate.session_id == session.session_id); |
| 99 | let title = desktop_session |
| 100 | .map(|candidate| candidate.title.clone()) |
| 101 | .filter(|title| !title.is_empty()) |
| 102 | .or_else(|| session.name.clone()) |
| 103 | .unwrap_or_else(|| session.session_id.clone()); |
| 104 | let working_dir = desktop_session |
| 105 | .map(|candidate| candidate.working_dir.clone()) |
| 106 | .filter(|working_dir| !working_dir.is_empty()) |
| 107 | .unwrap_or_else(|| session.working_dir.clone()); |
| 108 | entries.push(( |
| 109 | SessionOption { |
| 110 | session_id: session.session_id.clone(), |
| 111 | working_dir, |
| 112 | label: truncated(&title, LABEL_CHARS), |
| 113 | meta: "Running".to_owned(), |
| 114 | running: true, |
| 115 | inbox: Some(InboxTarget { |
| 116 | session: session.clone(), |
| 117 | sessions_dir: sessions_dir.to_path_buf(), |
| 118 | }), |
| 119 | }, |
| 120 | desktop_session.map_or(0, |candidate| candidate.last_activity_millis), |
| 121 | )); |
| 122 | } |
| 123 | for session in desktop { |
| 124 | if !seen.insert(session.session_id.clone()) { |
| 125 | continue; |
| 126 | } |
| 127 | let activity = DateTime::<Utc>::from_timestamp_millis(session.last_activity_millis); |
| 128 | entries.push(( |
| 129 | SessionOption { |
| 130 | session_id: session.session_id.clone(), |
| 131 | working_dir: session.working_dir.clone(), |
| 132 | label: truncated(&session.title, LABEL_CHARS), |
| 133 | meta: activity.map_or_else( |
| 134 | || "Idle".to_owned(), |
| 135 | |activity| format!("Idle - {}", relative_age(now, activity)), |
| 136 | ), |
| 137 | running: false, |
| 138 | inbox: None, |
| 139 | }, |
| 140 | session.last_activity_millis, |
| 141 | )); |
| 142 | } |
| 143 | entries.sort_by(|left, right| { |
| 144 | right |
| 145 | .0 |
| 146 | .running |
| 147 | .cmp(&left.0.running) |
| 148 | .then(right.1.cmp(&left.1)) |
| 149 | }); |
| 150 | entries |
| 151 | .into_iter() |
| 152 | .take(SESSION_LIMIT) |
| 153 | .map(|(option, _)| option) |
| 154 | .collect() |
| 155 | } |
| 156 | |
| 157 | fn pick_home<'a>(environment: &Environment, homes: &'a Homes) -> Option<&'a PathBuf> { |
| 158 | homes |
| 159 | .entries |
| 160 | .iter() |
| 161 | .find(|(location, _)| match (environment, location) { |
| 162 | (Environment::Host, Location::Windows | Location::Native) => true, |
| 163 | ( |
| 164 | Environment::Wsl { |
| 165 | distro: Some(wanted), |
| 166 | }, |
| 167 | Location::Wsl { distro }, |
| 168 | ) => wanted == distro, |
| 169 | (Environment::Wsl { distro: None }, Location::Wsl { .. }) => true, |
| 170 | (Environment::Wsl { .. }, Location::Native) => true, |
| 171 | _ => false, |
| 172 | }) |
| 173 | .map(|(_, home)| home) |
| 174 | } |
| 175 | |
| 176 | fn registry_dir(environment: &Environment, homes: &Homes) -> Option<PathBuf> { |
| 177 | Some( |
| 178 | pick_home(environment, homes)? |
| 179 | .join(".claude") |
| 180 | .join("sessions"), |
| 181 | ) |
| 182 | } |
| 183 | |
| 184 | fn desktop_dir() -> Option<PathBuf> { |
| 185 | std::env::var_os("APPDATA").map(|appdata| PathBuf::from(appdata).join("Claude")) |
| 186 | } |
| 187 | |
| 188 | #[derive(Default)] |
| 189 | pub struct SessionLoad { |
| 190 | pub desktop: Vec<DesktopSession>, |
| 191 | pub running: Vec<RunningSession>, |
| 192 | pub sessions_dir: PathBuf, |
| 193 | } |
| 194 | |
| 195 | pub fn load_sessions(environment: &Environment, demo: bool) -> SessionLoad { |
| 196 | let Some(sessions_dir) = registry_dir(environment, &agent_homes(demo)) else { |
| 197 | return SessionLoad::default(); |
| 198 | }; |
| 199 | SessionLoad { |
| 200 | desktop: if demo { |
| 201 | Vec::new() |
| 202 | } else { |
| 203 | desktop_dir() |
| 204 | .map(|directory| agents::desktop_sessions(&directory)) |
| 205 | .unwrap_or_default() |
| 206 | }, |
| 207 | running: agents::running_sessions(&sessions_dir), |
| 208 | sessions_dir, |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | pub fn attach_inboxes(options: &mut [SessionOption], load: &SessionLoad) { |
| 213 | for option in options.iter_mut().filter(|option| !option.running) { |
| 214 | if let Some(session) = load |
| 215 | .running |
| 216 | .iter() |
| 217 | .find(|session| session.session_id == option.session_id) |
| 218 | { |
| 219 | option.running = true; |
| 220 | option.meta = "Running".to_owned(); |
| 221 | option.inbox = Some(InboxTarget { |
| 222 | session: session.clone(), |
| 223 | sessions_dir: load.sessions_dir.clone(), |
| 224 | }); |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | pub fn default_wsl_distro(demo: bool) -> Option<String> { |
| 230 | agent_homes(demo) |
| 231 | .entries |
| 232 | .into_iter() |
| 233 | .find_map(|(location, _)| match location { |
| 234 | Location::Wsl { distro } => Some(distro), |
| 235 | _ => None, |
| 236 | }) |
| 237 | } |
| 238 | |
| 239 | #[cfg(test)] |
| 240 | mod tests { |
| 241 | use chrono::TimeZone; |
| 242 | |
| 243 | use super::*; |
| 244 | |
| 245 | #[test] |
| 246 | fn relative_age_uses_minutes_hours_weekday_and_date() { |
| 247 | let now = Utc.with_ymd_and_hms(2026, 10, 13, 12, 0, 0).unwrap(); |
| 248 | let ago = |seconds: i64| relative_age(now, now - chrono::Duration::seconds(seconds)); |
| 249 | assert_eq!(ago(20), "now"); |
| 250 | assert_eq!(ago(5 * 60), "5m"); |
| 251 | assert_eq!(ago(3 * 3600), "3h"); |
| 252 | assert_eq!(ago(2 * 86400).len(), 3); |
| 253 | assert!(ago(10 * 86400).contains(char::is_whitespace)); |
| 254 | } |
| 255 | |
| 256 | #[test] |
| 257 | fn runs_that_never_created_a_session_are_left_out() { |
| 258 | let state = AppState::new( |
| 259 | std::sync::Arc::new(store::Store::open_in_memory().unwrap()), |
| 260 | crate::app_state::Mode::default(), |
| 261 | ); |
| 262 | let mut created = crate::agents::fixtures::finished_run(1); |
| 263 | created.launched = true; |
| 264 | let mut never_started = crate::agents::fixtures::finished_run(2); |
| 265 | never_started.launched = false; |
| 266 | let mut sent = crate::agents::fixtures::finished_run(3); |
| 267 | sent.launched = false; |
| 268 | sent.sent_to = Some(crate::agents::runs::SessionTarget { |
| 269 | session_id: sent.session_id.clone(), |
| 270 | working_dir: "~".to_owned(), |
| 271 | inbox: None, |
| 272 | }); |
| 273 | let options = run_options(&[&created, &never_started, &sent], &state, Utc::now()); |
| 274 | let ids: Vec<&str> = options |
| 275 | .iter() |
| 276 | .map(|option| option.session_id.as_str()) |
| 277 | .collect(); |
| 278 | assert_eq!(ids, ["session-1", "session-3"]); |
| 279 | } |
| 280 | |
| 281 | #[test] |
| 282 | fn the_home_matches_the_agent_environment() { |
| 283 | let homes = Homes { |
| 284 | entries: vec![ |
| 285 | (Location::Windows, PathBuf::from(r"C:\Users\dd")), |
| 286 | ( |
| 287 | Location::Wsl { |
| 288 | distro: "Ubuntu".to_owned(), |
| 289 | }, |
| 290 | PathBuf::from(r"\\wsl.localhost\Ubuntu\home\daniel"), |
| 291 | ), |
| 292 | ], |
| 293 | }; |
| 294 | let wsl = |distro: Option<&str>| Environment::Wsl { |
| 295 | distro: distro.map(str::to_owned), |
| 296 | }; |
| 297 | assert_eq!( |
| 298 | pick_home(&Environment::Host, &homes), |
| 299 | Some(&PathBuf::from(r"C:\Users\dd")) |
| 300 | ); |
| 301 | assert!(pick_home(&wsl(None), &homes).is_some()); |
| 302 | assert!(pick_home(&wsl(Some("Ubuntu")), &homes).is_some()); |
| 303 | assert_eq!(pick_home(&wsl(Some("Debian")), &homes), None); |
| 304 | } |
| 305 | |
| 306 | fn desktop(session_id: &str, last_activity_millis: i64) -> DesktopSession { |
| 307 | DesktopSession { |
| 308 | session_id: session_id.to_owned(), |
| 309 | working_dir: format!("/srv/{session_id}"), |
| 310 | title: format!("Title {session_id}"), |
| 311 | last_activity_millis, |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | fn running(session_id: &str) -> RunningSession { |
| 316 | RunningSession { |
| 317 | session_id: session_id.to_owned(), |
| 318 | name: Some(format!("Name {session_id}")), |
| 319 | working_dir: "/registry".to_owned(), |
| 320 | socket_path: Some("/run/s.sock".to_owned()), |
| 321 | process_id: 7, |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | fn ids(options: &[SessionOption]) -> Vec<&str> { |
| 326 | options |
| 327 | .iter() |
| 328 | .map(|option| option.session_id.as_str()) |
| 329 | .collect() |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn running_sessions_come_first_then_the_newest_activity() { |
| 334 | let options = merged_options( |
| 335 | &[ |
| 336 | desktop("old", 1_000), |
| 337 | desktop("live", 500), |
| 338 | desktop("new", 9_000), |
| 339 | ], |
| 340 | &[running("live"), running("registry-only")], |
| 341 | Path::new("/sessions"), |
| 342 | &HashSet::new(), |
| 343 | Utc::now(), |
| 344 | ); |
| 345 | assert_eq!(ids(&options), ["live", "registry-only", "new", "old"]); |
| 346 | assert!(options[0].running && options[0].inbox.is_some()); |
| 347 | assert_eq!(options[0].label, "Title live"); |
| 348 | assert_eq!(options[0].working_dir, "/srv/live"); |
| 349 | assert_eq!(options[1].label, "Name registry-only"); |
| 350 | assert_eq!(options[1].working_dir, "/registry"); |
| 351 | assert!(!options[2].running && options[2].inbox.is_none()); |
| 352 | } |
| 353 | |
| 354 | #[test] |
| 355 | fn known_run_ids_are_excluded_and_the_limit_applies() { |
| 356 | let sessions: Vec<DesktopSession> = (0..15) |
| 357 | .map(|index| desktop(&format!("s{index}"), index)) |
| 358 | .collect(); |
| 359 | let known = HashSet::from(["s14".to_owned(), "live".to_owned()]); |
| 360 | let options = merged_options( |
| 361 | &sessions, |
| 362 | &[running("live")], |
| 363 | Path::new("/sessions"), |
| 364 | &known, |
| 365 | Utc::now(), |
| 366 | ); |
| 367 | assert_eq!(options.len(), SESSION_LIMIT); |
| 368 | assert_eq!(options[0].session_id, "s13"); |
| 369 | assert!(!ids(&options).contains(&"live")); |
| 370 | } |
| 371 | |
| 372 | #[test] |
| 373 | fn a_session_known_to_the_registry_gets_an_inbox_on_a_run_option() { |
| 374 | let option = |session_id: &str, running: bool| SessionOption { |
| 375 | session_id: session_id.to_owned(), |
| 376 | working_dir: "/repo".to_owned(), |
| 377 | label: String::new(), |
| 378 | meta: String::new(), |
| 379 | running, |
| 380 | inbox: None, |
| 381 | }; |
| 382 | let mut options = vec![option("a", false), option("b", false), option("c", true)]; |
| 383 | let load = SessionLoad { |
| 384 | desktop: Vec::new(), |
| 385 | running: vec![running("a"), running("c")], |
| 386 | sessions_dir: PathBuf::from("/sessions"), |
| 387 | }; |
| 388 | attach_inboxes(&mut options, &load); |
| 389 | let inboxes: Vec<bool> = options |
| 390 | .iter() |
| 391 | .map(|option| option.inbox.is_some()) |
| 392 | .collect(); |
| 393 | assert_eq!(inboxes, [true, false, false]); |
| 394 | assert!(options[0].running); |
| 395 | } |
| 396 | } |