use std::fs;
use std::path::{Path, PathBuf};
use serde::Deserialize;
pub fn resume_command(session_id: &str, conversation_exists: bool) -> Vec<String> {
if conversation_exists && super::is_uuid(session_id) {
vec!["claude".into(), "--resume".into(), session_id.into()]
} else {
vec!["claude".into()]
}
}
pub fn is_claude_process(name: &str, command_line: &str) -> bool {
let name = name.to_ascii_lowercase();
match name.as_str() {
"claude" | "claude.exe" => true,
"node" | "node.exe" => command_line.contains("claude-code"),
_ => false,
}
}
pub fn is_interactive(command_line: &str) -> bool {
!command_line.split_whitespace().any(|arg| {
matches!(arg, "-p" | "--print")
|| arg.starts_with("--output-format")
|| arg.starts_with("--input-format")
})
}
pub fn config_dir() -> Option<PathBuf> {
std::env::var_os("CLAUDE_CONFIG_DIR")
.map(PathBuf::from)
.or_else(|| dirs::home_dir().map(|home| home.join(".claude")))
}
pub fn find_transcript(config_dir: &Path, session_id: &str) -> Option<PathBuf> {
if !super::is_uuid(session_id) {
return None;
}
fs::read_dir(config_dir.join("projects"))
.ok()?
.filter_map(|entry| Some(entry.ok()?.path().join(format!("{session_id}.jsonl"))))
.find(|path| path.is_file())
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Running {
pub pid: u32,
#[serde(rename = "sessionId")]
pub session_id: String,
#[serde(default)]
pub cwd: Option<String>,
#[serde(default, rename = "startedAt")]
pub started_ms: Option<u64>,
#[serde(default)]
pub kind: Option<String>,
}
impl Running {
pub fn is_interactive(&self) -> bool {
self.kind
.as_deref()
.is_none_or(|kind| kind == "interactive")
}
}
pub fn running_sessions(config_dir: &Path) -> Vec<Running> {
let Ok(entries) = fs::read_dir(config_dir.join("sessions")) else {
return Vec::new();
};
entries
.filter_map(|entry| Some(entry.ok()?.path()))
.filter(|path| {
path.extension()
.is_some_and(|extension| extension == "json")
})
.filter_map(|path| serde_json::from_str::<Running>(&fs::read_to_string(path).ok()?).ok())
.collect()
}
pub fn registered_pid(config_dir: &Path, session_id: &str) -> Option<u32> {
running_sessions(config_dir)
.into_iter()
.find(|running| running.session_id == session_id)
.map(|running| running.pid)
}
#[cfg(test)]
mod tests {
use super::*;
const ID: &str = "00000000-0000-4000-8000-000000000001";
#[test]
fn resumes_only_conversations_that_exist() {
assert_eq!(resume_command(ID, true), ["claude", "--resume", ID]);
assert_eq!(resume_command(ID, false), ["claude"]);
assert_eq!(resume_command("bad", true), ["claude"]);
}
#[test]
fn recognizes_the_claude_process() {
assert!(is_claude_process("claude.exe", ""));
assert!(is_claude_process("claude", ""));
assert!(is_claude_process(
"node",
"node /usr/lib/node_modules/@anthropic-ai/claude-code/cli.js"
));
assert!(!is_claude_process("node", "node server.js"));
assert!(!is_claude_process("bash", ""));
}
#[test]
fn print_mode_is_not_interactive() {
assert!(is_interactive(r#""C:\tools\claude.exe""#));
assert!(is_interactive("claude --model sonnet"));
assert!(!is_interactive("claude -p hello"));
assert!(!is_interactive("claude --print hello"));
assert!(!is_interactive("claude --output-format=json"));
}
#[test]
fn a_registered_session_gives_its_process_id() {
let dir = tempfile::tempdir().unwrap();
let sessions = dir.path().join("sessions");
fs::create_dir(&sessions).unwrap();
let other = "00000000-0000-4000-8000-000000000009";
fs::write(
sessions.join("111.json"),
format!(r#"{{"pid":111,"sessionId":"{other}","kind":"interactive"}}"#),
)
.unwrap();
fs::write(
sessions.join("222.json"),
format!(r#"{{"pid":222,"sessionId":"{ID}","kind":"interactive"}}"#),
)
.unwrap();
fs::write(sessions.join("333.json"), "not json").unwrap();
assert_eq!(registered_pid(dir.path(), ID), Some(222));
assert_eq!(
registered_pid(dir.path(), "00000000-0000-4000-8000-00000000000f"),
None
);
assert_eq!(registered_pid(&dir.path().join("missing"), ID), None);
let running = running_sessions(dir.path());
assert_eq!(running.len(), 2);
assert!(running.iter().all(Running::is_interactive));
}
#[test]
fn a_background_session_is_not_interactive() {
let running: Running = serde_json::from_str(&format!(
r#"{{"pid":1,"sessionId":"{ID}","kind":"bg","startedAt":5,"cwd":"/home/demo"}}"#
))
.unwrap();
assert!(!running.is_interactive());
assert_eq!(running.started_ms, Some(5));
assert_eq!(running.cwd.as_deref(), Some("/home/demo"));
}
#[test]
fn a_conversation_is_found_in_its_project_folder() {
let dir = tempfile::tempdir().unwrap();
let project = dir
.path()
.join("projects")
.join("C--Users-demo-code-mobile-app");
fs::create_dir_all(&project).unwrap();
fs::write(project.join(format!("{ID}.jsonl")), "{}").unwrap();
assert_eq!(
find_transcript(dir.path(), ID),
Some(project.join(format!("{ID}.jsonl")))
);
assert_eq!(
find_transcript(dir.path(), "00000000-0000-4000-8000-00000000000f"),
None
);
assert_eq!(find_transcript(dir.path(), "../../etc"), None);
}
}