hyuskui

Test Results

A test run the agent started, grouped by file. A failing run opens down to the failed test and its error; passing files stay folded.

Loading GPUI…
use std::collections::HashMap;
use std::time::Duration;

use gpui::{div, prelude::*, px, AnyElement, Context, SharedString, Task, Window};

use crate::icons::{CHECK, CIRCLE_DASHED, FILE_CODE, FLASK_CONICAL, X};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
use crate::ui::message::{Message, MessageAlign};
use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus};

const MONO: &str = "Geist Mono";

/// The mock transport's pace: one word every 20ms. The run takes as long as the script sleeps
/// between the tool's input and its output.
const CHUNK: Duration = Duration::from_millis(20);
const TESTS_RUN: Duration = Duration::from_millis(1500);

const QUESTION: &str = "Run the checkout tests.";
const ANSWER: &str = "One test failed. The payment client does not retry a declined card, so the second charge attempt never happens.";
const COMMAND: &str = "pnpm test checkout";

#[derive(Clone, Copy, PartialEq)]
enum Status {
    Passed,
    Failed,
    Skipped,
}

struct Test {
    name: &'static str,
    status: Status,
    error: &'static str,
}

const fn passed(name: &'static str) -> Test {
    Test { name, status: Status::Passed, error: "" }
}

const SUITES: [(&str, &[Test]); 2] = [
    ("cart.test.ts", &[passed("adds an item"), passed("removes an item"), passed("applies a discount code")]),
    (
        "payment.test.ts",
        &[
            passed("charges the saved card"),
            Test {
                name: "retries a declined card",
                status: Status::Failed,
                error: "Expected 2 charge attempts, received 1\n\n  at Object.<anonymous> (src/payment.test.ts:58:22)",
            },
        ],
    ),
];

/// shadcn's `formatCounts`: "5 tests, 1 failed", leaving out zero counts.
fn counts<'a>(tests: impl Iterator<Item = &'a Test>) -> (usize, String) {
    let (mut total, mut failed, mut skipped) = (0, 0, 0);
    for test in tests {
        total += 1;
        failed += (test.status == Status::Failed) as usize;
        skipped += (test.status == Status::Skipped) as usize;
    }
    let mut label = format!("{total} tests");
    if failed > 0 {
        label += &format!(", {failed} failed");
    }
    if skipped > 0 {
        label += &format!(", {skipped} skipped");
    }
    (failed, label)
}

pub struct TestResultsPattern {
    replied: bool,
    /// Whether the run has reported back.
    ran: bool,
    words: usize,
    busy: bool,
    /// Rows the reader opened or closed; the rest open when they hold a failure.
    open: HashMap<SharedString, bool>,
    stream: Option<Task<()>>,
}

impl Default for TestResultsPattern {
    /// Starts on the finished transcript.
    fn default() -> Self {
        Self {
            replied: true,
            ran: true,
            words: ANSWER.split_inclusive(' ').count(),
            busy: false,
            open: HashMap::new(),
            stream: None,
        }
    }
}

impl TestResultsPattern {
    fn replay(&mut self, cx: &mut Context<Self>) {
        *self = Self { ran: false, words: 0, busy: true, ..Self::default() };
        self.stream = Some(cx.spawn(async move |this, cx| {
            cx.background_executor().timer(TESTS_RUN).await;
            if this.update(cx, |this, cx| {
                this.ran = true;
                cx.notify();
            })
            .is_err()
            {
                return;
            }
            for _ in 0..ANSWER.split_inclusive(' ').count() {
                cx.background_executor().timer(CHUNK).await;
                if this.update(cx, |this, cx| {
                    this.words += 1;
                    cx.notify();
                })
                .is_err()
                {
                    return;
                }
            }
            let _ = this.update(cx, |this, cx| {
                this.busy = false;
                cx.notify();
            });
        }));
        cx.notify();
    }

    /// A row that opens by default when it holds a failure, like shadcn's `defaultOpen`.
    fn collapsible(&self, id: SharedString, failed: bool, line: TraceLine, cx: &mut Context<Self>) -> TraceCollapsible {
        let open = self.open.get(&id).copied().unwrap_or(failed);
        let key = id.clone();
        TraceCollapsible::new(id, open, line).on_open_change(cx.listener(move |this, open: &bool, _, cx| {
            this.open.insert(key.clone(), *open);
            cx.notify();
        }))
    }

    fn results(&self, cx: &mut Context<Self>) -> AnyElement {
        if !self.ran {
            return TraceLine::new("run", format!("Running {COMMAND}"))
                .icon(FLASK_CONICAL)
                .status(TraceStatus::Running)
                .into_any_element();
        }
        let status = |failed: usize| if failed > 0 { TraceStatus::Error } else { TraceStatus::Done };
        let (failed, label) = counts(SUITES.iter().flat_map(|(_, tests)| tests.iter()));

        let suites: Vec<AnyElement> = SUITES
            .iter()
            .map(|(name, tests)| {
                let (failed, label) = counts(tests.iter());
                let rows: Vec<AnyElement> = tests.iter().map(|test| self.test_row(name, test, cx)).collect();
                self.collapsible(
                    format!("suite-{name}").into(),
                    failed > 0,
                    TraceLine::new(SharedString::from(format!("suite-title-{name}")), format!("{name}, {label}"))
                        .icon(FILE_CODE)
                        .status(status(failed)),
                    cx,
                )
                .child(Trace::new().children(rows))
                .into_any_element()
            })
            .collect();

        self.collapsible(
            "run".into(),
            failed > 0,
            TraceLine::new("run-title", format!("Ran {label}")).icon(FLASK_CONICAL).status(status(failed)),
            cx,
        )
        .child(Trace::new().children(suites))
        .into_any_element()
    }

    fn test_row(&self, suite: &str, test: &Test, cx: &mut Context<Self>) -> AnyElement {
        let id = SharedString::from(format!("{suite}/{}", test.name));
        match test.status {
            Status::Failed => {
                let theme = cx.theme();
                // shadcn's small code block: a muted panel with 12px mono text that wraps.
                let error = div()
                    .max_h(px(256.0))
                    .overflow_hidden()
                    .p_3()
                    .rounded(px(14.0))
                    .bg(theme.muted)
                    .font_family(MONO)
                    .text_xs()
                    .line_height(px(19.5))
                    .text_color(theme.foreground)
                    .children(test.error.lines().map(wrapping_line));
                self.collapsible(
                    id.clone(),
                    true,
                    TraceLine::new(SharedString::from(format!("{id}-title")), test.name).icon(X).status(TraceStatus::Error),
                    cx,
                )
                .child(error)
                .into_any_element()
            }
            Status::Skipped => TraceLine::new(id, format!("Skipped {}", test.name)).icon(CIRCLE_DASHED).into_any_element(),
            Status::Passed => TraceLine::new(id, test.name).icon(CHECK).into_any_element(),
        }
    }
}

impl Render for TestResultsPattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect();
        let results = self.replied.then(|| self.results(cx));
        let theme = cx.theme();

        div()
            .w(px(384.0))
            .min_h(px(288.0))
            .flex()
            .flex_col()
            .gap_4()
            .py_6()
            .text_sm()
            .text_color(theme.foreground)
            .child(
                Message::new()
                    .align(MessageAlign::End)
                    .child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION)),
            )
            .when_some(results, |this, results| {
                this.child(
                    Message::new().child(
                        div()
                            .flex()
                            .flex_col()
                            .gap_4()
                            .w_full()
                            .line_height(px(20.0))
                            .child(Trace::new().child(results))
                            .when(!answer.is_empty(), |this| this.child(answer)),
                    ),
                )
            })
            .when(!self.busy, |this| {
                this.child(div().mt_auto().flex().child(Button::new("replay", "Replay")
                        .variant(ButtonVariant::Outline)
                        .size(ButtonSize::Compact)
                        .rounded_full()
                        .on_click(cx.listener(|this, _, _, cx| this.replay(cx)))))
            })
    }
}



/// The width of one Geist Mono cell at 12px.
const CELL: f32 = 7.2;

/// A line of the error that wraps between words, like the browser's `pre-wrap`. GPUI would
/// also break after a slash. Leading indentation stays on the first row only.
fn wrapping_line(line: &str) -> gpui::Div {
    let indent = line.len() - line.trim_start().len();
    div()
        .flex()
        .flex_wrap()
        .gap_x(px(CELL))
        .min_h(px(19.5))
        // The gap after the spacer is the indent's last cell.
        .when(indent > 0, |this| this.child(div().w(px(CELL * (indent - 1) as f32))))
        .children(line.split_whitespace().map(|word| div().flex_none().child(word.to_string())))
}

Installation

  1. Add the components

    $ cargo hyuskui add bubble button message trace icons

    Uses Bubble, Button, Message and Trace.

  2. Copy the pattern

    Paste the code into src/ai/test_results.rs and declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.

    src/ai/test_results.rs
    use std::collections::HashMap;
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, AnyElement, Context, SharedString, Task, Window};
    
    use crate::icons::{CHECK, CIRCLE_DASHED, FILE_CODE, FLASK_CONICAL, X};
    use crate::theme::ActiveTheme;
    use crate::ui::button::{Button, ButtonSize, ButtonVariant};
    use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
    use crate::ui::message::{Message, MessageAlign};
    use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus};
    
    const MONO: &str = "Geist Mono";
    
    /// The mock transport's pace: one word every 20ms. The run takes as long as the script sleeps
    /// between the tool's input and its output.
    const CHUNK: Duration = Duration::from_millis(20);
    const TESTS_RUN: Duration = Duration::from_millis(1500);
    
    const QUESTION: &str = "Run the checkout tests.";
    const ANSWER: &str = "One test failed. The payment client does not retry a declined card, so the second charge attempt never happens.";
    const COMMAND: &str = "pnpm test checkout";
    
    #[derive(Clone, Copy, PartialEq)]
    enum Status {
        Passed,
        Failed,
        Skipped,
    }
    
    struct Test {
        name: &'static str,
        status: Status,
        error: &'static str,
    }
    
    const fn passed(name: &'static str) -> Test {
        Test { name, status: Status::Passed, error: "" }
    }
    
    const SUITES: [(&str, &[Test]); 2] = [
        ("cart.test.ts", &[passed("adds an item"), passed("removes an item"), passed("applies a discount code")]),
        (
            "payment.test.ts",
            &[
                passed("charges the saved card"),
                Test {
                    name: "retries a declined card",
                    status: Status::Failed,
                    error: "Expected 2 charge attempts, received 1\n\n  at Object.<anonymous> (src/payment.test.ts:58:22)",
                },
            ],
        ),
    ];
    
    /// shadcn's `formatCounts`: "5 tests, 1 failed", leaving out zero counts.
    fn counts<'a>(tests: impl Iterator<Item = &'a Test>) -> (usize, String) {
        let (mut total, mut failed, mut skipped) = (0, 0, 0);
        for test in tests {
            total += 1;
            failed += (test.status == Status::Failed) as usize;
            skipped += (test.status == Status::Skipped) as usize;
        }
        let mut label = format!("{total} tests");
        if failed > 0 {
            label += &format!(", {failed} failed");
        }
        if skipped > 0 {
            label += &format!(", {skipped} skipped");
        }
        (failed, label)
    }
    
    pub struct TestResultsPattern {
        replied: bool,
        /// Whether the run has reported back.
        ran: bool,
        words: usize,
        busy: bool,
        /// Rows the reader opened or closed; the rest open when they hold a failure.
        open: HashMap<SharedString, bool>,
        stream: Option<Task<()>>,
    }
    
    impl Default for TestResultsPattern {
        /// Starts on the finished transcript.
        fn default() -> Self {
            Self {
                replied: true,
                ran: true,
                words: ANSWER.split_inclusive(' ').count(),
                busy: false,
                open: HashMap::new(),
                stream: None,
            }
        }
    }
    
    impl TestResultsPattern {
        fn replay(&mut self, cx: &mut Context<Self>) {
            *self = Self { ran: false, words: 0, busy: true, ..Self::default() };
            self.stream = Some(cx.spawn(async move |this, cx| {
                cx.background_executor().timer(TESTS_RUN).await;
                if this.update(cx, |this, cx| {
                    this.ran = true;
                    cx.notify();
                })
                .is_err()
                {
                    return;
                }
                for _ in 0..ANSWER.split_inclusive(' ').count() {
                    cx.background_executor().timer(CHUNK).await;
                    if this.update(cx, |this, cx| {
                        this.words += 1;
                        cx.notify();
                    })
                    .is_err()
                    {
                        return;
                    }
                }
                let _ = this.update(cx, |this, cx| {
                    this.busy = false;
                    cx.notify();
                });
            }));
            cx.notify();
        }
    
        /// A row that opens by default when it holds a failure, like shadcn's `defaultOpen`.
        fn collapsible(&self, id: SharedString, failed: bool, line: TraceLine, cx: &mut Context<Self>) -> TraceCollapsible {
            let open = self.open.get(&id).copied().unwrap_or(failed);
            let key = id.clone();
            TraceCollapsible::new(id, open, line).on_open_change(cx.listener(move |this, open: &bool, _, cx| {
                this.open.insert(key.clone(), *open);
                cx.notify();
            }))
        }
    
        fn results(&self, cx: &mut Context<Self>) -> AnyElement {
            if !self.ran {
                return TraceLine::new("run", format!("Running {COMMAND}"))
                    .icon(FLASK_CONICAL)
                    .status(TraceStatus::Running)
                    .into_any_element();
            }
            let status = |failed: usize| if failed > 0 { TraceStatus::Error } else { TraceStatus::Done };
            let (failed, label) = counts(SUITES.iter().flat_map(|(_, tests)| tests.iter()));
    
            let suites: Vec<AnyElement> = SUITES
                .iter()
                .map(|(name, tests)| {
                    let (failed, label) = counts(tests.iter());
                    let rows: Vec<AnyElement> = tests.iter().map(|test| self.test_row(name, test, cx)).collect();
                    self.collapsible(
                        format!("suite-{name}").into(),
                        failed > 0,
                        TraceLine::new(SharedString::from(format!("suite-title-{name}")), format!("{name}, {label}"))
                            .icon(FILE_CODE)
                            .status(status(failed)),
                        cx,
                    )
                    .child(Trace::new().children(rows))
                    .into_any_element()
                })
                .collect();
    
            self.collapsible(
                "run".into(),
                failed > 0,
                TraceLine::new("run-title", format!("Ran {label}")).icon(FLASK_CONICAL).status(status(failed)),
                cx,
            )
            .child(Trace::new().children(suites))
            .into_any_element()
        }
    
        fn test_row(&self, suite: &str, test: &Test, cx: &mut Context<Self>) -> AnyElement {
            let id = SharedString::from(format!("{suite}/{}", test.name));
            match test.status {
                Status::Failed => {
                    let theme = cx.theme();
                    // shadcn's small code block: a muted panel with 12px mono text that wraps.
                    let error = div()
                        .max_h(px(256.0))
                        .overflow_hidden()
                        .p_3()
                        .rounded(px(14.0))
                        .bg(theme.muted)
                        .font_family(MONO)
                        .text_xs()
                        .line_height(px(19.5))
                        .text_color(theme.foreground)
                        .children(test.error.lines().map(wrapping_line));
                    self.collapsible(
                        id.clone(),
                        true,
                        TraceLine::new(SharedString::from(format!("{id}-title")), test.name).icon(X).status(TraceStatus::Error),
                        cx,
                    )
                    .child(error)
                    .into_any_element()
                }
                Status::Skipped => TraceLine::new(id, format!("Skipped {}", test.name)).icon(CIRCLE_DASHED).into_any_element(),
                Status::Passed => TraceLine::new(id, test.name).icon(CHECK).into_any_element(),
            }
        }
    }
    
    impl Render for TestResultsPattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect();
            let results = self.replied.then(|| self.results(cx));
            let theme = cx.theme();
    
            div()
                .w(px(384.0))
                .min_h(px(288.0))
                .flex()
                .flex_col()
                .gap_4()
                .py_6()
                .text_sm()
                .text_color(theme.foreground)
                .child(
                    Message::new()
                        .align(MessageAlign::End)
                        .child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION)),
                )
                .when_some(results, |this, results| {
                    this.child(
                        Message::new().child(
                            div()
                                .flex()
                                .flex_col()
                                .gap_4()
                                .w_full()
                                .line_height(px(20.0))
                                .child(Trace::new().child(results))
                                .when(!answer.is_empty(), |this| this.child(answer)),
                        ),
                    )
                })
                .when(!self.busy, |this| {
                    this.child(div().mt_auto().flex().child(Button::new("replay", "Replay")
                            .variant(ButtonVariant::Outline)
                            .size(ButtonSize::Compact)
                            .rounded_full()
                            .on_click(cx.listener(|this, _, _, cx| this.replay(cx)))))
                })
        }
    }
    
    
    
    /// The width of one Geist Mono cell at 12px.
    const CELL: f32 = 7.2;
    
    /// A line of the error that wraps between words, like the browser's `pre-wrap`. GPUI would
    /// also break after a slash. Leading indentation stays on the first row only.
    fn wrapping_line(line: &str) -> gpui::Div {
        let indent = line.len() - line.trim_start().len();
        div()
            .flex()
            .flex_wrap()
            .gap_x(px(CELL))
            .min_h(px(19.5))
            // The gap after the spacer is the indent's last cell.
            .when(indent > 0, |this| this.child(div().w(px(CELL * (indent - 1) as f32))))
            .children(line.split_whitespace().map(|word| div().flex_none().child(word.to_string())))
    }