Skip to main content

agentmux_launcher/splash_linux/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Session-aware Linux startup splash.
5//!
6//! The launcher is up in milliseconds; `agentmux-cef` *is* the multi-second cold
7//! start (CEF init + GPU channel + page load). This paints a pulsing logo
8//! over a dark backdrop in that gap — the Linux analogue of `splash.rs` (Win32)
9//! and `splash_mac.rs` (Cocoa).
10//!
11//! The backend is chosen for **centering fidelity**, not to mirror the host's
12//! ozone choice: the X11 backend draws an `override_redirect` window it positions
13//! itself (centered on the primary monitor) and XWayland honors that, so it
14//! centers under both X11 and native-Wayland sessions. A native-Wayland
15//! `xdg_toplevel`, by contrast, cannot self-position — Mutter drops small
16//! toplevels at the top-left, not centered. XWayland is present in nearly every
17//! Wayland session, so we prefer the X11 backend whenever an X server is reachable
18//! and fall back to the Wayland backend only when there is no X display at all.
19//!
20//! Dismiss protocol is the macOS one: `spawn()` sets `AGENTMUX_SPLASH_READY_FILE`
21//! (the host inherits it and writes the file on first paint); the splash thread
22//! polls for that file and tears down, with a safety timeout for a host that
23//! crashes before painting.
24//!
25//! Spec: docs/specs/SPEC_LINUX_SPLASH_SESSION_AWARE_2026_06_20.md
26
27mod wayland;
28mod x11;
29
30use std::sync::mpsc::Receiver;
31use std::time::{Duration, Instant};
32
33use crate::splash_core::{tally_label, trunc, visible_rows, DetailLayout, RowKind, StageTimeline};
34use crate::startup_events::{StartupEvent, StartupStatus};
35
36// ── Shared look (matches splash_mac.rs / splash.rs) ─────────────────────────
37/// Opaque dark backdrop RGB(26, 26, 31) = #1A1A1F.
38pub(crate) const BG_R: u8 = 0x1A;
39pub(crate) const BG_G: u8 = 0x1A;
40pub(crate) const BG_B: u8 = 0x1F;
41/// Backdrop padding around the brain, in px.
42pub(crate) const PADDING: i32 = 28;
43/// ~60 fps animation tick.
44pub(crate) const FRAME_MS: u64 = 16;
45const FADE_IN_S: f32 = 0.2;
46const PULSE_HZ: f32 = 1.1;
47const PULSE_MIN: f32 = 0.73;
48const PULSE_MAX: f32 = 1.0;
49/// Self-dismiss if the host never signals first paint (crash before frame).
50pub(crate) const DISMISS_TIMEOUT: Duration = Duration::from_secs(10);
51/// Rounded-corner radius for the backdrop (px). Matches splash_mac.rs.
52pub(crate) const CORNER_RADIUS_PX: f32 = 16.0;
53/// Opacity fade-out duration on dismiss. Matches splash_mac.rs.
54pub(crate) const FADE_OUT: Duration = Duration::from_millis(160);
55
56// Darkened window-edge border — SPEC_SPLASH_SCREEN_BORDER_2026_08_25.md.
57// Roughly half BG's RGB values, a straightforward "darker than the
58// backdrop" reading; not yet confirmed against a real display. Matches
59// splash.rs / splash_mac.rs.
60pub(crate) const BORDER_R: u8 = 0x0D;
61pub(crate) const BORDER_G: u8 = 0x0D;
62pub(crate) const BORDER_B: u8 = 0x10;
63pub(crate) const BORDER_WIDTH_PX: i32 = 2;
64
65/// Brain logo as straight (non-pre-multiplied) RGBA8, emitted by build.rs.
66pub(crate) static BRAIN_RGBA: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/brain_rgba.bin"));
67include!(concat!(env!("OUT_DIR"), "/brain_dims.rs")); // pub const BRAIN_W / BRAIN_H (i32)
68
69// ── Stage list band (startup telemetry between brain and footer) ─────────────
70/// Muted stage text color — slightly brighter than the footer for readability.
71pub(crate) const STAGE_COLOR: [u8; 3] = [0xA0, 0xA0, 0xAA];
72/// Vertical padding above the first stage line.
73pub(crate) const STAGE_PAD_TOP: i32 = 10;
74/// Vertical gap between stage lines.
75pub(crate) const STAGE_LINE_GAP: i32 = 4;
76/// Maximum number of stage lines shown simultaneously.
77pub(crate) const STAGE_MAX_LINES: usize = 4;
78/// Height of the stage band.
79pub(crate) const STAGE_H: i32 = STAGE_PAD_TOP
80    + STAGE_MAX_LINES as i32 * crate::splash_font::GLYPH_H as i32
81    + (STAGE_MAX_LINES as i32 - 1) * STAGE_LINE_GAP;
82/// Left margin for stage lines (px from card edge).
83pub(crate) const STAGE_X: i32 = 20;
84
85// ── Footer (identity strip near the bottom) ─────────────────────────────────
86/// Muted footer text color (#8A8A93) on the #1A1A1F backdrop.
87pub(crate) const FOOTER_COLOR: [u8; 3] = [0x8A, 0x8A, 0x93];
88pub(crate) const FOOTER_PAD_TOP: i32 = 12;
89pub(crate) const FOOTER_LINE_GAP: i32 = 3;
90pub(crate) const FOOTER_PAD_BOTTOM: i32 = 12;
91/// Bottom band height: top pad + 2 glyph rows + inter-line gap + bottom pad.
92pub(crate) const FOOTER_H: i32 =
93    FOOTER_PAD_TOP + 2 * crate::splash_font::GLYPH_H as i32 + FOOTER_LINE_GAP + FOOTER_PAD_BOTTOM;
94/// Full card dimensions: brain + padding, stage band, footer band.
95pub(crate) const CARD_W: i32 = BRAIN_W + PADDING * 2;
96pub(crate) const CARD_H: i32 = BRAIN_H + PADDING * 2 + STAGE_H + FOOTER_H;
97
98// ── Startup telemetry stage list ─────────────────────────────────────────────
99// Row model, event application (with same-tick count-up deferral), and the
100// frozen-row finalizer now live in `splash_core`, shared with `splash.rs`
101// (Windows) and `splash_mac.rs` (macOS) — see that module's doc comment.
102// Only this band's own line-formatting stays here: Linux's tight
103// `STAGE_MAX_LINES` (4, vs. the other two platforms' 12) makes the
104// mac/Windows "other: Xms" / "total: Xms" reconciliation rows a poor fit —
105// they'd frequently crowd out real stage content in a 4-line budget — so
106// that part of the mac/Windows parity work is deliberately not ported here;
107// see docs/reports/REPORT_SPLASH_SCREEN_ARCHITECTURE_RETHINK_2026_09_14.md.
108
109/// A finished row's end detail: the stage rows are 28 characters wide (`ok `,
110/// 18 for the label, 5 for the time and `ms`), so a detail line is that less
111/// its three-space indent, and at most two lines of it are shown.
112const DETAIL_LAYOUT: DetailLayout = DetailLayout { width: 25, max_lines: 2 };
113
114/// Accumulates startup events and emits rendered text lines for the stage band.
115pub(super) struct StageList {
116    timeline: StageTimeline,
117}
118
119impl StageList {
120    pub(super) fn new() -> Self {
121        Self { timeline: StageTimeline::new() }
122    }
123
124    /// Batch-apply one tick's worth of freshly-drained events. Must be
125    /// called with a whole batch, not one event at a time — see
126    /// `StageTimeline::apply_tick`'s doc comment: the same-tick count-up
127    /// deferral only recognizes a Begin+End pair as "same tick" when both
128    /// arrive in the same call.
129    pub(super) fn apply_tick(&mut self, fresh: Vec<StartupEvent>) -> bool {
130        self.timeline.apply_tick(fresh)
131    }
132
133    /// Call once, at the instant dismiss becomes eligible (fade about to
134    /// start), so a row with no matching End — e.g. the host stage if the
135    /// splash times out before the host ever reports it — freezes with a
136    /// definite outcome instead of staying visually "running" for the rest
137    /// of the fade. See `StageTimeline::finalize_running`'s doc comment.
138    pub(super) fn finalize_running(&mut self, at: Instant) {
139        self.timeline.finalize_running(at);
140    }
141
142    /// Up to `STAGE_MAX_LINES` formatted lines for the stage band.
143    ///
144    /// Row selection — which sub-items are shown in detail, which collapse
145    /// into a tally, and which rows survive when the band overflows — is
146    /// `splash_core::visible_rows`, shared with the Windows and macOS
147    /// renderers. This file owns only the formatting. Before that, this
148    /// method showed `subs.last()` and nothing else, so a migration batch
149    /// was one ever-changing line with no sense of how far along it was,
150    /// and the stage loop stopped at the cap oldest-first, which could hide
151    /// the stage actually running.
152    pub(super) fn lines(&self) -> Vec<String> {
153        let mut out = Vec::new();
154        for entry in visible_rows(&self.timeline.stages, STAGE_MAX_LINES, Some(DETAIL_LAYOUT)) {
155            match entry.kind {
156                RowKind::Stage(s) => {
157            let pfx = match &s.done {
158                None => ">> ",
159                Some((_, status, _)) => match status {
160                    StartupStatus::Ok => "ok ",
161                    _ => "!! ",
162                },
163            };
164            let ms = match &s.done {
165                Some((ms, ..)) => *ms,
166                None => s.started_at.elapsed().as_millis() as u64,
167            };
168            // "ok  Saga recovery       42ms"
169            //
170            // Truncated to the SAME width as the `{:<N}` padding below, not
171            // just an unbounded min-width pad: `label` is `s.label`, a
172            // fixed, short, engineer-chosen string, so this rarely bites —
173            // but `sub.label` below is a migration's free-text
174            // `description()` (since PR #3223, real ones up to 48-90 chars),
175            // and this card is only ~29 chars wide at GLYPH_W=10px
176            // (CARD_W=312px). An unclamped label pushes the whole duration
177            // column off the visible card edge — the label consumes the row
178            // before the live duration is even drawn, so the feature this
179            // PR adds would be invisible on Linux specifically (codex P2 on
180            // #3223). `splash_core::trunc` is the same char-safe truncation
181            // Windows/macOS already apply to their own stage/sub labels.
182            out.push(format!("{pfx}{:<18}{:>5}ms", trunc(s.label, 18), ms));
183                }
184                // Collapsed older sub-items. No duration column: the
185                // per-item times are exactly what this row stands in for.
186                RowKind::SubTally { done, total } => {
187                    out.push(format!("   >{:<16}", trunc(&tally_label(done, total), 16)));
188                }
189                // Why the row above warned or failed. Plain text under it: this
190                // band is one colour, and the row's "!!" already says it went wrong.
191                RowKind::Detail { text, indented, .. } => {
192                    let pad = if indented { "     " } else { "   " };
193                    out.push(format!("{pad}{text}"));
194                }
195                RowKind::Sub(sub) => {
196                    let sub_ms = match &sub.done {
197                        Some((ms, ..)) => *ms,
198                        None => sub.started_at.elapsed().as_millis() as u64,
199                    };
200                    out.push(format!("   >{:<16}{:>5}ms", trunc(&sub.label, 16), sub_ms));
201                }
202            }
203        }
204        out
205    }
206}
207
208enum Session {
209    Wayland,
210    X11,
211}
212
213/// Pick the splash backend by **centering ability**. The X11 backend self-centers
214/// (override-redirect, positioned on the RANDR primary) and XWayland honors that,
215/// so prefer it whenever an X server is actually reachable — including under a
216/// native-Wayland session, where the Wayland backend can't self-center and Mutter
217/// drops the splash top-left. Only with no usable X display do we fall back to the
218/// best-effort Wayland backend.
219///
220/// An explicit `AGENTMUX_OZONE_PLATFORM=x11|wayland` still pins a specific backend
221/// (escape hatch / for exercising the Wayland path itself); note that pinning
222/// `wayland` re-introduces the top-left placement Mutter gives uncentered toplevels.
223fn detect() -> Session {
224    match std::env::var("AGENTMUX_OZONE_PLATFORM").ok().as_deref() {
225        Some("x11") => return Session::X11,
226        Some("wayland") => return Session::Wayland,
227        _ => {}
228    }
229    // Without XAUTHORITY (a login entry, the AppImage binfmt path or an agent
230    // shell doesn't get Mutter's cookie, #4011) XWayland refuses us and we'd fall
231    // back to the uncentered Wayland splash, so find the cookie first. Called from
232    // `spawn()`, where the launcher is still single-threaded.
233    if std::env::var_os("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty()) {
234        agentmux_common::xauthority::ensure_xauthority();
235    }
236    // `DISPLAY` being set doesn't prove a server is live (stale env / no
237    // XWayland), so probe a real connection — a failed handshake is fast.
238    if x11::server_reachable() {
239        Session::X11
240    } else {
241        Session::Wayland
242    }
243}
244
245/// Minimum on-screen time before the splash is allowed to dismiss, so a fast
246/// cold start can't produce a sub-perceptible flash (worse than no splash).
247/// Overridable via `AGENTMUX_SPLASH_HOLD_MS` — also handy for eyeballing the
248/// splash during testing (e.g. `AGENTMUX_SPLASH_HOLD_MS=3000`).
249pub(crate) fn min_hold() -> Duration {
250    std::env::var("AGENTMUX_SPLASH_HOLD_MS")
251        .ok()
252        .and_then(|s| s.parse::<u64>().ok())
253        .map(Duration::from_millis)
254        .unwrap_or(Duration::from_millis(450))
255}
256
257/// Pulse alpha in 0..=1 for elapsed seconds since the splash appeared: a linear
258/// ramp 0→1 over `FADE_IN_S`, then a `PULSE_HZ` sine between `PULSE_MIN..PULSE_MAX`
259/// (the backdrop stays opaque; only the brain's alpha breathes). Shared by both
260/// backends.
261pub(crate) fn pulse_alpha(t: f32) -> f32 {
262    if t < FADE_IN_S {
263        return t / FADE_IN_S;
264    }
265    let s = (((t - FADE_IN_S) * std::f32::consts::TAU * PULSE_HZ).sin() + 1.0) * 0.5;
266    PULSE_MIN + s * (PULSE_MAX - PULSE_MIN)
267}
268
269/// Global fade-out opacity in 0..=1. Returns 1.0 until `fade_start` is set, then
270/// ramps linearly to 0.0 over `FADE_OUT`. Shared by both backends.
271pub(crate) fn fade_alpha(fade_start: Option<Instant>, now: Instant) -> f32 {
272    match fade_start {
273        None => 1.0,
274        Some(s) => (1.0 - now.duration_since(s).as_secs_f32() / FADE_OUT.as_secs_f32())
275            .clamp(0.0, 1.0),
276    }
277}
278
279/// Rounded-rect coverage (0..=1) at pixel (x, y) for a `w`×`h` rect with corner
280/// `radius` (0 = square), anti-aliased over a 1-px band on the corner arcs.
281fn corner_coverage(x: i32, y: i32, w: i32, h: i32, radius: f32) -> f32 {
282    let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
283    if radius <= 0.0 {
284        // No rounding to compute -- but still bounds-check (x, y) against
285        // the w×h rect rather than unconditionally returning 1.0. The old
286        // unconditional shortcut was only ever safe because render_frame's
287        // one call site always passed in-bounds coordinates by
288        // construction (x in 0..w, y in 0..h); the border-band check below
289        // calls this a second time with coordinates shifted relative to a
290        // SHRUNK inner rect, which are legitimately out-of-bounds for
291        // border-band pixels. Under the square X11-fallback path
292        // (radius=0, no compositor), inner_radius also clamps to 0
293        // (BORDER_WIDTH_PX - BORDER_WIDTH_PX), so without this bounds
294        // check interior_t was always 1.0 and the border never rendered
295        // at all in that fallback (Codex P2, PR #2804 review).
296        return if fx >= 0.0 && fx <= w as f32 && fy >= 0.0 && fy <= h as f32 {
297            1.0
298        } else {
299            0.0
300        };
301    }
302    // Clamp to the corner-arc center; in the straight edges/interior this yields
303    // dist 0 → full coverage. Only the four corner boxes produce a nonzero dist.
304    let cx = fx.clamp(radius, w as f32 - radius);
305    let cy = fy.clamp(radius, h as f32 - radius);
306    let dist = ((fx - cx).powi(2) + (fy - cy).powi(2)).sqrt();
307    if dist <= radius - 0.5 {
308        1.0
309    } else if dist >= radius + 0.5 {
310        0.0
311    } else {
312        radius + 0.5 - dist
313    }
314}
315
316/// Composite one frame, **pre-multiplied**, into a 4-byte-per-pixel buffer: the
317/// dark backdrop with the centered brain blended at `brain_alpha`, the stage list
318/// band, and the footer identity strip — all masked to a `radius`-rounded rect
319/// and scaled by the global `window_alpha` (fade-out). Pre-multiplied output is
320/// what both X Render compositors and `wl_shm` ARGB8888 expect. `bgr` selects
321/// byte order: `true` → B,G,R,A (X11 ARGB / Wayland ARGB8888 on LE), `false` →
322/// R,G,B,A. Shared by both backends.
323///
324/// `radius=0` + `window_alpha=1` yields a fully-opaque square (the X11
325/// no-compositor fallback path). `stages` may be empty (no events received).
326pub(crate) fn render_frame(
327    buf: &mut [u8],
328    w: i32,
329    h: i32,
330    brain_alpha: f32,
331    window_alpha: f32,
332    radius: f32,
333    bgr: bool,
334    footer: &[String],
335    stages: &[String],
336) {
337    let ox = (w - BRAIN_W) / 2;
338    // Center the brain in the brain region (above stage band and footer), not the
339    // whole card — otherwise the stage band + footer would push it off-center.
340    let oy = (h - FOOTER_H - STAGE_H - BRAIN_H) / 2;
341    for y in 0..h {
342        for x in 0..w {
343            // Backdrop, in RGB.
344            let mut rr = BG_R as f32;
345            let mut gg = BG_G as f32;
346            let mut bb = BG_B as f32;
347            // Brain over backdrop (straight alpha).
348            let (bx, by) = (x - ox, y - oy);
349            if bx >= 0 && bx < BRAIN_W && by >= 0 && by < BRAIN_H {
350                let si = ((by * BRAIN_W + bx) * 4) as usize;
351                let ba = (BRAIN_RGBA[si + 3] as f32 / 255.0) * brain_alpha;
352                rr = rr * (1.0 - ba) + BRAIN_RGBA[si] as f32 * ba;
353                gg = gg * (1.0 - ba) + BRAIN_RGBA[si + 1] as f32 * ba;
354                bb = bb * (1.0 - ba) + BRAIN_RGBA[si + 2] as f32 * ba;
355            }
356            // Darkened border band: blend toward BORDER_* the further a pixel
357            // falls outside the shrunk "interior" rect (inset by
358            // BORDER_WIDTH_PX on all sides, radius reduced to match) versus
359            // the outer rect — same anti-aliased coverage math as the corner
360            // rounding itself, just against two nested rects instead of one.
361            // The brain only ever occupies well-interior pixels (PADDING=28
362            // >> BORDER_WIDTH_PX), so blending the already-brain-composited
363            // color here is safe. SPEC_SPLASH_SCREEN_BORDER_2026_08_25.md.
364            let outer_cov = corner_coverage(x, y, w, h, radius);
365            let inner_radius = (radius - BORDER_WIDTH_PX as f32).max(0.0);
366            let inner_cov = corner_coverage(
367                x - BORDER_WIDTH_PX,
368                y - BORDER_WIDTH_PX,
369                w - 2 * BORDER_WIDTH_PX,
370                h - 2 * BORDER_WIDTH_PX,
371                inner_radius,
372            );
373            let interior_t = if outer_cov > 0.0 { (inner_cov / outer_cov).clamp(0.0, 1.0) } else { 0.0 };
374            rr = BORDER_R as f32 * (1.0 - interior_t) + rr * interior_t;
375            gg = BORDER_G as f32 * (1.0 - interior_t) + gg * interior_t;
376            bb = BORDER_B as f32 * (1.0 - interior_t) + bb * interior_t;
377
378            // Coverage (rounded corners) × global fade → pre-multiplied alpha.
379            let a = outer_cov * window_alpha;
380            let di = ((y * w + x) * 4) as usize;
381            let (o0, o2) = if bgr { (bb, rr) } else { (rr, bb) };
382            buf[di] = (o0 * a) as u8;
383            buf[di + 1] = (gg * a) as u8;
384            buf[di + 2] = (o2 * a) as u8;
385            buf[di + 3] = (a * 255.0) as u8;
386        }
387    }
388
389    // Stage list: startup telemetry lines above the footer.
390    let stage_top = h - FOOTER_H - STAGE_H + STAGE_PAD_TOP;
391    for (i, line) in stages.iter().enumerate() {
392        let y = stage_top + i as i32 * (crate::splash_font::GLYPH_H as i32 + STAGE_LINE_GAP);
393        crate::splash_text::draw_text(buf, w, h, STAGE_X, y, line, STAGE_COLOR, window_alpha, bgr);
394    }
395
396    // Footer: muted identity lines in the bottom band (static; fades with the card).
397    let footer_top = h - FOOTER_H + FOOTER_PAD_TOP;
398    for (i, line) in footer.iter().enumerate() {
399        let y = footer_top + i as i32 * (crate::splash_font::GLYPH_H as i32 + FOOTER_LINE_GAP);
400        crate::splash_text::draw_text_centered(buf, w, h, y, line, FOOTER_COLOR, window_alpha, bgr);
401    }
402}
403
404/// Spawn the startup splash. Sets `AGENTMUX_SPLASH_READY_FILE` (inherited by the
405/// host, which writes it on first paint) and runs the matching backend on a
406/// dedicated thread, so the launcher's main thread continues to start srv + host.
407/// The thread self-terminates on first-paint or the safety timeout. Best-effort:
408/// any failure (no display, protocol error) just means no splash — the launcher
409/// is unaffected.
410///
411/// `startup_rx` is the receiver end of the startup event bus. The splash thread
412/// drains it every animation frame to update the stage list. Pass the receiver
413/// from `startup_events::StartupEventSink::new()` created in `main()` before
414/// the Tokio runtime is started.
415pub fn spawn(startup_rx: Receiver<StartupEvent>) {
416    let ready_file =
417        std::env::temp_dir().join(format!("agentmux-splash-ready-{}", std::process::id()));
418    let _ = std::fs::remove_file(&ready_file);
419    // Set before any host is spawned so the host inherits it (same trick as
420    // splash_mac.rs). Safe: the launcher is single-threaded at this point.
421    std::env::set_var("AGENTMUX_SPLASH_READY_FILE", &ready_file);
422
423    // Footer identity, gathered once and clamped to the card width.
424    let info = crate::splash_info::SplashInfo::gather_and_log("start");
425    let max_chars = ((CARD_W - 24) / crate::splash_font::GLYPH_W as i32).max(8) as usize;
426    let footer = info.footer_lines(max_chars);
427
428    match detect() {
429        Session::X11 => {
430            std::thread::Builder::new()
431                .name("agentmux-splash".into())
432                .spawn(move || {
433                    if let Err(e) = x11::run(&ready_file, footer, startup_rx) {
434                        eprintln!("[splash] x11 backend disabled: {e}");
435                    }
436                })
437                .ok();
438        }
439        Session::Wayland => {
440            std::thread::Builder::new()
441                .name("agentmux-splash".into())
442                .spawn(move || {
443                    if let Err(e) = wayland::run(&ready_file, footer, startup_rx) {
444                        eprintln!("[splash] wayland backend disabled: {e}");
445                    }
446                })
447                .ok();
448        }
449    }
450}