kaeru 0.1.1

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! A note is what kaeru remembers about one process: a shell tab or an agent
//! session. Each note is a small JSON file; docs/architecture.md says where
//! the files are kept.

use serde::{Deserialize, Serialize};

use crate::engine::rules::TerminalShape;

/// A process, identified by its id and its start time, to avoid mistaking a
/// new process that reused an old id for the one in a note.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProcessRef {
    pub pid: u32,
    /// The start time, in milliseconds since the Unix epoch.
    pub started_ms: u64,
}

/// The terminal a tab runs in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TerminalRef {
    /// The adapter's id, such as `windows-terminal`.
    pub adapter: String,
    /// The terminal app's process.
    pub process: ProcessRef,
    /// The terminal's shape, from its adapter.
    pub shape: TerminalShape,
    /// A tab id that survives the terminal's own session restore, if the
    /// terminal has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tab_id: Option<String>,
    /// The terminal profile to reopen the tab with, if the terminal has
    /// profiles.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile: Option<String>,
    /// The terminal app's executable, so that tabs reopen in the same copy
    /// of the terminal, such as a portable one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exe: Option<String>,
}

/// One note: a shell tab or an agent session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Note {
    /// A shell running in a tab.
    Shell(ShellNote),
    /// An agent session running in a tab.
    Agent(AgentNote),
}

impl Note {
    /// Returns the process the note is about.
    pub fn process(&self) -> &ProcessRef {
        match self {
            Note::Shell(note) => &note.process,
            Note::Agent(note) => &note.process,
        }
    }

    /// Returns the terminal the note's tab runs in, if kaeru knows it.
    pub fn terminal(&self) -> Option<&TerminalRef> {
        match self {
            Note::Shell(note) => note.terminal.as_ref(),
            Note::Agent(note) => note.terminal.as_ref(),
        }
    }

    /// Returns the boot and sign-in session the note was written in.
    pub fn session(&self) -> &str {
        match self {
            Note::Shell(note) => &note.session,
            Note::Agent(note) => &note.session,
        }
    }

    /// Returns whether a new tab already asked the user about this note.
    pub fn offered(&self) -> bool {
        match self {
            Note::Shell(note) => note.offered,
            Note::Agent(note) => note.offered,
        }
    }

    /// Records that a new tab asked the user about this note.
    pub fn set_offered(&mut self) {
        match self {
            Note::Shell(note) => note.offered = true,
            Note::Agent(note) => note.offered = true,
        }
    }
}

/// A shell running in a terminal tab.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShellNote {
    /// The shell's process.
    pub process: ProcessRef,
    /// The shell's name, such as `powershell`, `bash` or `zsh`.
    pub shell: String,
    /// The last known folder. The shell snippet keeps it current.
    pub cwd: String,
    /// The terminal the tab runs in, if kaeru knows it.
    pub terminal: Option<TerminalRef>,
    /// The boot and sign-in session the note was written in.
    pub session: String,
    /// Whether the user was already asked about this tab.
    #[serde(default)]
    pub offered: bool,
}

/// An agent session, such as Claude Code or Codex, running in a tab.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentNote {
    /// The agent's process.
    pub process: ProcessRef,
    /// The agent's id, such as `claude`.
    pub agent: String,
    /// The agent's own id for the conversation, used to resume it.
    pub conversation: String,
    /// The folder the session started in, which its tab comes back in.
    pub cwd: String,
    /// The tab's shell, which the agent runs in. It links this note to that
    /// tab's [`ShellNote`].
    pub shell: Option<ProcessRef>,
    /// The name of that shell, such as `powershell`, so that the tab can come
    /// back in the same shell even when the shell has no note.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shell_name: Option<String>,
    /// The terminal the tab runs in, if kaeru knows it.
    pub terminal: Option<TerminalRef>,
    /// Where the agent keeps the conversation, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transcript: Option<String>,
    /// The boot and sign-in session the note was written in.
    pub session: String,
    /// Whether the user was already asked about this session.
    #[serde(default)]
    pub offered: bool,
}

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

    fn terminal() -> TerminalRef {
        TerminalRef {
            adapter: "windows-terminal".into(),
            process: ProcessRef {
                pid: 1000,
                started_ms: 1_700_000_000_000,
            },
            shape: TerminalShape::Tabs,
            tab_id: Some("00000000-0000-4000-8000-00000000000a".into()),
            profile: None,
            exe: Some(r"C:\tools\terminal\WindowsTerminal.exe".into()),
        }
    }

    #[test]
    fn notes_survive_a_round_trip_through_json() {
        let notes = [
            Note::Shell(ShellNote {
                process: ProcessRef {
                    pid: 2000,
                    started_ms: 1_700_000_100_000,
                },
                shell: "powershell".into(),
                cwd: r"C:\Users\demo\code\api-server".into(),
                terminal: Some(terminal()),
                session: "boot-1".into(),
                offered: false,
            }),
            Note::Agent(AgentNote {
                process: ProcessRef {
                    pid: 3000,
                    started_ms: 1_700_000_200_000,
                },
                agent: "claude".into(),
                conversation: "00000000-0000-4000-8000-000000000001".into(),
                cwd: "/home/demo/code/mobile-app".into(),
                shell: Some(ProcessRef {
                    pid: 2000,
                    started_ms: 1_700_000_100_000,
                }),
                shell_name: Some("powershell".into()),
                terminal: Some(terminal()),
                transcript: None,
                session: "boot-1".into(),
                offered: true,
            }),
        ];
        for note in notes {
            let json = serde_json::to_string(&note).unwrap();
            assert_eq!(serde_json::from_str::<Note>(&json).unwrap(), note);
        }
    }

    #[test]
    fn the_kind_is_written_as_a_tag() {
        let json = serde_json::to_value(Note::Shell(ShellNote {
            process: ProcessRef {
                pid: 1,
                started_ms: 1,
            },
            shell: "bash".into(),
            cwd: "/tmp".into(),
            terminal: None,
            session: "s".into(),
            offered: false,
        }))
        .unwrap();
        assert_eq!(json["kind"], "shell");
    }

    #[test]
    fn fields_from_newer_versions_are_ignored() {
        let json = r#"{"kind":"shell","process":{"pid":1,"started_ms":1},"shell":"zsh",
            "cwd":"/tmp","terminal":null,"session":"s","added_later":42}"#;
        let note: Note = serde_json::from_str(json).unwrap();
        assert!(matches!(
            note,
            Note::Shell(ShellNote { offered: false, .. })
        ));
    }
}