#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProcRow {
pub pid: String,
pub depth: usize,
pub args: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProcState {
Rows(Vec<ProcRow>),
Message(String),
}
pub const MESSAGE_ROW: usize = usize::MAX;
pub const AGENT_NAMES: &[&str] = &[
"zidane",
"claude",
"claude-code",
"codex",
"crush",
"aider",
"goose",
"gemini",
"opencode",
"cline",
"qwen",
"cursor-agent",
"amp",
"plandex",
"copilot",
];
pub fn is_agent(args: &str) -> bool {
args.split_whitespace()
.filter(|tok| !tok.starts_with('-'))
.any(|tok| {
let base = tok.rsplit(['/', '\\']).next().unwrap_or(tok);
AGENT_NAMES.iter().any(|name| base.eq_ignore_ascii_case(name))
})
}
pub fn parse_top(out: &str) -> Vec<(String, String, String)> {
out.lines()
.skip(1)
.filter_map(|line| {
let mut it = line.split_whitespace();
let pid = it.next()?;
let ppid = it.next()?;
let args = remainder_after(line, pid, ppid)?;
Some((pid.to_string(), ppid.to_string(), args.to_string()))
})
.collect()
}
fn remainder_after<'a>(line: &'a str, pid: &str, ppid: &str) -> Option<&'a str> {
let after_pid = line.trim_start().strip_prefix(pid)?;
let after_ppid = after_pid.trim_start().strip_prefix(ppid)?;
let args = after_ppid.trim_start();
if args.is_empty() {
None
} else {
Some(args)
}
}
pub fn build_forest(rows: Vec<(String, String, String)>) -> Vec<ProcRow> {
use std::collections::{BTreeSet, HashMap};
let pids: BTreeSet<&str> = rows.iter().map(|(pid, _, _)| pid.as_str()).collect();
let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
let mut args: HashMap<&str, &str> = HashMap::new();
for (pid, ppid, arg) in &rows {
args.insert(pid.as_str(), arg.as_str());
children.entry(ppid.as_str()).or_default().push(pid.as_str());
}
for list in children.values_mut() {
list.sort_by(|a, b| match (a.parse::<u64>(), b.parse::<u64>()) {
(Ok(x), Ok(y)) => x.cmp(&y),
_ => a.cmp(b),
});
}
let mut roots: Vec<&str> = rows
.iter()
.filter(|(_, ppid, _)| !pids.contains(ppid.as_str()))
.map(|(pid, _, _)| pid.as_str())
.collect();
roots.sort_by(|a, b| match (a.parse::<u64>(), b.parse::<u64>()) {
(Ok(x), Ok(y)) => x.cmp(&y),
_ => a.cmp(b),
});
let mut out = Vec::with_capacity(rows.len());
let mut visited: BTreeSet<&str> = BTreeSet::new();
let mut stack: Vec<(&str, usize)> = roots.into_iter().rev().map(|pid| (pid, 0)).collect();
while let Some((pid, depth)) = stack.pop() {
if !visited.insert(pid) {
continue; }
out.push(ProcRow {
pid: pid.to_string(),
depth,
args: args.get(pid).copied().unwrap_or("").to_string(),
});
if let Some(kids) = children.get(pid) {
for kid in kids.iter().rev() {
stack.push((kid, depth + 1));
}
}
}
for (pid, _, arg) in &rows {
if visited.insert(pid.as_str()) {
out.push(ProcRow { pid: pid.clone(), depth: 0, args: arg.clone() });
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_top_skips_header_and_keeps_arg_spacing() {
let out = concat!(
"PID PPID COMMAND\n",
"1 0 /sbin/init\n",
"42 1 node server.js --port 3000\n",
);
let rows = parse_top(out);
assert_eq!(
rows,
vec![
("1".into(), "0".into(), "/sbin/init".into()),
("42".into(), "1".into(), "node server.js --port 3000".into()),
],
);
}
#[test]
fn parse_top_skips_short_lines() {
let out = "PID PPID ARGS\n1 0\n2 0 sh\n";
let rows = parse_top(out);
assert_eq!(rows, vec![("2".into(), "0".into(), "sh".into())]);
}
fn row(pid: &str, ppid: &str, args: &str) -> (String, String, String) {
(pid.into(), ppid.into(), args.into())
}
#[test]
fn build_forest_nests_children_under_parents() {
let rows = vec![
row("1", "0", "init"),
row("10", "1", "b"),
row("5", "1", "a"),
row("11", "5", "a-child"),
];
let forest = build_forest(rows);
assert_eq!(
forest,
vec![
ProcRow { pid: "1".into(), depth: 0, args: "init".into() },
ProcRow { pid: "5".into(), depth: 1, args: "a".into() },
ProcRow { pid: "11".into(), depth: 2, args: "a-child".into() },
ProcRow { pid: "10".into(), depth: 1, args: "b".into() },
],
);
}
#[test]
fn build_forest_multiple_orphan_ppids_are_roots() {
let rows = vec![row("7", "99", "g"), row("3", "0", "a")];
let forest = build_forest(rows);
let pids: Vec<&str> = forest.iter().map(|r| r.pid.as_str()).collect();
assert_eq!(pids, vec!["3", "7"]); assert!(forest.iter().all(|r| r.depth == 0));
}
#[test]
fn build_forest_survives_a_cycle() {
let rows = vec![row("1", "2", "a"), row("2", "1", "b")];
let forest = build_forest(rows);
assert_eq!(forest.len(), 2);
let pids: std::collections::BTreeSet<&str> =
forest.iter().map(|r| r.pid.as_str()).collect();
assert_eq!(pids, ["1", "2"].into_iter().collect());
}
#[test]
fn build_forest_empty_is_empty() {
assert!(build_forest(Vec::new()).is_empty());
}
#[test]
fn is_agent_matches_bare_name_and_path_and_wrapper() {
assert!(is_agent("zidane"));
assert!(is_agent("/usr/local/bin/zidane --resume"));
assert!(is_agent("node /opt/claude-code/dist/claude"));
assert!(is_agent("CLAUDE")); assert!(is_agent("codex exec"));
}
#[test]
fn is_agent_rejects_non_agents_and_partial_matches() {
assert!(!is_agent(""));
assert!(!is_agent("/sbin/init"));
assert!(!is_agent("node server.js"));
assert!(!is_agent("claudette"));
assert!(!is_agent("/opt/gemini-tools/run"));
assert!(!is_agent("mytool --amp"));
}
}