rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Discovery of past Claude Code sessions for a directory.

use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

const MAX_SESSIONS: usize = 40;

pub struct Session {
    pub id: String,
    pub title: String,
    pub branch: String,
    pub modified: SystemTime,
}

/// Claude stores sessions in ~/.claude/projects/<cwd with non-alphanumerics replaced by '-'>.
fn project_dir(cwd: &Path) -> Option<PathBuf> {
    let encoded: String =
        cwd.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
    Some(dirs::home_dir()?.join(".claude").join("projects").join(encoded))
}

pub fn list_sessions(cwd: &Path) -> Vec<Session> {
    let Some(dir) = project_dir(cwd) else { return Vec::new() };
    let Ok(entries) = std::fs::read_dir(&dir) else { return Vec::new() };
    let mut files: Vec<(PathBuf, SystemTime)> = entries
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| p.extension().is_some_and(|x| x == "jsonl"))
        .filter_map(|p| {
            let m = std::fs::metadata(&p).ok()?.modified().ok()?;
            Some((p, m))
        })
        .collect();
    files.sort_by_key(|a| std::cmp::Reverse(a.1));
    files.into_iter().filter_map(|(p, m)| read_session(&p, m)).take(MAX_SESSIONS).collect()
}

fn read_session(path: &Path, modified: SystemTime) -> Option<Session> {
    let id = path.file_stem()?.to_string_lossy().into_owned();
    let file = std::fs::File::open(path).ok()?;
    let mut custom_title = None;
    let mut ai_title = None;
    let mut last_prompt = None;
    let mut first_prompt = None;
    let mut branch = String::new();

    for line in BufReader::new(file).lines().map_while(Result::ok) {
        // Cheap substring checks first; only parse the lines we care about.
        let interesting = line.contains("\"custom-title\"")
            || line.contains("\"ai-title\"")
            || line.contains("\"last-prompt\"")
            || (first_prompt.is_none() && line.contains("\"type\":\"user\""));
        if !interesting {
            continue;
        }
        let Ok(v) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
        let s = |key: &str| v.get(key).and_then(|x| x.as_str()).map(str::to_string);
        match v.get("type").and_then(|t| t.as_str()) {
            Some("custom-title") => custom_title = s("customTitle").or(custom_title),
            Some("ai-title") => ai_title = s("aiTitle").or(ai_title),
            Some("last-prompt") => last_prompt = s("lastPrompt").or(last_prompt),
            Some("user") if first_prompt.is_none() => {
                if v.get("isMeta").and_then(|m| m.as_bool()) == Some(true) {
                    continue;
                }
                if let Some(text) = v.pointer("/message/content").and_then(|c| c.as_str()) {
                    let t = text.trim();
                    if !t.is_empty() && !t.starts_with('<') && !t.starts_with("Caveat:") {
                        first_prompt = Some(t.to_string());
                        branch = s("gitBranch").unwrap_or_default();
                    }
                }
            }
            _ => {}
        }
    }

    let title = custom_title.or(ai_title).or(last_prompt).or(first_prompt)?;
    let title: String = title.split_whitespace().collect::<Vec<_>>().join(" ");
    Some(Session { id, title, branch, modified })
}

pub fn relative_time(t: SystemTime) -> String {
    let secs = SystemTime::now().duration_since(t).map(|d| d.as_secs()).unwrap_or(0);
    match secs {
        0..=59 => "just now".into(),
        60..=3599 => format!("{}m ago", secs / 60),
        3600..=86_399 => format!("{}h ago", secs / 3600),
        86_400..=604_799 => format!("{}d ago", secs / 86_400),
        _ => format!("{}w ago", secs / 604_800),
    }
}

/// One rate-limit window (5-hour or weekly).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Window {
    pub used_pct: f32,
    /// Unix epoch seconds.
    pub resets_at: i64,
}

/// Live session data from Claude's status line JSON.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Status {
    pub model: String,
    pub context_pct: Option<f32>,
    pub five_hour: Option<Window>,
    pub seven_day: Option<Window>,
    pub lines_added: u64,
    pub lines_removed: u64,
}

pub fn parse_status(json: &str) -> Option<Status> {
    let v: serde_json::Value = serde_json::from_str(json).ok()?;
    let f = |p: &str| v.pointer(p).and_then(|x| x.as_f64());
    let window = |name: &str| {
        Some(Window {
            used_pct: f(&format!("/rate_limits/{name}/used_percentage"))? as f32,
            resets_at: f(&format!("/rate_limits/{name}/resets_at"))? as i64,
        })
    };
    Some(Status {
        model: v.pointer("/model/display_name").and_then(|x| x.as_str()).unwrap_or("Claude").to_string(),
        // Null until the first reply; an empty context is 0%.
        context_pct: f("/context_window/used_percentage")
            .or_else(|| v.pointer("/context_window/context_window_size").map(|_| 0.0))
            .map(|x| x as f32),
        five_hour: window("five_hour"),
        seven_day: window("seven_day"),
        lines_added: f("/cost/total_lines_added").unwrap_or(0.0) as u64,
        lines_removed: f("/cost/total_lines_removed").unwrap_or(0.0) as u64,
    })
}

pub fn now_epoch() -> i64 {
    SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}

/// "2h 10m", "3d 4h", "12m" until `at`.
pub fn until(at: i64) -> String {
    let s = (at - now_epoch()).max(0);
    let (d, h, m) = (s / 86_400, (s % 86_400) / 3600, (s % 3600) / 60);
    if d > 0 {
        format!("{d}d {h}h")
    } else if h > 0 {
        format!("{h}h {m}m")
    } else {
        format!("{}m", m.max(1))
    }
}

/// Account-wide usage survives across sessions: remember the latest windows on disk
/// so a fresh session can show them before its first reply.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Usage {
    pub five_hour: Option<Window>,
    pub seven_day: Option<Window>,
}

impl Usage {
    /// Drop windows whose reset time has passed.
    pub fn fresh(self) -> Usage {
        let now = now_epoch();
        let keep = |w: Option<Window>| w.filter(|w| w.resets_at > now);
        Usage { five_hour: keep(self.five_hour), seven_day: keep(self.seven_day) }
    }

    pub fn load(path: &Path) -> Usage {
        let Ok(text) = std::fs::read_to_string(path) else { return Usage::default() };
        let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) else { return Usage::default() };
        let w = |k: &str| {
            Some(Window {
                used_pct: v.pointer(&format!("/{k}/used_pct"))?.as_f64()? as f32,
                resets_at: v.pointer(&format!("/{k}/resets_at"))?.as_i64()?,
            })
        };
        Usage { five_hour: w("five_hour"), seven_day: w("seven_day") }.fresh()
    }

    pub fn save(&self, path: &Path) {
        let w = |w: Option<Window>| w.map(|w| serde_json::json!({ "used_pct": w.used_pct, "resets_at": w.resets_at }));
        let v = serde_json::json!({ "five_hour": w(self.five_hour), "seven_day": w(self.seven_day) });
        let _ = std::fs::write(path, v.to_string());
    }
}