use crate::components::button::{Button, ButtonKind, ButtonSize, ButtonVariant};
use crate::t3::action::{ActionButton, ActionKind, Part};
use crate::t3::base::{EASE, Spin, fmt_elapsed_opt, pulse};
use crate::t3::press::{Handler, rem};
use crate::t3::shell::{IdentitySize, ProviderIcon};
use crate::{icons::CarbonIcon, theme::color, tokens::ColorRole};
use gpui_kit::{
AnyElement, App, BoxShadow, ElementId, FontWeight, Hsla, IntoElement, ParentElement,
RenderOnce, SharedString, Styled, Window, div, prelude::FluentBuilder as _, px,
};
use std::rc::Rc;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SubagentStatus {
#[default]
Running,
Queued,
Waiting,
Idle,
Completed,
Failed,
Stopped,
}
impl SubagentStatus {
pub const ALL: [SubagentStatus; 7] = [
Self::Running,
Self::Queued,
Self::Waiting,
Self::Idle,
Self::Completed,
Self::Failed,
Self::Stopped,
];
pub const fn name(self) -> &'static str {
match self {
Self::Running => "running",
Self::Queued => "queued",
Self::Waiting => "waiting",
Self::Idle => "idle",
Self::Completed => "completed",
Self::Failed => "failed",
Self::Stopped => "stopped",
}
}
pub const fn label(self) -> &'static str {
match self {
Self::Running => "Running",
Self::Queued => "Queued",
Self::Waiting => "Waiting",
Self::Idle => "Idle · resumable",
Self::Completed => "Completed",
Self::Failed => "Failed",
Self::Stopped => "Stopped",
}
}
pub fn dot(self) -> (Hsla, Option<Hsla>) {
match self {
Self::Running => (color(ColorRole::Interactive), None),
Self::Completed => (color(ColorRole::SupportSuccess), None),
Self::Failed => (color(ColorRole::SupportError), None),
Self::Waiting => (color(ColorRole::SupportWarning), None),
Self::Queued | Self::Idle | Self::Stopped => (
gpui_kit::transparent_black(),
Some(color(ColorRole::IconSecondary)),
),
}
}
}
#[derive(IntoElement)]
pub struct SubagentStatusDot {
id: ElementId,
status: SubagentStatus,
}
impl SubagentStatusDot {
pub fn new(id: impl Into<ElementId>, status: SubagentStatus) -> Self {
Self {
id: id.into(),
status,
}
}
}
impl RenderOnce for SubagentStatusDot {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let (fill, ring) = self.status.dot();
let dot = div()
.flex_none()
.size(px(8.))
.rounded_full()
.bg(fill)
.when_some(ring, |this, c| {
this.shadow(vec![
BoxShadow::new(px(0.), px(0.), c)
.spread_radius(px(1.5))
.inset(),
])
});
if self.status == SubagentStatus::Running {
pulse(dot, self.id, EASE).into_any_element()
} else {
dot.into_any_element()
}
}
}
#[derive(Clone)]
pub struct SubagentTexts {
pub open: SharedString,
pub stop: SharedString,
pub label: Rc<dyn Fn(SubagentStatus) -> SharedString>,
}
impl Default for SubagentTexts {
fn default() -> Self {
Self {
open: "Open chat".into(),
stop: "Stop subagent".into(),
label: Rc::new(|s| s.label().into()),
}
}
}
#[derive(IntoElement)]
pub struct SubagentRow {
id: ElementId,
name: SharedString,
task: SharedString,
status: SubagentStatus,
elapsed: Option<u64>,
provider: Option<SharedString>,
texts: SubagentTexts,
on_open: Option<Handler>,
on_stop: Option<Handler>,
}
impl SubagentRow {
pub fn new(
id: impl Into<ElementId>,
name: impl Into<SharedString>,
task: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
name: name.into(),
task: task.into(),
status: SubagentStatus::Running,
elapsed: None,
provider: None,
texts: SubagentTexts::default(),
on_open: None,
on_stop: None,
}
}
pub fn status(mut self, status: SubagentStatus) -> Self {
self.status = status;
self
}
pub fn elapsed(mut self, seconds: u64) -> Self {
self.elapsed = Some(seconds);
self
}
pub fn provider(mut self, provider: impl Into<SharedString>) -> Self {
self.provider = Some(provider.into());
self
}
pub fn texts(mut self, texts: SubagentTexts) -> Self {
self.texts = texts;
self
}
pub fn on_open(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_open = Some(Rc::new(f));
self
}
pub fn on_stop(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_stop = Some(Rc::new(f));
self
}
}
pub const SUBAGENT_COLUMNS: (f32, f32, f32) = (64., 44., 40.);
impl RenderOnce for SubagentRow {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
let running = self.status == SubagentStatus::Running;
let texts = self.texts.clone();
let slot: AnyElement = if running {
div()
.flex_none()
.mx(px(1.))
.child(
Spin::new((id.clone(), "spin"))
.size(14.)
.label(texts.label.as_ref()(self.status)),
)
.into_any_element()
} else {
div()
.flex_none()
.mx(px(4.))
.child(SubagentStatusDot::new((id.clone(), "dot"), self.status))
.into_any_element()
};
let open = self.on_open.clone();
let stop = self.on_stop.clone();
div()
.flex()
.flex_row()
.items_center()
.w_full()
.min_w_0()
.gap(rem(8.))
.min_h(rem(40.))
.pl(rem(12.))
.pr(rem(4.))
.bg(color(ColorRole::Layer01))
.text_size(rem(14.))
.line_height(rem(18.))
.text_color(color(ColorRole::TextPrimary))
.child(slot)
.when_some(self.provider.clone(), |this, p| {
this.child(ProviderIcon::new(p).size(IdentitySize::Xs))
})
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.items_start()
.py(rem(4.))
.child(
div()
.flex_none()
.whitespace_nowrap()
.font_weight(FontWeight::SEMIBOLD)
.child(self.name.clone()),
)
.child(
div()
.max_w_full()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.text_size(rem(12.))
.line_height(gpui_kit::relative(18. / 14.))
.text_color(color(ColorRole::TextSecondary))
.child(self.task.clone()),
),
)
.child(
div()
.flex_none()
.w(rem(SUBAGENT_COLUMNS.0))
.whitespace_nowrap()
.text_size(rem(12.))
.text_color(color(if self.status == SubagentStatus::Failed {
ColorRole::TextError
} else {
ColorRole::TextSecondary
}))
.child(texts.label.as_ref()(self.status)),
)
.child(
div()
.flex_none()
.w(rem(SUBAGENT_COLUMNS.1))
.text_size(rem(12.))
.text_color(color(ColorRole::TextHelper))
.child(SharedString::from(fmt_elapsed_opt(self.elapsed))),
)
.child(
div()
.flex_none()
.when(!running, |this| this.mr(rem(SUBAGENT_COLUMNS.2)))
.child(
Button::new((id.clone(), "open"), texts.open.clone())
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.when_some(open, |b, f| b.on_click(move |_, w, cx| f(w, cx))),
),
)
.when(running, |this| {
this.child(
div()
.relative()
.flex_none()
.child(
ActionButton::new(
(id.clone(), "stop"),
texts.stop.clone(),
ActionKind::Carbon(ButtonKind::Ghost),
)
.padding(0., 0.)
.square(true)
.ink(color(ColorRole::IconSecondary))
.part(Part::Icon(CarbonIcon::StopFilled))
.tooltip(texts.stop.clone())
.on_click(stop),
)
.child(
div()
.absolute()
.inset_0()
.border_1()
.border_color(color(ColorRole::BorderSubtle01)),
),
)
})
}
}
const DOTS: usize = 10;
fn dots(n: usize) -> (usize, usize) {
if n <= DOTS {
(n, 0)
} else {
(DOTS - 1, n - (DOTS - 1))
}
}
#[derive(IntoElement)]
pub struct SubagentBar {
id: ElementId,
agents: Vec<SubagentStatus>,
count: Rc<dyn Fn(usize) -> SharedString>,
running: Rc<dyn Fn(usize) -> SharedString>,
view_all: SharedString,
on_view_all: Option<Handler>,
}
impl SubagentBar {
pub fn new(id: impl Into<ElementId>, agents: Vec<SubagentStatus>) -> Self {
Self {
id: id.into(),
agents,
count: Rc::new(|n| format!("{n} subagents").into()),
running: Rc::new(|n| format!("{n} running").into()),
view_all: "View all".into(),
on_view_all: None,
}
}
pub fn on_view_all(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_view_all = Some(Rc::new(f));
self
}
pub fn texts(
mut self,
count: impl Fn(usize) -> SharedString + 'static,
running: impl Fn(usize) -> SharedString + 'static,
view_all: impl Into<SharedString>,
) -> Self {
self.count = Rc::new(count);
self.running = Rc::new(running);
self.view_all = view_all.into();
self
}
}
impl RenderOnce for SubagentBar {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
let running = self
.agents
.iter()
.filter(|s| **s == SubagentStatus::Running)
.count();
let view = self.on_view_all.clone();
let (shown, more) = dots(self.agents.len());
div()
.flex()
.flex_row()
.items_center()
.w_full()
.gap(rem(8.))
.min_h(rem(40.))
.pl(rem(12.))
.pr(rem(4.))
.bg(color(ColorRole::Layer01))
.text_size(rem(14.))
.line_height(rem(18.))
.text_color(color(ColorRole::TextPrimary))
.child(
div()
.flex()
.flex_row()
.flex_none()
.items_center()
.gap(px(3.))
.children(self.agents.iter().take(shown).enumerate().map(|(i, s)| {
SubagentStatusDot::new(
(id.clone(), SharedString::from(format!("dot-{i}"))),
*s,
)
}))
.when(more > 0, |d| {
d.child(
div()
.pl(px(2.))
.text_size(rem(12.))
.text_color(color(ColorRole::TextSecondary))
.child(format!("+{more}")),
)
}),
)
.child(div().flex_none().child((self.count)(self.agents.len())))
.child(
div()
.min_w_0()
.truncate()
.text_size(rem(12.))
.text_color(color(ColorRole::TextSecondary))
.child((self.running)(running)),
)
.child(div().flex_1())
.child(
Button::new((id.clone(), "all"), self.view_all.clone())
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.icon(CarbonIcon::ChevronRight)
.when_some(view, |b, f| b.on_click(move |_, w, cx| f(w, cx))),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tokens::CarbonTheme;
#[test]
fn a_row_whose_time_is_not_known_shows_none() {
assert_eq!(SubagentRow::new("r", "n", "t").elapsed, None);
assert_eq!(
SubagentRow::new("r", "n", "t").elapsed(48).elapsed,
Some(48)
);
assert_eq!(fmt_elapsed_opt(None), "");
}
#[test]
fn many_subagents_draw_at_most_ten_marks_the_rest_told_as_a_count() {
assert_eq!(dots(0), (0, 0));
assert_eq!(dots(10), (10, 0));
assert_eq!(dots(11), (9, 2));
assert_eq!(dots(40), (9, 31));
}
#[test]
fn dots_follow_the_status_vocabulary() {
crate::theme::tests_set(CarbonTheme::White);
assert_eq!(
SubagentStatus::Running.dot().0,
color(ColorRole::Interactive)
);
assert_eq!(
SubagentStatus::Waiting.dot().0,
color(ColorRole::SupportWarning)
);
let (fill, ring) = SubagentStatus::Idle.dot();
assert_eq!(fill.a, 0.);
assert_eq!(ring, Some(color(ColorRole::IconSecondary)));
assert_eq!(SubagentStatus::Idle.label(), "Idle · resumable");
}
}