hyuskui

Queue

Displays the agent's todo list, split into what is left and what is done.

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

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

use crate::icons::{CIRCLE, CIRCLE_CHECK, CIRCLE_DOT, LIST_CHECKS, LIST_TODO};
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};

/// The mock transport's pace: each word of the reply waits one chunk.
const CHUNK: Duration = Duration::from_millis(20);
/// The agent rewrites its todo list once per item, 1400ms apart.
const STEP: Duration = Duration::from_millis(1400);

const QUESTION: &str = "Add dark mode to the settings page.";
const ANSWER: &str = "Dark mode is in. The toggle is under Settings, Appearance.";

const TODOS: [&str; 4] = [
    "Add a dark variant to the theme tokens",
    "Read the theme from a cookie",
    "Add a toggle to the settings page",
    "Check contrast on the charts",
];

/// Splits like the mock transport, `/\S+\s*/g`: each chunk keeps its trailing space.
fn chunks(text: &str) -> impl Iterator<Item = &str> {
    text.split_inclusive(' ')
}

pub struct QueuePattern {
    /// `None` until the assistant's first todo list arrives; then the index of the item in
    /// progress (`TODOS.len()` once everything is done).
    current: Option<usize>,
    /// Words of the closing text shown so far.
    words: usize,
    stream: Option<Task<()>>,
    /// Each group opens again whenever it reappears, like `defaultOpen` on a fresh mount.
    todo_open: bool,
    done_open: bool,
}

impl Default for QueuePattern {
    /// Starts on the finished transcript.
    fn default() -> Self {
        Self {
            current: Some(TODOS.len()),
            words: chunks(ANSWER).count(),
            stream: None,
            todo_open: true,
            done_open: true,
        }
    }
}

impl QueuePattern {
    /// Moves to the todo list where item `current` is in progress.
    fn advance(&mut self, current: usize) {
        let had_todo = self.current.is_some_and(|ix| ix < TODOS.len());
        let had_done = self.current.is_some_and(|ix| ix > 0);
        if current < TODOS.len() && !had_todo {
            self.todo_open = true;
        }
        if current > 0 && !had_done {
            self.done_open = true;
        }
        self.current = Some(current);
    }

    fn replay(&mut self, cx: &mut Context<Self>) {
        self.current = None;
        self.words = 0;
        self.stream = Some(cx.spawn(async move |this, cx| {
            for current in 0..=TODOS.len() {
                if current > 0 {
                    cx.background_executor().timer(STEP).await;
                }
                let updated = this.update(cx, |this, cx| {
                    this.advance(current);
                    cx.notify();
                });
                if updated.is_err() {
                    return;
                }
            }
            for _ in chunks(ANSWER) {
                cx.background_executor().timer(CHUNK).await;
                let shown = this.update(cx, |this, cx| {
                    this.words += 1;
                    cx.notify();
                });
                if shown.is_err() {
                    return;
                }
            }
            this.update(cx, |this, cx| {
                this.stream = None;
                cx.notify();
            })
            .ok();
        }));
        cx.notify();
    }
}

impl Render for QueuePattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = cx.theme();
        let fg = theme.foreground;
        let streaming = self.stream.is_some();

        let todo_line = move |ix: usize, current: usize| {
            let (data, status) = if ix < current {
                (CIRCLE_CHECK, TraceStatus::Done)
            } else if ix == current {
                (CIRCLE_DOT, if streaming { TraceStatus::Running } else { TraceStatus::Done })
            } else {
                (CIRCLE, TraceStatus::Done)
            };
            TraceLine::new(("todo", ix), TODOS[ix]).icon(data).status(status)
        };

        let queue = self.current.map(|current| {
            let pending: Vec<usize> = (current.min(TODOS.len())..TODOS.len()).collect();
            let completed: Vec<usize> = (0..current.min(TODOS.len())).collect();
            Trace::new()
                .when(!pending.is_empty(), |this| {
                    let title = format!("{} to do", pending.len());
                    this.child(
                        TraceCollapsible::new("pending", self.todo_open, TraceLine::new("pending-line", title).icon(LIST_TODO))
                            .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                                this.todo_open = *open;
                                cx.notify();
                            }))
                            .child(Trace::new().children(pending.iter().map(|&ix| todo_line(ix, current)))),
                    )
                })
                .when(!completed.is_empty(), |this| {
                    let title = format!("{} completed", completed.len());
                    this.child(
                        TraceCollapsible::new("completed", self.done_open, TraceLine::new("completed-line", title).icon(LIST_CHECKS))
                            .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                                this.done_open = *open;
                                cx.notify();
                            }))
                            .child(Trace::new().children(completed.iter().map(|&ix| todo_line(ix, current)))),
                    )
                })
        });
        let text: String = chunks(ANSWER).take(self.words).collect();

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

    src/ai/queue.rs
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, Context, Task, Window};
    
    use crate::icons::{CIRCLE, CIRCLE_CHECK, CIRCLE_DOT, LIST_CHECKS, LIST_TODO};
    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};
    
    /// The mock transport's pace: each word of the reply waits one chunk.
    const CHUNK: Duration = Duration::from_millis(20);
    /// The agent rewrites its todo list once per item, 1400ms apart.
    const STEP: Duration = Duration::from_millis(1400);
    
    const QUESTION: &str = "Add dark mode to the settings page.";
    const ANSWER: &str = "Dark mode is in. The toggle is under Settings, Appearance.";
    
    const TODOS: [&str; 4] = [
        "Add a dark variant to the theme tokens",
        "Read the theme from a cookie",
        "Add a toggle to the settings page",
        "Check contrast on the charts",
    ];
    
    /// Splits like the mock transport, `/\S+\s*/g`: each chunk keeps its trailing space.
    fn chunks(text: &str) -> impl Iterator<Item = &str> {
        text.split_inclusive(' ')
    }
    
    pub struct QueuePattern {
        /// `None` until the assistant's first todo list arrives; then the index of the item in
        /// progress (`TODOS.len()` once everything is done).
        current: Option<usize>,
        /// Words of the closing text shown so far.
        words: usize,
        stream: Option<Task<()>>,
        /// Each group opens again whenever it reappears, like `defaultOpen` on a fresh mount.
        todo_open: bool,
        done_open: bool,
    }
    
    impl Default for QueuePattern {
        /// Starts on the finished transcript.
        fn default() -> Self {
            Self {
                current: Some(TODOS.len()),
                words: chunks(ANSWER).count(),
                stream: None,
                todo_open: true,
                done_open: true,
            }
        }
    }
    
    impl QueuePattern {
        /// Moves to the todo list where item `current` is in progress.
        fn advance(&mut self, current: usize) {
            let had_todo = self.current.is_some_and(|ix| ix < TODOS.len());
            let had_done = self.current.is_some_and(|ix| ix > 0);
            if current < TODOS.len() && !had_todo {
                self.todo_open = true;
            }
            if current > 0 && !had_done {
                self.done_open = true;
            }
            self.current = Some(current);
        }
    
        fn replay(&mut self, cx: &mut Context<Self>) {
            self.current = None;
            self.words = 0;
            self.stream = Some(cx.spawn(async move |this, cx| {
                for current in 0..=TODOS.len() {
                    if current > 0 {
                        cx.background_executor().timer(STEP).await;
                    }
                    let updated = this.update(cx, |this, cx| {
                        this.advance(current);
                        cx.notify();
                    });
                    if updated.is_err() {
                        return;
                    }
                }
                for _ in chunks(ANSWER) {
                    cx.background_executor().timer(CHUNK).await;
                    let shown = this.update(cx, |this, cx| {
                        this.words += 1;
                        cx.notify();
                    });
                    if shown.is_err() {
                        return;
                    }
                }
                this.update(cx, |this, cx| {
                    this.stream = None;
                    cx.notify();
                })
                .ok();
            }));
            cx.notify();
        }
    }
    
    impl Render for QueuePattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let theme = cx.theme();
            let fg = theme.foreground;
            let streaming = self.stream.is_some();
    
            let todo_line = move |ix: usize, current: usize| {
                let (data, status) = if ix < current {
                    (CIRCLE_CHECK, TraceStatus::Done)
                } else if ix == current {
                    (CIRCLE_DOT, if streaming { TraceStatus::Running } else { TraceStatus::Done })
                } else {
                    (CIRCLE, TraceStatus::Done)
                };
                TraceLine::new(("todo", ix), TODOS[ix]).icon(data).status(status)
            };
    
            let queue = self.current.map(|current| {
                let pending: Vec<usize> = (current.min(TODOS.len())..TODOS.len()).collect();
                let completed: Vec<usize> = (0..current.min(TODOS.len())).collect();
                Trace::new()
                    .when(!pending.is_empty(), |this| {
                        let title = format!("{} to do", pending.len());
                        this.child(
                            TraceCollapsible::new("pending", self.todo_open, TraceLine::new("pending-line", title).icon(LIST_TODO))
                                .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                                    this.todo_open = *open;
                                    cx.notify();
                                }))
                                .child(Trace::new().children(pending.iter().map(|&ix| todo_line(ix, current)))),
                        )
                    })
                    .when(!completed.is_empty(), |this| {
                        let title = format!("{} completed", completed.len());
                        this.child(
                            TraceCollapsible::new("completed", self.done_open, TraceLine::new("completed-line", title).icon(LIST_CHECKS))
                                .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                                    this.done_open = *open;
                                    cx.notify();
                                }))
                                .child(Trace::new().children(completed.iter().map(|&ix| todo_line(ix, current)))),
                        )
                    })
            });
            let text: String = chunks(ANSWER).take(self.words).collect();
    
            div()
                .w(px(384.0))
                .min_h(px(288.0))
                .flex()
                .flex_col()
                .gap_4()
                .py_6()
                .text_sm()
                // shadcn's text-sm: 14px on a 20px line.
                .line_height(px(20.0))
                .child(
                    Message::new().align(MessageAlign::End).child(
                        Bubble::new("question")
                            .align(BubbleAlign::End)
                            .variant(BubbleVariant::Muted)
                            .child(QUESTION),
                    ),
                )
                .when_some(queue, |this, queue| {
                    this.child(
                        Message::new()
                            .gap(px(16.0))
                            .child(queue)
                            .when(!text.is_empty(), |this| this.child(div().w_full().text_color(fg).child(text))),
                    )
                })
                .when(!streaming, |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))),
                        ),
                    )
                })
        }
    }