kaeru 0.1.1

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! The rule that decides what a note means: the tab is open, closed, or
//! waiting to come back.
//!
//! [`decide`] is the exact definition. docs/architecture.md explains it with
//! a table, and the tests below follow that table row by row, so change all
//! three together.

use serde::{Deserialize, Serialize};

/// Whether a process recorded in a note is still the same running process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Liveness {
    /// It runs, and its start time matches the note.
    Running,
    /// It ended, or its id now belongs to another process.
    Gone,
    /// It exists but can't be inspected, for example because it runs
    /// elevated. It counts as running, to avoid offering a tab that may
    /// still be open.
    Unknown,
}

/// How a terminal maps tabs to processes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TerminalShape {
    /// One app process hosts many tabs, as in Windows Terminal, Warp and
    /// iTerm2. When the app is gone, the whole terminal went away.
    Tabs,
    /// Each window is its own process with one shell, as in Git Bash
    /// (mintty) and the classic Windows console. Closing the window is the
    /// same as closing the tab.
    SingleWindow,
}

/// What closing a single-window terminal means. The user chooses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SingleWindowClose {
    /// Like closing a tab: kaeru forgets the tab. It still comes back after
    /// a restart or sign-out.
    #[default]
    Forget,
    /// Like closing the whole terminal: kaeru offers to reopen the tab.
    Offer,
}

/// What a note means right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabState {
    /// The tab still runs.
    Open,
    /// You closed the tab, so its note can be deleted.
    Closed,
    /// The tab went away together with its terminal, so kaeru offers to
    /// reopen it.
    Waiting,
}

/// Everything the rule needs to know about one note.
#[derive(Debug, Clone, Copy)]
pub struct Facts {
    /// Whether the note's own process still runs.
    pub program: Liveness,
    /// Whether the terminal still runs, or `None` when the note has no known
    /// terminal. A note without one is treated like a single window.
    pub terminal: Option<Liveness>,
    /// The terminal's shape, from its adapter.
    pub shape: TerminalShape,
    /// Whether the note was written during the current boot and sign-in.
    pub same_session: bool,
    /// What the user chose for closed single-window terminals.
    pub single_window_close: SingleWindowClose,
}

/// Returns what a note means, given the facts about it.
pub fn decide(facts: &Facts) -> TabState {
    // No process outlives a restart or a sign-out, so in a later session a
    // process that can't be inspected is one that reused the id. Windows
    // hides the start time of many system processes.
    let gone = |liveness: Liveness| {
        liveness == Liveness::Gone || (liveness == Liveness::Unknown && !facts.same_session)
    };
    if !gone(facts.program) {
        return TabState::Open;
    }
    let terminal = facts.terminal.map(|terminal| {
        if gone(terminal) {
            Liveness::Gone
        } else {
            terminal
        }
    });
    match (terminal, facts.shape) {
        (Some(Liveness::Running | Liveness::Unknown), _) => TabState::Closed,
        (Some(Liveness::Gone), TerminalShape::Tabs) => TabState::Waiting,
        // A single window, or an unknown terminal: the window and the tab
        // ended together.
        _ if !facts.same_session => TabState::Waiting,
        _ => match facts.single_window_close {
            SingleWindowClose::Forget => TabState::Closed,
            SingleWindowClose::Offer => TabState::Waiting,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::Liveness::{Gone, Running, Unknown};
    use super::SingleWindowClose::{Forget, Offer};
    use super::TabState::{Closed, Open, Waiting};
    use super::TerminalShape::{SingleWindow, Tabs};
    use super::*;

    fn decide_for(
        program: Liveness,
        terminal: Option<Liveness>,
        shape: TerminalShape,
        same_session: bool,
        single_window_close: SingleWindowClose,
    ) -> TabState {
        decide(&Facts {
            program,
            terminal,
            shape,
            same_session,
            single_window_close,
        })
    }

    #[test]
    fn a_running_program_is_open() {
        for terminal in [Some(Running), Some(Gone), Some(Unknown), None] {
            assert_eq!(decide_for(Running, terminal, Tabs, true, Forget), Open);
            assert_eq!(decide_for(Unknown, terminal, Tabs, true, Offer), Open);
        }
    }

    #[test]
    fn a_tab_closed_while_its_terminal_runs_is_closed() {
        for shape in [Tabs, SingleWindow] {
            assert_eq!(decide_for(Gone, Some(Running), shape, true, Offer), Closed);
            assert_eq!(decide_for(Gone, Some(Unknown), shape, true, Offer), Closed);
        }
    }

    #[test]
    fn after_a_restart_a_process_that_cant_be_inspected_reused_the_id() {
        // The terminal's old id now belongs to a hidden system process.
        assert_eq!(
            decide_for(Gone, Some(Unknown), Tabs, false, Forget),
            Waiting
        );
        // The shell's old id does.
        assert_eq!(
            decide_for(Unknown, Some(Gone), Tabs, false, Forget),
            Waiting
        );
        assert_eq!(
            decide_for(Unknown, Some(Unknown), Tabs, false, Forget),
            Waiting
        );
    }

    #[test]
    fn a_tab_whose_whole_terminal_went_away_is_waiting() {
        assert_eq!(decide_for(Gone, Some(Gone), Tabs, true, Forget), Waiting);
        assert_eq!(decide_for(Gone, Some(Gone), Tabs, false, Forget), Waiting);
    }

    #[test]
    fn a_closed_single_window_is_forgotten_by_default() {
        assert_eq!(
            decide_for(Gone, Some(Gone), SingleWindow, true, Forget),
            Closed
        );
    }

    #[test]
    fn a_closed_single_window_can_be_offered_instead() {
        assert_eq!(
            decide_for(Gone, Some(Gone), SingleWindow, true, Offer),
            Waiting
        );
    }

    #[test]
    fn a_single_window_comes_back_after_a_restart() {
        for option in [Forget, Offer] {
            assert_eq!(
                decide_for(Gone, Some(Gone), SingleWindow, false, option),
                Waiting
            );
        }
    }

    #[test]
    fn an_unknown_terminal_behaves_like_a_single_window() {
        assert_eq!(decide_for(Gone, None, Tabs, true, Forget), Closed);
        assert_eq!(decide_for(Gone, None, Tabs, false, Forget), Waiting);
    }
}