Skip to main content

agentmux_launcher/
splash_info.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Identity shown in the splash footer: `user@host` and `v<version>` (+ a dev
5//! label on non-stable builds). Gathered once in the launcher and handed to each
6//! platform's splash backend, so the three render identical content.
7//!
8//! All sourcing is dependency-light and best-effort — a missing field falls back
9//! to a placeholder and never blocks or crashes the splash.
10
11#[cfg(windows)]
12use agentmux_common::win32::NoWindow;
13use std::process::Command;
14
15pub struct SplashInfo {
16    pub user: String,
17    pub host: String,
18    pub version: String,
19    /// `Some` only on non-stable builds (dev / explicit channel); `None` on a
20    /// stable release (footer then shows just the version).
21    pub dev_label: Option<String>,
22}
23
24impl SplashInfo {
25    pub fn gather() -> Self {
26        SplashInfo {
27            user: username(),
28            host: hostname(),
29            version: env!("CARGO_PKG_VERSION").to_string(),
30            dev_label: dev_label(),
31        }
32    }
33
34    /// `gather`, and one line in the launcher log saying what this splash presents and why it is on screen
35    /// (`reason`: `start`, `restart`, `upgrade`). The splash's version is the launcher's own, fixed when it
36    /// was built; this line is the record of it, so a splash that showed a version other than the one starting
37    /// can be told from the log, with the path of the launcher that painted it.
38    pub fn gather_and_log(reason: &str) -> Self {
39        let info = Self::gather();
40        let exe = std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default();
41        crate::log(&info.log_line(reason, &exe));
42        info
43    }
44
45    /// `stable` for a release; the dev label (`dev`, or the explicit channel) otherwise.
46    pub fn channel(&self) -> &str {
47        self.dev_label.as_deref().unwrap_or("stable")
48    }
49
50    /// The launcher-log line for a splash being painted.
51    pub fn log_line(&self, reason: &str, exe: &str) -> String {
52        format!("splash: painting version={} channel={} reason={} exe={}", self.version, self.channel(), reason, exe)
53    }
54
55    /// The footer lines to render (each clamped to `max_chars`):
56    /// line 1 = `user@host`, line 2 = `v<version>` (+ ` DEV` on dev builds).
57    pub fn footer_lines(&self, max_chars: usize) -> Vec<String> {
58        let l1 = ellipsize(&format!("{}@{}", self.user, self.host), max_chars);
59        let l2 = match &self.dev_label {
60            Some(d) => format!("v{} {}", self.version, d.to_uppercase()),
61            None => format!("v{}", self.version),
62        };
63        vec![l1, ellipsize(&l2, max_chars)]
64    }
65}
66
67fn username() -> String {
68    for k in ["USER", "USERNAME", "LOGNAME"] {
69        if let Ok(v) = std::env::var(k) {
70            let v = sanitize(v.trim());
71            if !v.is_empty() {
72                return v;
73            }
74        }
75    }
76    cmd_first_line("whoami", &[])
77        .map(|s| sanitize(s.trim()))
78        .filter(|s| !s.is_empty())
79        .unwrap_or_else(|| "user".into())
80}
81
82fn hostname() -> String {
83    // Prefer env (no subprocess); COMPUTERNAME on Windows, HOSTNAME elsewhere.
84    for k in ["HOSTNAME", "COMPUTERNAME", "HOST"] {
85        if let Ok(v) = std::env::var(k) {
86            let v = short_host(v.trim());
87            if !v.is_empty() {
88                return v;
89            }
90        }
91    }
92    cmd_first_line("hostname", &[])
93        .map(|s| short_host(s.trim()))
94        .filter(|s| !s.is_empty())
95        .unwrap_or_else(|| "host".into())
96}
97
98/// `None` on a stable release; otherwise a short badge.
99/// - `AGENTMUX_DEV=1` (set by `task dev`) → `dev`.
100/// - explicit `AGENTMUX_CHANNEL` other than `stable` → that channel.
101/// (Baked per-build local channels without an env override are treated as stable
102/// for the footer in v1 — see SPEC §3 "dev_label".)
103fn dev_label() -> Option<String> {
104    if std::env::var("AGENTMUX_DEV")
105        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
106        .unwrap_or(false)
107    {
108        return Some("dev".into());
109    }
110    if let Ok(ch) = std::env::var("AGENTMUX_CHANNEL") {
111        let ch = sanitize(ch.trim());
112        if !ch.is_empty() && ch != "stable" {
113            return Some(ch);
114        }
115    }
116    None
117}
118
119/// First non-empty stdout line of `cmd args`, trimmed. `None` on any failure.
120fn cmd_first_line(cmd: &str, args: &[&str]) -> Option<String> {
121    let mut command = Command::new(cmd);
122    command.args(args);
123    #[cfg(windows)]
124    {
125        // CREATE_NO_WINDOW: console-flash suppression.
126        command.no_window();
127    }
128    let out = command.output().ok()?;
129    if !out.status.success() {
130        return None;
131    }
132    String::from_utf8_lossy(&out.stdout)
133        .lines()
134        .map(|l| l.trim().to_string())
135        .find(|l| !l.is_empty())
136}
137
138/// Keep printable ASCII (0x20..0x7E); replace anything else with '?'. The splash
139/// font only carries ASCII, so this keeps the footer legible for odd names.
140fn sanitize(s: &str) -> String {
141    s.chars()
142        .map(|c| if (' '..='~').contains(&c) { c } else { '?' })
143        .collect()
144}
145
146/// Short hostname: first dot-segment, sanitized (`devbox.local` → `devbox`).
147fn short_host(s: &str) -> String {
148    sanitize(s.split('.').next().unwrap_or(s))
149}
150
151/// Middle-ellipsize `s` to at most `max` chars so the footer never widens the card.
152pub(crate) fn ellipsize(s: &str, max: usize) -> String {
153    let chars: Vec<char> = s.chars().collect();
154    if chars.len() <= max {
155        return s.to_string();
156    }
157    if max <= 3 {
158        return chars.iter().take(max).collect();
159    }
160    let keep = max - 3;
161    let left = keep.div_ceil(2);
162    let right = keep - left;
163    let head: String = chars[..left].iter().collect();
164    let tail: String = chars[chars.len() - right..].iter().collect();
165    format!("{head}...{tail}")
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    fn info(version: &str, dev_label: Option<&str>) -> SplashInfo {
173        SplashInfo { user: "asaf".into(), host: "narko".into(), version: version.into(), dev_label: dev_label.map(str::to_string) }
174    }
175
176    #[test]
177    fn footer_names_the_user_and_the_version_of_this_build() {
178        assert_eq!(info("0.60.34", None).footer_lines(40), vec!["asaf@narko".to_string(), "v0.60.34".to_string()]);
179    }
180
181    #[test]
182    fn a_dev_or_explicit_channel_build_says_so_in_capitals() {
183        assert_eq!(info("0.60.34", Some("dev")).footer_lines(40)[1], "v0.60.34 DEV");
184        assert_eq!(info("0.60.34", Some("canary")).footer_lines(40)[1], "v0.60.34 CANARY");
185    }
186
187    #[test]
188    fn a_long_footer_is_clamped_to_the_card() {
189        let lines = info("0.60.34", Some("a-very-long-channel-name")).footer_lines(12);
190        assert!(lines.iter().all(|l| l.chars().count() <= 12), "{lines:?}");
191    }
192
193    #[test]
194    fn the_version_is_this_build_s_own() {
195        assert_eq!(SplashInfo::gather().version, env!("CARGO_PKG_VERSION"));
196    }
197
198    #[test]
199    fn the_log_line_says_version_channel_reason_and_which_launcher() {
200        let line = info("0.60.34", None).log_line("start", "C:/Programs/AgentMux/agentmux.exe");
201        assert_eq!(line, "splash: painting version=0.60.34 channel=stable reason=start exe=C:/Programs/AgentMux/agentmux.exe");
202        let dev = info("0.60.34", Some("dev")).log_line("restart", "x");
203        assert_eq!(dev, "splash: painting version=0.60.34 channel=dev reason=restart exe=x");
204    }
205}