Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust
55.3 KB
Raw Blame
//! First-run onboarding surface: the brand mark over its animated lab field, the welcome line, and
//! the flow panels the first-run flow mounts inside the block. [`OnboardingChoice`] is the reusable
//! question panel. A startup model that is ready skips to the question (TS `immediate: true`); no
//! usable model runs the full flow (TS `runOnboardingFlow`).

use crate::keybindings::KeybindingsManager;
use crate::keys::KeyId;
use crate::onboarding_choice::{OnboardingChoice, OnboardingChoiceOption, OnboardingChoiceOptions};
use crate::onboarding_flow::{welcome_action_row, welcome_rows, OnboardingPanel};
use crate::theme::{Theme, ThemeColor};
use crate::{Line, Span};
use ratatui::style::{Color, Modifier, Style};

pub const TRACE_OPT_IN_PROMPT: &str = "Share agent traces with Prime Intellect?";
const TRACE_OPT_IN_DESCRIPTION: &str = "Trace sharing helps us train better open-source models and improve the open agent ecosystem for everyone.";
const TRACE_OPT_IN_NOTE: &str = "You can change this anytime with /traces.";
/// Choice rows: `Share` opts in (index 0), `Not now` keeps traces off.
const CHOICES: [&str; 2] = ["Share", "Not now"];

pub(crate) fn trace_question_options() -> Vec<OnboardingChoiceOption> {
    CHOICES
        .iter()
        .map(|label| OnboardingChoiceOption {
            label: (*label).to_string(),
            detail: None,
        })
        .collect()
}

pub(crate) fn trace_question_config() -> OnboardingChoiceOptions {
    OnboardingChoiceOptions {
        prompt: Some(TRACE_OPT_IN_PROMPT.to_string()),
        description: Some(TRACE_OPT_IN_DESCRIPTION.to_string()),
        note: Some(TRACE_OPT_IN_NOTE.to_string()),
        row_width: None,
    }
}

pub const TEAM_QUESTION_PROMPT: &str = "Which account should Prime Agent use?";
pub const PERSONAL_ACCOUNT_LABEL: &str = "Personal account";

/// The team question's rows: the personal account first, then one row per
/// team with its slug as the dim `@detail` identifier.
pub(crate) fn team_question_options(
    teams: &[crate::auth_panel::PrimeTeamOption],
) -> Vec<OnboardingChoiceOption> {
    let mut options = vec![OnboardingChoiceOption {
        label: PERSONAL_ACCOUNT_LABEL.to_string(),
        detail: None,
    }];
    options.extend(teams.iter().map(|team| {
        OnboardingChoiceOption {
            // Provider-supplied rows get the control-character scrub.
            label: crate::menu_panel::scrub_controls(&team.name),
            detail: team
                .slug
                .clone()
                .map(|slug| crate::menu_panel::scrub_controls(&slug)),
        }
    }));
    options
}

pub(crate) fn team_question_config() -> OnboardingChoiceOptions {
    OnboardingChoiceOptions {
        prompt: Some(TEAM_QUESTION_PROMPT.to_string()),
        description: None,
        note: None,
        row_width: None,
    }
}

const LOGO_LINES: [&str; 7] = [
    "                 ▗▄▄█▀",
    "   ███▄       ▗▄███▀",
    "  ▗█▛▐█▙   ▗▄█▀▗█▀",
    " ▗█▛ ▟██▙▄██▛ ▟▛",
    " ▗▟▌ ▐███▛▘▗▄█▖",
    "▟███▄  ▄▄▟███▀",
    "▜█▛▀▘  ▜█▛▀▘",
];
const LOGO_WIDTH: usize = 22;
const LOGO_INDENT: usize = 5;
const HIGHLIGHT_LIFT: f64 = 0.08;

#[derive(Clone)]
struct SplashCell {
    character: char,
    tone: ThemeColor,
    priority: u8,
}

fn cell(character: char, tone: ThemeColor, priority: u8) -> SplashCell {
    SplashCell {
        character,
        tone,
        priority,
    }
}

/// The outcome of one onboarding key press.
pub enum OnboardingDecision {
    /// Enter on a choice row: the index of the selected option.
    Selected(usize),
    /// Cancel: the flow completed without an answer.
    Cancelled,
    /// Exit keys while onboarding owns the pane: quit the app.
    Exit,
    /// Enter on the welcome screen's login action: the full flow starts.
    Begin,
    /// The connect-more-providers picker's answer.
    Pick(crate::onboarding_flow::ProviderPick),
}

/// The onboarding pane state: the animation frame, the started flag (the welcome text never returns
/// once a flow owns the block), and the mounted flow panel.
#[derive(Debug)]
pub struct OnboardingScreen {
    frame: u64,
    flow_started: bool,
    /// The mounted flow panel (the flow never nests its panels, so one slot
    /// covers the sequence).
    panel: Option<OnboardingPanel>,
}

impl Default for OnboardingScreen {
    fn default() -> Self {
        Self {
            frame: 0,
            flow_started: true,
            panel: Some(OnboardingPanel::Question(OnboardingChoice::new(
                trace_question_options(),
                None,
                trace_question_config(),
            ))),
        }
    }
}

impl OnboardingScreen {
    /// The model-ready branch's splash (TS `immediate: true`): the trace
    /// question mounts directly under the brand mark.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// The full flow's splash: the welcome text and the single login action, until Enter starts the
    /// flow.
    #[must_use]
    pub fn welcome() -> Self {
        Self {
            frame: 0,
            flow_started: false,
            panel: None,
        }
    }

    /// Mount one flow panel — the flow has started, and the welcome text never comes back.
    pub fn mount_panel(&mut self, panel: OnboardingPanel) {
        self.flow_started = true;
        self.panel = Some(panel);
    }

    pub fn tick(&mut self) {
        self.frame = self.frame.wrapping_add(1);
    }

    /// Handle one key id. `None` keeps the pane waiting. `osc_sink` carries a
    /// copy's OSC 52 fallback (the login dialog's URL copy).
    pub(crate) fn handle_key(
        &mut self,
        key: &KeyId,
        kb: &KeybindingsManager,
        osc_sink: &mut crate::clipboard::OscSink,
    ) -> Option<OnboardingDecision> {
        // Onboarding owns the pane before the editor exists, so its panels answer the exit keys
        // themselves.
        if kb.matches(key, "app.clear") || kb.matches(key, "app.exit") {
            return Some(OnboardingDecision::Exit);
        }
        if let Some(panel) = self.panel.as_mut() {
            return panel.handle_key(key, kb, osc_sink);
        }
        // The welcome screen binds one key: Enter starts the flow (cancel is
        // deliberately unbound — signing in is the only way forward).
        if !self.flow_started && kb.matches(key, "tui.select.confirm") {
            return Some(OnboardingDecision::Begin);
        }
        None
    }

    /// One paste payload: the login dialog's field or the picker's search.
    pub fn handle_paste(&mut self, text: &str) {
        if let Some(panel) = self.panel.as_mut() {
            panel.handle_paste(text);
        }
    }

    /// Fold one auth-panel request into the mounted login dialog: render requests mount into the
    /// panel; a request with no mounted dialog cancels its flow.
    pub fn apply_auth_request(&mut self, request: crate::auth_panel::AuthPanelRequest) {
        use crate::auth_panel::AuthPanelRequest;
        match request {
            // The guarded arm: step chatter never renders on this surface ("onboarding narrates
            // itself"), while a direct showProgress line (the browser-sign-in fallback) does.
            AuthPanelRequest::Progress { message, chatter } => {
                let Some(OnboardingPanel::Auth { panel, .. }) = self.panel.as_mut() else {
                    return;
                };
                if !chatter {
                    panel.push_progress(&message);
                }
            }

            AuthPanelRequest::Waiting { message } => {
                let Some(OnboardingPanel::Auth { panel, .. }) = self.panel.as_mut() else {
                    return;
                };
                panel.push_waiting(&message);
            }
            AuthPanelRequest::AuthUrl { url, instructions } => {
                let Some(OnboardingPanel::Auth { panel, .. }) = self.panel.as_mut() else {
                    return;
                };
                panel.show_auth_url(url, instructions);
            }
            AuthPanelRequest::PastePrompt {
                prompt,
                tone,
                style,
                allow_empty,
                reply,
            } => {
                let Some(OnboardingPanel::Auth { panel, .. }) = self.panel.as_mut() else {
                    return;
                };
                panel.mount_paste(&prompt, tone, style, allow_empty, reply);
            }
            // The team selection is a question in the onboarding selection language (no heading —
            // the brand line returns), not the `/login` surface's team picker.
            AuthPanelRequest::SelectTeam {
                teams,
                current,
                reply,
            } => {
                let seed = teams
                    .iter()
                    .position(|team| Some(team.team_id.as_str()) == current.as_deref())
                    .map_or(0, |position| position + 1);
                self.mount_panel(OnboardingPanel::TeamQuestion {
                    choice: OnboardingChoice::new(
                        team_question_options(&teams),
                        Some(seed),
                        team_question_config(),
                    ),
                    teams,
                    reply: Some(reply),
                });
            }
            AuthPanelRequest::ProviderSettled { .. }
            | AuthPanelRequest::McpSettled { .. }
            | AuthPanelRequest::TracesSettled { .. } => {}
        }
    }

    /// The full pane frame; the keybindings manager feeds the mounted panel's hint row.
    pub(crate) fn render(
        &mut self,
        theme: &Theme,
        width: usize,
        height: usize,
        kb: &crate::keybindings::KeybindingsManager,
    ) -> Vec<Line> {
        let width = width.max(1);
        let auth_panel_open = matches!(self.panel.as_ref(), Some(OnboardingPanel::Auth { .. }));
        let mut lines: Vec<Line> = vec![Vec::new()];
        lines.extend(self.mark_rows(theme, width));
        lines.push(Vec::new());
        lines.push(self.heading_line(theme));
        // The welcome text and action render only before the flow starts; once a panel owns the
        // block, its rows mount directly under the heading.
        match self.panel.as_mut() {
            None if !self.flow_started => {
                lines.extend(welcome_rows(theme, width));
                lines.push(welcome_action_row(theme, width));
            }
            // A started flow with no mounted panel keeps one blank row in the gap.
            None => lines.push(Vec::new()),
            Some(panel) => lines.extend(panel.render(theme, width, kb)),
        }
        // A long sign-in link can wrap through the splash's fixed logo rows. Yield the logo
        // first so the full auth block fits whenever the pane can hold it. On a shorter terminal,
        // keep the block's final input and action rows visible like the session dock does.
        if auth_panel_open && lines.len() > height {
            lines.drain(..(LOGO_LINES.len() + 2));
            if lines.len() > height {
                lines.drain(..lines.len() - height);
            }
        }
        while lines.len() < height {
            lines.push(Vec::new());
        }
        lines.truncate(height);
        lines
    }

    /// The block's heading: the mounted panel that names itself replaces the brand line.
    fn heading_line(&self, theme: &Theme) -> Line {
        let heading = self.panel.as_ref().and_then(|panel| panel.heading());
        if let Some(heading) = heading {
            let mut row: Line = vec![Span::styled(" ".to_string(), Style::default())];
            row.push(Span::styled(
                heading.to_string(),
                theme
                    .fg_style(ThemeColor::Text)
                    .add_modifier(Modifier::BOLD),
            ));
            return row;
        }
        Self::brand_line(theme)
    }

    fn brand_line(theme: &Theme) -> Line {
        let text = theme.fg_style(ThemeColor::Text);
        let mut row: Line = vec![Span::styled(" ".to_string(), Style::default())];
        row.push(Span::styled("Welcome to ".to_string(), text));
        row.push(Span::styled(
            "PRIME".to_string(),
            text.add_modifier(Modifier::BOLD),
        ));
        row.push(Span::styled(
            " Agent".to_string(),
            text.add_modifier(Modifier::ITALIC),
        ));
        row
    }

    fn mark_rows(&self, theme: &Theme, width: usize) -> Vec<Line> {
        let rows = LOGO_LINES.len();
        let mut canvas = vec![vec![cell(' ', ThemeColor::Dim, 0); width]; rows];
        // The mark keeps a quiet zone on the field: ambient dots and contours still drift across
        // the full width, scan columns only trail to the right of the zone.
        let quiet = (LOGO_INDENT, LOGO_INDENT + LOGO_WIDTH - 1, 0, rows - 1);
        self.draw_field(&mut canvas, width, rows, quiet);
        for (y, line) in LOGO_LINES.iter().enumerate() {
            for (x, character) in line.chars().enumerate() {
                if character != ' ' {
                    put(
                        &mut canvas,
                        LOGO_INDENT + x,
                        y,
                        character,
                        ThemeColor::Text,
                        8,
                    );
                }
            }
        }
        canvas
            .into_iter()
            .map(|row| render_cells(theme, row))
            .collect()
    }

    /// The lab field of the old full-screen splash, scaled to the mark's band: drifting ambient
    /// dots, a contour wave, a horizon of dashes, scan columns, and three particle traces.
    fn draw_field(
        &self,
        canvas: &mut [Vec<SplashCell>],
        width: usize,
        height: usize,
        quiet: (usize, usize, usize, usize),
    ) {
        let frame = self.frame;
        for y in 0..height {
            for x in 0..width {
                let hash = (x * 37 + y * 53 + (frame as usize) * 11 + x * y * 3) % 101;
                if hash < 3 {
                    put(canvas, x, y, '·', ThemeColor::Dim, 1);
                }
                let center_x = width * 36 / 100;
                let center_y = height * 54 / 100;
                let contour = (x as i64 - center_x as i64).abs()
                    + (y as i64 - center_y as i64).abs() * 4
                    + (x / 6) as i64
                    - frame as i64;
                if x < width * 82 / 100 && contour.rem_euclid(24) == 12 {
                    let character = if (x + y) % 5 == 0 { '╌' } else { '·' };
                    put(canvas, x, y, character, ThemeColor::BorderMuted, 2);
                }
                let horizon_y = height * 58 / 100;
                if y == horizon_y && x % 2 == 0 && (x + frame as usize) % 13 < 2 {
                    let tone = if (x + frame as usize).is_multiple_of(3) {
                        ThemeColor::Accent
                    } else {
                        ThemeColor::Dim
                    };
                    put(canvas, x, y, '─', tone, 3);
                }
                if x >= quiet.0 && !inside_quiet(x, y, quiet) && x % 4 == 0 {
                    let scan_index = x / 4;
                    let segment = (y + scan_index * 2 + (frame as usize / 2)) % 6;
                    if y > 0 && y < height - 1 && segment < 2 {
                        let character = if (scan_index + y) % 4 == 0 {
                            '┃'
                        } else {
                            '▎'
                        };
                        put(canvas, x, y, character, ThemeColor::MdLink, 4);
                    }
                }
            }
        }
        for trace_index in 0..3usize {
            let base = match trace_index {
                0 => height * 30 / 100,
                1 => height * 49 / 100,
                _ => height * 72 / 100,
            };
            for x in 0..width {
                let mut wave = (x * 2 + frame as usize + trace_index * 7) % 16;
                if wave > 7 {
                    wave = 15 - wave;
                }
                // `Math.trunc((wave - 3) / 2)`: negative waves pull the trace one
                // row up, so keep the signed division.
                let trace_y = (base as i64 + (wave as i64 - 3) / 2).max(0) as usize;
                if (x + frame as usize + trace_index * 13).is_multiple_of(41) {
                    put(canvas, x, trace_y, '◆', ThemeColor::Warning, 6);
                } else if (x + frame as usize).is_multiple_of(12) {
                    put(canvas, x, trace_y, '•', ThemeColor::Accent, 6);
                } else {
                    put(canvas, x, trace_y, '·', ThemeColor::Accent, 3);
                }
            }
        }
    }
}

/// Overwrite one cell when the new priority is at least the current one.
fn put(
    canvas: &mut [Vec<SplashCell>],
    x: usize,
    y: usize,
    character: char,
    tone: ThemeColor,
    priority: u8,
) {
    if y >= canvas.len() || x >= canvas[y].len() {
        return;
    }
    if canvas[y][x].priority > priority {
        return;
    }
    canvas[y][x] = cell(character, tone, priority);
}

fn inside_quiet(x: usize, y: usize, zone: (usize, usize, usize, usize)) -> bool {
    x >= zone.0 && x <= zone.1 && y >= zone.2 && y <= zone.3
}

fn render_cells(theme: &Theme, cells: Vec<SplashCell>) -> Line {
    let mut row: Line = Vec::new();
    let mut current: Option<ThemeColor> = None;
    let mut segment = String::new();
    for cell in cells {
        if current != Some(cell.tone) {
            if let Some(tone) = current.replace(cell.tone) {
                if !segment.is_empty() {
                    row.push(Span::styled(
                        std::mem::take(&mut segment),
                        theme.fg_style(tone),
                    ));
                }
            }
        }
        segment.push(cell.character);
    }
    if !segment.is_empty() {
        let tone = current.unwrap_or(ThemeColor::Dim);
        row.push(Span::styled(segment, theme.fg_style(tone)));
    }
    row
}

/// The selected-row wash: the canvas lifted a few percent toward the text colour — the theme
/// record's `background`, else the hardcoded dark/light canvas by the text luma.
pub(crate) fn highlight_wash(theme: &Theme) -> Color {
    let text = theme.fg_style(ThemeColor::Text).fg;
    // `onDark = !text || isLightColor(text)` — empty or light text both mean
    // light text over a dark canvas.
    let on_dark = match text {
        Some(Color::Rgb(r, g, b)) => {
            0.299 * f64::from(r) + 0.587 * f64::from(g) + 0.114 * f64::from(b) > 128.0
        }
        None | Some(Color::Reset | _) => true,
    };
    let lift = if on_dark {
        (255u16, 255, 255)
    } else {
        (0u16, 0, 0)
    };
    // `canvas = parseHexColor(colors.background) ?? (onDark ? DARK_CANVAS : LIGHT_CANVAS)`.
    let canvas = theme.background_rgb().map_or(
        if on_dark {
            (16u16, 16, 16)
        } else {
            (255u16, 255, 255)
        },
        |(r, g, b)| (u16::from(r), u16::from(g), u16::from(b)),
    );
    let blend = |lift: u16, canvas: u16| -> u8 {
        let value = f64::from(lift) * HIGHLIGHT_LIFT + f64::from(canvas) * (1.0 - HIGHLIGHT_LIFT);
        value.round().clamp(0.0, 255.0) as u8
    };
    let washed = (
        blend(lift.0, canvas.0),
        blend(lift.1, canvas.1),
        blend(lift.2, canvas.2),
    );
    match theme.mode {
        crate::theme::ColorMode::Color256 => Color::Indexed(crate::theme::rgb_to_256(washed)),
        crate::theme::ColorMode::TrueColor => Color::Rgb(washed.0, washed.1, washed.2),
    }
}

/// Greedy word wrap at `width` columns.
pub(crate) fn wrap_words(text: &str, width: usize) -> Vec<String> {
    let mut rows = Vec::new();
    let mut row = String::new();
    for word in text.split(' ') {
        if row.is_empty() {
            row = word.to_string();
        } else if row.chars().count() + 1 + word.chars().count() <= width {
            row.push(' ');
            row.push_str(word);
        } else {
            rows.push(std::mem::take(&mut row));
            row = word.to_string();
        }
        while row.chars().count() > width {
            let cut: String = row.chars().take(width).collect();
            rows.push(cut);
            row = row.chars().skip(width).collect();
        }
    }
    if !row.is_empty() {
        rows.push(row);
    }
    if rows.is_empty() {
        rows.push(String::new());
    }
    rows
}

#[cfg(test)]
mod tests {
    fn kb() -> crate::keybindings::KeybindingsManager {
        crate::keybindings::KeybindingsManager::new()
    }

    use super::*;
    use crate::theme::{ColorMode, Theme, ThemeJson};

    fn custom_theme(json: &str, mode: ColorMode) -> Theme {
        let json: ThemeJson = serde_json::from_str(json).expect("valid theme json");
        Theme::from_json(&json, mode)
    }

    /// The trace-question pane at 80x24, byte-identical to the pre-PR-C render: the golden was
    /// captured from the base commit's `OnboardingScreen::render` Debug output in the CI VM, so the
    /// parameterized choice panel must not move a single styled cell.
    #[test]
    fn trace_question_render_is_unchanged() {
        const GOLDEN: &str = r#"[[], [Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "·   " }, Span { style: Style::new().fg(Color::Rgb(82, 82, 91)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "                 " }, Span { style: Style::new().fg(Color::Reset), content: "▗▄▄█▀" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "              ·   " }, Span { style: Style::new().fg(Color::Rgb(82, 82, 91)), content: "╌" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "                         ·        " }], [Span { style: Style::new().fg(Color::Rgb(245, 158, 11)), content: "◆" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "      " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Reset), content: "███▄" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Reset), content: "▗▄███▀" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(82, 82, 91)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "· " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "      " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "      " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "┃" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "      " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "    · " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }], [Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "···" }, Span { style: Style::new().fg(Color::Reset), content: "▗█▛▐█▙" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Reset), content: "▗▄█▀▗█▀" }, Span { style: Style::new().fg(Color::Rgb(82, 82, 91)), content: "╌·" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(245, 158, 11)), content: "◆" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(82, 82, 91)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "•··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(245, 158, 11)), content: "◆" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "···" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "┃" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "•··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(245, 158, 11)), content: "◆" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "···" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }], [Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Reset), content: "▗█▛" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Reset), content: "▟██▙▄██▛" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Reset), content: "▟▛" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(82, 82, 91)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "┃" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }], [Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "•·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Reset), content: "▗▟▌" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Reset), content: "▐███▛▘▗▄█▖" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·•·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "─ " }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "···" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·•·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(245, 158, 11)), content: "◆" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "┃" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·─" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·•·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "· " }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "─·" }], [Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Reset), content: "▟███▄" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Reset), content: "▄▄▟███▀" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "┃" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "▎" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "··" }, Span { style: Style::new().fg(Color::Rgb(56, 189, 248)), content: "┃" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }], [Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "    " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Reset), content: "▜█▛▀▘" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "  " }, Span { style: Style::new().fg(Color::Reset), content: "▜█▛▀▘" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "     " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "     " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "   · " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(82, 82, 91)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "     " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "     " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "•" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " ·   " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "     " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }, Span { style: Style::new().fg(Color::Rgb(124, 111, 175)), content: "·" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " " }], [], [Span { style: Style::new(), content: " " }, Span { style: Style::new().fg(Color::Reset), content: "Welcome to " }, Span { style: Style::new().fg(Color::Reset).bold(), content: "PRIME" }, Span { style: Style::new().fg(Color::Reset).italic(), content: " Agent" }], [], [Span { style: Style::new().fg(Color::Reset), content: " Share agent traces with Prime Intellect?" }], [], [Span { style: Style::new().fg(Color::Rgb(161, 161, 170)), content: " Trace sharing helps us train better open-source" }], [Span { style: Style::new().fg(Color::Rgb(161, 161, 170)), content: " models and improve the open agent ecosystem for" }], [Span { style: Style::new().fg(Color::Rgb(161, 161, 170)), content: " everyone." }], [], [Span { style: Style::new(), content: " " }, Span { style: Style::new().fg(Color::Reset).bg(Color::Rgb(35, 35, 35)).bold(), content: "> Share" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)).bg(Color::Rgb(35, 35, 35)), content: "                       " }], [Span { style: Style::new(), content: " " }, Span { style: Style::new().fg(Color::Rgb(161, 161, 170)), content: "  Not now" }, Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: "                     " }], [], [Span { style: Style::new().fg(Color::Rgb(113, 113, 122)), content: " You can change this anytime with /traces." }], [], [], []]"#;
        let theme = Theme::builtin("prime", ColorMode::TrueColor);
        let kb = crate::keybindings::KeybindingsManager::new();
        let lines = OnboardingScreen::new().render(&theme, 80, 24, &kb);
        assert_eq!(format!("{lines:?}"), GOLDEN);
    }

    #[test]
    fn wash_blends_against_the_theme_background() {
        let theme = custom_theme(
            r##"{ "name": "custom", "colors": { "text": "#f4f4f5", "background": "#050506" } }"##,
            ColorMode::TrueColor,
        );
        // Light text lifts white over the canvas (TS `HIGHLIGHT_LIFT` 0.08):
        // blend(255, 5) = 25, blend(255, 6) = 26.
        assert_eq!(highlight_wash(&theme), Color::Rgb(25, 25, 26));
        let theme = custom_theme(
            r##"{ "name": "custom", "colors": { "text": "#f4f4f5", "background": "#050506" } }"##,
            ColorMode::Color256,
        );
        // The 256-color mode quantizes the washed colour, not the canvas.
        assert_eq!(
            highlight_wash(&theme),
            Color::Indexed(crate::theme::rgb_to_256((25, 25, 26)))
        );

        let theme = custom_theme(
            r##"{ "name": "custom", "colors": { "text": "#000000", "background": "#f0f0f0" } }"##,
            ColorMode::TrueColor,
        );
        // Dark text lifts black over the light canvas: blend(0, 240) = 221.
        assert_eq!(highlight_wash(&theme), Color::Rgb(221, 221, 221));
    }

    #[test]
    fn wash_falls_back_to_the_hardcoded_canvas() {
        // The built-in themes carry no background key: dark canvas (16,16,16)
        // lifted toward white — blend(255, 16) = 35.
        let theme = Theme::builtin("prime", ColorMode::TrueColor);
        assert_eq!(highlight_wash(&theme), Color::Rgb(35, 35, 35));
        let theme = Theme::builtin("prime", ColorMode::Color256);
        assert_eq!(
            highlight_wash(&theme),
            Color::Indexed(crate::theme::rgb_to_256((35, 35, 35)))
        );
        // A 3-hex background is not the TS `parseHexColor` shape: fallback.
        let theme = custom_theme(
            r##"{ "name": "custom", "colors": { "text": "#f4f4f5", "background": "#abc" } }"##,
            ColorMode::TrueColor,
        );
        assert_eq!(highlight_wash(&theme), Color::Rgb(35, 35, 35));
        // Dark text without a background washes over the light canvas:
        // blend(0, 255) = 235.
        let theme = custom_theme(
            r##"{ "name": "custom", "colors": { "text": "#000000" } }"##,
            ColorMode::TrueColor,
        );
        assert_eq!(highlight_wash(&theme), Color::Rgb(235, 235, 235));
    }

    /// The guarded arm: `onProgress` step chatter never renders on the onboarding block, the
    /// browser-fallback's direct line does.
    #[test]
    fn the_onboarding_fold_drops_step_chatter_keeps_direct_lines() {
        let mut screen = OnboardingScreen::welcome();
        screen.mount_panel(crate::onboarding_flow::OnboardingPanel::Auth {
            panel: std::boxed::Box::new(crate::auth_panel::AuthPanel::onboarding(
                "Login to Prime Inference",
            )),
            heading: Some(crate::onboarding_flow::PRIME_LOGIN_HEADING.to_string()),
        });
        screen.apply_auth_request(crate::auth_panel::AuthPanelRequest::Progress {
            message: "Generating the browser challenge...".to_string(),
            chatter: true,
        });
        let theme = Theme::builtin("prime", ColorMode::TrueColor);
        let rows = screen.render(&theme, 80, 24, &kb());
        let text = rows
            .iter()
            .map(|line| {
                line.iter()
                    .map(|span| span.content.clone())
                    .collect::<String>()
            })
            .collect::<Vec<_>>();
        assert!(
            !text
                .iter()
                .any(|row| row.contains("Generating the browser challenge")),
            "the step chatter stays out of the onboarding block: {text:?}"
        );
        assert!(
            !text
                .iter()
                .any(|row| row.contains("Preparing authentication")),
            "no progress block opened: {text:?}"
        );
        screen.apply_auth_request(crate::auth_panel::AuthPanelRequest::Progress {
            message: "Browser sign-in unavailable (mock).".to_string(),
            chatter: false,
        });
        let rows = screen.render(&theme, 80, 24, &kb());
        let text = rows
            .iter()
            .map(|line| {
                line.iter()
                    .map(|span| span.content.clone())
                    .collect::<String>()
            })
            .collect::<Vec<_>>();
        assert!(
            text.iter()
                .any(|row| row.contains("Browser sign-in unavailable (mock).")),
            "the direct fallback line renders: {text:?}"
        );
    }

    /// `showWaiting` carries no onboarding guard, so the waiting line renders here too — below the
    /// browser URL block.
    #[test]
    fn the_onboarding_fold_renders_the_device_flow_waiting_line() {
        let mut screen = OnboardingScreen::welcome();
        screen.mount_panel(crate::onboarding_flow::OnboardingPanel::Auth {
            panel: std::boxed::Box::new(crate::auth_panel::AuthPanel::onboarding(
                "Login to GitHub Copilot",
            )),
            heading: Some(crate::onboarding_flow::PRIME_LOGIN_HEADING.to_string()),
        });
        screen.apply_auth_request(crate::auth_panel::AuthPanelRequest::AuthUrl {
            url: "https://fixture.example/device".to_string(),
            instructions: None,
        });
        screen.apply_auth_request(crate::auth_panel::AuthPanelRequest::Waiting {
            message: "Waiting for browser authentication...".to_string(),
        });
        let theme = Theme::builtin("prime", ColorMode::TrueColor);
        let rows = screen.render(&theme, 80, 24, &kb());
        let text = rows
            .iter()
            .map(|line| {
                line.iter()
                    .map(|span| span.content.clone())
                    .collect::<String>()
            })
            .collect::<Vec<_>>();
        let url = text
            .iter()
            .position(|row| row.contains("fixture.example/device"))
            .expect("the url row");
        let waiting = text
            .iter()
            .position(|row| row.contains("Waiting for browser authentication"))
            .expect("the waiting row");
        assert!(
            waiting > url,
            "the waiting line rides below the URL block: {text:?}"
        );
    }

    /// When the link wraps, the decorative mark yields its rows to the complete link and the
    /// action row. A 24-row terminal has room for both once the mark is omitted.
    #[test]
    fn wrapped_onboarding_auth_url_keeps_the_link_and_actions_visible() {
        let mut screen = OnboardingScreen::welcome();
        screen.mount_panel(crate::onboarding_flow::OnboardingPanel::Auth {
            panel: std::boxed::Box::new(crate::auth_panel::AuthPanel::onboarding(
                "Login to Prime Inference",
            )),
            heading: Some(crate::onboarding_flow::PRIME_LOGIN_HEADING.to_string()),
        });
        let url = format!("https://example.test/oauth?state={}", "a".repeat(450));
        screen.apply_auth_request(crate::auth_panel::AuthPanelRequest::AuthUrl {
            url: url.clone(),
            instructions: None,
        });
        screen.apply_auth_request(crate::auth_panel::AuthPanelRequest::PastePrompt {
            prompt: "Redirect URL:".to_string(),
            tone: crate::auth_panel::PastePromptTone::Text,
            style: crate::auth_panel::PasteStyle::Visible,
            allow_empty: false,
            reply: tokio::sync::oneshot::channel().0,
        });
        let theme = Theme::builtin("prime", ColorMode::TrueColor);
        let rows = screen.render(&theme, 40, 24, &kb());
        let text: Vec<String> = rows
            .iter()
            .map(|row| {
                let raw = row
                    .iter()
                    .map(|span| span.content.as_str())
                    .collect::<String>();
                crate::hyperlinks::strip_osc8_content(&raw)
            })
            .collect();
        let joined = text.iter().map(|row| row.trim()).collect::<String>();
        assert!(
            joined.contains(&url),
            "the complete URL remains visible: {text:?}"
        );
        assert!(
            joined.contains("Redirect URL:"),
            "the paste prompt remains visible: {text:?}"
        );
        assert!(
            joined.contains("Paste value"),
            "the paste field remains visible: {text:?}"
        );
        assert!(
            joined.contains("copy") && joined.contains("cancel"),
            "the URL actions remain visible: {text:?}"
        );
    }

    /// The `SelectTeam` request mounts the onboarding choice question (the brand line returns — no
    /// heading) with the personal account first and the teams' slugs as identifiers.
    #[test]
    fn the_team_selection_mounts_the_onboarding_choice_question() {
        use crate::auth_panel::{AuthPanelRequest, PrimeTeamOption, PrimeTeamPick};
        let mut screen = OnboardingScreen::welcome();
        screen.mount_panel(crate::onboarding_flow::OnboardingPanel::Auth {
            panel: std::boxed::Box::new(crate::auth_panel::AuthPanel::onboarding(
                "Login to Prime Inference",
            )),
            heading: Some(crate::onboarding_flow::PRIME_LOGIN_HEADING.to_string()),
        });
        let (reply, answer) = tokio::sync::oneshot::channel();
        screen.apply_auth_request(AuthPanelRequest::SelectTeam {
            teams: vec![
                PrimeTeamOption {
                    team_id: "team-acme".to_string(),
                    name: "Acme Corp".to_string(),
                    slug: Some("acme".to_string()),
                    role: Some("Owner".to_string()),
                    created_at: None,
                },
                PrimeTeamOption {
                    team_id: "team-beta".to_string(),
                    name: "Beta Team".to_string(),
                    slug: None,
                    role: None,
                    created_at: None,
                },
            ],
            current: Some("team-beta".to_string()),
            reply,
        });
        let theme = Theme::builtin("prime", ColorMode::TrueColor);
        let rows = screen.render(&theme, 80, 24, &kb());
        let text = rows
            .iter()
            .map(|line| {
                line.iter()
                    .map(|span| span.content.clone())
                    .collect::<String>()
            })
            .collect::<Vec<_>>();
        // The heading reverted to the brand line.
        assert!(
            text.iter().any(|row| row.contains("Welcome to ")),
            "the brand line returns over the team question: {text:?}"
        );
        assert!(
            !text
                .iter()
                .any(|row| row.contains("Login with Prime Intellect")),
            "no login heading rides the question: {text:?}"
        );
        assert!(
            text.iter().any(|row| row.contains(TEAM_QUESTION_PROMPT)),
            "the TS prompt: {text:?}"
        );
        let seed = text
            .iter()
            .find(|row| row.contains("> Beta Team"))
            .expect("the stored team is seeded");
        assert!(
            seed.starts_with(" > Beta Team"),
            "the seeded row renders in the selection language: {seed:?}"
        );
        assert!(
            text.iter().any(|row| row.contains("  Personal account")),
            "the personal row rides first: {text:?}"
        );
        assert!(
            text.iter().any(|row| row.contains("@acme")),
            "the team slug renders as the dim identifier: {text:?}"
        );
        let kb = crate::keybindings::KeybindingsManager::new();
        let mut sink = crate::clipboard::OscSink::Buffer(Vec::new());
        screen.handle_key(&crate::keys::KeyId::from("enter"), &kb, &mut sink);
        match answer.blocking_recv().expect("the pick answered") {
            PrimeTeamPick::Team(team) => assert_eq!(team.team_id, "team-beta"),
            other => panic!("the seeded team answered, got {other:?}"),
        }
    }

    /// The installer's banner (install-rust.sh's awk port of this splash)
    /// draws the same canvas as `mark_rows` — every character and tone —
    /// for the same frame and width, so the two cannot drift.
    #[test]
    #[cfg(unix)]
    fn the_installer_banner_matches_the_splash() {
        let script = include_str!("../../../install-rust.sh");
        let program = script
            .split("# BANNER_AWK_BEGIN\n")
            .nth(1)
            .and_then(|rest| rest.split("# BANNER_AWK_END").next())
            .expect("the installer carries the banner program");
        let theme = Theme::builtin("prime", ColorMode::TrueColor);
        let tone = |color: Option<Color>| match color {
            Some(Color::Rgb(113, 113, 122)) => 'D',
            Some(Color::Rgb(82, 82, 91)) => 'B',
            Some(Color::Rgb(124, 111, 175)) => 'A',
            Some(Color::Rgb(56, 189, 248)) => 'L',
            Some(Color::Rgb(245, 158, 11)) => 'W',
            Some(Color::Reset) | None => 'T',
            other => panic!("unexpected splash tone {other:?}"),
        };
        for (frame, width) in [(0_u64, 80_usize), (1, 80), (7, 40), (113, 61), (250, 119)] {
            let mut screen = OnboardingScreen::new();
            screen.frame = frame;
            let expected: Vec<String> = screen
                .mark_rows(&theme, width)
                .iter()
                .map(|row| {
                    let chars: String = row.iter().map(|span| span.content.as_str()).collect();
                    let tones: String = row
                        .iter()
                        .flat_map(|span| {
                            std::iter::repeat_n(tone(span.style.fg), span.content.chars().count())
                        })
                        .collect();
                    format!("{chars}\t{tones}")
                })
                .collect();
            let output = std::process::Command::new("awk")
                .args(["-v", "parity=1"])
                .args(["-v", &format!("frame={frame}")])
                .args(["-v", &format!("width={width}")])
                .arg(program)
                .output()
                .expect("run awk");
            assert!(output.status.success(), "awk failed: {output:?}");
            let actual: Vec<String> = String::from_utf8_lossy(&output.stdout)
                .lines()
                .map(str::to_string)
                .collect();
            assert_eq!(actual, expected, "frame {frame} at width {width}");
        }
    }
}