curd-editor 0.27.2

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
//! What the `claude` command keeps on disk: the earlier conversations about a
//! project, and the user's own commands.

use super::*;

// ---- Earlier conversations ------------------------------------------------
//
// The `claude` command keeps every conversation as a file of JSON lines,
// one folder per project, under `~/.claude/projects`. Reading them is how
// the panel lists the earlier conversations and shows one again; carrying
// one on is the command's own `--resume`.

/// The most earlier conversations listed.
pub(super) const MAX_SESSIONS: usize = 50;
/// How many lines into a conversation its first question is looked for.
pub(super) const TITLE_LINES: usize = 400;

/// An earlier conversation about the project.
#[derive(Debug, PartialEq)]
pub struct SessionInfo {
    pub id: String,
    /// The first thing that was asked in it.
    pub title: String,
    pub modified: SystemTime,
}

/// The folder where `claude` keeps the conversations about the project in
/// `root`: under `home`, named after the project's path with everything
/// but letters and digits turned into `-`.
pub fn sessions_dir(home: &Path, root: &Path) -> PathBuf {
    let name: String = root
        .to_string_lossy()
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect();
    home.join(".claude").join("projects").join(name)
}

/// What a line of a conversation file holds, as lines for the panel.
pub(super) fn transcript_line(line: &str) -> Vec<(Who, String)> {
    let Ok(message) = serde_json::from_str::<Value>(line) else {
        return Vec::new();
    };
    // Notes the command wrote for itself, and its helpers' side talk.
    if message["isMeta"].as_bool() == Some(true) || message["isSidechain"].as_bool() == Some(true) {
        return Vec::new();
    }
    let content = &message["message"]["content"];
    let mut entries = Vec::new();
    let mut said = |who: Who, text: &str| {
        let text = text.trim();
        // Anything in <tags> was put there by a program, not typed.
        if !text.is_empty() && !text.starts_with('<') {
            entries.push((who, text.to_string()));
        }
    };
    match message["type"].as_str() {
        Some("user") => match content.as_str() {
            Some(text) => said(Who::You, text),
            None => {
                for block in content.as_array().into_iter().flatten() {
                    if block["type"].as_str() == Some("text") {
                        said(Who::You, block["text"].as_str().unwrap_or_default());
                    }
                }
            }
        },
        Some("assistant") => {
            for block in content.as_array().into_iter().flatten() {
                match block["type"].as_str() {
                    Some("text") => said(Who::Claude, block["text"].as_str().unwrap_or_default()),
                    Some("tool_use") => said(Who::Note, &step(block)),
                    _ => {}
                }
            }
        }
        _ => {}
    }
    entries
}

/// The earlier conversations kept in `dir`, newest first.
pub fn list_sessions(dir: &Path) -> Vec<SessionInfo> {
    let mut sessions: Vec<SessionInfo> = std::fs::read_dir(dir)
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|item| {
            let path = item.path();
            let id = path.file_stem()?.to_str()?.to_string();
            if path.extension()?.to_str()? != "jsonl" {
                return None;
            }
            let modified = item.metadata().ok()?.modified().ok()?;
            let lines = BufReader::new(std::fs::File::open(&path).ok()?).lines();
            let title = lines
                .map_while(Result::ok)
                .take(TITLE_LINES)
                .flat_map(|line| transcript_line(&line))
                .find(|(who, _)| *who == Who::You)?
                .1;
            let title = title.lines().next().unwrap_or_default().to_string();
            Some(SessionInfo { id, title, modified })
        })
        .collect();
    sessions.sort_by_key(|session| std::cmp::Reverse(session.modified));
    sessions.truncate(MAX_SESSIONS);
    sessions
}

/// Everything said in conversation `id` kept in `dir`.
pub fn load_session(dir: &Path, id: &str) -> Vec<(Who, String)> {
    let Ok(file) = std::fs::File::open(dir.join(format!("{id}.jsonl"))) else {
        return Vec::new();
    };
    BufReader::new(file)
        .lines()
        .map_while(Result::ok)
        .flat_map(|line| transcript_line(&line))
        .collect()
}

/// How long ago `then` was, in a few characters: "5m", "3h", "12d".
pub fn age(then: SystemTime, now: SystemTime) -> String {
    let minutes = now.duration_since(then).map_or(0, |passed| passed.as_secs() / 60);
    match minutes {
        0 => "now".into(),
        1..60 => format!("{minutes}m"),
        60..1440 => format!("{}h", minutes / 60),
        _ => format!("{}d", minutes / 1440),
    }
}

// ---- The `/` commands ------------------------------------------------------

/// The commands of the user's own that the `claude` command knows: the
/// files in the `commands` folders and the folders in the `skills`
/// folders, under `.claude` in the project `root` and in `home`.
pub fn own_commands(home: &Path, root: &Path) -> Vec<String> {
    let mut names = Vec::new();
    for base in [root.join(".claude"), home.join(".claude")] {
        for (folder, wants_dir) in [("commands", false), ("skills", true)] {
            for item in std::fs::read_dir(base.join(folder)).into_iter().flatten().flatten() {
                let path = item.path();
                let is_command = !wants_dir && path.extension().is_some_and(|ext| ext == "md");
                let is_skill = wants_dir && path.is_dir();
                if let (true, Some(name)) = (is_command || is_skill, path.file_stem()) {
                    names.push(name.to_string_lossy().into_owned());
                }
            }
        }
    }
    names.sort();
    names.dedup();
    names
}