hyuskui

Stack Trace

A failed command and where it broke. The error opens on its message and your code's frames; the framework's frames fold away under one row.

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

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

use crate::icons::{FILE_CODE, LAYERS, TERMINAL};
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 commands take as long as the script
/// sleeps between their input and their result.
const CHUNK: Duration = Duration::from_millis(20);
const RESET_RUNS: Duration = Duration::from_millis(900);
const SEED_RUNS: Duration = Duration::from_millis(1200);

const QUESTION: &str = "Reset the database and seed it.";
const ANSWER: &str = "The migrations ran, but the seed failed in seedUsers. One fixture has no profile, so profile.email is undefined.";

const RESET: &str = "pnpm prisma migrate reset --skip-seed";
const RESET_OUTPUT: &str = "Database reset successful

The following migrations have been applied:

migrations/
  └─ 20260912_init/
  └─ 20260920_add_profiles/";
const SEED: &str = "pnpm prisma db seed";
const STACK: &str = "TypeError: Cannot read properties of undefined (reading 'email')
    at seedUsers (prisma/seed.ts:27:34)
    at main (prisma/seed.ts:51:9)
    at Module._compile (node:internal/modules/cjs/loader:1554:14)
    at Object.transformer (node_modules/tsx/dist/register.cjs:3:1104)
    at Module.load (node:internal/modules/cjs/loader:1289:32)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)";

#[derive(Clone, Copy, PartialEq)]
enum Run {
    Running,
    Done,
    Failed,
}

pub struct StackTracePattern {
    replied: bool,
    reset: Option<Run>,
    seed: Option<Run>,
    words: usize,
    busy: bool,
    /// Each row's open state, as its `defaultOpen` sets it when it mounts.
    reset_open: bool,
    error_open: bool,
    frames_open: bool,
    stream: Option<Task<()>>,
}

impl Default for StackTracePattern {
    /// Starts on the finished transcript.
    fn default() -> Self {
        Self {
            replied: true,
            reset: Some(Run::Done),
            seed: Some(Run::Failed),
            words: ANSWER.split_inclusive(' ').count(),
            busy: false,
            reset_open: false,
            error_open: true,
            frames_open: false,
            stream: None,
        }
    }
}

impl StackTracePattern {
    fn replay(&mut self, cx: &mut Context<Self>) {
        *self = Self { replied: true, reset: Some(Run::Running), seed: None, words: 0, busy: true, ..Self::default() };
        self.stream = Some(cx.spawn(async move |this, cx| {
            let step = |cx: &mut gpui::AsyncApp, f: fn(&mut Self)| {
                this.update(cx, |this, cx| {
                    f(this);
                    cx.notify();
                })
                .is_ok()
            };
            cx.background_executor().timer(RESET_RUNS).await;
            if !step(cx, |this| {
                this.reset = Some(Run::Done);
                this.seed = Some(Run::Running);
            }) {
                return;
            }
            cx.background_executor().timer(SEED_RUNS).await;
            if !step(cx, |this| this.seed = Some(Run::Failed)) {
                return;
            }
            for _ in 0..ANSWER.split_inclusive(' ').count() {
                cx.background_executor().timer(CHUNK).await;
                if !step(cx, |this| this.words += 1) {
                    return;
                }
            }
            step(cx, |this| this.busy = false);
        }));
        cx.notify();
    }

    fn command(&self, id: &'static str, command: &str, run: Run, cx: &mut Context<Self>) -> AnyElement {
        let theme = cx.theme();
        match run {
            Run::Running => TraceLine::new(id, format!("Running {command}"))
                .icon(TERMINAL)
                .status(TraceStatus::Running)
                .into_any_element(),
            Run::Done => TraceCollapsible::new(
                id,
                self.reset_open,
                TraceLine::new((id, 1usize), format!("Ran {command}")).icon(TERMINAL),
            )
            .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                this.reset_open = *open;
                cx.notify();
            }))
            .child(
                // shadcn's small code block: a muted panel with 12px mono text that wraps.
                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(RESET_OUTPUT.lines().map(|line| div().min_h(px(19.5)).child(line.to_string()))),
            )
            .into_any_element(),
            Run::Failed => self.stack_trace(cx),
        }
    }

    fn stack_trace(&self, cx: &mut Context<Self>) -> AnyElement {
        let theme = cx.theme();
        let mut lines = STACK.lines().map(str::trim);
        let error = lines.next().unwrap_or_default();
        let frames: Vec<Frame> = lines.map(Frame::parse).collect();
        let app_frames = frames.iter().filter(|frame| !frame.internal).enumerate().map(|(ix, frame)| {
            TraceLine::new(("frame", ix), format!("{} in {}:{}", frame.name, frame.file, frame.line_number))
                .icon(FILE_CODE)
                // Each frame links to its line; there is no file to open here.
                .on_click(|_, _, _| {})
        });
        let internal: Vec<&Frame> = frames.iter().filter(|frame| frame.internal).collect();

        let framework = TraceCollapsible::new(
            "framework",
            self.frames_open,
            TraceLine::new("framework-title", format!("{} framework frames", internal.len())).icon(LAYERS),
        )
        .on_open_change(cx.listener(|this, open: &bool, _, cx| {
            this.frames_open = *open;
            cx.notify();
        }))
        .child(
            div()
                .id("framework-frames")
                .flex()
                .flex_col()
                .gap_1()
                .overflow_x_scroll()
                .p_3()
                .rounded(px(8.0))
                .bg(theme.muted)
                .font_family(MONO)
                .text_xs()
                .line_height(px(16.0))
                .children(internal.iter().map(|frame| div().flex_none().whitespace_nowrap().child(frame.text))),
        );

        TraceCollapsible::new(
            "seed",
            self.error_open,
            TraceLine::new("seed-title", format!("Failed: {error}")).icon(TERMINAL).status(TraceStatus::Error),
        )
        .on_open_change(cx.listener(|this, open: &bool, _, cx| {
            this.error_open = *open;
            cx.notify();
        }))
        .child(
            div()
                .flex()
                .flex_col()
                .gap_2()
                .child(
                    div()
                        .font_family(MONO)
                        .text_xs()
                        .line_height(px(16.0))
                        .text_color(theme.destructive)
                        .child(error),
                )
                .child(Trace::new().children(app_frames).child(framework)),
        )
        .into_any_element()
    }
}

/// One `at name (file:line:column)` line of the stack.
struct Frame {
    text: &'static str,
    name: &'static str,
    file: &'static str,
    line_number: &'static str,
    /// Node's and the dependencies' frames, as opposed to the app's.
    internal: bool,
}

impl Frame {
    fn parse(text: &'static str) -> Self {
        let call = text.strip_prefix("at ").unwrap_or(text);
        let (name, location) = call.split_once(" (").unwrap_or((call, ""));
        let mut parts = location.trim_end_matches(')').rsplitn(3, ':');
        let _column = parts.next();
        let line_number = parts.next().unwrap_or_default();
        let file = parts.next().unwrap_or_default();
        Self {
            text,
            name,
            file,
            line_number,
            internal: text.contains("node_modules") || text.contains("node:"),
        }
    }
}

impl Render for StackTracePattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect();
        let tools: Vec<AnyElement> = [("reset", RESET, self.reset), ("seed", SEED, self.seed)]
            .into_iter()
            .filter_map(|(id, command, run)| run.map(|run| self.command(id, command, run, cx)))
            .collect();
        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(self.replied, |this| {
                this.child(
                    Message::new().child(
                        div()
                            .flex()
                            .flex_col()
                            .gap_4()
                            .w_full()
                            .line_height(px(20.0))
                            .when(!tools.is_empty(), |this| this.child(Trace::new().children(tools)))
                            .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)))))
            })
    }
}

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/stack_trace.rs and declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.

    src/ai/stack_trace.rs
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, AnyElement, Context, Task, Window};
    
    use crate::icons::{FILE_CODE, LAYERS, TERMINAL};
    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 commands take as long as the script
    /// sleeps between their input and their result.
    const CHUNK: Duration = Duration::from_millis(20);
    const RESET_RUNS: Duration = Duration::from_millis(900);
    const SEED_RUNS: Duration = Duration::from_millis(1200);
    
    const QUESTION: &str = "Reset the database and seed it.";
    const ANSWER: &str = "The migrations ran, but the seed failed in seedUsers. One fixture has no profile, so profile.email is undefined.";
    
    const RESET: &str = "pnpm prisma migrate reset --skip-seed";
    const RESET_OUTPUT: &str = "Database reset successful
    
    The following migrations have been applied:
    
    migrations/
      └─ 20260912_init/
      └─ 20260920_add_profiles/";
    const SEED: &str = "pnpm prisma db seed";
    const STACK: &str = "TypeError: Cannot read properties of undefined (reading 'email')
        at seedUsers (prisma/seed.ts:27:34)
        at main (prisma/seed.ts:51:9)
        at Module._compile (node:internal/modules/cjs/loader:1554:14)
        at Object.transformer (node_modules/tsx/dist/register.cjs:3:1104)
        at Module.load (node:internal/modules/cjs/loader:1289:32)
        at process.processTicksAndRejections (node:internal/process/task_queues:105:5)";
    
    #[derive(Clone, Copy, PartialEq)]
    enum Run {
        Running,
        Done,
        Failed,
    }
    
    pub struct StackTracePattern {
        replied: bool,
        reset: Option<Run>,
        seed: Option<Run>,
        words: usize,
        busy: bool,
        /// Each row's open state, as its `defaultOpen` sets it when it mounts.
        reset_open: bool,
        error_open: bool,
        frames_open: bool,
        stream: Option<Task<()>>,
    }
    
    impl Default for StackTracePattern {
        /// Starts on the finished transcript.
        fn default() -> Self {
            Self {
                replied: true,
                reset: Some(Run::Done),
                seed: Some(Run::Failed),
                words: ANSWER.split_inclusive(' ').count(),
                busy: false,
                reset_open: false,
                error_open: true,
                frames_open: false,
                stream: None,
            }
        }
    }
    
    impl StackTracePattern {
        fn replay(&mut self, cx: &mut Context<Self>) {
            *self = Self { replied: true, reset: Some(Run::Running), seed: None, words: 0, busy: true, ..Self::default() };
            self.stream = Some(cx.spawn(async move |this, cx| {
                let step = |cx: &mut gpui::AsyncApp, f: fn(&mut Self)| {
                    this.update(cx, |this, cx| {
                        f(this);
                        cx.notify();
                    })
                    .is_ok()
                };
                cx.background_executor().timer(RESET_RUNS).await;
                if !step(cx, |this| {
                    this.reset = Some(Run::Done);
                    this.seed = Some(Run::Running);
                }) {
                    return;
                }
                cx.background_executor().timer(SEED_RUNS).await;
                if !step(cx, |this| this.seed = Some(Run::Failed)) {
                    return;
                }
                for _ in 0..ANSWER.split_inclusive(' ').count() {
                    cx.background_executor().timer(CHUNK).await;
                    if !step(cx, |this| this.words += 1) {
                        return;
                    }
                }
                step(cx, |this| this.busy = false);
            }));
            cx.notify();
        }
    
        fn command(&self, id: &'static str, command: &str, run: Run, cx: &mut Context<Self>) -> AnyElement {
            let theme = cx.theme();
            match run {
                Run::Running => TraceLine::new(id, format!("Running {command}"))
                    .icon(TERMINAL)
                    .status(TraceStatus::Running)
                    .into_any_element(),
                Run::Done => TraceCollapsible::new(
                    id,
                    self.reset_open,
                    TraceLine::new((id, 1usize), format!("Ran {command}")).icon(TERMINAL),
                )
                .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                    this.reset_open = *open;
                    cx.notify();
                }))
                .child(
                    // shadcn's small code block: a muted panel with 12px mono text that wraps.
                    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(RESET_OUTPUT.lines().map(|line| div().min_h(px(19.5)).child(line.to_string()))),
                )
                .into_any_element(),
                Run::Failed => self.stack_trace(cx),
            }
        }
    
        fn stack_trace(&self, cx: &mut Context<Self>) -> AnyElement {
            let theme = cx.theme();
            let mut lines = STACK.lines().map(str::trim);
            let error = lines.next().unwrap_or_default();
            let frames: Vec<Frame> = lines.map(Frame::parse).collect();
            let app_frames = frames.iter().filter(|frame| !frame.internal).enumerate().map(|(ix, frame)| {
                TraceLine::new(("frame", ix), format!("{} in {}:{}", frame.name, frame.file, frame.line_number))
                    .icon(FILE_CODE)
                    // Each frame links to its line; there is no file to open here.
                    .on_click(|_, _, _| {})
            });
            let internal: Vec<&Frame> = frames.iter().filter(|frame| frame.internal).collect();
    
            let framework = TraceCollapsible::new(
                "framework",
                self.frames_open,
                TraceLine::new("framework-title", format!("{} framework frames", internal.len())).icon(LAYERS),
            )
            .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                this.frames_open = *open;
                cx.notify();
            }))
            .child(
                div()
                    .id("framework-frames")
                    .flex()
                    .flex_col()
                    .gap_1()
                    .overflow_x_scroll()
                    .p_3()
                    .rounded(px(8.0))
                    .bg(theme.muted)
                    .font_family(MONO)
                    .text_xs()
                    .line_height(px(16.0))
                    .children(internal.iter().map(|frame| div().flex_none().whitespace_nowrap().child(frame.text))),
            );
    
            TraceCollapsible::new(
                "seed",
                self.error_open,
                TraceLine::new("seed-title", format!("Failed: {error}")).icon(TERMINAL).status(TraceStatus::Error),
            )
            .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                this.error_open = *open;
                cx.notify();
            }))
            .child(
                div()
                    .flex()
                    .flex_col()
                    .gap_2()
                    .child(
                        div()
                            .font_family(MONO)
                            .text_xs()
                            .line_height(px(16.0))
                            .text_color(theme.destructive)
                            .child(error),
                    )
                    .child(Trace::new().children(app_frames).child(framework)),
            )
            .into_any_element()
        }
    }
    
    /// One `at name (file:line:column)` line of the stack.
    struct Frame {
        text: &'static str,
        name: &'static str,
        file: &'static str,
        line_number: &'static str,
        /// Node's and the dependencies' frames, as opposed to the app's.
        internal: bool,
    }
    
    impl Frame {
        fn parse(text: &'static str) -> Self {
            let call = text.strip_prefix("at ").unwrap_or(text);
            let (name, location) = call.split_once(" (").unwrap_or((call, ""));
            let mut parts = location.trim_end_matches(')').rsplitn(3, ':');
            let _column = parts.next();
            let line_number = parts.next().unwrap_or_default();
            let file = parts.next().unwrap_or_default();
            Self {
                text,
                name,
                file,
                line_number,
                internal: text.contains("node_modules") || text.contains("node:"),
            }
        }
    }
    
    impl Render for StackTracePattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect();
            let tools: Vec<AnyElement> = [("reset", RESET, self.reset), ("seed", SEED, self.seed)]
                .into_iter()
                .filter_map(|(id, command, run)| run.map(|run| self.command(id, command, run, cx)))
                .collect();
            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(self.replied, |this| {
                    this.child(
                        Message::new().child(
                            div()
                                .flex()
                                .flex_col()
                                .gap_4()
                                .w_full()
                                .line_height(px(20.0))
                                .when(!tools.is_empty(), |this| this.child(Trace::new().children(tools)))
                                .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)))))
                })
        }
    }