use std::collections::HashMap;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Agent,
Server,
App,
}
impl Kind {
pub fn is_local(self) -> bool {
self == Server
}
}
pub fn labels(local: bool) -> impl Iterator<Item = &'static str> {
TOOLS
.iter()
.filter(move |t| t.kind.is_local() == local)
.map(|t| t.label)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tool {
pub label: &'static str,
pub kind: Kind,
pub names: &'static [&'static str],
}
use Kind::{Agent, App, Server};
#[rustfmt::skip]
pub const TOOLS: &[Tool] = &[
Tool { label: "Claude Code", kind: Agent, names: &["claude"] },
Tool { label: "Codex", kind: Agent, names: &["codex"] },
Tool { label: "Cursor Agent", kind: Agent, names: &["cursor-agent"] },
Tool { label: "Gemini CLI", kind: Agent, names: &["gemini"] },
Tool { label: "Grok", kind: Agent, names: &["grok"] },
Tool { label: "opencode", kind: Agent, names: &["opencode"] },
Tool { label: "pi", kind: Agent, names: &["pi"] },
Tool { label: "Aider", kind: Agent, names: &["aider"] },
Tool { label: "Goose", kind: Agent, names: &["goose"] },
Tool { label: "Amp", kind: Agent, names: &["amp"] },
Tool { label: "Crush", kind: Agent, names: &["crush"] },
Tool { label: "Droid", kind: Agent, names: &["droid"] },
Tool { label: "Copilot CLI", kind: Agent, names: &["copilot"] },
Tool { label: "Qwen Code", kind: Agent, names: &["qwen"] },
Tool { label: "the Claude app", kind: App, names: &["Claude"] },
Tool { label: "ChatGPT", kind: App, names: &["ChatGPT"] },
Tool { label: "Cursor", kind: App, names: &["Cursor"] },
Tool { label: "Windsurf", kind: App, names: &["Windsurf"] },
Tool { label: "Ollama", kind: Server, names: &["ollama"] },
Tool { label: "llama.cpp", kind: Server, names: &["llama-server", "llama-cli", "llama-run"] },
Tool { label: "MLX", kind: Server, names: &["mlx_lm", "mlx-lm", "mlx_vlm", "mlx-serve", "mlx_serve"] },
Tool { label: "LM Studio", kind: Server, names: &["lm studio", "lms", "lmstudio"] },
Tool { label: "oMLX", kind: Server, names: &["omlx"] },
Tool { label: "Nativ", kind: Server, names: &["nativ"] },
Tool { label: "vLLM", kind: Server, names: &["vllm"] },
Tool { label: "KoboldCpp", kind: Server, names: &["koboldcpp"] },
Tool { label: "LocalAI", kind: Server, names: &["local-ai", "localai"] },
Tool { label: "Jan", kind: Server, names: &["jan"] },
Tool { label: "Msty", kind: Server, names: &["msty"] },
Tool { label: "exo", kind: Server, names: &["exo"] },
];
pub const INTERPRETERS: &[&str] = &[
"node", "bun", "deno", "python", "python3", "uv", "uvx", "npx", "java",
];
const SOURCE_FILES: &[&str] = &[".js", ".mjs", ".cjs", ".ts", ".py", ".rb", ".sh"];
pub fn is_version(name: &str) -> bool {
name.split('.').count() >= 2
&& name
.split('.')
.all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
}
pub fn identify(name: &str, args: &[String]) -> Option<&'static Tool> {
if let Some(app) = TOOLS
.iter()
.find(|t| t.kind == App && t.names.contains(&name))
{
return Some(app);
}
if is_version(name) {
let first = args.first()?;
return identify(first.rsplit('/').next().unwrap_or(first), &[]);
}
let name = name.to_lowercase();
let interpreter = INTERPRETERS
.iter()
.any(|i| name == *i || name.starts_with(&format!("{i}3.")));
let candidates = std::iter::once(name.clone()).chain(
args.iter()
.skip(1)
.filter(|a| !a.starts_with('-'))
.take(if interpreter { 2 } else { 0 })
.map(|a| a.rsplit('/').next().unwrap_or(a).to_lowercase())
.filter(|a| !SOURCE_FILES.iter().any(|ext| a.ends_with(ext))),
);
candidates.into_iter().find_map(|c| {
TOOLS
.iter()
.filter(|t| t.kind != App)
.find(|t| t.names.iter().any(|n| matches(n, &c)))
})
}
fn matches(name: &str, candidate: &str) -> bool {
candidate == name
|| candidate
.strip_prefix(name)
.is_some_and(|rest| rest.starts_with('.'))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Seen {
pub pid: u32,
pub tool: &'static Tool,
pub procs: Vec<(u32, Duration)>,
}
const AGENT_BUSY: f64 = 0.005;
const SERVER_BUSY: f64 = 0.05;
const APP_BUSY: f64 = 0.05;
const GPU_BUSY: u8 = 20;
const SERVER_ALIVE: f64 = 0.005;
pub const SAMPLE_EVERY: Duration = Duration::from_secs(15);
pub const QUIET_MINUTES: u32 = 15;
pub const QUIET_MINUTES_MAX: u32 = 1440;
pub const QUIET_CPU_PERCENT: u8 = 10;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Settings {
pub grace: Duration,
pub idle_cpu: f64,
pub agents: bool,
pub local: bool,
}
impl Settings {
fn watches(&self, kind: Kind) -> bool {
if kind.is_local() {
self.local
} else {
self.agents
}
}
}
impl Default for Settings {
fn default() -> Self {
Settings {
grace: Duration::from_secs(u64::from(QUIET_MINUTES) * 60),
idle_cpu: f64::from(QUIET_CPU_PERCENT) / 100.0,
agents: true,
local: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CpuTicks {
pub busy: u64,
pub total: u64,
}
#[derive(Debug, Default)]
pub struct Watch {
settings: Settings,
last: HashMap<u32, Duration>,
last_at: Option<Duration>,
last_cpu: Option<CpuTicks>,
busy: Option<(Duration, &'static str)>,
}
impl Watch {
pub fn new(settings: Settings) -> Self {
Watch {
settings,
..Watch::default()
}
}
pub fn set_settings(&mut self, settings: Settings) {
self.settings = settings;
}
pub fn system_share(&self, cpu: CpuTicks) -> Option<f64> {
let last = self.last_cpu?;
let total = cpu.total.checked_sub(last.total).filter(|&t| t > 0)?;
Some(cpu.busy.saturating_sub(last.busy) as f64 / total as f64)
}
pub fn share(&self, s: &Seen, elapsed: Duration) -> f64 {
if elapsed.is_zero() {
return 0.0;
}
let gained: Duration = s
.procs
.iter()
.filter_map(|(pid, cpu)| self.last.get(pid).map(|was| cpu.saturating_sub(*was)))
.sum();
gained.as_secs_f64() / elapsed.as_secs_f64()
}
pub fn sample(
&mut self,
now: Duration,
seen: &[Seen],
gpu: Option<u8>,
cpu: Option<CpuTicks>,
) -> Option<String> {
let system_busy = cpu
.and_then(|c| self.system_share(c))
.is_some_and(|share| share > self.settings.idle_cpu);
if let (true, Some((_, label))) = (system_busy, self.holding(now)) {
self.busy = Some((now, label));
}
if cpu.is_some() {
self.last_cpu = cpu;
}
if let Some(elapsed) = self.last_at.map(|t| now.saturating_sub(t)) {
let gpu_busy = gpu.is_some_and(|g| g >= GPU_BUSY);
let working = seen
.iter()
.filter(|s| self.settings.watches(s.tool.kind))
.filter(|s| {
let share = self.share(s, elapsed);
share
>= match s.tool.kind {
Agent => AGENT_BUSY,
Server if gpu_busy => SERVER_ALIVE,
Server => SERVER_BUSY,
App => APP_BUSY,
}
})
.min_by_key(|s| s.tool.kind as u8);
if let Some(s) = working {
self.busy = Some((now, s.tool.label));
}
}
self.last = seen.iter().flat_map(|s| s.procs.iter().copied()).collect();
self.last_at = Some(now);
self.reason(now)
}
pub fn is_new(&self) -> bool {
self.last_at.is_none()
}
fn holding(&self, now: Duration) -> Option<(Duration, &'static str)> {
self.busy
.filter(|(at, _)| now.saturating_sub(*at) < self.settings.grace)
}
pub fn reason(&self, now: Duration) -> Option<String> {
self.holding(now)
.map(|(_, label)| format!("{label} is working"))
}
pub fn countdown(&self, now: Duration) -> Option<Duration> {
let (at, _) = self.holding(now)?;
Some((at + self.settings.grace).saturating_sub(now))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn args(a: &[&str]) -> Vec<String> {
a.iter().map(|s| s.to_string()).collect()
}
#[test]
fn identifies_tools_by_name_or_script() {
let label = |n: &str, a: &[&str]| identify(n, &args(a)).map(|t| t.label);
assert_eq!(label("claude", &[]), Some("Claude Code"));
assert_eq!(label("ollama", &["ollama", "serve"]), Some("Ollama"));
assert_eq!(label("llama-server", &[]), Some("llama.cpp"));
assert_eq!(label("LM Studio", &[]), Some("LM Studio"));
assert_eq!(label("node", &["node", "/opt/homebrew/bin/pi"]), Some("pi"));
assert_eq!(
label(
"Python",
&["python3", "-m", "mlx_lm.server", "--port", "8080"]
),
Some("MLX")
);
assert_eq!(
label("python3.12", &["python3.12", "-m", "vllm"]),
Some("vLLM")
);
assert_eq!(label("vim", &["vim", "claude"]), None);
assert_eq!(label("node", &["node", "server.js"]), None);
assert_eq!(label("node", &["node", "jan.config.js"]), None);
assert_eq!(label("python3", &["python3", "llama.py"]), None);
assert_eq!(label("claude.exe", &[]), Some("Claude Code"));
assert_eq!(
label("2.1.335", &["claude", "--resume"]),
Some("Claude Code")
);
assert_eq!(label("2.1.335", &["/usr/bin/vim"]), None);
assert_eq!(label("claudette", &[]), None);
assert_eq!(label("Claude", &[]), Some("the Claude app"));
assert_eq!(label("CLAUDE", &[]), Some("Claude Code"));
}
fn tool(label: &str) -> &'static Tool {
TOOLS.iter().find(|t| t.label == label).unwrap()
}
fn seen(pid: u32, label: &str, cpu_ms: u64) -> Seen {
Seen {
pid,
tool: tool(label),
procs: vec![(pid, Duration::from_millis(cpu_ms))],
}
}
#[test]
fn a_child_exiting_does_not_hide_work() {
let ms = Duration::from_millis;
let tree = |procs: Vec<(u32, Duration)>| Seen {
pid: 7,
tool: tool("Claude Code"),
procs,
};
let mut w = Watch::default();
w.sample(
S(0),
&[tree(vec![(7, ms(10_000)), (8, ms(100_000))])],
None,
None,
);
assert!(
w.sample(S(15), &[tree(vec![(7, ms(10_500))])], None, None)
.is_some()
);
}
const S: fn(u64) -> Duration = Duration::from_secs;
#[test]
fn only_the_chosen_categories_count() {
let agents_only = Settings {
local: false,
..Settings::default()
};
let mut w = Watch::new(agents_only);
w.sample(S(0), &[seen(1, "Ollama", 0)], None, None);
assert_eq!(
w.sample(S(15), &[seen(1, "Ollama", 10_000)], None, None),
None
);
w.sample(S(30), &[seen(2, "Claude Code", 0)], None, None);
assert!(
w.sample(S(45), &[seen(2, "Claude Code", 500)], None, None)
.is_some()
);
}
#[test]
fn every_tool_is_in_one_category() {
let agents: Vec<_> = labels(false).collect();
let local: Vec<_> = labels(true).collect();
assert!(agents.contains(&"Claude Code") && agents.contains(&"Cursor"));
assert!(local.contains(&"Ollama") && local.contains(&"LM Studio"));
assert_eq!(agents.len() + local.len(), TOOLS.len());
}
#[test]
fn busy_agent_holds_and_grace_runs_out() {
let mut w = Watch::default();
assert_eq!(
w.sample(S(0), &[seen(7, "Claude Code", 1000)], None, None),
None
);
assert_eq!(
w.sample(S(15), &[seen(7, "Claude Code", 1300)], None, None)
.as_deref(),
Some("Claude Code is working")
);
assert!(
w.sample(S(30), &[seen(7, "Claude Code", 1300)], None, None)
.is_some()
);
let grace = Settings::default().grace;
assert_eq!(grace, S(15 * 60));
assert_eq!(w.countdown(S(30)), Some(grace - S(15)));
assert!(w.reason(S(15) + grace - S(1)).is_some());
assert_eq!(w.reason(S(15) + grace), None);
assert_eq!(w.countdown(S(15) + grace), None);
}
#[test]
fn open_but_idle_tools_do_not_hold() {
let mut w = Watch::default();
let idle = [seen(7, "Claude Code", 1000), seen(9, "Ollama", 5000)];
w.sample(S(0), &idle, Some(3), None);
let idle = [seen(7, "Claude Code", 1030), seen(9, "Ollama", 5100)];
assert_eq!(w.sample(S(15), &idle, Some(3), None), None);
}
#[test]
fn server_needs_real_work_or_a_busy_gpu() {
let mut w = Watch::default();
w.sample(S(0), &[seen(9, "Ollama", 0)], None, None);
assert_eq!(w.sample(S(15), &[seen(9, "Ollama", 400)], None, None), None);
assert_eq!(
w.sample(S(30), &[seen(9, "Ollama", 600)], Some(85), None)
.as_deref(),
Some("Ollama is working")
);
let mut w = Watch::default();
w.sample(S(0), &[seen(9, "Ollama", 0)], Some(90), None);
assert_eq!(
w.sample(S(15), &[seen(9, "Ollama", 10)], Some(90), None),
None
);
let mut w = Watch::default();
w.sample(S(0), &[seen(7, "Claude Code", 0)], Some(90), None);
assert_eq!(
w.sample(S(15), &[seen(7, "Claude Code", 0)], Some(90), None),
None
);
}
#[test]
fn names_the_agent_when_its_app_is_busy_too() {
let mut w = Watch::default();
w.sample(
S(0),
&[seen(1, "the Claude app", 0), seen(2, "Claude Code", 0)],
None,
None,
);
let busy = [seen(1, "the Claude app", 5000), seen(2, "Claude Code", 500)];
assert_eq!(
w.sample(S(15), &busy, None, None).as_deref(),
Some("Claude Code is working")
);
}
fn ticks(busy: u64, total: u64) -> Option<CpuTicks> {
Some(CpuTicks { busy, total })
}
#[test]
fn a_busy_mac_extends_an_ai_hold_but_never_starts_one() {
let mut w = Watch::new(Settings {
grace: S(60),
idle_cpu: 0.10,
..Settings::default()
});
let quiet = [seen(7, "Claude Code", 0)];
w.sample(S(0), &quiet, None, ticks(0, 1000));
assert_eq!(w.sample(S(15), &quiet, None, ticks(500, 2000)), None);
assert!(
w.sample(
S(30),
&[seen(7, "Claude Code", 500)],
None,
ticks(600, 3000)
)
.is_some()
);
let mut now = 30;
let mut t = (600, 3000);
for _ in 0..10 {
now += 15;
t = (t.0 + 300, t.1 + 1000);
assert!(
w.sample(
S(now),
&[seen(7, "Claude Code", 500)],
None,
ticks(t.0, t.1)
)
.is_some()
);
}
for _ in 0..4 {
now += 15;
t = (t.0 + 100, t.1 + 1000);
w.sample(
S(now),
&[seen(7, "Claude Code", 500)],
None,
ticks(t.0, t.1),
);
}
assert_eq!(w.reason(S(now)), None);
}
#[test]
fn new_process_starts_from_its_first_sample() {
let mut w = Watch::default();
w.sample(S(0), &[], None, None);
assert_eq!(
w.sample(S(15), &[seen(3, "Codex", 10_000)], None, None),
None
);
assert!(
w.sample(S(30), &[seen(3, "Codex", 10_500)], None, None)
.is_some()
);
}
}