Skip to main content

agentmux_srv_core/backend/cli_native/
pids.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The CLI process srv runs for each agent pane, by block: what a sender's
5//! process id is walked up to ([`super::sender`]).
6
7use std::collections::HashMap;
8use std::sync::{LazyLock, Mutex};
9
10static CLI_PIDS: LazyLock<Mutex<HashMap<String, u32>>> = LazyLock::new(Default::default);
11
12fn pids() -> std::sync::MutexGuard<'static, HashMap<String, u32>> {
13    CLI_PIDS.lock().unwrap_or_else(|e| e.into_inner())
14}
15
16/// `pid` is now the CLI process of `block_id`.
17pub fn set(block_id: &str, pid: u32) {
18    if pid != 0 {
19        pids().insert(block_id.to_string(), pid);
20    }
21}
22
23/// The CLI process `pid` of `block_id` ended. A replacement that already took
24/// the slot stays.
25pub fn clear(block_id: &str, pid: u32) {
26    let mut g = pids();
27    if g.get(block_id) == Some(&pid) {
28        g.remove(block_id);
29    }
30}
31
32/// Every (block, CLI process) pair.
33pub fn snapshot() -> Vec<(String, u32)> {
34    pids().iter().map(|(b, p)| (b.clone(), *p)).collect()
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn a_replacement_process_is_not_cleared_by_the_old_ones_exit() {
43        let b = format!("pids-{}", uuid::Uuid::new_v4());
44        set(&b, 111);
45        set(&b, 222);
46        clear(&b, 111);
47        assert!(snapshot().contains(&(b.clone(), 222)));
48        clear(&b, 222);
49        assert!(!snapshot().iter().any(|(k, _)| *k == b));
50    }
51}