kaeru 0.1.7

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! The OS's process table, read with sysinfo, which uses each OS's native
//! process APIs.

use std::path::Path;

use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};

use super::{ProcInfo, ProcessTable, lineage, liveness};
use crate::engine::note::ProcessRef;
use crate::engine::rules::Liveness;

/// A snapshot of the processes that run on this computer.
///
/// The snapshot reads every process's id, parent, name and start time at
/// once, which is fast. The slower details, the executable path, the command
/// line and the working folder, are read only for the processes that
/// [`SystemTable::lineage`] walks or [`SystemTable::find`] finds.
pub struct SystemTable {
    system: System,
}

impl SystemTable {
    /// Returns a snapshot of the processes that run now.
    pub fn snapshot() -> Self {
        let mut system = System::new();
        system.refresh_processes_specifics(
            ProcessesToUpdate::All,
            true,
            ProcessRefreshKind::nothing(),
        );
        SystemTable { system }
    }

    /// Returns the process and its ancestors, nearest first, with their
    /// executable paths and command lines.
    pub fn lineage(&mut self, pid: u32) -> Vec<ProcInfo> {
        let pids: Vec<Pid> = lineage(self, pid)
            .iter()
            .map(|process| Pid::from_u32(process.pid))
            .collect();
        self.system.refresh_processes_specifics(
            ProcessesToUpdate::Some(&pids),
            false,
            ProcessRefreshKind::nothing()
                .with_exe(UpdateKind::Always)
                .with_cmd(UpdateKind::Always),
        );
        lineage(self, pid)
    }

    /// Returns the processes whose executable name `wanted` accepts, with
    /// their executable paths, command lines and working folders.
    pub fn find(&mut self, wanted: impl Fn(&str) -> bool) -> Vec<ProcInfo> {
        let pids: Vec<Pid> = self
            .system
            .processes()
            .iter()
            .filter(|(_, process)| wanted(&process.name().to_string_lossy()))
            .map(|(&pid, _)| pid)
            .collect();
        self.system.refresh_processes_specifics(
            ProcessesToUpdate::Some(&pids),
            false,
            ProcessRefreshKind::nothing()
                .with_exe(UpdateKind::Always)
                .with_cmd(UpdateKind::Always)
                .with_cwd(UpdateKind::Always),
        );
        pids.iter()
            .filter_map(|pid| self.get(pid.as_u32()))
            .collect()
    }
}

impl SystemTable {
    /// Ends a process, when it is still the process that `process` names,
    /// and returns whether it did. A process whose start time doesn't match
    /// is another one that got the same id, and is left alone.
    pub fn end(&self, process: &ProcessRef) -> bool {
        liveness(self, process) == Liveness::Running
            && self
                .system
                .process(Pid::from_u32(process.pid))
                .is_some_and(sysinfo::Process::kill)
    }
}

impl ProcessTable for SystemTable {
    fn get(&self, pid: u32) -> Option<ProcInfo> {
        let process = self.system.process(Pid::from_u32(pid))?;
        let arguments: Vec<String> = process
            .cmd()
            .iter()
            .map(|argument| argument.to_string_lossy().into_owned())
            .collect();
        let parent = process.parent().map(Pid::as_u32);
        // sysinfo reports start times in whole seconds, and 0 when it can't
        // inspect the process.
        let (parent, started_ms) = match process.start_time() {
            0 => not_inspected(pid).unwrap_or((parent, None)),
            seconds => (parent, Some(seconds * 1000)),
        };
        Some(ProcInfo {
            pid,
            parent,
            name: process.name().to_string_lossy().into_owned(),
            exe: process.exe().map(Path::to_path_buf),
            started_ms,
            command_line: (!arguments.is_empty()).then(|| arguments.join(" ")),
            arguments,
            cwd: process.cwd().map(Path::to_path_buf),
        })
    }
}

/// Returns the parent and the start time of a process that sysinfo can't
/// inspect, from the OS. On macOS, sysinfo can't inspect a process of
/// another user, such as `login`, which runs as root and starts each
/// terminal tab's shell, so without this a tab's lineage would end there.
#[cfg(target_os = "macos")]
fn not_inspected(pid: u32) -> Option<(Option<u32>, Option<u64>)> {
    crate::os::process_basics(pid).map(|basics| (basics.parent, basics.started_ms))
}

/// Returns `None`: on this OS, the OS tells nothing more about a process
/// that sysinfo can't inspect.
#[cfg(not(target_os = "macos"))]
fn not_inspected(_pid: u32) -> Option<(Option<u32>, Option<u64>)> {
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn finds_this_test_process() {
        let me = SystemTable::snapshot().get(std::process::id()).unwrap();
        assert!(me.started_ms.is_some());
        assert!(me.parent.is_some());
    }

    #[test]
    fn the_lineage_has_details() {
        let chain = SystemTable::snapshot().lineage(std::process::id());
        let me = chain.first().unwrap();
        assert_eq!(me.pid, std::process::id());
        assert!(me.exe.is_some());
        assert!(me.command_line.is_some());
        assert!(!me.arguments.is_empty());
    }

    // launchd, the first process, runs as root, and so do the login
    // programs between a terminal and its tabs' shells.
    #[cfg(target_os = "macos")]
    #[test]
    fn processes_of_other_users_have_a_parent_and_a_start_time() {
        let table = SystemTable::snapshot();
        assert!(table.get(1).unwrap().started_ms.is_some());
        for (pid, process) in table.system.processes() {
            let pid = pid.as_u32();
            // A process that ended since the snapshot is skipped.
            if pid > 1 && process.start_time() == 0 && crate::os::process_basics(pid).is_some() {
                let found = table.get(pid).unwrap();
                assert!(found.parent.is_some(), "{found:?}");
                assert!(found.started_ms.is_some(), "{found:?}");
            }
        }
    }

    #[test]
    fn found_processes_have_their_working_folder() {
        let mut table = SystemTable::snapshot();
        let me = table.get(std::process::id()).unwrap();
        let found = table.find(|name| name == me.name);
        let me = found
            .iter()
            .find(|process| process.pid == std::process::id())
            .unwrap();
        assert_eq!(me.cwd, Some(std::env::current_dir().unwrap()));
    }
}