BlueGit

ict rusty-teams

Files

rusty-teams / crates / agents / src / sessions.rs

sessions.rs

sessions.rs 21.0 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::fs::File;
3use std::io::{BufRead, BufReader, Read};
4use std::path::{Path, PathBuf};
5use std::time::SystemTime;
6
7use serde::{Deserialize, Serialize};
8
9const TITLE_READ_LIMIT: u64 = 1024 * 1024;
10const PROJECT_DIR_NAME_LIMIT: usize = 200;
11
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub struct ExternalSession {
14 pub session_id: String,
15 pub title: String,
16 pub modified: SystemTime,
17 pub live: bool,
18}
19
20pub fn encode_project_dir(working_dir: &str) -> String {
21 working_dir
22 .chars()
23 .map(|character| {
24 if character.is_ascii_alphanumeric() {
25 character
26 } else {
27 '-'
28 }
29 })
30 .collect()
31}
32
33pub fn resolve_project_dir(projects_dir: &Path, working_dir: &str) -> PathBuf {
34 let trimmed = working_dir.trim_end_matches(['/', '\\']);
35 let encoded = encode_project_dir(if trimmed.is_empty() {
36 working_dir
37 } else {
38 trimmed
39 });
40 let exact = projects_dir.join(&encoded);
41 if exact.exists() || encoded.len() <= PROJECT_DIR_NAME_LIMIT {
42 return exact;
43 }
44 let prefix = &encoded[..PROJECT_DIR_NAME_LIMIT];
45 std::fs::read_dir(projects_dir)
46 .into_iter()
47 .flatten()
48 .flatten()
49 .find(|entry| entry.file_name().to_string_lossy().starts_with(prefix))
50 .map_or(exact, |entry| entry.path())
51}
52
53fn proc_root(sessions_dir: &Path) -> Option<PathBuf> {
54 let text = sessions_dir.to_string_lossy();
55 let unc = text
56 .strip_prefix(r"\\wsl.localhost\")
57 .or_else(|| text.strip_prefix(r"\\wsl$\"));
58 match unc {
59 Some(rest) => {
60 let distro = rest.split('\\').next()?;
61 let prefix = &text[..text.len() - rest.len()];
62 Some(PathBuf::from(format!("{prefix}{distro}\\proc")))
63 }
64 None if cfg!(unix) => Some(PathBuf::from("/proc")),
65 None => None,
66 }
67}
68
69#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
70pub 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
78pub fn running_sessions(sessions_dir: &Path) -> Vec<RunningSession> {
79 running_sessions_in(sessions_dir, proc_root(sessions_dir).as_deref())
80}
81
82pub fn live_session_names(sessions_dir: &Path) -> HashMap<String, Option<String>> {
83 running_sessions(sessions_dir)
84 .into_iter()
85 .map(|session| (session.session_id, session.name))
86 .collect()
87}
88
89fn running_sessions_in(sessions_dir: &Path, proc_root: Option<&Path>) -> Vec<RunningSession> {
90 let Ok(entries) = std::fs::read_dir(sessions_dir) else {
91 return Vec::new();
92 };
93 let checkable_root = proc_root.filter(|root| root.is_dir());
94 entries
95 .flatten()
96 .filter(|entry| {
97 let path = entry.path();
98 path.extension()
99 .is_some_and(|extension| extension == "json")
100 && checkable_root
101 .is_none_or(|root| path.file_stem().is_some_and(|pid| root.join(pid).exists()))
102 })
103 .filter_map(|entry| {
104 let value: serde_json::Value =
105 serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;
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 })
130 })
131 .collect()
132}
133
134fn is_session_file_stem(stem: &str) -> bool {
135 stem.len() == 36
136 && stem.char_indices().all(|(index, character)| {
137 if matches!(index, 8 | 13 | 18 | 23) {
138 character == '-'
139 } else {
140 character.is_ascii_hexdigit()
141 }
142 })
143}
144
145fn is_lone_tag(line: &str) -> bool {
146 let Some(inner) = line
147 .strip_prefix('<')
148 .and_then(|rest| rest.strip_suffix('>'))
149 else {
150 return false;
151 };
152 let inner = inner.strip_prefix('/').unwrap_or(inner);
153 let (name, attributes) = inner.split_once(' ').unwrap_or((inner, ""));
154 !name.is_empty()
155 && name
156 .chars()
157 .all(|character| character.is_ascii_lowercase() || character == '_' || character == '-')
158 && !attributes.contains('>')
159}
160
161fn open_tag_name(line: &str) -> Option<&str> {
162 let rest = line.strip_prefix('<')?;
163 let name_end = rest
164 .find(|character: char| {
165 !(character.is_ascii_lowercase() || character == '_' || character == '-')
166 })
167 .unwrap_or(rest.len());
168 let (name, after) = rest.split_at(name_end);
169 (!name.is_empty() && after.starts_with(['>', ' '])).then_some(name)
170}
171
172fn plain_line(text: &str) -> Option<String> {
173 let lines: Vec<&str> = text.lines().map(str::trim).collect();
174 let mut index = 0;
175 while index < lines.len() {
176 let line = lines[index];
177 if line.is_empty() {
178 index += 1;
179 continue;
180 }
181 let closing = open_tag_name(line).and_then(|name| {
182 let close = format!("</{name}>");
183 lines[index..]
184 .iter()
185 .enumerate()
186 .position(|(offset, later)| {
187 if offset == 0 {
188 later.ends_with(&close)
189 } else {
190 later.contains(&close)
191 }
192 })
193 });
194 if let Some(offset) = closing {
195 index += offset + 1;
196 } else if is_lone_tag(line) {
197 index += 1;
198 } else {
199 return Some(line.to_owned());
200 }
201 }
202 None
203}
204
205fn text_parts(content: &serde_json::Value) -> Vec<&str> {
206 match content {
207 serde_json::Value::String(text) => vec![text],
208 serde_json::Value::Array(parts) => parts
209 .iter()
210 .filter(|part| part["type"] == "text")
211 .filter_map(|part| part["text"].as_str())
212 .collect(),
213 _ => Vec::new(),
214 }
215}
216
217fn first_user_message(path: &Path) -> Option<String> {
218 let mut reader = BufReader::new(File::open(path).ok()?.take(TITLE_READ_LIMIT));
219 let mut line = Vec::new();
220 loop {
221 line.clear();
222 if reader.read_until(b'\n', &mut line).ok()? == 0 {
223 return None;
224 }
225 let Ok(entry) = serde_json::from_slice::<serde_json::Value>(&line) else {
226 continue;
227 };
228 if entry["type"] != "user" || entry["isMeta"] == true {
229 continue;
230 }
231 if let Some(title) = text_parts(&entry["message"]["content"])
232 .into_iter()
233 .find_map(plain_line)
234 {
235 return Some(title);
236 }
237 }
238}
239
240pub fn scan_external_sessions(
241 project_dir: &Path,
242 live_sessions: &HashMap<String, Option<String>>,
243 known_session_ids: &HashSet<String>,
244 limit: usize,
245) -> Vec<ExternalSession> {
246 let Ok(entries) = std::fs::read_dir(project_dir) else {
247 return Vec::new();
248 };
249 let mut files: Vec<(String, SystemTime)> = entries
250 .flatten()
251 .filter_map(|entry| {
252 let path = entry.path();
253 if path.extension()? != "jsonl" {
254 return None;
255 }
256 let session_id = path.file_stem()?.to_str()?.to_owned();
257 if !is_session_file_stem(&session_id) {
258 return None;
259 }
260 let modified = entry.metadata().ok()?.modified().ok()?;
261 (!known_session_ids.contains(&session_id)).then_some((session_id, modified))
262 })
263 .collect();
264 files.sort_by(|left, right| right.1.cmp(&left.1));
265 files
266 .into_iter()
267 .filter_map(|(session_id, modified)| {
268 let live_name = live_sessions.get(&session_id);
269 let title = live_name
270 .cloned()
271 .flatten()
272 .or_else(|| first_user_message(&project_dir.join(format!("{session_id}.jsonl"))))?;
273 Some(ExternalSession {
274 live: live_name.is_some(),
275 session_id,
276 title,
277 modified,
278 })
279 })
280 .take(limit)
281 .collect()
282}
283
284#[cfg(test)]
285mod tests {
286 use std::time::Duration;
287
288 use super::*;
289
290 const PLAIN: &str =
291 r#"{"type":"user","message":{"role":"user","content":"Fix the build\nplease"}}"#;
292
293 fn id(number: u32) -> String {
294 format!("00000000-0000-0000-0000-{number:012}")
295 }
296
297 fn user_line(content: &str) -> String {
298 serde_json::json!({"type": "user", "message": {"role": "user", "content": content}})
299 .to_string()
300 }
301
302 fn write_session(directory: &Path, session_id: &str, body: &str, age: Duration) {
303 let path = directory.join(format!("{session_id}.jsonl"));
304 std::fs::write(&path, body).unwrap();
305 File::options()
306 .write(true)
307 .open(&path)
308 .unwrap()
309 .set_modified(SystemTime::now() - age)
310 .unwrap();
311 }
312
313 fn scan(directory: &Path, limit: usize) -> Vec<ExternalSession> {
314 scan_external_sessions(directory, &HashMap::new(), &HashSet::new(), limit)
315 }
316
317 #[test]
318 fn encoding_replaces_every_non_alphanumeric_character() {
319 assert_eq!(
320 encode_project_dir("/home/daniel/Projects/ms-teams-linux"),
321 "-home-daniel-Projects-ms-teams-linux"
322 );
323 assert_eq!(
324 encode_project_dir("/home/daniel/repo/.claude/worktrees/x_y"),
325 "-home-daniel-repo--claude-worktrees-x-y"
326 );
327 assert_eq!(encode_project_dir(r"C:\Users\dd"), "C--Users-dd");
328 }
329
330 #[test]
331 fn trailing_separators_are_dropped_before_encoding() {
332 let projects = tempfile::tempdir().unwrap();
333 for working_dir in ["/home/x/repo/", "/home/x/repo", r"C:\x\repo\"] {
334 let resolved = resolve_project_dir(projects.path(), working_dir);
335 assert!(!resolved.to_string_lossy().ends_with("--"));
336 }
337 assert_eq!(
338 resolve_project_dir(projects.path(), "/home/x/repo/"),
339 projects.path().join("-home-x-repo")
340 );
341 assert_eq!(
342 resolve_project_dir(projects.path(), "/"),
343 projects.path().join("-")
344 );
345 }
346
347 #[test]
348 fn a_long_working_dir_falls_back_to_the_prefix_folder() {
349 let projects = tempfile::tempdir().unwrap();
350 let long_dir = format!("/home/daniel/{}", "deep/".repeat(45));
351 let encoded = encode_project_dir(long_dir.trim_end_matches('/'));
352 assert!(encoded.len() > PROJECT_DIR_NAME_LIMIT);
353 let truncated = projects
354 .path()
355 .join(format!("{}-abc123", &encoded[..PROJECT_DIR_NAME_LIMIT]));
356 std::fs::create_dir(&truncated).unwrap();
357 assert_eq!(resolve_project_dir(projects.path(), &long_dir), truncated);
358 std::fs::create_dir(projects.path().join(&encoded)).unwrap();
359 assert_eq!(
360 resolve_project_dir(projects.path(), &long_dir),
361 projects.path().join(&encoded)
362 );
363 assert_eq!(
364 resolve_project_dir(projects.path(), "/short"),
365 projects.path().join("-short")
366 );
367 }
368
369 #[test]
370 fn scan_takes_titles_from_the_first_plain_user_line_and_skips_known_ids() {
371 let directory = tempfile::tempdir().unwrap();
372 let meta = r#"{"type":"user","isMeta":true,"message":{"role":"user","content":"meta"}}"#;
373 let command = user_line("<command-name>/clear</command-name>");
374 let assistant = r#"{"type":"assistant","message":{"role":"assistant","content":"hi"}}"#;
375 let tagged = user_line("<pasted_content id=\"1\">\n<system-reminder>\nReal question here");
376 let parts = r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"x"},{"type":"text","text":"Parts title"}]}}"#;
377 write_session(
378 directory.path(),
379 &id(1),
380 &format!("{meta}\n{command}\n{assistant}\n{PLAIN}\n"),
381 Duration::from_secs(60),
382 );
383 write_session(
384 directory.path(),
385 &id(2),
386 &format!("{tagged}\n"),
387 Duration::from_secs(120),
388 );
389 write_session(
390 directory.path(),
391 &id(3),
392 &format!("not json\n{parts}\n"),
393 Duration::from_secs(3600),
394 );
395 write_session(directory.path(), &id(4), "", Duration::from_secs(7200));
396 write_session(
397 directory.path(),
398 &id(5),
399 assistant,
400 Duration::from_secs(7300),
401 );
402 write_session(directory.path(), &id(6), PLAIN, Duration::from_secs(10));
403 write_session(
404 directory.path(),
405 "agent-notes",
406 PLAIN,
407 Duration::from_secs(5),
408 );
409 std::fs::write(directory.path().join("notes.txt"), "x").unwrap();
410 let known = HashSet::from([id(6)]);
411 let sessions = scan_external_sessions(directory.path(), &HashMap::new(), &known, 10);
412 let summary: Vec<(String, &str)> = sessions
413 .iter()
414 .map(|session| (session.session_id.clone(), session.title.as_str()))
415 .collect();
416 assert_eq!(
417 summary,
418 [
419 (id(1), "Fix the build"),
420 (id(2), "Real question here"),
421 (id(3), "Parts title"),
422 ]
423 );
424 assert!(sessions.iter().all(|session| !session.live));
425 let age = SystemTime::now()
426 .duration_since(sessions[0].modified)
427 .unwrap();
428 assert!(age >= Duration::from_secs(60) && age < Duration::from_secs(120));
429 }
430
431 #[test]
432 fn enclosed_blocks_are_skipped_across_lines_and_parts() {
433 assert_eq!(
434 plain_line("<system-reminder>\nIDE note\nmore\n</system-reminder>\nFix it").as_deref(),
435 Some("Fix it")
436 );
437 assert_eq!(
438 plain_line("<ide_opened_file>The user opened a.rs</ide_opened_file>"),
439 None
440 );
441 assert_eq!(
442 plain_line("<b>bold</b> text").as_deref(),
443 Some("<b>bold</b> text")
444 );
445 let directory = tempfile::tempdir().unwrap();
446 let body = serde_json::json!({"type": "user", "message": {"role": "user", "content": [
447 {"type": "text", "text": "<ide_opened_file>The user opened a.rs</ide_opened_file>"},
448 {"type": "text", "text": "<ide_selection>\nlet x = 1;\n</ide_selection>"},
449 {"type": "text", "text": "Refactor this"}
450 ]}})
451 .to_string();
452 write_session(directory.path(), &id(1), &body, Duration::ZERO);
453 assert_eq!(scan(directory.path(), 1)[0].title, "Refactor this");
454 }
455
456 #[test]
457 fn lone_tags_are_recognised() {
458 assert!(is_lone_tag("<system-reminder>"));
459 assert!(is_lone_tag("</system-reminder>"));
460 assert!(is_lone_tag(r#"<pasted_content id="1" size="9">"#));
461 assert!(!is_lone_tag("<b>bold</b> text"));
462 assert!(!is_lone_tag("a < b > c"));
463 assert!(!is_lone_tag("<>"));
464 }
465
466 #[test]
467 fn a_title_past_the_first_user_line_is_still_found_and_the_read_is_capped() {
468 let directory = tempfile::tempdir().unwrap();
469 let filler = r#"{"type":"assistant","message":{"role":"assistant","content":"x"}}"#;
470 let body = format!("{}\n{PLAIN}\n", vec![filler; 2000].join("\n"));
471 assert!(body.len() as u64 > 64 * 1024);
472 write_session(directory.path(), &id(1), &body, Duration::ZERO);
473 assert_eq!(scan(directory.path(), 1)[0].title, "Fix the build");
474 let late = format!("{}\n{PLAIN}\n", " ".repeat(TITLE_READ_LIMIT as usize));
475 write_session(directory.path(), &id(2), &late, Duration::ZERO);
476 let found: Vec<String> = scan(directory.path(), 10)
477 .into_iter()
478 .map(|session| session.session_id)
479 .collect();
480 assert_eq!(found, [id(1)]);
481 }
482
483 #[test]
484 fn scan_keeps_the_newest_ten() {
485 let directory = tempfile::tempdir().unwrap();
486 for index in 0..12u32 {
487 write_session(
488 directory.path(),
489 &id(index),
490 PLAIN,
491 Duration::from_secs(u64::from(index) * 100),
492 );
493 }
494 let sessions = scan(directory.path(), 10);
495 assert_eq!(sessions.len(), 10);
496 assert_eq!(sessions[0].session_id, id(0));
497 assert_eq!(sessions[9].session_id, id(9));
498 }
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
534 #[test]
535 fn live_sessions_need_a_running_pid_and_use_their_name_as_title() {
536 let sessions_dir = tempfile::tempdir().unwrap();
537 let proc_root = tempfile::tempdir().unwrap();
538 std::fs::create_dir(proc_root.path().join("111")).unwrap();
539 std::fs::create_dir(proc_root.path().join("222")).unwrap();
540 let file = |pid: u32, session_id: &str, name: &str| {
541 std::fs::write(
542 sessions_dir.path().join(format!("{pid}.json")),
543 format!(r#"{{"pid":{pid},"sessionId":"{session_id}","name":"{name}"}}"#),
544 )
545 .unwrap();
546 };
547 file(111, &id(1), "Refactor auth");
548 file(222, &id(2), "");
549 file(333, &id(3), "Dead one");
550 std::fs::write(sessions_dir.path().join("444.json"), "garbage").unwrap();
551 let live = names(running_sessions_in(
552 sessions_dir.path(),
553 Some(proc_root.path()),
554 ));
555 assert_eq!(live.len(), 2);
556 assert!(!live.contains_key(&id(3)));
557 assert_eq!(
558 running_sessions_in(sessions_dir.path(), Some(Path::new("/nonexistent"))).len(),
559 3
560 );
561 let directory = tempfile::tempdir().unwrap();
562 write_session(directory.path(), &id(1), PLAIN, Duration::from_secs(5000));
563 write_session(directory.path(), &id(2), PLAIN, Duration::from_secs(6000));
564 write_session(directory.path(), &id(7), PLAIN, Duration::from_secs(7000));
565 let sessions = scan_external_sessions(directory.path(), &live, &HashSet::new(), 10);
566 let summary: Vec<(String, &str, bool)> = sessions
567 .iter()
568 .map(|session| {
569 (
570 session.session_id.clone(),
571 session.title.as_str(),
572 session.live,
573 )
574 })
575 .collect();
576 assert_eq!(
577 summary,
578 [
579 (id(1), "Refactor auth", true),
580 (id(2), "Fix the build", true),
581 (id(7), "Fix the build", false),
582 ]
583 );
584 assert!(live_session_names(Path::new("/nonexistent")).is_empty());
585 }
586
587 #[test]
588 fn the_proc_root_follows_the_environment_of_the_sessions_dir() {
589 assert_eq!(
590 proc_root(Path::new(r"\\wsl.localhost\Ubuntu\home\x\.claude\sessions")),
591 Some(PathBuf::from(r"\\wsl.localhost\Ubuntu\proc"))
592 );
593 assert_eq!(
594 proc_root(Path::new(r"\\wsl$\Debian\home\x")),
595 Some(PathBuf::from(r"\\wsl$\Debian\proc"))
596 );
597 assert_eq!(
598 proc_root(Path::new("/home/x/.claude/sessions")),
599 cfg!(unix).then(|| PathBuf::from("/proc"))
600 );
601 }
602
603 #[test]
604 fn a_missing_directory_yields_no_sessions() {
605 assert!(scan(Path::new("/nonexistent/projects"), 10).is_empty());
606 }
607}