hyuskui

Sources

The pages the agent read to write a reply. Once the answer is in, a trace row counts the sources and opens on a link to each one.

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

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

use crate::icons::{ARROW_UP_RIGHT, GLOBE};
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};

/// The mock transport's pace: one word every 20ms.
const CHUNK: Duration = Duration::from_millis(20);

const QUESTION: &str = "How do I start an Astro project with pnpm?";
const ANSWER: &str = "Run pnpm create astro@latest and follow the prompts. It scaffolds the project and installs the dependencies.";

/// (url, title). The agent cited the Astro docs twice; the list keeps the first.
const SOURCES: [(&str, &str); 4] = [
    ("https://docs.astro.build/en/install-and-setup/", "Install Astro | docs.astro.build"),
    ("https://www.npmjs.com/package/create-astro", "create-astro | npmjs.com"),
    ("https://docs.astro.build/en/install-and-setup/", "Install Astro | docs.astro.build"),
    ("https://pnpm.io/cli/create", "pnpm create | pnpm.io"),
];

pub struct SourcesPattern {
    /// Whether the assistant's turn has started.
    replied: bool,
    /// Words of the answer shown so far.
    words: usize,
    /// The sources arrive together, after the text.
    sourced: bool,
    open: bool,
    busy: bool,
    stream: Option<Task<()>>,
}

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

impl SourcesPattern {
    fn replay(&mut self, cx: &mut Context<Self>) {
        // The trace row mounts again, so it opens again.
        *self = Self { replied: true, words: 0, sourced: false, open: true, busy: true, stream: None };
        self.stream = Some(cx.spawn(async move |this, cx| {
            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.sourced = true;
                this.busy = false;
                cx.notify();
            });
        }));
        cx.notify();
    }
}

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

        let mut unique: Vec<(&str, &str)> = Vec::new();
        for (url, title) in SOURCES {
            if !unique.iter().any(|(seen, _)| *seen == url) {
                unique.push((url, title));
            }
        }

        let sources = self.sourced.then(|| {
            let links = unique.iter().enumerate().map(|(ix, (url, title))| {
                let url = url.to_string();
                TraceLine::new(("source", ix), *title)
                    .indicator(ARROW_UP_RIGHT)
                    .on_click(move |_, _, cx| cx.open_url(&url))
            });
            Trace::new().child(
                TraceCollapsible::new(
                    "sources",
                    self.open,
                    TraceLine::new("sources-title", format!("Used {} sources", unique.len())).icon(GLOBE),
                )
                .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                    this.open = *open;
                    cx.notify();
                }))
                .child(Trace::new().children(links)),
            )
        });

        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(!answer.is_empty(), |this| this.child(answer))
                            .children(sources),
                    ),
                )
            })
            .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/sources.rs and declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.

    src/ai/sources.rs
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, Context, Task, Window};
    
    use crate::icons::{ARROW_UP_RIGHT, GLOBE};
    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};
    
    /// The mock transport's pace: one word every 20ms.
    const CHUNK: Duration = Duration::from_millis(20);
    
    const QUESTION: &str = "How do I start an Astro project with pnpm?";
    const ANSWER: &str = "Run pnpm create astro@latest and follow the prompts. It scaffolds the project and installs the dependencies.";
    
    /// (url, title). The agent cited the Astro docs twice; the list keeps the first.
    const SOURCES: [(&str, &str); 4] = [
        ("https://docs.astro.build/en/install-and-setup/", "Install Astro | docs.astro.build"),
        ("https://www.npmjs.com/package/create-astro", "create-astro | npmjs.com"),
        ("https://docs.astro.build/en/install-and-setup/", "Install Astro | docs.astro.build"),
        ("https://pnpm.io/cli/create", "pnpm create | pnpm.io"),
    ];
    
    pub struct SourcesPattern {
        /// Whether the assistant's turn has started.
        replied: bool,
        /// Words of the answer shown so far.
        words: usize,
        /// The sources arrive together, after the text.
        sourced: bool,
        open: bool,
        busy: bool,
        stream: Option<Task<()>>,
    }
    
    impl Default for SourcesPattern {
        /// Starts on the finished transcript.
        fn default() -> Self {
            Self {
                replied: true,
                words: ANSWER.split_inclusive(' ').count(),
                sourced: true,
                open: true,
                busy: false,
                stream: None,
            }
        }
    }
    
    impl SourcesPattern {
        fn replay(&mut self, cx: &mut Context<Self>) {
            // The trace row mounts again, so it opens again.
            *self = Self { replied: true, words: 0, sourced: false, open: true, busy: true, stream: None };
            self.stream = Some(cx.spawn(async move |this, cx| {
                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.sourced = true;
                    this.busy = false;
                    cx.notify();
                });
            }));
            cx.notify();
        }
    }
    
    impl Render for SourcesPattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let theme = cx.theme();
            let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect();
    
            let mut unique: Vec<(&str, &str)> = Vec::new();
            for (url, title) in SOURCES {
                if !unique.iter().any(|(seen, _)| *seen == url) {
                    unique.push((url, title));
                }
            }
    
            let sources = self.sourced.then(|| {
                let links = unique.iter().enumerate().map(|(ix, (url, title))| {
                    let url = url.to_string();
                    TraceLine::new(("source", ix), *title)
                        .indicator(ARROW_UP_RIGHT)
                        .on_click(move |_, _, cx| cx.open_url(&url))
                });
                Trace::new().child(
                    TraceCollapsible::new(
                        "sources",
                        self.open,
                        TraceLine::new("sources-title", format!("Used {} sources", unique.len())).icon(GLOBE),
                    )
                    .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                        this.open = *open;
                        cx.notify();
                    }))
                    .child(Trace::new().children(links)),
                )
            });
    
            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(!answer.is_empty(), |this| this.child(answer))
                                .children(sources),
                        ),
                    )
                })
                .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)))))
                })
        }
    }