kaeru 0.1.3

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Claude Code: how to recognize its process, which runs are interactive,
//! where it keeps its files, and how to resume a session. Its `SessionStart`
//! hook sends the fields that `agents::HookInput` reads.

use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;

/// Returns the command that brings a session back: `claude --resume <id>`,
/// or plain `claude` when the conversation can't be resumed because it never
/// got a message or its file is gone.
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()]
    }
}

/// Returns whether a process is the Claude Code CLI. The native build runs
/// as `claude` or `claude.exe`, and the npm build as `node` running
/// `.../claude-code/cli.js`.
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,
    }
}

/// Returns whether a command line starts an interactive session. Runs such
/// as `claude -p` and SDK runs are not tabs, so kaeru ignores them.
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")
    })
}

/// Returns Claude Code's config folder: `CLAUDE_CONFIG_DIR` when that is set,
/// or else `~/.claude`.
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")))
}

/// Returns the file of the conversation `session_id`, for a note that didn't
/// record it. Claude Code keeps conversations as `projects/<folder>/<id>.jsonl`
/// in its config folder.
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())
}

/// Returns the process id of the session `session_id` from Claude Code's own
/// list of running sessions: the files in the `sessions` folder of its config
/// folder. The list is not a documented interface, so kaeru uses it only when
/// the hook's process tree doesn't lead to Claude Code.
pub fn registered_pid(config_dir: &Path, session_id: &str) -> Option<u32> {
    /// The part of a session file that kaeru reads.
    #[derive(Deserialize)]
    struct Registered {
        pid: u32,
        #[serde(rename = "sessionId")]
        session_id: String,
    }
    fs::read_dir(config_dir.join("sessions"))
        .ok()?
        .filter_map(|entry| Some(entry.ok()?.path()))
        .filter(|path| {
            path.extension()
                .is_some_and(|extension| extension == "json")
        })
        .filter_map(|path| serde_json::from_str::<Registered>(&fs::read_to_string(path).ok()?).ok())
        .find(|registered| registered.session_id == session_id)
        .map(|registered| registered.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);
    }

    #[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);
    }
}