hyuskui

Plan

Displays the steps an agent plans to take. The plan stays open and ticks its steps off as the agent works through them, with a count of what's done.

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

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

use crate::icons::{CIRCLE, CIRCLE_CHECK, CIRCLE_DOT, ROUTE};
use crate::theme::ActiveTheme;
use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::message::{Message, MessageAlign};
use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus};

/// Each step takes 1.2s; the answer then streams a word every 20ms.
const STEP: Duration = Duration::from_millis(1200);
const CHUNK: Duration = Duration::from_millis(20);

const QUESTION: &str = "Migrate the dialog components to Base UI.";
const TITLE: &str = "Plan: migrate to Base UI";
const ANSWER: &str = "Migrated Dialog and AlertDialog. The type checker passes.";

const STEPS: [&str; 4] = [
    "Install @base-ui/react",
    "Replace the Radix imports",
    "Rename asChild to render",
    "Run the type checker",
];

pub struct PlanPattern {
    /// `None` until the plan arrives; then how many steps are done. The next one is running.
    done: Option<usize>,
    /// Words of the answer shown so far.
    words: usize,
    /// The plan opens when it arrives and stays open until the reader closes it.
    open: bool,
    busy: bool,
    stream: Option<Task<()>>,
}

impl Default for PlanPattern {
    /// Starts on the finished transcript.
    fn default() -> Self {
        Self {
            done: Some(STEPS.len()),
            words: ANSWER.split_inclusive(' ').count(),
            open: true,
            busy: false,
            stream: None,
        }
    }
}

impl PlanPattern {
    fn replay(&mut self, cx: &mut Context<Self>) {
        self.done = Some(0);
        self.words = 0;
        self.open = true;
        self.busy = true;
        self.stream = Some(cx.spawn(async move |this, cx| {
            for done in 1..=STEPS.len() {
                cx.background_executor().timer(STEP).await;
                if this.update(cx, |this, cx| { this.done = Some(done); 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();
    }
}

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

        let plan = self.done.map(|done| {
            let running = self.busy && done < STEPS.len();
            let line = TraceLine::new("plan", TITLE)
                .icon(ROUTE)
                .description(format!("{done} of {} done", STEPS.len()))
                .status(if running { TraceStatus::Running } else { TraceStatus::Done });
            let steps = STEPS.iter().enumerate().map(|(ix, title)| {
                let (icon, status) = if ix < done {
                    (CIRCLE_CHECK, TraceStatus::Done)
                } else if ix == done {
                    (CIRCLE_DOT, if self.busy { TraceStatus::Running } else { TraceStatus::Done })
                } else {
                    (CIRCLE, TraceStatus::Pending)
                };
                TraceLine::new(("step", ix), *title).icon(icon).status(status)
            });
            Trace::new().child(
                TraceCollapsible::new("row", self.open, line)
                    .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                        this.open = *open;
                        cx.notify();
                    }))
                    .child(Trace::new().children(steps)),
            )
        });

        div()
            .w(px(384.0))
            .min_h(px(288.0))
            .flex()
            .flex_col()
            .gap_4()
            .py_6()
            .text_sm()
            .child(
                Message::new()
                    .align(MessageAlign::End)
                    .child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION)),
            )
            .when_some(plan, |this, plan| {
                this.child(
                    Message::new().child(
                        div()
                            .flex()
                            .flex_col()
                            .gap_4()
                            .w_full()
                            .child(plan)
                            .when(!answer.is_empty(), |this| {
                                this.child(div().line_height(relative(1.4286)).text_color(fg).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/plan.rs and declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.

    src/ai/plan.rs
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, relative, Context, Task, Window};
    
    use crate::icons::{CIRCLE, CIRCLE_CHECK, CIRCLE_DOT, ROUTE};
    use crate::theme::ActiveTheme;
    use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
    use crate::ui::button::{Button, ButtonSize, ButtonVariant};
    use crate::ui::message::{Message, MessageAlign};
    use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus};
    
    /// Each step takes 1.2s; the answer then streams a word every 20ms.
    const STEP: Duration = Duration::from_millis(1200);
    const CHUNK: Duration = Duration::from_millis(20);
    
    const QUESTION: &str = "Migrate the dialog components to Base UI.";
    const TITLE: &str = "Plan: migrate to Base UI";
    const ANSWER: &str = "Migrated Dialog and AlertDialog. The type checker passes.";
    
    const STEPS: [&str; 4] = [
        "Install @base-ui/react",
        "Replace the Radix imports",
        "Rename asChild to render",
        "Run the type checker",
    ];
    
    pub struct PlanPattern {
        /// `None` until the plan arrives; then how many steps are done. The next one is running.
        done: Option<usize>,
        /// Words of the answer shown so far.
        words: usize,
        /// The plan opens when it arrives and stays open until the reader closes it.
        open: bool,
        busy: bool,
        stream: Option<Task<()>>,
    }
    
    impl Default for PlanPattern {
        /// Starts on the finished transcript.
        fn default() -> Self {
            Self {
                done: Some(STEPS.len()),
                words: ANSWER.split_inclusive(' ').count(),
                open: true,
                busy: false,
                stream: None,
            }
        }
    }
    
    impl PlanPattern {
        fn replay(&mut self, cx: &mut Context<Self>) {
            self.done = Some(0);
            self.words = 0;
            self.open = true;
            self.busy = true;
            self.stream = Some(cx.spawn(async move |this, cx| {
                for done in 1..=STEPS.len() {
                    cx.background_executor().timer(STEP).await;
                    if this.update(cx, |this, cx| { this.done = Some(done); 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();
        }
    }
    
    impl Render for PlanPattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let fg = cx.theme().foreground;
            let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect();
    
            let plan = self.done.map(|done| {
                let running = self.busy && done < STEPS.len();
                let line = TraceLine::new("plan", TITLE)
                    .icon(ROUTE)
                    .description(format!("{done} of {} done", STEPS.len()))
                    .status(if running { TraceStatus::Running } else { TraceStatus::Done });
                let steps = STEPS.iter().enumerate().map(|(ix, title)| {
                    let (icon, status) = if ix < done {
                        (CIRCLE_CHECK, TraceStatus::Done)
                    } else if ix == done {
                        (CIRCLE_DOT, if self.busy { TraceStatus::Running } else { TraceStatus::Done })
                    } else {
                        (CIRCLE, TraceStatus::Pending)
                    };
                    TraceLine::new(("step", ix), *title).icon(icon).status(status)
                });
                Trace::new().child(
                    TraceCollapsible::new("row", self.open, line)
                        .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                            this.open = *open;
                            cx.notify();
                        }))
                        .child(Trace::new().children(steps)),
                )
            });
    
            div()
                .w(px(384.0))
                .min_h(px(288.0))
                .flex()
                .flex_col()
                .gap_4()
                .py_6()
                .text_sm()
                .child(
                    Message::new()
                        .align(MessageAlign::End)
                        .child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION)),
                )
                .when_some(plan, |this, plan| {
                    this.child(
                        Message::new().child(
                            div()
                                .flex()
                                .flex_col()
                                .gap_4()
                                .w_full()
                                .child(plan)
                                .when(!answer.is_empty(), |this| {
                                    this.child(div().line_height(relative(1.4286)).text_color(fg).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))),
                        ),
                    )
                })
        }
    }