| 1 | use std::collections::HashSet; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use agents::{Environment, ExternalSession}; |
| 6 | use chrono::{DateTime, Local, Utc}; |
| 7 | use mcp::install::{Homes, Location}; |
| 8 | |
| 9 | use super::message_context; |
| 10 | use super::runs::{AgentRun, RunState}; |
| 11 | use crate::agent_api::agent_homes; |
| 12 | use crate::app_state::AppState; |
| 13 | use crate::notice::truncated; |
| 14 | |
| 15 | pub const SESSION_LIMIT: usize = 10; |
| 16 | const ACTIVE_WINDOW: Duration = Duration::from_secs(120); |
| 17 | const LABEL_CHARS: usize = 60; |
| 18 | const WEEK_DAYS: i64 = 7; |
| 19 | |
| 20 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 21 | pub struct SessionOption { |
| 22 | pub session_id: String, |
| 23 | pub working_dir: String, |
| 24 | pub label: String, |
| 25 | pub meta: String, |
| 26 | pub running: bool, |
| 27 | pub fork: bool, |
| 28 | } |
| 29 | |
| 30 | pub fn relative_age(now: DateTime<Utc>, then: DateTime<Utc>) -> String { |
| 31 | let age = now - then; |
| 32 | if age.num_minutes() < 1 { |
| 33 | "now".to_owned() |
| 34 | } else if age.num_hours() < 1 { |
| 35 | format!("{}m", age.num_minutes()) |
| 36 | } else if age.num_days() < 1 { |
| 37 | format!("{}h", age.num_hours()) |
| 38 | } else if age.num_days() < WEEK_DAYS { |
| 39 | then.with_timezone(&Local).format("%a").to_string() |
| 40 | } else { |
| 41 | then.with_timezone(&Local).format("%b %-d").to_string() |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | fn run_meta(run: &AgentRun, now: DateTime<Utc>) -> String { |
| 46 | let age = relative_age(now, run.ended_at.unwrap_or(run.started_at)); |
| 47 | match run.state { |
| 48 | RunState::Running => "Running".to_owned(), |
| 49 | RunState::Done => format!("Done - {age}"), |
| 50 | RunState::Failed { .. } => format!("Failed - {age}"), |
| 51 | RunState::Stopped => format!("Stopped - {age}"), |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | pub fn run_options(runs: &[&AgentRun], state: &AppState, now: DateTime<Utc>) -> Vec<SessionOption> { |
| 56 | let mut seen = HashSet::new(); |
| 57 | runs.iter() |
| 58 | .filter(|run| { |
| 59 | !run.session_id.is_empty() |
| 60 | && (run.launched || run.sent_to.is_some()) |
| 61 | && seen.insert(run.session_id.clone()) |
| 62 | }) |
| 63 | .take(SESSION_LIMIT) |
| 64 | .map(|run| { |
| 65 | let message = |
| 66 | message_context::message_line(state, &run.conversation_id, &run.message_id) |
| 67 | .unwrap_or_else(|| run.chat_title.clone()); |
| 68 | SessionOption { |
| 69 | session_id: run.session_id.clone(), |
| 70 | working_dir: run.working_dir.clone(), |
| 71 | label: format!( |
| 72 | "{} - {}", |
| 73 | run.action_label, |
| 74 | truncated(&message, LABEL_CHARS) |
| 75 | ), |
| 76 | meta: run_meta(run, now), |
| 77 | running: run.is_running(), |
| 78 | fork: false, |
| 79 | } |
| 80 | }) |
| 81 | .collect() |
| 82 | } |
| 83 | |
| 84 | pub fn external_options( |
| 85 | sessions: &[ExternalSession], |
| 86 | working_dir: &str, |
| 87 | now: DateTime<Utc>, |
| 88 | ) -> Vec<SessionOption> { |
| 89 | sessions |
| 90 | .iter() |
| 91 | .map(|session| { |
| 92 | let modified = DateTime::<Utc>::from(session.modified); |
| 93 | let active = session.live |
| 94 | || modified > now |
| 95 | || (now - modified) |
| 96 | .to_std() |
| 97 | .is_ok_and(|age| age < ACTIVE_WINDOW); |
| 98 | SessionOption { |
| 99 | session_id: session.session_id.clone(), |
| 100 | working_dir: working_dir.to_owned(), |
| 101 | label: truncated(&session.title, LABEL_CHARS), |
| 102 | meta: if active { |
| 103 | "Active elsewhere - sends to a copy".to_owned() |
| 104 | } else { |
| 105 | format!("Idle - {}", relative_age(now, modified)) |
| 106 | }, |
| 107 | running: false, |
| 108 | fork: active, |
| 109 | } |
| 110 | }) |
| 111 | .collect() |
| 112 | } |
| 113 | |
| 114 | fn pick_home<'a>(environment: &Environment, homes: &'a Homes) -> Option<&'a PathBuf> { |
| 115 | homes |
| 116 | .entries |
| 117 | .iter() |
| 118 | .find(|(location, _)| match (environment, location) { |
| 119 | (Environment::Host, Location::Windows | Location::Native) => true, |
| 120 | ( |
| 121 | Environment::Wsl { |
| 122 | distro: Some(wanted), |
| 123 | }, |
| 124 | Location::Wsl { distro }, |
| 125 | ) => wanted == distro, |
| 126 | (Environment::Wsl { distro: None }, Location::Wsl { .. }) => true, |
| 127 | (Environment::Wsl { .. }, Location::Native) => true, |
| 128 | _ => false, |
| 129 | }) |
| 130 | .map(|(_, home)| home) |
| 131 | } |
| 132 | |
| 133 | fn resolve_working_dir(environment: &Environment, working_dir: &str, home: &Path) -> String { |
| 134 | let home_text = home.to_string_lossy(); |
| 135 | let home_text = match environment { |
| 136 | Environment::Host => home_text.into_owned(), |
| 137 | Environment::Wsl { .. } => agents::linux_path(&home_text), |
| 138 | }; |
| 139 | match working_dir.strip_prefix('~') { |
| 140 | Some(rest) if rest.is_empty() || rest.starts_with(['/', '\\']) => { |
| 141 | format!("{home_text}{rest}") |
| 142 | } |
| 143 | _ => working_dir.to_owned(), |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | fn claude_dirs( |
| 148 | environment: &Environment, |
| 149 | working_dir: &str, |
| 150 | homes: &Homes, |
| 151 | ) -> Option<(PathBuf, PathBuf)> { |
| 152 | let home = pick_home(environment, homes)?; |
| 153 | let resolved = resolve_working_dir(environment, working_dir, home); |
| 154 | let claude = home.join(".claude"); |
| 155 | Some(( |
| 156 | agents::resolve_project_dir(&claude.join("projects"), &resolved), |
| 157 | claude.join("sessions"), |
| 158 | )) |
| 159 | } |
| 160 | |
| 161 | #[derive(Default)] |
| 162 | pub struct ExternalLoad { |
| 163 | pub sessions: Vec<ExternalSession>, |
| 164 | pub live_session_ids: HashSet<String>, |
| 165 | } |
| 166 | |
| 167 | pub fn load_external( |
| 168 | environment: &Environment, |
| 169 | working_dir: &str, |
| 170 | known_session_ids: &HashSet<String>, |
| 171 | demo: bool, |
| 172 | ) -> ExternalLoad { |
| 173 | let Some((project_dir, sessions_dir)) = |
| 174 | claude_dirs(environment, working_dir, &agent_homes(demo)) |
| 175 | else { |
| 176 | return ExternalLoad::default(); |
| 177 | }; |
| 178 | let live = agents::live_session_names(&sessions_dir); |
| 179 | ExternalLoad { |
| 180 | sessions: agents::scan_external_sessions( |
| 181 | &project_dir, |
| 182 | &live, |
| 183 | known_session_ids, |
| 184 | SESSION_LIMIT, |
| 185 | ), |
| 186 | live_session_ids: live.into_keys().collect(), |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | pub fn mark_live_runs(options: &mut [SessionOption], live_session_ids: &HashSet<String>) { |
| 191 | for option in options { |
| 192 | option.fork = !option.running && live_session_ids.contains(&option.session_id); |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | pub fn default_wsl_distro(demo: bool) -> Option<String> { |
| 197 | agent_homes(demo) |
| 198 | .entries |
| 199 | .into_iter() |
| 200 | .find_map(|(location, _)| match location { |
| 201 | Location::Wsl { distro } => Some(distro), |
| 202 | _ => None, |
| 203 | }) |
| 204 | } |
| 205 | |
| 206 | #[cfg(test)] |
| 207 | mod tests { |
| 208 | use std::time::SystemTime; |
| 209 | |
| 210 | use chrono::TimeZone; |
| 211 | |
| 212 | use super::*; |
| 213 | |
| 214 | fn external(age: Duration) -> ExternalSession { |
| 215 | ExternalSession { |
| 216 | session_id: "abc".to_owned(), |
| 217 | title: "Fix the build".to_owned(), |
| 218 | modified: SystemTime::now() - age, |
| 219 | live: false, |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | #[test] |
| 224 | fn relative_age_uses_minutes_hours_weekday_and_date() { |
| 225 | let now = Utc.with_ymd_and_hms(2026, 10, 13, 12, 0, 0).unwrap(); |
| 226 | let ago = |seconds: i64| relative_age(now, now - chrono::Duration::seconds(seconds)); |
| 227 | assert_eq!(ago(20), "now"); |
| 228 | assert_eq!(ago(5 * 60), "5m"); |
| 229 | assert_eq!(ago(3 * 3600), "3h"); |
| 230 | assert_eq!(ago(2 * 86400).len(), 3); |
| 231 | assert!(ago(10 * 86400).contains(char::is_whitespace)); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn external_sessions_are_active_under_two_minutes_and_fork() { |
| 236 | let now = Utc::now(); |
| 237 | let options = external_options( |
| 238 | &[ |
| 239 | external(Duration::from_secs(30)), |
| 240 | external(Duration::from_secs(3 * 3600 + 30)), |
| 241 | ], |
| 242 | "/repo", |
| 243 | now, |
| 244 | ); |
| 245 | assert_eq!(options[0].meta, "Active elsewhere - sends to a copy"); |
| 246 | assert!(options[0].fork); |
| 247 | assert_eq!(options[1].meta, "Idle - 3h"); |
| 248 | assert!(!options[1].fork); |
| 249 | assert_eq!(options[1].label, "Fix the build"); |
| 250 | assert_eq!(options[1].working_dir, "/repo"); |
| 251 | let live = ExternalSession { |
| 252 | live: true, |
| 253 | ..external(Duration::from_secs(3 * 3600)) |
| 254 | }; |
| 255 | let options = external_options(&[live], "/repo", now); |
| 256 | assert_eq!(options[0].meta, "Active elsewhere - sends to a copy"); |
| 257 | assert!(options[0].fork); |
| 258 | } |
| 259 | |
| 260 | #[test] |
| 261 | fn app_sessions_open_in_a_terminal_are_forked_unless_running_here() { |
| 262 | let option = |session_id: &str, running: bool| SessionOption { |
| 263 | session_id: session_id.to_owned(), |
| 264 | working_dir: "/repo".to_owned(), |
| 265 | label: String::new(), |
| 266 | meta: String::new(), |
| 267 | running, |
| 268 | fork: false, |
| 269 | }; |
| 270 | let mut options = vec![option("a", false), option("b", false), option("c", true)]; |
| 271 | mark_live_runs( |
| 272 | &mut options, |
| 273 | &HashSet::from(["a".to_owned(), "c".to_owned()]), |
| 274 | ); |
| 275 | let forks: Vec<bool> = options.iter().map(|option| option.fork).collect(); |
| 276 | assert_eq!(forks, [true, false, false]); |
| 277 | } |
| 278 | |
| 279 | #[test] |
| 280 | fn runs_that_never_created_a_session_are_left_out() { |
| 281 | let state = AppState::new( |
| 282 | std::sync::Arc::new(store::Store::open_in_memory().unwrap()), |
| 283 | crate::app_state::Mode::default(), |
| 284 | ); |
| 285 | let mut created = crate::agents::runs::tests::finished_run(1); |
| 286 | created.launched = true; |
| 287 | let mut never_started = crate::agents::runs::tests::finished_run(2); |
| 288 | never_started.launched = false; |
| 289 | let mut sent = crate::agents::runs::tests::finished_run(3); |
| 290 | sent.launched = false; |
| 291 | sent.sent_to = Some(crate::agents::runs::SessionTarget { |
| 292 | session_id: sent.session_id.clone(), |
| 293 | working_dir: "~".to_owned(), |
| 294 | fork: false, |
| 295 | }); |
| 296 | let options = run_options(&[&created, &never_started, &sent], &state, Utc::now()); |
| 297 | let ids: Vec<&str> = options |
| 298 | .iter() |
| 299 | .map(|option| option.session_id.as_str()) |
| 300 | .collect(); |
| 301 | assert_eq!(ids, ["session-1", "session-3"]); |
| 302 | } |
| 303 | |
| 304 | #[test] |
| 305 | fn the_home_matches_the_agent_environment() { |
| 306 | let homes = Homes { |
| 307 | entries: vec![ |
| 308 | (Location::Windows, PathBuf::from(r"C:\Users\dd")), |
| 309 | ( |
| 310 | Location::Wsl { |
| 311 | distro: "Ubuntu".to_owned(), |
| 312 | }, |
| 313 | PathBuf::from(r"\\wsl.localhost\Ubuntu\home\daniel"), |
| 314 | ), |
| 315 | ], |
| 316 | }; |
| 317 | let wsl = |distro: Option<&str>| Environment::Wsl { |
| 318 | distro: distro.map(str::to_owned), |
| 319 | }; |
| 320 | assert_eq!( |
| 321 | pick_home(&Environment::Host, &homes), |
| 322 | Some(&PathBuf::from(r"C:\Users\dd")) |
| 323 | ); |
| 324 | assert!(pick_home(&wsl(None), &homes).is_some()); |
| 325 | assert!(pick_home(&wsl(Some("Ubuntu")), &homes).is_some()); |
| 326 | assert_eq!(pick_home(&wsl(Some("Debian")), &homes), None); |
| 327 | } |
| 328 | |
| 329 | #[test] |
| 330 | fn a_wsl_home_encodes_the_linux_path_of_the_working_dir() { |
| 331 | let homes = Homes { |
| 332 | entries: vec![( |
| 333 | Location::Wsl { |
| 334 | distro: "Ubuntu".to_owned(), |
| 335 | }, |
| 336 | PathBuf::from(r"\\wsl.localhost\Ubuntu\home\daniel"), |
| 337 | )], |
| 338 | }; |
| 339 | let environment = Environment::Wsl { distro: None }; |
| 340 | let (directory, sessions) = claude_dirs(&environment, "~/Projects/x", &homes).unwrap(); |
| 341 | assert!(sessions.ends_with(".claude/sessions")); |
| 342 | assert_eq!( |
| 343 | directory.file_name().unwrap().to_string_lossy(), |
| 344 | "-home-daniel-Projects-x" |
| 345 | ); |
| 346 | assert_eq!( |
| 347 | resolve_working_dir(&environment, "/srv/app", Path::new("/home/daniel")), |
| 348 | "/srv/app" |
| 349 | ); |
| 350 | } |
| 351 | |
| 352 | #[test] |
| 353 | fn a_host_home_expands_the_tilde_before_encoding() { |
| 354 | let homes = Homes { |
| 355 | entries: vec![(Location::Native, PathBuf::from("/home/daniel"))], |
| 356 | }; |
| 357 | let (directory, _) = claude_dirs(&Environment::Host, "~", &homes).unwrap(); |
| 358 | assert!(directory.ends_with(".claude/projects/-home-daniel")); |
| 359 | } |
| 360 | } |