kaeru 0.1.4

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Tabs: notes grouped into the tabs they belong to. An agent session joins
//! the note of the shell it ran in, so that the tab is listed once and comes
//! back once, with the session resumed.

use crate::engine::config::Config;
use crate::engine::note::{AgentNote, Note, ProcessRef, TerminalRef};

/// A tab: the note of its shell, and the notes of the agent sessions that
/// ran in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tab {
    /// The indexes of the tab's notes in the list that [`group`] got.
    pub notes: Vec<usize>,
    /// The folder the tab is in, which is also the one it comes back in.
    pub cwd: String,
    /// The tab's shell, such as `powershell`, or `None` when no note says.
    pub shell: Option<String>,
    /// The agent session that ran in the tab, if one did.
    pub agent: Option<AgentNote>,
    /// The terminal the tab ran in.
    pub terminal: TerminalRef,
    /// When the tab's shell, or its agent when it has no shell note,
    /// started.
    pub started_ms: u64,
}

/// How long after an agent started its tab's prompt must have shown, for
/// kaeru to know that the agent ended. Start times are whole seconds, so a
/// prompt that showed just before the agent started can look a little later.
const PROMPT_AFTER_AGENT_MS: u64 = 2_000;

/// What kaeru last saw of a note's tab.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Seen {
    /// The folder the tab was last in.
    pub cwd: String,
    /// When the tab's shell last showed its prompt, in milliseconds since
    /// the Unix epoch, if its snippet records that.
    pub prompt_ms: Option<u64>,
}

/// Returns the tabs that notes belong to, in the order the picker shows them:
/// tabs with an agent session first, then the others, each oldest first.
/// Each note comes with what kaeru last saw of its tab. Notes without a
/// terminal are left out, because their tabs can't come back. An agent whose
/// tab showed its prompt after the agent started has ended, because the
/// prompt shows only once the agent no longer runs, so its tab comes back as
/// a plain shell.
pub fn group(notes: &[(Note, Seen)]) -> Vec<Tab> {
    let mut tabs = Vec::new();
    let mut shells: Vec<(ProcessRef, Option<u64>)> = Vec::new();
    for (index, (note, seen)) in notes.iter().enumerate() {
        if let Note::Shell(shell) = note
            && let Some(terminal) = &shell.terminal
        {
            shells.push((shell.process, seen.prompt_ms));
            tabs.push(Tab {
                notes: vec![index],
                cwd: seen.cwd.clone(),
                shell: Some(shell.shell.clone()),
                agent: None,
                terminal: terminal.clone(),
                started_ms: shell.process.started_ms,
            });
        }
    }
    for (index, (note, _)) in notes.iter().enumerate() {
        let Note::Agent(agent) = note else { continue };
        let Some(terminal) = &agent.terminal else {
            continue;
        };
        let shell_tab = agent
            .shell
            .and_then(|shell| shells.iter().position(|(known, _)| *known == shell));
        match shell_tab {
            Some(position) => {
                let ended = shells[position].1.is_some_and(|prompt_ms| {
                    prompt_ms > agent.process.started_ms + PROMPT_AFTER_AGENT_MS
                });
                let tab = &mut tabs[position];
                tab.notes.push(index);
                // Of two sessions in one tab, the newer one comes back.
                if !ended
                    && tab
                        .agent
                        .as_ref()
                        .is_none_or(|known| known.process.started_ms < agent.process.started_ms)
                {
                    tab.cwd = agent.cwd.clone();
                    tab.agent = Some(agent.clone());
                }
            }
            None => tabs.push(Tab {
                notes: vec![index],
                cwd: agent.cwd.clone(),
                shell: agent.shell_name.clone(),
                agent: Some(agent.clone()),
                terminal: terminal.clone(),
                started_ms: agent.process.started_ms,
            }),
        }
    }
    tabs.sort_by_key(|tab| (tab.agent.is_none(), tab.started_ms));
    tabs
}

/// Returns the waiting tabs that the picker offers: the tabs that [`group`]
/// returns, without the kinds of tabs that the options leave out.
pub fn to_offer(waiting: &[(Note, Seen)], config: &Config) -> Vec<Tab> {
    let mut tabs = group(waiting);
    tabs.retain(|tab| {
        if tab.agent.is_some() {
            config.offer_agents
        } else {
            config.offer_shells
        }
    });
    tabs
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::note::ShellNote;
    use crate::engine::rules::TerminalShape;

    fn terminal() -> TerminalRef {
        TerminalRef {
            adapter: "windows-terminal".into(),
            process: ProcessRef {
                pid: 1,
                started_ms: 100,
            },
            shape: TerminalShape::Tabs,
            tab_id: None,
            profile: None,
            exe: None,
        }
    }

    fn shell(pid: u32, started_ms: u64) -> (Note, Seen) {
        let note = Note::Shell(ShellNote {
            process: ProcessRef { pid, started_ms },
            shell: "powershell".into(),
            cwd: r"C:\Users\demo".into(),
            terminal: Some(terminal()),
            session: "win-1".into(),
            offered: false,
        });
        let seen = Seen {
            cwd: format!(r"C:\Users\demo\code\tab-{pid}"),
            prompt_ms: None,
        };
        (note, seen)
    }

    fn agent(pid: u32, started_ms: u64, shell: Option<(u32, u64)>) -> (Note, Seen) {
        let note = Note::Agent(AgentNote {
            process: ProcessRef { pid, started_ms },
            agent: "claude".into(),
            conversation: "00000000-0000-4000-8000-000000000001".into(),
            cwd: format!(r"C:\Users\demo\code\agent-{pid}"),
            shell: shell.map(|(pid, started_ms)| ProcessRef { pid, started_ms }),
            shell_name: Some("pwsh".into()),
            shell_exe: None,
            terminal: Some(terminal()),
            transcript: None,
            session: "win-1".into(),
            offered: false,
        });
        (note, Seen::default())
    }

    #[test]
    fn an_agent_that_ended_before_its_tab_showed_a_prompt_again_is_dropped() {
        let (shell_note, mut seen) = shell(10, 1_000);
        // The prompt showed again well after the agent started: it ended.
        seen.prompt_ms = Some(60_000);
        let notes = [(shell_note, seen), agent(20, 2_000, Some((10, 1_000)))];
        let tabs = group(&notes);
        assert_eq!(tabs[0].notes, [0, 1], "the agent's note still goes with it");
        assert!(tabs[0].agent.is_none());
        assert_eq!(tabs[0].cwd, r"C:\Users\demo\code\tab-10");
    }

    #[test]
    fn an_agent_still_runs_when_the_last_prompt_came_before_it() {
        let (shell_note, mut seen) = shell(10, 1_000);
        // The prompt the user typed the agent's command at, rounded later.
        seen.prompt_ms = Some(3_500);
        let notes = [(shell_note, seen), agent(20, 2_000, Some((10, 1_000)))];
        assert!(group(&notes)[0].agent.is_some());
    }

    #[test]
    fn an_agent_joins_the_tab_of_its_shell() {
        let notes = [shell(10, 1_000), agent(20, 2_000, Some((10, 1_000)))];
        let tabs = group(&notes);
        assert_eq!(tabs.len(), 1);
        assert_eq!(tabs[0].notes, [0, 1]);
        assert_eq!(tabs[0].shell.as_deref(), Some("powershell"));
        assert_eq!(tabs[0].cwd, r"C:\Users\demo\code\agent-20");
        assert!(tabs[0].agent.is_some());
    }

    #[test]
    fn an_agent_without_a_shell_note_is_a_tab_of_its_own() {
        let tabs = group(&[agent(20, 2_000, None)]);
        assert_eq!(tabs.len(), 1);
        assert_eq!(tabs[0].shell.as_deref(), Some("pwsh"));
    }

    #[test]
    fn agent_tabs_come_first_then_the_oldest() {
        let notes = [
            shell(10, 3_000),
            shell(11, 1_000),
            shell(12, 2_000),
            agent(20, 4_000, Some((12, 2_000))),
        ];
        let tabs = group(&notes);
        let first: Vec<usize> = tabs.iter().map(|tab| tab.notes[0]).collect();
        assert_eq!(first, [2, 1, 0]);
    }

    #[test]
    fn the_options_leave_out_a_kind_of_tab() {
        let notes = [
            shell(10, 1_000),
            shell(11, 1_500),
            agent(20, 2_000, Some((11, 1_500))),
        ];
        let no_shells = Config {
            offer_shells: false,
            ..Config::default()
        };
        let no_agents = Config {
            offer_agents: false,
            ..Config::default()
        };
        assert_eq!(to_offer(&notes, &no_shells).len(), 1);
        assert!(to_offer(&notes, &no_shells)[0].agent.is_some());
        assert_eq!(to_offer(&notes, &no_agents).len(), 1);
        assert!(to_offer(&notes, &no_agents)[0].agent.is_none());
        assert_eq!(group(&notes).len(), 2, "every kind is listed");
    }

    #[test]
    fn a_note_without_a_terminal_is_left_out() {
        let (mut note, seen) = shell(10, 1_000);
        if let Note::Shell(shell) = &mut note {
            shell.terminal = None;
        }
        assert!(group(&[(note, seen)]).is_empty());
    }
}