Asks the user to approve a tool call before the agent runs it. The request waits as a card with Deny and Approve, then becomes a trace row with the outcome.
Loading GPUI…
use std::time::Duration;
use gpui::{div, prelude::*, px, relative, Context, Task, Window};
use crate::icons::{icon, CIRCLE_CHECK, LOADER_CIRCLE, TERMINAL};
use crate::theme::ActiveTheme;
use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::item::{Item, ItemSize, ItemVariant};
use crate::ui::message::{Message, MessageAlign};
use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus};
/// The mock chat waits 600ms before the first turn, streams a word every 20ms, pauses 400ms
/// before asking, and 600ms after the decision before it answers.
const START: Duration = Duration::from_millis(600);
const CHUNK: Duration = Duration::from_millis(20);
const ASK: Duration = Duration::from_millis(400);
const ANSWER_DELAY: Duration = Duration::from_millis(600);
const QUESTION: &str = "Clean up the build folder.";
const REASONING: &str = "The build output lives in dist. Deleting it cannot be undone, so I should ask before I run the command.";
const COMMAND: &str = "rm -rf dist";
const APPROVED: &str = "Removed the dist folder.";
const DENIED: &str = "Okay, I left the dist folder in place.";
#[derive(Clone, Copy, PartialEq)]
enum Approval {
/// Waiting on the user.
Requested,
/// Approved; the command is running.
Running,
Ran,
Denied,
}
#[derive(Default)]
pub struct ConfirmationPattern {
sent: bool,
/// Whether the assistant's turn has started, and how many reasoning words have streamed.
answering: bool,
reasoning_words: usize,
thinking: bool,
/// The reader's choice for the reasoning row. `None` keeps it open only while thinking.
reasoning_open: Option<bool>,
approval: Option<Approval>,
/// Words of the reply shown so far.
words: usize,
busy: bool,
stream: Option<Task<()>>,
}
impl ConfirmationPattern {
/// The first turn: the agent reasons, then asks before running the command.
fn send(&mut self, cx: &mut Context<Self>) {
self.sent = true;
self.busy = true;
self.stream = Some(cx.spawn(async move |this, cx| {
cx.background_executor().timer(START).await;
let started = this.update(cx, |this, cx| {
this.answering = true;
this.thinking = true;
cx.notify();
});
if started.is_err() {
return;
}
for _ in 0..REASONING.split_inclusive(' ').count() {
cx.background_executor().timer(CHUNK).await;
if this.update(cx, |this, cx| { this.reasoning_words += 1; cx.notify(); }).is_err() {
return;
}
}
let _ = this.update(cx, |this, cx| { this.thinking = false; cx.notify(); });
cx.background_executor().timer(ASK).await;
let _ = this.update(cx, |this, cx| {
this.approval = Some(Approval::Requested);
this.busy = false;
cx.notify();
});
}));
cx.notify();
}
/// The second turn, sent automatically once the user decides.
fn decide(&mut self, approved: bool, cx: &mut Context<Self>) {
self.approval = Some(if approved { Approval::Running } else { Approval::Denied });
self.busy = true;
let reply = if approved { APPROVED } else { DENIED };
self.stream = Some(cx.spawn(async move |this, cx| {
if approved {
cx.background_executor().timer(CHUNK).await;
if this.update(cx, |this, cx| { this.approval = Some(Approval::Ran); cx.notify(); }).is_err() {
return;
}
}
cx.background_executor().timer(ANSWER_DELAY).await;
for _ in 0..reply.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 ConfirmationPattern {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let fg = theme.foreground;
let reasoning: String = REASONING.split_inclusive(' ').take(self.reasoning_words).collect();
let reasoning_line = if self.thinking {
TraceLine::new("reasoning", "Thinking").icon(LOADER_CIRCLE).spin(true).status(TraceStatus::Running)
} else {
TraceLine::new("reasoning", "Thought").icon(CIRCLE_CHECK)
};
let reasoning_row = TraceCollapsible::new("thought", self.reasoning_open.unwrap_or(self.thinking), reasoning_line)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.reasoning_open = Some(*open);
cx.notify();
}))
.child(reasoning);
let tool = self.approval.map(|approval| match approval {
// A pending approval is a prompt, not activity, so it is a card rather than a trace row.
Approval::Requested => Item::new(format!("Run {COMMAND}?"))
.description("The command runs in this project.")
.variant(ItemVariant::Outline)
.size(ItemSize::Compact)
.radius(px(18.0))
.media(icon(TERMINAL).text_color(fg))
.actions(
div()
.flex()
.gap_2()
.child(
Button::new("deny", "Deny")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Compact)
.rounded_full()
.on_click(cx.listener(|this, _, _, cx| this.decide(false, cx))),
)
.child(
Button::new("approve", "Approve")
.size(ButtonSize::Compact)
.rounded_full()
.on_click(cx.listener(|this, _, _, cx| this.decide(true, cx))),
),
)
.into_any_element(),
outcome => {
let (verb, status) = match outcome {
Approval::Running => ("Running", TraceStatus::Running),
Approval::Ran => ("Ran", TraceStatus::Done),
_ => ("Denied", TraceStatus::Done),
};
Trace::new()
.child(TraceLine::new("command", format!("{verb} {COMMAND}")).icon(TERMINAL).status(status))
.into_any_element()
}
});
let reply = if self.approval == Some(Approval::Denied) { DENIED } else { APPROVED };
let reply: String = reply.split_inclusive(' ').take(self.words).collect();
div()
.w(px(384.0))
.min_h(px(288.0))
.flex()
.flex_col()
.gap_4()
.py_6()
.text_sm()
.when(self.sent, |this| {
this.child(
Message::new()
.align(MessageAlign::End)
.child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION)),
)
})
.when(self.answering, |this| {
this.child(
Message::new().child(
div()
.flex()
.flex_col()
.gap_4()
.w_full()
.child(Trace::new().child(reasoning_row))
.children(tool)
.when(!reply.is_empty(), |this| {
this.child(div().line_height(relative(1.4286)).text_color(fg).child(reply))
}),
),
)
})
.when(!self.busy, |this| {
// Before the first message the button sends it; after that it starts over.
let label = if self.sent { "Reset" } else { "Send message" };
this.child(
div().mt_auto().flex().child(
Button::new("next", label)
.variant(ButtonVariant::Outline)
.size(ButtonSize::Compact)
.rounded_full()
.on_click(cx.listener(|this, _, _, cx| {
if this.sent {
*this = Self::default();
cx.notify();
} else {
this.send(cx);
}
})),
),
)
})
}
}Installation
Add the components
$ cargo hyuskui add bubble button item message trace iconsCopy the pattern
Paste the code into
src/ai/confirmation.rsand declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.src/ai/confirmation.rs use std::time::Duration; use gpui::{div, prelude::*, px, relative, Context, Task, Window}; use crate::icons::{icon, CIRCLE_CHECK, LOADER_CIRCLE, TERMINAL}; use crate::theme::ActiveTheme; use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant}; use crate::ui::button::{Button, ButtonSize, ButtonVariant}; use crate::ui::item::{Item, ItemSize, ItemVariant}; use crate::ui::message::{Message, MessageAlign}; use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus}; /// The mock chat waits 600ms before the first turn, streams a word every 20ms, pauses 400ms /// before asking, and 600ms after the decision before it answers. const START: Duration = Duration::from_millis(600); const CHUNK: Duration = Duration::from_millis(20); const ASK: Duration = Duration::from_millis(400); const ANSWER_DELAY: Duration = Duration::from_millis(600); const QUESTION: &str = "Clean up the build folder."; const REASONING: &str = "The build output lives in dist. Deleting it cannot be undone, so I should ask before I run the command."; const COMMAND: &str = "rm -rf dist"; const APPROVED: &str = "Removed the dist folder."; const DENIED: &str = "Okay, I left the dist folder in place."; #[derive(Clone, Copy, PartialEq)] enum Approval { /// Waiting on the user. Requested, /// Approved; the command is running. Running, Ran, Denied, } #[derive(Default)] pub struct ConfirmationPattern { sent: bool, /// Whether the assistant's turn has started, and how many reasoning words have streamed. answering: bool, reasoning_words: usize, thinking: bool, /// The reader's choice for the reasoning row. `None` keeps it open only while thinking. reasoning_open: Option<bool>, approval: Option<Approval>, /// Words of the reply shown so far. words: usize, busy: bool, stream: Option<Task<()>>, } impl ConfirmationPattern { /// The first turn: the agent reasons, then asks before running the command. fn send(&mut self, cx: &mut Context<Self>) { self.sent = true; self.busy = true; self.stream = Some(cx.spawn(async move |this, cx| { cx.background_executor().timer(START).await; let started = this.update(cx, |this, cx| { this.answering = true; this.thinking = true; cx.notify(); }); if started.is_err() { return; } for _ in 0..REASONING.split_inclusive(' ').count() { cx.background_executor().timer(CHUNK).await; if this.update(cx, |this, cx| { this.reasoning_words += 1; cx.notify(); }).is_err() { return; } } let _ = this.update(cx, |this, cx| { this.thinking = false; cx.notify(); }); cx.background_executor().timer(ASK).await; let _ = this.update(cx, |this, cx| { this.approval = Some(Approval::Requested); this.busy = false; cx.notify(); }); })); cx.notify(); } /// The second turn, sent automatically once the user decides. fn decide(&mut self, approved: bool, cx: &mut Context<Self>) { self.approval = Some(if approved { Approval::Running } else { Approval::Denied }); self.busy = true; let reply = if approved { APPROVED } else { DENIED }; self.stream = Some(cx.spawn(async move |this, cx| { if approved { cx.background_executor().timer(CHUNK).await; if this.update(cx, |this, cx| { this.approval = Some(Approval::Ran); cx.notify(); }).is_err() { return; } } cx.background_executor().timer(ANSWER_DELAY).await; for _ in 0..reply.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 ConfirmationPattern { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let theme = cx.theme(); let fg = theme.foreground; let reasoning: String = REASONING.split_inclusive(' ').take(self.reasoning_words).collect(); let reasoning_line = if self.thinking { TraceLine::new("reasoning", "Thinking").icon(LOADER_CIRCLE).spin(true).status(TraceStatus::Running) } else { TraceLine::new("reasoning", "Thought").icon(CIRCLE_CHECK) }; let reasoning_row = TraceCollapsible::new("thought", self.reasoning_open.unwrap_or(self.thinking), reasoning_line) .on_open_change(cx.listener(|this, open: &bool, _, cx| { this.reasoning_open = Some(*open); cx.notify(); })) .child(reasoning); let tool = self.approval.map(|approval| match approval { // A pending approval is a prompt, not activity, so it is a card rather than a trace row. Approval::Requested => Item::new(format!("Run {COMMAND}?")) .description("The command runs in this project.") .variant(ItemVariant::Outline) .size(ItemSize::Compact) .radius(px(18.0)) .media(icon(TERMINAL).text_color(fg)) .actions( div() .flex() .gap_2() .child( Button::new("deny", "Deny") .variant(ButtonVariant::Outline) .size(ButtonSize::Compact) .rounded_full() .on_click(cx.listener(|this, _, _, cx| this.decide(false, cx))), ) .child( Button::new("approve", "Approve") .size(ButtonSize::Compact) .rounded_full() .on_click(cx.listener(|this, _, _, cx| this.decide(true, cx))), ), ) .into_any_element(), outcome => { let (verb, status) = match outcome { Approval::Running => ("Running", TraceStatus::Running), Approval::Ran => ("Ran", TraceStatus::Done), _ => ("Denied", TraceStatus::Done), }; Trace::new() .child(TraceLine::new("command", format!("{verb} {COMMAND}")).icon(TERMINAL).status(status)) .into_any_element() } }); let reply = if self.approval == Some(Approval::Denied) { DENIED } else { APPROVED }; let reply: String = reply.split_inclusive(' ').take(self.words).collect(); div() .w(px(384.0)) .min_h(px(288.0)) .flex() .flex_col() .gap_4() .py_6() .text_sm() .when(self.sent, |this| { this.child( Message::new() .align(MessageAlign::End) .child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION)), ) }) .when(self.answering, |this| { this.child( Message::new().child( div() .flex() .flex_col() .gap_4() .w_full() .child(Trace::new().child(reasoning_row)) .children(tool) .when(!reply.is_empty(), |this| { this.child(div().line_height(relative(1.4286)).text_color(fg).child(reply)) }), ), ) }) .when(!self.busy, |this| { // Before the first message the button sends it; after that it starts over. let label = if self.sent { "Reset" } else { "Send message" }; this.child( div().mt_auto().flex().child( Button::new("next", label) .variant(ButtonVariant::Outline) .size(ButtonSize::Compact) .rounded_full() .on_click(cx.listener(|this, _, _, cx| { if this.sent { *this = Self::default(); cx.notify(); } else { this.send(cx); } })), ), ) }) } }