use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use crate::procfs::Snapshot;
#[derive(Debug, Clone, Copy)]
pub enum Match {
Exact(&'static str),
Prefix(&'static str),
}
impl Match {
fn matches(&self, name: &str) -> bool {
match self {
Match::Exact(s) => name == *s,
Match::Prefix(s) => name.starts_with(s),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct AgentKind {
pub id: &'static str,
pub display: &'static str,
pub matches: &'static [Match],
}
pub const AGENT_KINDS: &[AgentKind] = &[
AgentKind {
id: "claude",
display: "claude",
matches: &[Match::Exact("claude"), Match::Prefix("claude-")],
},
AgentKind {
id: "opencode",
display: "opencode",
matches: &[Match::Exact("opencode"), Match::Prefix("opencode-")],
},
AgentKind {
id: "codex",
display: "codex",
matches: &[Match::Exact("codex"), Match::Prefix("codex-")],
},
AgentKind {
id: "grok",
display: "grok",
matches: &[Match::Exact("grok"), Match::Prefix("grok-")],
},
AgentKind {
id: "kimi",
display: "kimi",
matches: &[Match::Exact("kimi"), Match::Prefix("kimi-")],
},
AgentKind {
id: "muse",
display: "muse",
matches: &[Match::Exact("muse"), Match::Prefix("muse-")],
},
AgentKind {
id: "pi",
display: "pi",
matches: &[Match::Exact("pi"), Match::Prefix("pi-")],
},
];
const INTERPRETERS: &[&str] = &["node", "deno", "bun", "bunx", "python", "python3", "ruby"];
fn basename(path: &str) -> String {
Path::new(path)
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| path.to_string())
}
pub fn extract_candidates(cmdline: &[String]) -> Vec<String> {
let mut out = Vec::new();
let Some(a0) = cmdline.first() else {
return out;
};
let b = basename(a0);
out.push(b.clone());
if INTERPRETERS.contains(&b.as_str()) {
for tok in cmdline.iter().skip(1) {
if !tok.starts_with('-') {
out.push(basename(tok));
break;
}
}
}
out
}
pub fn detect_kind(cmdline: &[String]) -> Option<&'static AgentKind> {
let cands = extract_candidates(cmdline);
for kind in AGENT_KINDS {
for matcher in kind.matches {
for cand in &cands {
if matcher.matches(cand) {
return Some(kind);
}
}
}
}
None
}
#[derive(Debug, Clone)]
pub struct Session {
pub kind: &'static AgentKind,
pub pid: i32,
pub cpu_percent: f64,
pub rss_kib: u64,
pub elapsed_secs: u64,
pub task: String,
pub task_project: Option<String>,
pub model: String,
pub activity: crate::activity::Activity,
}
fn nearest_agent_ancestor(
snap: &Snapshot,
agents: &HashMap<i32, &'static AgentKind>,
start: i32,
) -> Option<i32> {
let mut pid = start;
let mut seen = HashSet::new();
loop {
if !seen.insert(pid) {
return None;
}
let parent = snap.procs.get(&pid).map(|e| e.stat.ppid).unwrap_or(0);
if parent == 0 {
return None;
}
if agents.contains_key(&parent) {
return Some(parent);
}
pid = parent;
}
}
pub fn build_sessions(curr: &Snapshot, prev: Option<&Snapshot>) -> Vec<Session> {
let mut agents: HashMap<i32, &'static AgentKind> = HashMap::new();
for (&pid, entry) in &curr.procs {
let mut kind = detect_kind(&entry.cmdline);
if kind.is_none() && entry.cmdline.is_empty() && !entry.stat.comm.is_empty() {
kind = detect_kind(std::slice::from_ref(&entry.stat.comm));
}
if let Some(k) = kind {
agents.insert(pid, k);
}
}
if agents.is_empty() {
return Vec::new();
}
let mut owner_of: HashMap<i32, i32> = HashMap::new();
for &pid in curr.procs.keys() {
let owner = if agents.contains_key(&pid) {
pid
} else {
nearest_agent_ancestor(curr, &agents, pid).unwrap_or(0)
};
if owner != 0 {
owner_of.insert(pid, owner);
}
}
let mut rss: HashMap<i32, u64> = HashMap::new();
let mut ticks: HashMap<i32, u64> = HashMap::new();
for (&pid, entry) in &curr.procs {
let Some(&owner) = owner_of.get(&pid) else {
continue;
};
*rss.entry(owner).or_default() += entry.stat.rss_kib();
if let Some(p) = prev {
if let Some(pe) = p.procs.get(&pid) {
let d = entry
.stat
.utime
.saturating_sub(pe.stat.utime)
.saturating_add(entry.stat.stime.saturating_sub(pe.stat.stime));
*ticks.entry(owner).or_default() += d;
}
}
}
let num_cores = curr
.cpus
.iter()
.filter(|c| !c.is_aggregate())
.count()
.max(1) as f64;
let total_delta = prev
.and_then(|p| {
let ca = curr.cpus.iter().find(|c| c.is_aggregate());
let pa = p.cpus.iter().find(|c| c.is_aggregate());
match (ca, pa) {
(Some(c), Some(pn)) => Some(c.total().saturating_sub(pn.total())),
_ => None,
}
})
.unwrap_or(0);
let mut sessions = Vec::with_capacity(agents.len());
for (&pid, &kind) in &agents {
let Some(entry) = curr.procs.get(&pid) else {
continue;
};
let cpu_percent = if total_delta > 0 {
let dt = ticks.get(&pid).copied().unwrap_or(0) as f64;
dt / total_delta as f64 * 100.0 * num_cores
} else {
0.0
};
let start_secs = entry.stat.starttime as f64 / curr.tick_hz.max(1) as f64;
let elapsed_secs = (curr.uptime.secs - start_secs).max(0.0) as u64;
sessions.push(Session {
kind,
pid,
cpu_percent,
rss_kib: rss.get(&pid).copied().unwrap_or(0),
elapsed_secs,
task: String::new(),
task_project: None,
model: String::new(),
activity: crate::activity::Activity::default(),
});
}
sessions.sort_by(|a, b| {
b.cpu_percent
.partial_cmp(&a.cpu_percent)
.unwrap_or(Ordering::Equal)
});
sessions
}
#[cfg(test)]
mod tests {
use super::*;
use crate::procfs::{CpuLine, ProcEntry, ProcStat, Uptime, CLK_TZ};
fn agent(pid: i32, ppid: i32, comm: &str, cmdline: &[&str]) -> ProcEntry {
ProcEntry {
stat: ProcStat {
pid,
ppid,
comm: comm.to_string(),
utime: 100,
stime: 50,
rss_pages: 1024,
..Default::default()
},
cmdline: cmdline.iter().map(|s| s.to_string()).collect(),
cwd: None,
}
}
fn proc_(pid: i32, ppid: i32, comm: &str) -> ProcEntry {
ProcEntry {
stat: ProcStat {
pid,
ppid,
comm: comm.to_string(),
utime: 100,
stime: 50,
rss_pages: 512,
..Default::default()
},
cmdline: vec![comm.to_string()],
cwd: None,
}
}
fn snap(procs: Vec<(i32, ProcEntry)>, agg_total: u64) -> Snapshot {
let mut s = Snapshot {
tick_hz: CLK_TZ,
uptime: Uptime { secs: 10_000.0 },
cpus: vec![
CpuLine {
name: "cpu".to_string(),
fields: vec![agg_total; 8],
},
CpuLine {
name: "cpu0".to_string(),
fields: vec![agg_total / 2; 8],
},
CpuLine {
name: "cpu1".to_string(),
fields: vec![agg_total / 2; 8],
},
],
..Default::default()
};
for (pid, e) in procs {
s.procs.insert(pid, e);
}
s
}
#[test]
fn detect_direct_basenames() {
assert_eq!(
detect_kind(&["claude".to_string()]).map(|k| k.id),
Some("claude")
);
assert_eq!(
detect_kind(&["opencode".to_string()]).map(|k| k.id),
Some("opencode")
);
}
#[test]
fn detect_versioned_and_wrappers() {
assert_eq!(
detect_kind(&["muse-bin-1.2.3".to_string()]).map(|k| k.id),
Some("muse")
);
assert_eq!(
detect_kind(&["pi-launcher".to_string()]).map(|k| k.id),
Some("pi")
);
assert_eq!(
detect_kind(&["/usr/bin/opencode".to_string()]).map(|k| k.id),
Some("opencode")
);
}
#[test]
fn detect_through_interpreter() {
assert_eq!(
detect_kind(&["node".to_string(), "/opt/claude/claude".to_string()]).map(|k| k.id),
Some("claude")
);
}
#[test]
fn detect_rejects_lookalikes() {
assert!(detect_kind(&["pip".to_string()]).is_none());
assert!(detect_kind(&["ping".to_string()]).is_none());
assert!(detect_kind(&["cargo".to_string()]).is_none());
}
#[test]
fn subtree_aggregates_into_one_session() {
let procs = vec![
(1, agent(1, 0, "claude", &["claude"])),
(2, proc_(2, 1, "cargo")),
(3, proc_(3, 2, "cc")),
];
let curr = snap(procs.clone(), 2000);
let mut prev = snap(procs, 1000);
for e in prev.procs.values_mut() {
e.stat.utime -= 10;
}
let sessions = build_sessions(&curr, Some(&prev));
assert_eq!(sessions.len(), 1);
let s = &sessions[0];
assert_eq!(s.kind.id, "claude");
assert_eq!(s.pid, 1);
assert_eq!(s.rss_kib, (1024 + 512 + 512) * 4);
assert!((s.cpu_percent - 0.75).abs() < 1e-6, "got {}", s.cpu_percent);
}
#[test]
fn nested_agent_is_separate_and_excluded_from_ancestor() {
let procs = vec![
(1, agent(1, 0, "opencode", &["opencode"])),
(2, proc_(2, 1, "cargo")),
(5, agent(5, 1, "claude", &["claude"])),
(6, proc_(6, 5, "bash")),
];
let curr = snap(procs.clone(), 2000);
let mut prev = snap(procs, 1000);
for e in prev.procs.values_mut() {
e.stat.utime -= 10;
}
let sessions = build_sessions(&curr, Some(&prev));
assert_eq!(sessions.len(), 2, "two sessions");
let by_id: HashMap<&str, &Session> = sessions.iter().map(|s| (s.kind.id, s)).collect();
let oc = by_id.get("opencode").unwrap();
let cl = by_id.get("claude").unwrap();
assert_eq!(oc.rss_kib, (1024 + 512) * 4);
assert_eq!(cl.rss_kib, (1024 + 512) * 4);
}
#[test]
fn no_agents_returns_empty() {
let procs = vec![(1, proc_(1, 0, "bash"))];
let curr = snap(procs, 2000);
assert!(build_sessions(&curr, None).is_empty());
}
#[test]
fn first_tick_has_zero_cpu() {
let procs = vec![(1, agent(1, 0, "claude", &["claude"]))];
let curr = snap(procs, 2000);
let sessions = build_sessions(&curr, None);
assert_eq!(sessions.len(), 1);
assert_eq!(sessions[0].cpu_percent, 0.0);
}
#[test]
fn sorted_by_cpu_desc() {
let procs = vec![
(1, agent(1, 0, "claude", &["claude"])),
(2, agent(2, 0, "opencode", &["opencode"])),
];
let curr = snap(procs.clone(), 2000);
let mut prev = snap(procs, 1000);
prev.procs.get_mut(&1).unwrap().stat.utime -= 5; prev.procs.get_mut(&2).unwrap().stat.utime -= 80; let sessions = build_sessions(&curr, Some(&prev));
assert_eq!(sessions.len(), 2);
assert!(sessions[0].cpu_percent >= sessions[1].cpu_percent);
assert_eq!(sessions[0].kind.id, "opencode");
}
}