hyuskui

Checkpoint

Marks a point in the conversation you can return to.

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

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

use crate::theme::ActiveTheme;
use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::marker::{Marker, MarkerVariant};
use crate::ui::message::{Message, MessageAlign};

/// The mock transport's pace: each word of a reply waits one chunk.
const CHUNK: Duration = Duration::from_millis(20);

/// The scripted turns: (user, reply, checkpoint after the reply).
const TURNS: [(&str, &str, Option<&str>); 2] = [
    (
        "Rename the button component to action.",
        "Renamed Button to Action in components/ui/button.tsx.",
        Some("Button renamed"),
    ),
    ("Update the docs to match.", "Updated the Button page to say Action.", None),
];

/// One turn on screen.
struct Turn {
    /// Index into `TURNS`.
    script: usize,
    /// Words of the reply shown so far.
    words: usize,
}

pub struct CheckpointPattern {
    turns: Vec<Turn>,
    stream: Option<Task<()>>,
}

impl Default for CheckpointPattern {
    /// Starts on the whole transcript, like `useChat({ messages: transcript })`.
    fn default() -> Self {
        Self {
            turns: (0..TURNS.len())
                .map(|script| Turn { script, words: words(TURNS[script].1) })
                .collect(),
            stream: None,
        }
    }
}

/// 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(' ')
}

fn words(text: &str) -> usize {
    chunks(text).count()
}

impl CheckpointPattern {
    fn busy(&self) -> bool {
        self.stream.is_some()
    }

    /// Drops every turn after the checkpoint's own.
    fn restore(&mut self, turn: usize, cx: &mut Context<Self>) {
        self.turns.truncate(turn + 1);
        cx.notify();
    }

    /// Sends the next scripted message and streams its reply.
    fn send_next(&mut self, cx: &mut Context<Self>) {
        let script = self.turns.len();
        if script >= TURNS.len() {
            return;
        }
        self.turns.push(Turn { script, words: 0 });
        let ix = self.turns.len() - 1;
        self.stream = Some(cx.spawn(async move |this, cx| {
            for _ in 0..words(TURNS[script].1) {
                cx.background_executor().timer(CHUNK).await;
                let shown = this.update(cx, |this, cx| {
                    if let Some(turn) = this.turns.get_mut(ix) {
                        turn.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 CheckpointPattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let fg = cx.theme().foreground;
        let count = self.turns.len();


        let mut rows = Vec::new();
        for (ix, turn) in self.turns.iter().enumerate() {
            let (ask, reply, checkpoint) = TURNS[turn.script];
            let text: String = chunks(reply).take(turn.words).collect();
            let streaming = self.busy() && ix + 1 == count;
            rows.push(
                Message::new()
                    .align(MessageAlign::End)
                    .child(
                        Bubble::new(("ask", ix))
                            .align(BubbleAlign::End)
                            .variant(BubbleVariant::Muted)
                            .child(ask),
                    )
                    .into_any_element(),
            );
            // The reply's message exists as soon as it starts streaming, empty or not.
            rows.push(Message::new().child(div().w_full().text_color(fg).child(text)).into_any_element());
            // The checkpoint is written after the reply, so it shows once the text is done.
            if let Some(label) = checkpoint.filter(|_| !streaming) {
                // Restoring only makes sense while something comes after the checkpoint.
                let can_restore = ix + 1 < count;
                rows.push(
                    Marker::new(("checkpoint", ix))
                        .variant(MarkerVariant::Separator)
                        .child(
                            div()
                                .flex()
                                .items_center()
                                .gap_2()
                                .child(label)
                                .when(can_restore, |this| {
                                    this.child(
                                        Button::new(("restore", ix), "Restore")
                                            .variant(ButtonVariant::Outline)
                                            .size(ButtonSize::Xs)
                                            .rounded_full()
                                            // It sits in the marker's muted text.
                                            .muted()
                                            .on_click(cx.listener(move |this, _, _, cx| this.restore(ix, cx))),
                                    )
                                }),
                        )
                        .into_any_element(),
                );
            }
        }

        let has_next = count < TURNS.len();
        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))
            .children(rows)
            .when(!self.busy() && has_next, |this| {
                this.child(
                    div().mt_auto().flex().child(
                        Button::new("continue", "Continue")
                            .variant(ButtonVariant::Outline)
                            .size(ButtonSize::Compact)
                            .rounded_full()
                            .on_click(cx.listener(|this, _, _, cx| this.send_next(cx))),
                    ),
                )
            })
    }
}

Installation

  1. Add the components

    $ cargo hyuskui add bubble button marker message

    Uses Bubble, Button, Marker and Message.

  2. Copy the pattern

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

    src/ai/checkpoint.rs
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, Context, Task, Window};
    
    use crate::theme::ActiveTheme;
    use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
    use crate::ui::button::{Button, ButtonSize, ButtonVariant};
    use crate::ui::marker::{Marker, MarkerVariant};
    use crate::ui::message::{Message, MessageAlign};
    
    /// The mock transport's pace: each word of a reply waits one chunk.
    const CHUNK: Duration = Duration::from_millis(20);
    
    /// The scripted turns: (user, reply, checkpoint after the reply).
    const TURNS: [(&str, &str, Option<&str>); 2] = [
        (
            "Rename the button component to action.",
            "Renamed Button to Action in components/ui/button.tsx.",
            Some("Button renamed"),
        ),
        ("Update the docs to match.", "Updated the Button page to say Action.", None),
    ];
    
    /// One turn on screen.
    struct Turn {
        /// Index into `TURNS`.
        script: usize,
        /// Words of the reply shown so far.
        words: usize,
    }
    
    pub struct CheckpointPattern {
        turns: Vec<Turn>,
        stream: Option<Task<()>>,
    }
    
    impl Default for CheckpointPattern {
        /// Starts on the whole transcript, like `useChat({ messages: transcript })`.
        fn default() -> Self {
            Self {
                turns: (0..TURNS.len())
                    .map(|script| Turn { script, words: words(TURNS[script].1) })
                    .collect(),
                stream: None,
            }
        }
    }
    
    /// 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(' ')
    }
    
    fn words(text: &str) -> usize {
        chunks(text).count()
    }
    
    impl CheckpointPattern {
        fn busy(&self) -> bool {
            self.stream.is_some()
        }
    
        /// Drops every turn after the checkpoint's own.
        fn restore(&mut self, turn: usize, cx: &mut Context<Self>) {
            self.turns.truncate(turn + 1);
            cx.notify();
        }
    
        /// Sends the next scripted message and streams its reply.
        fn send_next(&mut self, cx: &mut Context<Self>) {
            let script = self.turns.len();
            if script >= TURNS.len() {
                return;
            }
            self.turns.push(Turn { script, words: 0 });
            let ix = self.turns.len() - 1;
            self.stream = Some(cx.spawn(async move |this, cx| {
                for _ in 0..words(TURNS[script].1) {
                    cx.background_executor().timer(CHUNK).await;
                    let shown = this.update(cx, |this, cx| {
                        if let Some(turn) = this.turns.get_mut(ix) {
                            turn.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 CheckpointPattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let fg = cx.theme().foreground;
            let count = self.turns.len();
    
    
            let mut rows = Vec::new();
            for (ix, turn) in self.turns.iter().enumerate() {
                let (ask, reply, checkpoint) = TURNS[turn.script];
                let text: String = chunks(reply).take(turn.words).collect();
                let streaming = self.busy() && ix + 1 == count;
                rows.push(
                    Message::new()
                        .align(MessageAlign::End)
                        .child(
                            Bubble::new(("ask", ix))
                                .align(BubbleAlign::End)
                                .variant(BubbleVariant::Muted)
                                .child(ask),
                        )
                        .into_any_element(),
                );
                // The reply's message exists as soon as it starts streaming, empty or not.
                rows.push(Message::new().child(div().w_full().text_color(fg).child(text)).into_any_element());
                // The checkpoint is written after the reply, so it shows once the text is done.
                if let Some(label) = checkpoint.filter(|_| !streaming) {
                    // Restoring only makes sense while something comes after the checkpoint.
                    let can_restore = ix + 1 < count;
                    rows.push(
                        Marker::new(("checkpoint", ix))
                            .variant(MarkerVariant::Separator)
                            .child(
                                div()
                                    .flex()
                                    .items_center()
                                    .gap_2()
                                    .child(label)
                                    .when(can_restore, |this| {
                                        this.child(
                                            Button::new(("restore", ix), "Restore")
                                                .variant(ButtonVariant::Outline)
                                                .size(ButtonSize::Xs)
                                                .rounded_full()
                                                // It sits in the marker's muted text.
                                                .muted()
                                                .on_click(cx.listener(move |this, _, _, cx| this.restore(ix, cx))),
                                        )
                                    }),
                            )
                            .into_any_element(),
                    );
                }
            }
    
            let has_next = count < TURNS.len();
            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))
                .children(rows)
                .when(!self.busy() && has_next, |this| {
                    this.child(
                        div().mt_auto().flex().child(
                            Button::new("continue", "Continue")
                                .variant(ButtonVariant::Outline)
                                .size(ButtonSize::Compact)
                                .rounded_full()
                                .on_click(cx.listener(|this, _, _, cx| this.send_next(cx))),
                        ),
                    )
                })
        }
    }