kaeru 0.1.0

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,
}

/// 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 the folder its tab was last in. Notes without a
/// terminal are left out, because their tabs can't come back.
pub fn group(notes: &[(Note, String)]) -> Vec<Tab> {
    let mut tabs = Vec::new();
    let mut shells: Vec<ProcessRef> = Vec::new();
    for (index, (note, cwd)) in notes.iter().enumerate() {
        if let Note::Shell(shell) = note
            && let Some(terminal) = &shell.terminal
        {
            shells.push(shell.process);
            tabs.push(Tab {
                notes: vec![index],
                cwd: 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 tab = &mut tabs[position];
                tab.notes.push(index);
                // Of two sessions in one tab, the newer one comes back.
                if 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, String)], 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, String) {
        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,
        });
        (note, format!(r"C:\Users\demo\code\tab-{pid}"))
    }

    fn agent(pid: u32, started_ms: u64, shell: Option<(u32, u64)>) -> (Note, String) {
        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()),
            terminal: Some(terminal()),
            transcript: None,
            session: "win-1".into(),
            offered: false,
        });
        (note, String::new())
    }

    #[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, cwd) = shell(10, 1_000);
        if let Note::Shell(shell) = &mut note {
            shell.terminal = None;
        }
        assert!(group(&[(note, cwd)]).is_empty());
    }
}