Skip to main content

cellix_term/
notify.rs

1//! Desktop notifications through the terminal: a few bytes the terminal turns into its own
2//! notification, so they reach the person over SSH and through tmux with nothing installed.
3//! Terminals disagree on which sequence they read, so the one sent is chosen by name.
4
5/// Which sequence a terminal reads.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum Notice {
8    /// `OSC 777 ; notify ; title ; body`, with a title: Ghostty, WezTerm, foot, rxvt, Konsole.
9    Osc777,
10    /// `OSC 9 ; text`, iTerm2's, which most others read too. No title of its own.
11    Osc9,
12    /// `OSC 99`, Kitty's own; it reads neither of the others.
13    Osc99,
14}
15
16/// Terminals known to show `OSC 777`.
17const WITH_777: [&str; 6] = ["ghostty", "wezterm", "foot", "rxvt", "konsole", "contour"];
18
19impl Notice {
20    /// Chooses from what the terminal is called: `TERM`, `TERM_PROGRAM`, `LC_TERMINAL`, and
21    /// under tmux the name tmux heard from the terminal outside it, all in one string.
22    pub fn for_terminal(names: &str) -> Self {
23        let names = names.to_lowercase();
24        if names.contains("kitty") {
25            Self::Osc99
26        } else if WITH_777.iter().any(|t| names.contains(t)) {
27            Self::Osc777
28        } else {
29            Self::Osc9
30        }
31    }
32}
33
34/// What the terminal is called, from the environment through `var`, and from tmux when Cellix
35/// runs inside it: there `TERM` names tmux, and over SSH it's often a stand-in.
36pub fn terminal_names(var: impl Fn(&str) -> Option<String>) -> String {
37    let mut names: Vec<String> = ["TERM", "TERM_PROGRAM", "LC_TERMINAL"]
38        .iter()
39        .filter_map(|name| var(name))
40        .collect();
41    if var("TMUX").is_some_and(|v| !v.is_empty()) {
42        let asked = std::process::Command::new("tmux")
43            .args(["display", "-p", "#{client_termname} #{client_termtype}"])
44            .output();
45        if let Ok(output) = asked
46            && output.status.success()
47        {
48            names.push(String::from_utf8_lossy(&output.stdout).trim().to_string());
49        }
50    }
51    names.join(" ")
52}
53
54/// Text as a terminal can carry it in a sequence: no control characters, which would end it
55/// early or start another, and on one line.
56fn clean(text: &str) -> String {
57    let flat: String = text
58        .chars()
59        .map(|c| if c.is_control() { ' ' } else { c })
60        .collect();
61    flat.split_whitespace().collect::<Vec<_>>().join(" ")
62}
63
64/// The bytes that show `title` and `body` as a notification. Inside tmux they're wrapped to
65/// go past it to the terminal, which tmux allows with `allow-passthrough`.
66pub fn sequence(notice: Notice, title: &str, body: &str, tmux: bool) -> String {
67    let (title, body) = (clean(title), clean(body));
68    let inner = match notice {
69        // The title ends at a semicolon, so one inside it would cut it short.
70        Notice::Osc777 => format!("\x1b]777;notify;{};{body}\x1b\\", title.replace(';', ",")),
71        Notice::Osc9 => format!("\x1b]9;{title}: {body}\x1b\\"),
72        // The title, then the body as a second part of the same notification.
73        Notice::Osc99 => {
74            format!(
75                "\x1b]99;i=cellix:d=0:p=title;{title}\x1b\\\x1b]99;i=cellix:d=1:p=body;{body}\x1b\\"
76            )
77        }
78    };
79    if tmux {
80        format!("\x1bPtmux;{}\x1b\\", inner.replace('\x1b', "\x1b\x1b"))
81    } else {
82        inner
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn each_terminal_gets_the_sequence_it_reads() {
92        assert_eq!(
93            Notice::for_terminal("xterm-ghostty ghostty"),
94            Notice::Osc777
95        );
96        assert_eq!(
97            Notice::for_terminal("xterm-256color WezTerm"),
98            Notice::Osc777
99        );
100        assert_eq!(Notice::for_terminal("xterm-kitty"), Notice::Osc99);
101        assert_eq!(
102            Notice::for_terminal("xterm-256color iTerm.app iTerm2"),
103            Notice::Osc9
104        );
105        assert_eq!(Notice::for_terminal(""), Notice::Osc9);
106        // Under tmux over SSH, the name tmux heard is what tells.
107        assert_eq!(
108            Notice::for_terminal("tmux-256color tmux xterm-ghostty"),
109            Notice::Osc777
110        );
111    }
112
113    #[test]
114    fn a_notification_is_one_clean_sequence() {
115        assert_eq!(
116            sequence(Notice::Osc777, "Cellix · api", "Allow Bash?", false),
117            "\x1b]777;notify;Cellix · api;Allow Bash?\x1b\\"
118        );
119        assert_eq!(
120            sequence(Notice::Osc9, "Cellix · api", "Plan ready", false),
121            "\x1b]9;Cellix · api: Plan ready\x1b\\"
122        );
123        // What an agent wrote can't end the sequence early, or split the title.
124        assert_eq!(
125            sequence(Notice::Osc777, "a;b", "run\x1b]0;x\x07 now\nplease", false),
126            "\x1b]777;notify;a,b;run ]0;x now please\x1b\\"
127        );
128        let kitty = sequence(Notice::Osc99, "Cellix", "Done", false);
129        assert!(kitty.contains("p=title;Cellix\x1b\\") && kitty.contains("p=body;Done\x1b\\"));
130    }
131
132    #[test]
133    fn inside_tmux_it_goes_past_tmux() {
134        assert_eq!(
135            sequence(Notice::Osc9, "Cellix", "Done", true),
136            "\x1bPtmux;\x1b\x1b]9;Cellix: Done\x1b\x1b\\\x1b\\"
137        );
138    }
139}