use arc_motion::{is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, AiOrbTokens as T};
use gpui_kit::{
App, Bounds, ElementId, Hsla, IntoElement, ParentElement, Pixels, RenderOnce, Role,
SharedString, Styled, TestSupportExt as _, Window, canvas, div, fill, point, prelude::*, px,
size,
};
use std::{cell::RefCell, f32::consts::TAU, rc::Rc};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AiOrbState {
Idle,
Listening,
Thinking,
Reasoning,
ToolCall,
ToolResult,
Streaming,
WaitingApproval,
Error,
Done,
}
impl AiOrbState {
pub fn tone(self) -> AiOrbTone {
AiOrbTone::Neutral
}
pub fn variant(self) -> AiOrbVariant {
match self {
Self::Idle | Self::Done => AiOrbVariant::Base,
Self::Listening => AiOrbVariant::Searching,
Self::Thinking => AiOrbVariant::Working,
Self::Reasoning => AiOrbVariant::Reasoning,
Self::ToolCall => AiOrbVariant::Background,
Self::ToolResult => AiOrbVariant::Compacting,
Self::Streaming => AiOrbVariant::WorkingGyro,
Self::WaitingApproval => AiOrbVariant::Waiting,
Self::Error => AiOrbVariant::Retrying,
}
}
pub fn speed(self) -> f32 {
self.variant().period() / AiOrbVariant::Working.period()
}
pub fn is_animated(self) -> bool {
self != Self::Done
}
pub fn label(self) -> &'static str {
match self {
Self::Idle => "idle",
Self::Listening => "listening",
Self::Thinking => "thinking",
Self::Reasoning => "reasoning",
Self::ToolCall => "tool call",
Self::ToolResult => "tool result",
Self::Streaming => "streaming",
Self::WaitingApproval => "waiting approval",
Self::Error => "error",
Self::Done => "done",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(usize)]
pub enum AiOrbVariant {
Base,
Working,
WorkingGyro,
Reasoning,
ReasoningTwins,
Searching,
SearchingLighthouse,
Background,
BackgroundSpiral,
Retrying,
RetryingSurge,
Compacting,
CompactingSqueeze,
CompactingFuse,
Waiting,
}
impl AiOrbVariant {
pub const ALL: [Self; 15] = [
Self::Base,
Self::Working,
Self::WorkingGyro,
Self::Reasoning,
Self::ReasoningTwins,
Self::Searching,
Self::SearchingLighthouse,
Self::Background,
Self::BackgroundSpiral,
Self::Retrying,
Self::RetryingSurge,
Self::Compacting,
Self::CompactingSqueeze,
Self::CompactingFuse,
Self::Waiting,
];
pub fn label(self) -> &'static str {
match self {
Self::Base => "base",
Self::Working => "working",
Self::WorkingGyro => "working · gyro",
Self::Reasoning => "reasoning",
Self::ReasoningTwins => "reasoning · twins",
Self::Searching => "searching",
Self::SearchingLighthouse => "searching · lighthouse",
Self::Background => "background",
Self::BackgroundSpiral => "background · spiral",
Self::Retrying => "retrying",
Self::RetryingSurge => "retrying · surge",
Self::Compacting => "compacting",
Self::CompactingSqueeze => "compacting · squeeze",
Self::CompactingFuse => "compacting · fuse",
Self::Waiting => "waiting",
}
}
fn period(self) -> f32 {
T::PERIOD_SECS[self as usize]
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AiOrbTone {
Neutral,
Accent,
Info,
Violet,
Teal,
Amber,
Danger,
Success,
}
impl AiOrbTone {
pub fn resolve(self, colors: &arc_tokens::ArcColors) -> Hsla {
match self {
Self::Neutral => colors.foreground,
Self::Accent => colors.accent,
Self::Info => colors.info,
Self::Violet => colors.tone_violet,
Self::Teal => colors.tone_teal,
Self::Amber => colors.tone_amber,
Self::Danger => colors.danger,
Self::Success => colors.success,
}
}
}
pub fn orb_settle_secs(state: AiOrbState, override_ms: Option<f32>) -> f32 {
override_ms.map_or(
match state {
AiOrbState::Done => 0.4,
AiOrbState::Error => 0.6,
_ => 0.0,
},
|ms| {
if ms.is_finite() {
ms.max(0.0) / 1000.0
} else {
0.0
}
},
)
}
pub fn orb_aria_label(state: AiOrbState) -> SharedString {
format!("AI status: {}", state.label()).into()
}
#[derive(IntoElement)]
pub struct AiOrb {
id: ElementId,
state: AiOrbState,
variant: Option<AiOrbVariant>,
tone: Option<AiOrbTone>,
color: Option<Hsla>,
size: f32,
settle_ms: Option<f32>,
aria_label: Option<SharedString>,
}
impl AiOrb {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
state: AiOrbState::Idle,
variant: None,
tone: None,
color: None,
size: T::SIZE,
settle_ms: None,
aria_label: None,
}
}
pub fn state(mut self, value: AiOrbState) -> Self {
self.state = value;
self
}
pub fn variant(mut self, value: AiOrbVariant) -> Self {
self.variant = Some(value);
self
}
pub fn tone(mut self, value: AiOrbTone) -> Self {
self.tone = Some(value);
self
}
pub fn color(mut self, value: Hsla) -> Self {
self.color = Some(value);
self
}
pub fn size(mut self, value: f32) -> Self {
self.size = if value.is_finite() {
value.max(T::MIN_SIZE)
} else {
T::SIZE
};
self
}
pub fn settle_ms(mut self, value: f32) -> Self {
self.settle_ms = Some(value);
self
}
pub fn aria_label(mut self, value: impl Into<SharedString>) -> Self {
self.aria_label = Some(value.into());
self
}
}
#[derive(Clone, Copy, Debug, Default)]
struct Dot {
x: f32,
y: f32,
z: f32,
radius: f32,
alpha: f32,
}
impl Dot {
fn mix(self, to: Self, t: f32) -> Self {
let lerp = |a, b| a + (b - a) * t;
Self {
x: lerp(self.x, to.x),
y: lerp(self.y, to.y),
z: lerp(self.z, to.z),
radius: lerp(self.radius, to.radius),
alpha: lerp(self.alpha, to.alpha),
}
}
}
fn rotate([x, y, z]: [f32; 3], yaw: f32, tilt: f32) -> [f32; 3] {
let (sy, cy) = yaw.sin_cos();
let (sx, cx) = tilt.sin_cos();
let x1 = x * cy + z * sy;
let z1 = z * cy - x * sy;
[x1, y * cx - z1 * sx, y * sx + z1 * cx]
}
fn sample_dots(variant: AiOrbVariant, seconds: f32) -> Vec<Dot> {
let phase = seconds / variant.period() * TAU;
let golden_angle = std::f32::consts::PI * (3.0 - 5.0f32.sqrt());
(0..T::PARTICLES)
.map(|i| {
let y = 1.0 - 2.0 * (i as f32 + 0.5) / T::PARTICLES as f32;
let ring = (1.0 - y * y).sqrt();
let longitude = golden_angle * i as f32;
let mut p = [ring * longitude.cos(), y, ring * longitude.sin()];
let mut scale = 1.0 + T::BREATH * phase.sin();
let mut tilt = T::TILT;
let mut active = true;
let mut gain = 1.0;
match variant {
AiOrbVariant::WorkingGyro => tilt += T::GYRO_TILT * phase.sin(),
AiOrbVariant::Background => {
active = i % T::SPARSE_STRIDE == 0;
gain = 2.0;
}
AiOrbVariant::BackgroundSpiral => {
let band = i % T::SPIRAL_BANDS;
let t =
(i / T::SPIRAL_BANDS) as f32 / (T::PARTICLES / T::SPIRAL_BANDS - 1) as f32;
let yy = 1.0 - 2.0 * t;
let rr = (1.0 - yy * yy).max(0.0).sqrt();
let angle = band as f32 * TAU / T::SPIRAL_BANDS as f32 + t * TAU;
p = [rr * angle.cos(), yy, rr * angle.sin()];
gain = 0.8;
}
AiOrbVariant::Retrying => scale += T::RETRY_RIPPLE * (phase * 3.0 + y * TAU).sin(),
AiOrbVariant::RetryingSurge => {
scale += T::SURGE_RIPPLE * (phase * 2.0 + y * TAU).sin()
}
AiOrbVariant::Compacting => scale -= T::COMPACT_SCALE * (0.5 + 0.5 * phase.sin()),
AiOrbVariant::CompactingSqueeze => {
let squeeze = T::SQUEEZE_SCALE * phase.sin();
p[0] *= 1.0 + squeeze * 0.5;
p[1] *= 1.0 - squeeze;
}
AiOrbVariant::CompactingFuse => {
let fuse = T::FUSE_SCALE * (0.5 + 0.5 * phase.sin());
p[0] *= 1.0 - fuse;
p[2] *= 1.0 - fuse;
p[1] *= 1.0 + fuse * 0.5;
}
_ => {}
}
let [mut x, mut y, z] = rotate(p, phase, tilt);
if variant == AiOrbVariant::BackgroundSpiral {
let (sin, cos) = T::SPIRAL_ROLL.sin_cos();
(x, y) = (x * cos - y * sin, x * sin + y * cos);
}
let depth = (z + 1.0) * 0.5;
let mut spotlight = 0.0;
let spot = |sx: f32, sy: f32| {
let sz = (1.0 - sx * sx - sy * sy).max(0.0).sqrt();
(x * sx + y * sy + z * sz).max(0.0).powf(T::SPOT_SHARPNESS)
};
match variant {
AiOrbVariant::Reasoning => spotlight = spot(0.24 * phase.cos(), 0.22 * phase.sin()),
AiOrbVariant::ReasoningTwins => {
spotlight = spot(-0.42, 0.16 * phase.sin()).max(spot(0.42, -0.16 * phase.sin()))
}
AiOrbVariant::Searching => spotlight = spot(0.52 * phase.cos(), 0.40 * phase.sin()),
AiOrbVariant::SearchingLighthouse => spotlight = spot(0.7 * phase.cos(), 0.15),
AiOrbVariant::Waiting => {
spotlight =
spot(0.12, -0.18) * (0.85 + 0.15 * phase.cos()) * T::WAITING_FOCUS_GAIN
}
_ => {}
}
let focused = matches!(
variant,
AiOrbVariant::Reasoning
| AiOrbVariant::ReasoningTwins
| AiOrbVariant::Searching
| AiOrbVariant::SearchingLighthouse
| AiOrbVariant::Waiting
);
let alpha =
T::DEPTH_ALPHA[0] + (T::DEPTH_ALPHA[1] - T::DEPTH_ALPHA[0]) * depth.powf(1.4);
let perspective = T::CAMERA / (T::CAMERA - z);
Dot {
x: x * scale * T::RADIUS * perspective,
y: y * scale * T::RADIUS * perspective,
z,
radius: T::DOT_RADIUS
* (T::DEPTH_SIZE[0] + depth * (T::DEPTH_SIZE[1] - T::DEPTH_SIZE[0]))
* gain
* (1.0 + T::SPOT_DOT_GAIN * spotlight),
alpha: if active {
(alpha * if focused { 0.38 } else { 1.0 } + spotlight).min(1.0)
} else {
0.0
},
}
})
.collect()
}
struct OrbRuntime {
key: (AiOrbState, AiOrbVariant, f32),
anchor: f64,
from: Vec<Dot>,
current: Vec<Dot>,
}
impl OrbRuntime {
fn new(key: (AiOrbState, AiOrbVariant, f32), now: f64) -> Self {
Self {
key,
anchor: now,
from: Vec::new(),
current: sample_dots(key.1, 0.0),
}
}
fn sample(
&mut self,
key: (AiOrbState, AiOrbVariant, f32),
now: f64,
reduced: bool,
) -> (Vec<Dot>, bool) {
if self.key != key {
self.from = self.current.clone();
self.key = key;
self.anchor = now;
}
let elapsed = (now - self.anchor).max(0.0) as f32;
let settle = key.2;
let time = if reduced {
0.0
} else if settle > 0.0 {
elapsed.min(settle)
} else {
elapsed
};
let target = sample_dots(key.1, time);
let t = if reduced {
1.0
} else {
(elapsed / T::TRANSITION_SECS).clamp(0.0, 1.0)
};
let mix = t * t * (3.0 - 2.0 * t);
self.current = if self.from.is_empty() {
target
} else {
self.from
.iter()
.zip(target)
.map(|(from, to)| from.mix(to, mix))
.collect()
};
let changing = !self.from.is_empty() && t < 1.0;
if t >= 1.0 {
self.from.clear();
}
let animate = !reduced
&& (changing
|| (settle > 0.0 && elapsed < settle)
|| (settle <= 0.0 && key.0.is_animated()));
(self.current.clone(), animate)
}
}
impl RenderOnce for AiOrb {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let variant = self.variant.unwrap_or_else(|| self.state.variant());
let key = (
self.state,
variant,
orb_settle_secs(self.state, self.settle_ms),
);
let runtime = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "orb-runtime".into()),
cx,
|_, _| Rc::new(RefCell::new(OrbRuntime::new(key, now))),
)
.read(cx)
.clone();
let (mut dots, animate) = runtime.borrow_mut().sample(key, now, reduced);
dots.sort_by(|a, b| a.z.total_cmp(&b.z));
let color = self.color.unwrap_or_else(|| {
self.tone
.unwrap_or(AiOrbTone::Neutral)
.resolve(&cx.arc_theme().colors)
});
if animate {
window.request_animation_frame();
}
let label = self.aria_label.unwrap_or_else(|| {
if self.variant.is_some() {
format!("AI orb: {}", variant.label()).into()
} else {
orb_aria_label(self.state)
}
});
div()
.id(self.id)
.test_support()
.role(Role::Status)
.aria_label(label)
.flex_none()
.relative()
.size(px(self.size))
.child(
canvas(
move |bounds, _, _| bounds,
move |bounds: Bounds<Pixels>, _, window, _| {
let side = f32::from(bounds.size.width).min(f32::from(bounds.size.height));
let center = bounds.center();
for dot in &dots {
if dot.alpha <= 0.0 {
continue;
}
let radius = px(dot.radius * side);
let bounds = Bounds::new(
point(
center.x + px(dot.x * side) - radius,
center.y + px(dot.y * side) - radius,
),
size(radius * 2.0, radius * 2.0),
);
window.paint_quad(
fill(
bounds,
Hsla {
a: color.a * dot.alpha,
..color
},
)
.corner_radii(radius),
);
}
},
)
.size_full(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ai_orb_fifteen_variants_are_dense_depth_sorted_spheres() {
for variant in AiOrbVariant::ALL {
let dots = sample_dots(variant, 0.0);
assert_eq!(dots.len(), T::PARTICLES);
let visible: Vec<_> = dots.iter().filter(|d| d.alpha > 0.0).collect();
assert!(visible.len() >= 40);
assert!(visible.iter().any(|d| d.z < -0.5));
assert!(visible.iter().any(|d| d.z > 0.5));
assert!(
dots.iter()
.all(|d| d.x.is_finite() && d.y.is_finite() && d.radius < 0.06)
);
assert!(
dots.iter()
.all(|d| d.x.abs() + d.radius < 0.6 && d.y.abs() + d.radius < 0.6)
);
let later = sample_dots(variant, 1.0);
assert!(
dots.iter()
.zip(later)
.any(|(a, b)| (a.x - b.x).abs() > 0.001)
);
}
}
#[test]
fn ai_orb_reference_variants_have_distinct_geometry_or_lighting() {
let samples: Vec<_> = AiOrbVariant::ALL
.map(|v| sample_dots(v, 1.3))
.into_iter()
.collect();
for (i, a) in samples.iter().enumerate() {
for b in &samples[i + 1..] {
assert!(a.iter().zip(b).any(|(a, b)| (a.x - b.x).abs()
+ (a.y - b.y).abs()
+ (a.radius - b.radius).abs()
+ (a.alpha - b.alpha).abs()
> 0.001));
}
}
}
#[test]
fn ai_orb_transition_interruption_settle_and_reduced_motion() {
let base = (AiOrbState::Idle, AiOrbVariant::Base, 0.0);
let next = (AiOrbState::Thinking, AiOrbVariant::Background, 0.0);
let mut runtime = OrbRuntime::new(base, 100.0);
let (before, _) = runtime.sample(base, 101.0, false);
let (first, active) = runtime.sample(next, 101.0, false);
assert!(active);
assert_eq!(before[0].x, first[0].x);
let (middle, _) = runtime.sample(next, 101.1, false);
let freeze = (AiOrbState::Done, AiOrbVariant::Waiting, 0.4);
let (interrupted, _) = runtime.sample(freeze, 101.1, false);
assert_eq!(middle[0].x, interrupted[0].x);
assert!(runtime.sample(freeze, 101.2, false).1);
let (settled, active) = runtime.sample(freeze, 102.0, false);
assert!(!active);
assert_eq!(settled[0].x, runtime.sample(freeze, 105.0, false).0[0].x);
assert!(!runtime.sample(next, 106.0, true).1);
assert_eq!(runtime.current[0].x, sample_dots(next.1, 0.0)[0].x);
}
#[test]
fn ai_orb_semantic_compatibility_is_monochrome() {
for state in [
AiOrbState::Idle,
AiOrbState::Listening,
AiOrbState::Thinking,
AiOrbState::Reasoning,
AiOrbState::ToolCall,
AiOrbState::ToolResult,
AiOrbState::Streaming,
AiOrbState::WaitingApproval,
AiOrbState::Error,
AiOrbState::Done,
] {
assert_eq!(state.tone(), AiOrbTone::Neutral);
assert!(state.speed() > 0.0);
assert!(orb_aria_label(state).contains(state.label()));
}
assert_eq!(orb_settle_secs(AiOrbState::Done, None), 0.4);
assert_eq!(orb_settle_secs(AiOrbState::Thinking, Some(250.0)), 0.25);
}
}