BlueGit

ict rusty-teams

Files

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

sessions.rs

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