Skip to main content

agentmux_srv_core/backend/tower/
kind.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What kind of process each Tower row is (`TowerProcess::kind`;
5//! SPEC_TOWER_THEME_SURFACE_AND_COLOR_2026_10_17.md §3.2).
6//!
7//! The first rule that matches wins:
8//!
9//! 1. AgentMux's own: its task, a process it described, or an AgentMux name.
10//! 2. The main process of an agent pane: an agent, whatever its executable.
11//! 3. The main process of a terminal pane: a shell.
12//! 4. A generic runtime (`node`, `python`, …) inside a pane's task, by its
13//!    command line: a package manager or build tool, or an agent CLI's
14//!    package. Read here, never sent: only the kind leaves srv.
15//! 5. The name, in one table: every provider's CLI, then known names, then
16//!    known prefixes.
17//! 6. Anything else is an app.
18//!
19//! Another machine's rows carry names only, so they get rules 1 (by name)
20//! and 5 ([`fill_missing`]).
21
22use std::collections::{HashMap, HashSet};
23use std::sync::LazyLock;
24
25use crate::backend::rpc_types::{TowerProcessKind as K, TowerProcessRole, TowerSnapshot, TowerTaskKind};
26
27/// A name as the table knows it: lower case, without `.exe`, without a
28/// version after a dash (`agentmux-srv-0.59.30-windows.x64` → `agentmux-srv`)
29/// or glued on (`python3.12` → `python`, `idea64` → `idea`).
30pub fn normalize(name: &str) -> String {
31    let mut n = name.trim().to_lowercase();
32    if let Some(stripped) = n.strip_suffix(".exe") {
33        n = stripped.to_string();
34    }
35    let parts: Vec<&str> = n.split('-').collect();
36    if let Some(at) = parts.iter().position(|p| p.starts_with(|c: char| c.is_ascii_digit())) {
37        if at > 0 {
38            n = parts[..at].join("-");
39        }
40    }
41    let trimmed = n.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.');
42    if trimmed.len() >= 2 && trimmed.len() < n.len() && trimmed.ends_with(|c: char| c.is_ascii_alphabetic()) {
43        n = trimmed.to_string();
44    }
45    n
46}
47
48/// Names, after [`normalize`].
49const NAMES: &[(K, &[&str])] = &[
50    (
51        K::Agents,
52        &[
53            "ollama", "ollama app", "ollama_llama_server", "llama-server", "llama-cli", "lmstudio", "lm studio",
54            "lms", "koboldcpp", "jan", "gpt4all", "cursor-agent", "amp", "chatgpt",
55        ],
56    ),
57    (
58        K::Shells,
59        &[
60            // Shells and terminal hosts.
61            "bash", "sh", "zsh", "fish", "nu", "dash", "ksh", "tcsh", "csh", "elvish", "xonsh", "pwsh",
62            "powershell", "cmd", "conhost", "openconsole", "windowsterminal", "wt", "tmux", "screen", "login",
63            "wezterm", "wezterm-gui", "alacritty", "kitty", "iterm2", "terminal", "gnome-terminal-server",
64            "konsole", "xterm", "ghostty", "warp",
65            // Remote sessions.
66            "ssh", "sshd", "mosh-client", "mosh-server", "sftp", "scp", "telnet",
67            // Commands run in them.
68            "grep", "rg", "ag", "sed", "awk", "gawk", "find", "fd", "xargs", "head", "tail", "cat", "less",
69            "more", "sort", "uniq", "wc", "cut", "tr", "tee", "jq", "yq", "fold", "ls", "cp", "mv", "rm",
70            "mkdir", "touch", "chmod", "sleep", "watch", "timeout", "env", "curl", "wget", "http", "nc", "ping",
71            "tar", "zip", "unzip", "7z", "gzip", "xz", "du", "df", "ps", "top", "htop", "btop", "kill", "which",
72            "where", "findstr", "clip", "tasklist", "taskkill", "netstat", "ipconfig", "whoami", "hostname",
73            "date", "diff", "patch", "rsync", "fzf", "bat", "eza", "tree",
74        ],
75    ),
76    (
77        K::Builds,
78        &[
79            // Compilers, linkers, build systems.
80            "cargo", "rustc", "rustup", "rustfmt", "clippy-driver", "cargo-clippy", "cargo-nextest", "rustdoc",
81            "cc", "c++", "cl", "link", "lib", "ml", "rc", "mt", "lld", "lld-link", "ld", "ld.lld", "gold", "ar",
82            "ranlib", "nm", "strip", "objcopy", "clang", "clang++", "clang-cl", "gcc", "g++", "cc1", "cc1plus",
83            "as", "collect2", "make", "mingw32-make", "gmake", "cmake", "ninja", "meson", "bazel", "bazelisk",
84            "buck2", "msbuild", "vbcscompiler", "csc", "tsc", "esbuild", "swc", "go", "compile", "asm", "gradle",
85            "mvn", "ant", "javac", "kotlinc", "scalac", "sbt", "zig", "nim", "ghc", "dune", "swiftc",
86            "swift-frontend", "xcodebuild", "xcrun", "protoc", "flatc", "wasm-pack", "wasm-opt", "wasm-bindgen",
87            "trunk", "task", "just",
88            // Package managers.
89            "npm", "npx", "pnpm", "yarn", "pip", "uv", "uvx", "poetry", "pipx", "conda", "mamba", "gem", "bundle",
90            "bundler", "composer", "brew", "apt", "apt-get", "dpkg", "dnf", "yum", "pacman", "winget", "choco",
91            "scoop", "nuget", "vcpkg",
92            // Version control.
93            "git", "git-remote-https", "git-lfs", "git-credential-manager", "gh", "gh-agent", "glab", "hg", "svn",
94            "jj",
95            // Test runners with their own executable.
96            "pytest", "cargo-test",
97        ],
98    ),
99    (
100        K::Runtimes,
101        &[
102            "node", "nodejs", "deno", "bun", "python", "pythonw", "py", "ruby", "rubyw", "java", "javaw", "dotnet",
103            "php", "php-cgi", "perl", "lua", "luajit", "r", "rscript", "julia", "erl", "beam.smp", "elixir", "iex",
104            "mono", "wasmtime", "wasmer",
105            // Language servers.
106            "rust-analyzer", "gopls", "clangd", "pylsp", "omnisharp", "sourcekit-lsp", "lua-language-server",
107            "zls", "marksman", "taplo", "eslint_d",
108            // Databases and local servers.
109            "postgres", "postmaster", "mysqld", "mariadbd", "mongod", "mongos", "redis-server", "valkey-server",
110            "sqlservr", "memcached", "etcd", "clickhouse", "influxd", "nginx", "httpd", "apache2", "caddy",
111            "traefik", "envoy", "haproxy", "php-fpm", "iisexpress", "w3wp",
112        ],
113    ),
114    (
115        K::Browsers,
116        &[
117            "chrome", "msedge", "firefox", "brave", "opera", "vivaldi", "safari", "chromium", "chromium-browser",
118            "msedgewebview", "iexplore", "arc", "plugin-container", "chrome-native-host", "safariviewservice",
119        ],
120    ),
121    (
122        K::Containers,
123        &[
124            "docker", "dockerd", "docker desktop", "docker-desktop", "containerd", "runc", "podman",
125            "podman-machine", "buildkitd", "minikube", "colima", "limactl", "vboxheadless", "vboxsvc",
126            "vboxnetdhcp", "vmmem", "vmmemwsl", "vmwp", "vmcompute", "vmms", "wsl", "wslhost", "wslrelay",
127            "wslservice", "hyperkit", "vpnkit", "utm", "virtualbox", "vmnat", "vmnetdhcp",
128        ],
129    ),
130    (
131        K::Editors,
132        &[
133            "code", "code - insiders", "cursor", "windsurf", "zed", "sublime_text", "subl", "atom", "notepad++",
134            "notepad", "idea", "pycharm", "webstorm", "rider", "goland", "clion", "rustrover", "datagrip",
135            "phpstorm", "studio", "devenv", "xcode", "nvim", "vim", "gvim", "emacs", "nano", "hx", "helix", "kak",
136            "micro", "fleet",
137        ],
138    ),
139    (
140        K::System,
141        &[
142            // Windows.
143            "system", "registry", "idle", "secure system", "memory compression", "smss", "csrss", "wininit",
144            "winlogon", "services", "lsass", "lsaiso", "svchost", "dwm", "explorer", "runtimebroker", "dllhost",
145            "taskhostw", "sihost", "fontdrvhost", "ctfmon", "searchhost", "searchindexer", "searchprotocolhost",
146            "searchfilterhost", "wmiprvse", "spoolsv", "audiodg", "textinputhost", "startmenuexperiencehost",
147            "shellexperiencehost", "shellhost", "applicationframehost", "backgroundtaskhost", "unsecapp", "wudfhost",
148            "dashost", "aggregatorhost", "smartscreen", "securityhealthservice", "securityhealthsystray",
149            "securityhealthhost", "sechealthui", "msmpeng", "mpdefendercoreservice", "nissrv", "sgrmbroker",
150            "sysmon", "lsm", "ngciso", "widgetservice", "widgetboard", "phoneexperiencehost", "lockapp",
151            "useroobebroker", "crossdeviceresume", "tabtip", "mousocoreworker", "trustedinstaller", "tiworker",
152            "compattelrunner", "msiexec", "werfault", "ipoverusbsvc", "defendersessionhelper",
153            "midisrv", "monotificationux", "apphostregistrationverifier",
154            // macOS.
155            "kernel_task", "launchd", "windowserver", "mds", "mds_stores", "mdworker", "mdworker_shared",
156            "coreaudiod", "loginwindow", "distnoted", "cfprefsd", "trustd", "syspolicyd", "opendirectoryd",
157            "configd", "powerd", "logd", "notifyd", "coreservicesd", "bluetoothd", "airportd", "controlcenter",
158            "systemuiserver", "usereventagent", "secd", "nsurlsessiond", "sharingd", "rapportd", "finder", "dock",
159            "spotlight", "corespotlightd",
160            // Linux.
161            "init", "kthreadd", "kswapd", "dbus-daemon", "dbus-broker", "xorg", "xwayland", "gnome-shell",
162            "plasmashell", "kwin_x11", "kwin_wayland", "pipewire", "wireplumber", "pulseaudio", "networkmanager",
163            "polkitd", "udisksd", "upowerd", "cron", "crond", "rsyslogd", "snapd", "agetty", "kauditd",
164            "khugepaged", "oom_reaper", "gdm", "sddm", "lightdm",
165        ],
166    ),
167];
168
169/// Prefixes, after [`normalize`]; the longest that matches wins.
170const PREFIXES: &[(K, &[&str])] = &[
171    (K::Agentmux, &["agentmux"]),
172    (K::Browsers, &["google chrome", "microsoft edge", "firefox", "brave browser", "com.apple.webkit.", "msedgewebview"]),
173    (K::Containers, &["com.docker.", "containerd-shim", "qemu-", "qemu-system", "vmware", "virtualbox", "vbox", "lima", "com.apple.virtualization."]),
174    (K::Editors, &["code helper", "cursor helper", "jetbrains"]),
175    (
176        K::System,
177        &[
178            "systemd", "kworker/", "ksoftirqd/", "migration/", "rcu_", "irq/", "jbd2/", "watchdog/", "com.apple.",
179            "nvcontainer", "nvdisplay.container", "nvidia", "amd3dvcache", "amdrs", "amdppkg", "amdfend", "amdow",
180            "amdappcompat", "atiesrxx", "atieclxx", "radeonsoftware", "rtk", "realtek", "igfx", "intelcp", "logi_",
181            "logioptionsplus", "lghub", "razer", "asus", "dtsapo", "nahimic", "securityhealth", "mpdefender",
182            "searchapp", "microsoft.photos", "microsoftstartfeedprovider",
183        ],
184    ),
185];
186
187static BY_NAME: LazyLock<HashMap<&'static str, K>> = LazyLock::new(|| {
188    let mut m = HashMap::new();
189    for (kind, names) in NAMES {
190        for n in *names {
191            m.insert(*n, *kind);
192        }
193    }
194    m
195});
196
197/// Every provider's CLI, from the registry (`providers::all_providers`), so a
198/// new provider is an agent here with no edit.
199static AGENT_CLIS: LazyLock<HashSet<String>> =
200    LazyLock::new(|| crate::backend::providers::all_providers().map(|p| normalize(p.cli_command)).collect());
201
202/// Every provider's npm packages: what a `node` running an agent CLI has in
203/// its command line.
204static AGENT_PACKAGES: LazyLock<Vec<String>> = LazyLock::new(|| {
205    let mut out = Vec::new();
206    for p in crate::backend::providers::all_providers() {
207        if !p.npm_package.is_empty() {
208            out.push(p.npm_package.to_ascii_lowercase());
209        }
210        for (pkg, _) in p.companion_npm_packages() {
211            out.push(pkg.to_ascii_lowercase());
212        }
213    }
214    out
215});
216
217/// What `name` alone says (rules 1 by name, and 5).
218pub fn by_name(name: &str) -> K {
219    let n = normalize(name);
220    if AGENT_CLIS.contains(&n) {
221        return K::Agents;
222    }
223    if let Some(&kind) = BY_NAME.get(n.as_str()) {
224        return kind;
225    }
226    PREFIXES
227        .iter()
228        .flat_map(|(kind, prefixes)| prefixes.iter().map(move |p| (*kind, *p)))
229        .filter(|(_, p)| n.starts_with(p))
230        .max_by_key(|(_, p)| p.len())
231        .map(|(kind, _)| kind)
232        .unwrap_or(K::Apps)
233}
234
235/// A runtime whose command line says more than its name (rule 4).
236pub fn is_generic_runtime(name: &str) -> bool {
237    matches!(
238        normalize(name).as_str(),
239        "node" | "nodejs" | "python" | "pythonw" | "py" | "java" | "javaw" | "dotnet" | "deno" | "bun" | "ruby" | "php"
240    )
241}
242
243/// Build and package tools a runtime runs, by their npm package: matched only
244/// as the package directory of the script it runs (`/node_modules/<pkg>/`) or
245/// as a `node_modules/.bin/<tool>` shim, never as any part of a path, so a
246/// project at `~/turbo-app` is not a build.
247const BUILD_PACKAGES: &[&str] = &[
248    "npm", "pnpm", "yarn", "corepack", "vite", "webpack", "webpack-cli", "jest", "vitest", "mocha",
249    "esbuild", "rollup", "turbo", "playwright", "@playwright/test", "eslint", "prettier", "@biomejs/biome", "nx",
250    "parcel", "gulp", "grunt", "lerna", "@changesets/cli", "@angular/cli",
251];
252
253/// The same tools as a `node_modules/.bin/` shim names them.
254const BUILD_BINS: &[&str] = &[
255    "npm", "npx", "pnpm", "yarn", "vite", "webpack", "tsc", "jest", "vitest", "mocha", "esbuild", "rollup", "turbo",
256    "playwright", "eslint", "prettier", "biome", "nx", "parcel", "gulp", "grunt", "lerna", "changeset", "ng",
257];
258
259/// Python modules (`-m <module>`) and scripts that build, test or install.
260const BUILD_PYTHON: &[&str] = &[
261    "pytest", "pip", "pip3", "build", "unittest", "tox", "nox", "poetry", "pdm", "hatch", "twine", "maturin", "mypy",
262    "ruff", "setup.py",
263];
264
265/// A command line's words, double quotes respected: `"C:\Program Files\x"`
266/// is one word.
267fn words(command_line: &str) -> Vec<String> {
268    let mut out = Vec::new();
269    let mut word = String::new();
270    let mut quoted = false;
271    for ch in command_line.chars() {
272        match ch {
273            '"' => quoted = !quoted,
274            c if c.is_whitespace() && !quoted => {
275                if !word.is_empty() {
276                    out.push(std::mem::take(&mut word));
277                }
278            }
279            c => word.push(c),
280        }
281    }
282    if !word.is_empty() {
283        out.push(word);
284    }
285    out
286}
287
288/// The last part of a path, after `/`.
289fn basename(path: &str) -> &str {
290    path.rsplit('/').next().unwrap_or(path)
291}
292
293/// What a generic runtime's command line says (rule 4): `None` keeps it a
294/// runtime. Only what it runs counts, never any word of a path: the script's
295/// package directory, a `.bin` shim, Python's `-m` module or script name, a
296/// JVM's launcher class, `dotnet`'s verb. Pure: the caller reads the command
297/// line.
298pub fn by_command_line(command_line: &str) -> Option<K> {
299    let words: Vec<String> = words(&command_line.to_ascii_lowercase().replace('\\', "/"));
300    let program = basename(words.first()?).trim_end_matches(".exe").to_string();
301    let rest = &words[1..];
302    // The first word that isn't a flag: the script a runtime runs.
303    let script = rest.iter().find(|w| !w.starts_with('-')).map(String::as_str).unwrap_or("");
304    let in_package = |pkg: &str| script.contains(&format!("/node_modules/{pkg}/"));
305
306    if AGENT_PACKAGES.iter().any(|p| in_package(p)) {
307        return Some(K::Agents);
308    }
309    match normalize(&program).as_str() {
310        "node" | "nodejs" | "deno" | "bun" => {
311            let shim = script
312                .rsplit_once("/node_modules/.bin/")
313                .is_some_and(|(_, tool)| BUILD_BINS.contains(&tool.trim_end_matches(".js")));
314            let yarn_release = script.contains("/.yarn/releases/");
315            // TypeScript's package also holds its language server: only `tsc` builds.
316            let tsc = script.contains("/node_modules/typescript/bin/tsc")
317                || script.contains("/node_modules/typescript/lib/tsc.js");
318            (BUILD_PACKAGES.iter().any(|p| in_package(p)) || shim || yarn_release || tsc).then_some(K::Builds)
319        }
320        "python" | "pythonw" | "py" => {
321            let module = rest.iter().position(|w| w == "-m").and_then(|i| rest.get(i + 1));
322            let named = module.map(String::as_str).unwrap_or_else(|| basename(script));
323            let named = named.trim_end_matches(".exe");
324            BUILD_PYTHON.contains(&named).then_some(K::Builds)
325        }
326        // Gradle's daemon and Maven run in a JVM: their launcher classes say so.
327        "java" | "javaw" => rest
328            .iter()
329            .any(|w| w.starts_with("org.gradle.") || w.contains("org.codehaus.plexus.classworlds") || w.contains("plexus-classworlds"))
330            .then_some(K::Builds),
331        "dotnet" => {
332            let verb = matches!(script, "build" | "test" | "restore" | "publish" | "pack" | "msbuild");
333            let tool = matches!(basename(script), "msbuild.dll" | "vbcscompiler.dll");
334            (verb || tool).then_some(K::Builds)
335        }
336        _ => None,
337    }
338}
339
340/// Where a process sits, for rules 1–3.
341#[derive(Debug, Clone, Copy, Default)]
342pub struct Context {
343    /// Its part in a pane's task, and that task's kind.
344    pub task: Option<(TowerProcessRole, TowerTaskKind)>,
345    /// One of AgentMux's own, by its grouping or a description.
346    pub agentmux: bool,
347}
348
349/// The kind, from where the process sits (rules 1–3), else `named`: what its
350/// name, or its command line, said ([`by_name`], [`by_command_line`]).
351pub fn classify(ctx: Context, named: K) -> K {
352    if ctx.agentmux || named == K::Agentmux {
353        return K::Agentmux;
354    }
355    match ctx.task {
356        Some((_, TowerTaskKind::Agentmux)) => K::Agentmux,
357        Some((TowerProcessRole::Main, TowerTaskKind::Agent)) => K::Agents,
358        Some((TowerProcessRole::Main, TowerTaskKind::Terminal)) => K::Shells,
359        _ => named,
360    }
361}
362
363/// Fill the kind of every row that has none: another machine's frame (names
364/// only), or a paired computer's AgentMux that predates kinds, whose tasks
365/// still say what each process is to its pane, so rules 1–3 apply there too.
366pub fn fill_missing(snap: &mut TowerSnapshot) {
367    use crate::backend::rpc_types::TowerProcess;
368    let kind_of = |p: &TowerProcess, task: Option<TowerTaskKind>, role: Option<TowerProcessRole>| {
369        let ctx = Context {
370            task: task.map(|t| (role.unwrap_or(TowerProcessRole::Started), t)),
371            agentmux: p.detail.is_some(),
372        };
373        classify(ctx, by_name(&p.name))
374    };
375    // A host row names its task; its role is on the task's own row for it.
376    let mut placed: HashMap<String, (TowerTaskKind, Option<TowerProcessRole>)> = HashMap::new();
377    for t in &mut snap.tasks {
378        for p in t.processes.iter_mut().chain(t.exited.iter_mut().flatten()) {
379            placed.insert(p.id.clone(), (t.kind, p.role));
380            if p.kind.is_none() {
381                p.kind = Some(kind_of(p, Some(t.kind), p.role));
382            }
383        }
384    }
385    let task_kinds: HashMap<String, TowerTaskKind> = snap.tasks.iter().map(|t| (t.id.clone(), t.kind)).collect();
386    if let Some(host) = snap.host.as_mut() {
387        for p in &mut host.processes {
388            if p.kind.is_some() {
389                continue;
390            }
391            let (task, role) = match placed.get(&p.id) {
392                Some(&(kind, role)) => (Some(kind), role),
393                None => (p.task.as_ref().and_then(|t| task_kinds.get(t)).copied(), None),
394            };
395            p.kind = Some(kind_of(p, task, role));
396        }
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn names_are_normalized_before_lookup() {
406        assert_eq!(normalize("agentmux-srv-0.59.30-windows.x64.exe"), "agentmux-srv");
407        assert_eq!(normalize("agentmux-0.59.28.exe"), "agentmux");
408        assert_eq!(normalize("python3.12"), "python");
409        assert_eq!(normalize("idea64.exe"), "idea");
410        assert_eq!(normalize("MsEdgeWebView2.exe"), "msedgewebview");
411        assert_eq!(normalize("x86_64-w64-mingw32-gcc"), "x86_64-w64-mingw32-gcc");
412        assert_eq!(normalize("7z.exe"), "7z");
413        assert_eq!(normalize("Google Chrome Helper (Renderer)"), "google chrome helper (renderer)");
414    }
415
416    #[test]
417    fn names_from_each_os_get_their_kind() {
418        let cases = [
419            ("svchost.exe", K::System),
420            ("csrss.exe", K::System),
421            ("kernel_task", K::System),
422            ("WindowServer", K::System),
423            ("kworker/0:1H-events", K::System),
424            ("systemd-journald", K::System),
425            ("nvcontainer.exe", K::System),
426            ("conhost.exe", K::Shells),
427            ("bash", K::Shells),
428            ("pwsh.exe", K::Shells),
429            ("grep", K::Shells),
430            ("cargo.exe", K::Builds),
431            ("rustc", K::Builds),
432            ("git.exe", K::Builds),
433            ("gh-agent", K::Builds),
434            ("node.exe", K::Runtimes),
435            ("python3.11", K::Runtimes),
436            ("rust-analyzer", K::Runtimes),
437            ("postgres", K::Runtimes),
438            ("chrome.exe", K::Browsers),
439            ("msedgewebview2.exe", K::Browsers),
440            ("Google Chrome Helper (Renderer)", K::Browsers),
441            ("com.apple.WebKit.WebContent", K::Browsers),
442            ("vmmemWSL", K::Containers),
443            ("com.docker.backend.exe", K::Containers),
444            ("Docker Desktop.exe", K::Containers),
445            ("qemu-system-x86_64", K::Containers),
446            ("Code.exe", K::Editors),
447            ("Code Helper (Renderer)", K::Editors),
448            ("idea64.exe", K::Editors),
449            ("ollama.exe", K::Agents),
450            ("agentmux-cef.exe", K::Agentmux),
451            ("agentmux-srv-0.59.30-windows.x64.exe", K::Agentmux),
452            ("Discord.exe", K::Apps),
453            ("KeePass.exe", K::Apps),
454            ("CodeMeter.exe", K::Apps),
455            ("", K::Apps),
456        ];
457        for (name, want) in cases {
458            assert_eq!(by_name(name), want, "{name}");
459        }
460    }
461
462    #[test]
463    fn every_provider_cli_is_an_agent() {
464        for p in crate::backend::providers::all_providers() {
465            assert_eq!(by_name(p.cli_command), K::Agents, "{}", p.cli_command);
466            assert_eq!(by_name(&format!("{}.exe", p.cli_command)), K::Agents, "{}", p.cli_command);
467        }
468    }
469
470    #[test]
471    fn a_runtime_command_line_says_build_or_agent() {
472        let npm = r#""C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" install"#;
473        assert_eq!(by_command_line(npm), Some(K::Builds));
474        assert_eq!(by_command_line("node /repo/node_modules/vite/bin/vite.js --port 5173"), Some(K::Builds));
475        assert_eq!(by_command_line("node --max-old-space-size=4096 /repo/node_modules/.bin/vitest run"), Some(K::Builds));
476        assert_eq!(by_command_line("node /repo/.yarn/releases/yarn-4.1.0.cjs install"), Some(K::Builds));
477        assert_eq!(by_command_line("node /repo/node_modules/typescript/bin/tsc -p ."), Some(K::Builds));
478        assert_eq!(by_command_line("python -m pytest tests/"), Some(K::Builds));
479        assert_eq!(by_command_line("python3 /repo/.venv/bin/pytest -q"), Some(K::Builds));
480        assert_eq!(by_command_line("python setup.py build"), Some(K::Builds));
481        assert_eq!(by_command_line(r#""C:\dotnet\dotnet.exe" build app.sln"#), Some(K::Builds));
482        let gradle = "java -Xmx2g -cp /home/u/.gradle/wrapper/dists/gradle-8.5/lib/gradle-launcher-8.5.jar \
483                      org.gradle.launcher.daemon.bootstrap.GradleDaemon 8.5";
484        assert_eq!(by_command_line(gradle), Some(K::Builds));
485        let gemini = r"C:\Users\x\AppData\Roaming\npm\node_modules\@google\gemini-cli\dist\index.js";
486        assert_eq!(by_command_line(&format!("node {gemini}")), Some(K::Agents));
487        let claude = "/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js";
488        assert_eq!(by_command_line(&format!("node --no-warnings {claude} --print")), Some(K::Agents));
489        // A server or a language server stays a runtime.
490        assert_eq!(by_command_line("node server.js"), None);
491        assert_eq!(by_command_line("node /x/node_modules/typescript/lib/tsserver.js"), None);
492        assert_eq!(by_command_line("python manage.py runserver"), None);
493        assert!(is_generic_runtime("node.exe") && is_generic_runtime("python3.12") && !is_generic_runtime("cargo"));
494    }
495
496    #[test]
497    fn a_tool_name_in_a_project_path_is_not_a_build() {
498        // A tool's name as any part of a path proves nothing: only what runs counts.
499        for c in [
500            "node /home/u/yarn-site/server.js",
501            "node /home/u/turbo-app/server.js",
502            "node /srv/jest-dashboard/index.js",
503            "node /work/webpack-notes/serve.js --gradle",
504            "node /work/nx/app.js",
505            "python /home/u/setup.py.d/serve.py",
506            "python /home/u/pytest-reports/app.py",
507            "java -jar /opt/gradle-dashboard/app.jar",
508        ] {
509            assert_eq!(by_command_line(c), None, "{c}");
510        }
511    }
512
513    #[test]
514    fn where_a_process_sits_comes_before_its_name() {
515        let main_of = |kind| Context { task: Some((TowerProcessRole::Main, kind)), agentmux: false };
516        // An agent CLI run by a generic `node`: still the agent pane's agent.
517        assert_eq!(classify(main_of(TowerTaskKind::Agent), K::Runtimes), K::Agents);
518        assert_eq!(classify(main_of(TowerTaskKind::Terminal), K::Apps), K::Shells);
519        assert_eq!(classify(main_of(TowerTaskKind::Agentmux), K::Apps), K::Agentmux);
520        let started = Context { task: Some((TowerProcessRole::Started, TowerTaskKind::Agent)), agentmux: false };
521        assert_eq!(classify(started, K::Builds), K::Builds, "what an agent runs keeps its own kind");
522        assert_eq!(classify(Context { task: None, agentmux: true }, K::Browsers), K::Agentmux, "a renderer is AgentMux's");
523        assert_eq!(classify(Context::default(), K::Agentmux), K::Agentmux);
524    }
525
526    #[test]
527    fn an_older_paired_snapshot_is_filled_from_its_tasks() {
528        use crate::backend::rpc_types::{TowerHost, TowerProcess, TowerTask};
529        let row = |id: &str, name: &str, role: Option<TowerProcessRole>, task: Option<&str>| TowerProcess {
530            id: id.into(),
531            name: name.into(),
532            role,
533            task: task.map(str::to_string),
534            ..Default::default()
535        };
536        let task = |id: &str, kind, processes| TowerTask {
537            id: id.into(),
538            kind,
539            label: id.into(),
540            tracking: "high".into(),
541            cpu: None,
542            cpu_account: false,
543            mem: 0,
544            processes,
545            exited: None,
546        };
547        let mut snap = TowerSnapshot {
548            ts_ms: 0,
549            hostname: "studio".into(),
550            panes: None,
551            memory: None,
552            os: "macos".into(),
553            cpu_count: 1,
554            memory_metric: String::new(),
555            interval_ms: 2000,
556            remote: true,
557            tasks: vec![
558                task("agent-a", TowerTaskKind::Agent, vec![
559                    row("1:1", "node", Some(TowerProcessRole::Main), None),
560                    row("2:1", "cargo", Some(TowerProcessRole::Started), None),
561                ]),
562                task("agentmux", TowerTaskKind::Agentmux, vec![row("3:1", "helper-x", Some(TowerProcessRole::Main), None)]),
563            ],
564            machine: None,
565            host: Some(TowerHost {
566                processes: vec![
567                    row("1:1", "node", None, Some("agent-a")),
568                    row("3:1", "helper-x", None, Some("agentmux")),
569                    row("9:1", "node", None, None),
570                ],
571                unmeasured: 0,
572                cpu: None,
573                mem: 0,
574                total: 3,
575                matched: 3,
576            }),
577        };
578        fill_missing(&mut snap);
579        let kinds = |ps: &[TowerProcess]| ps.iter().map(|p| p.kind).collect::<Vec<_>>();
580        assert_eq!(kinds(&snap.tasks[0].processes), vec![Some(K::Agents), Some(K::Builds)], "the agent's own node is the agent");
581        assert_eq!(kinds(&snap.tasks[1].processes), vec![Some(K::Agentmux)]);
582        assert_eq!(
583            kinds(&snap.host.unwrap().processes),
584            vec![Some(K::Agents), Some(K::Agentmux), Some(K::Runtimes)],
585            "host rows take their task's reading; a node of no task is a runtime"
586        );
587    }
588
589    #[test]
590    fn a_frame_without_kinds_is_filled_by_name() {
591        use crate::backend::rpc_types::{TowerHost, TowerProcess};
592        let mut snap = TowerSnapshot {
593            ts_ms: 0,
594            hostname: "h".into(),
595            panes: None,
596            memory: None,
597            os: "linux".into(),
598            cpu_count: 1,
599            memory_metric: String::new(),
600            interval_ms: 2000,
601            remote: true,
602            tasks: Vec::new(),
603            machine: None,
604            host: Some(TowerHost {
605                processes: vec![
606                    TowerProcess { name: "cargo".into(), ..Default::default() },
607                    TowerProcess { name: "node".into(), kind: Some(K::Builds), ..Default::default() },
608                ],
609                unmeasured: 0,
610                cpu: None,
611                mem: 0,
612                total: 2,
613                matched: 2,
614            }),
615        };
616        fill_missing(&mut snap);
617        let kinds: Vec<_> = snap.host.unwrap().processes.into_iter().map(|p| p.kind).collect();
618        assert_eq!(kinds, vec![Some(K::Builds), Some(K::Builds)], "a kind already set is kept");
619    }
620}