gpui-ai 0.8.0

AI-native UI components for GPUI applications, built on gpui-component.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Voice controls: dictation and speech as typed intent.
//!
//! gpui-ai does not capture audio or synthesize speech. [`VoiceControls`]
//! renders the dictate and speak controls for a [`VoiceState`] the
//! application owns, shows the live input level and interim transcript it
//! is handed, and reports every press as a [`VoiceEvent`] so the
//! application starts, stops, or cancels the real audio work.

use crate::{
    control::{outlined_control_with_icon, outlined_control_with_label},
    handlers::SharedHandler,
    motion::{MotionTokens, VisibleAnimationExt as _},
    surface::icon_button,
    theme::SemanticStyledExt as _,
};
use gpui::{
    AnyElement, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement,
    ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
    StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _, rems,
};
use gpui_component::{
    ActiveTheme as _, IconName, Sizable as _, StyledExt as _, h_flex, spinner::Spinner, v_flex,
};
use std::rc::Rc;

/// Where the application's audio pipeline is.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VoiceState {
    /// Nothing is recording or playing.
    Idle,
    /// The microphone is open; `level` is the current input level (0–1).
    Listening {
        /// Normalized input level used for the meter.
        level: f32,
    },
    /// Audio stopped; speech-to-text is still finishing.
    Transcribing,
    /// Text-to-speech is playing.
    Speaking,
}

impl VoiceState {
    /// The short status word read to assistive technology.
    pub fn label(self) -> &'static str {
        match self {
            Self::Idle => "Idle",
            Self::Listening { .. } => "Listening",
            Self::Transcribing => "Transcribing",
            Self::Speaking => "Speaking",
        }
    }

    /// Whether the microphone is open.
    pub fn is_listening(self) -> bool {
        matches!(self, Self::Listening { .. })
    }
}

/// An interaction emitted by [`VoiceControls`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VoiceEvent {
    /// The user asked to start dictating.
    DictationStarted,
    /// The user asked to stop and transcribe what was heard.
    DictationStopped,
    /// The user discarded the dictation in progress.
    DictationCancelled,
    /// The user asked for the latest response to be read aloud.
    SpeakRequested,
    /// The user stopped playback.
    SpeakStopped,
}

/// Dictate and speak controls with a live level meter and interim transcript.
///
/// # Example
///
/// ```
/// # use gpui_ai::prelude::*;
/// VoiceControls::new("voice", VoiceState::Listening { level: 0.6 })
///     .transcript("compare the three suppl…")
///     .speakable(true)
///     .on_event(|event, _, _| { /* VoiceEvent::DictationStopped … */ });
/// ```
#[derive(IntoElement)]
pub struct VoiceControls {
    id: SharedString,
    style: StyleRefinement,
    state: VoiceState,
    transcript: Option<SharedString>,
    speakable: bool,
    on_event: Option<SharedHandler<VoiceEvent>>,
}

impl VoiceControls {
    /// Creates the controls for the given state.
    pub fn new(id: impl Into<SharedString>, state: VoiceState) -> Self {
        Self {
            id: id.into(),
            style: StyleRefinement::default(),
            state,
            transcript: None,
            speakable: false,
            on_event: None,
        }
    }

    /// Shows the interim transcript under the controls.
    pub fn transcript(mut self, transcript: impl Into<SharedString>) -> Self {
        let transcript = transcript.into();
        self.transcript = (!transcript.is_empty()).then_some(transcript);
        self
    }

    /// Offers a Speak / Stop control for reading responses aloud.
    pub fn speakable(mut self, speakable: bool) -> Self {
        self.speakable = speakable;
        self
    }

    /// Handles typed interactions. Without a handler the controls are inert.
    pub fn on_event(
        mut self,
        handler: impl Fn(&VoiceEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_event = Some(Rc::new(handler));
        self
    }
}

impl Styled for VoiceControls {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for VoiceControls {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let tokens = cx.theme().semantic_tokens();
        let root_id = ElementId::from(self.id.clone());
        let debug_id = self.id.to_string();
        let handler = self.on_event;
        let state = self.state;

        let (dictate_name, dictate_label, dictate_event): (&str, &str, Option<VoiceEvent>) =
            match state {
                VoiceState::Idle | VoiceState::Speaking => (
                    "Start dictation",
                    "Dictate",
                    Some(VoiceEvent::DictationStarted),
                ),
                VoiceState::Listening { .. } => (
                    "Stop dictation",
                    "Listening",
                    Some(VoiceEvent::DictationStopped),
                ),
                VoiceState::Transcribing => ("Transcribing", "Transcribing", None),
            };
        let indicator: AnyElement = match state {
            VoiceState::Listening { level } => {
                let field_debug = debug_id.clone();
                div()
                    .debug_selector(move || format!("voice-signal-{field_debug}"))
                    .child(signal_field(
                        ElementId::from((root_id.clone(), "signal-field")),
                        level,
                        cx,
                    ))
                    .into_any_element()
            }
            VoiceState::Transcribing => Spinner::new().xsmall().into_any_element(),
            VoiceState::Idle | VoiceState::Speaking => div()
                .flex_none()
                .size_2()
                .rounded(tokens.radius.full)
                .bg(cx.theme().muted_foreground.opacity(0.6))
                .into_any_element(),
        };
        let dictate_debug = debug_id.clone();
        let dictate = {
            let handler = handler.clone();
            let event = dictate_event.clone();
            outlined_control_with_label(
                (root_id.clone(), "dictate"),
                dictate_name,
                dictate_label,
                window,
                cx,
            )
            .debug_selector(move || format!("voice-dictate-{dictate_debug}"))
            .disabled(dictate_event.is_none() || handler.is_none())
            .when(state.is_listening(), |this| {
                this.border_color(cx.theme().primary)
                    .text_color(cx.theme().primary)
            })
            .gap(tokens.spacing.xs)
            .child(indicator)
            .on_click(move |_: &ClickEvent, window, cx| {
                if let (Some(handler), Some(event)) = (&handler, &event) {
                    handler(event, window, cx)
                }
            })
        };
        // The visible label is the last child of the pill; put the indicator
        // before it by rebuilding the children order.
        let cancel = (state.is_listening() && handler.is_some()).then(|| {
            let handler = handler.clone();
            let cancel_debug = debug_id.clone();
            icon_button(
                (root_id.clone(), "cancel"),
                IconName::Close,
                "Cancel dictation",
                window,
                cx,
            )
            .debug_selector(move || format!("voice-cancel-{cancel_debug}"))
            .on_click(move |_: &ClickEvent, window, cx| {
                if let Some(handler) = &handler {
                    handler(&VoiceEvent::DictationCancelled, window, cx)
                }
            })
        });
        let speak = self.speakable.then(|| {
            let handler = handler.clone();
            let speak_debug = debug_id.clone();
            let speaking = state == VoiceState::Speaking;
            let (name, icon, event) = if speaking {
                ("Stop speaking", IconName::Pause, VoiceEvent::SpeakStopped)
            } else {
                (
                    "Read the latest response aloud",
                    IconName::Play,
                    VoiceEvent::SpeakRequested,
                )
            };
            // The library's own icon-and-label control, tinted while
            // speaking. It used to be hand-built with a padding-derived
            // height, so it was the one control in the crate that did not
            // move when an application replaced the size policy — and the
            // one without the shared press decay.
            outlined_control_with_icon(
                (root_id.clone(), "speak"),
                name,
                icon,
                if speaking { "Stop" } else { "Speak" },
                window,
                cx,
            )
            .debug_selector(move || format!("voice-speak-{speak_debug}"))
            .when(speaking, |button| {
                button
                    .border_color(cx.theme().primary)
                    .text_color(cx.theme().primary)
            })
            .disabled(handler.is_none())
            .on_click(move |_: &ClickEvent, window, cx| {
                if let Some(handler) = &handler {
                    handler(&event, window, cx)
                }
            })
        });
        let transcript_debug = debug_id.clone();
        let transcript = self.transcript.map(|text| {
            div()
                .id((root_id.clone(), "transcript"))
                .role(Role::Status)
                .aria_label(format!("Heard: {text}"))
                .debug_selector(move || format!("voice-transcript-{transcript_debug}"))
                .min_w_0()
                .truncate()
                .text_token(tokens.typography.sm)
                .italic()
                .text_color(cx.theme().muted_foreground)
                .child(text)
        });

        v_flex()
            .id(self.id)
            .role(Role::Group)
            .aria_label(format!(
                "Voice controls, {}",
                state.label().to_ascii_lowercase()
            ))
            .debug_selector(move || format!("voice-{debug_id}"))
            .min_w_0()
            .gap(tokens.spacing.xs)
            .child(
                h_flex()
                    .items_center()
                    .gap(tokens.spacing.xs)
                    .child(dictate)
                    .children(cancel)
                    .children(speak),
            )
            .children(transcript)
            .refine_style(&self.style)
    }
}

/// Four bars that rise with the input level; heights stay in rems so the
/// meter scales with the UI.
/// The listening signal field: six lobes shaped by the controlled level,
/// pulsing on one shared clock.
///
/// Spike C's shipped outcome: plain layout primitives produce a clean
/// field with no shader, no overdraw pass, and no background job. Lobe
/// heights follow the application-owned level — sampled from the
/// controlled snapshot, never smoothed here — and a single phase-locked
/// animation drives a wave of opacity across the lobes, so the whole
/// field costs one scheduled clock. Reduced motion holds the phase at
/// zero, leaving a static graded envelope at the level's heights as the
/// meaningful mark; the status text remains the semantic carrier.
fn signal_field(id: ElementId, level: f32, cx: &App) -> impl IntoElement {
    let tokens = cx.theme().semantic_tokens();
    let color = cx.theme().primary;
    let level = level.clamp(0.0, 1.0);
    let gap = tokens.spacing.xxs;
    let radius = tokens.radius.full;
    let full = crate::motion::motion_is_full(cx);
    const WEIGHTS: [f32; 6] = [0.35, 0.65, 1.0, 0.85, 0.55, 0.3];
    h_flex()
        .flex_none()
        .items_end()
        .h(rems(0.9))
        .gap(gap)
        .with_visible_animation(
            id,
            // Frame demand: active while the state stays Listening — the
            // field is that state's indicator and settles by the state
            // changing, which unmounts it. Phase-locked to the shared
            // epoch, so a field remounted mid-session rejoins the beat.
            MotionTokens::read(cx).breathing().looping_synced(),
            move |field, delta| {
                let delta = if full { delta } else { 0.0 };
                field.children(WEIGHTS.iter().enumerate().map(|(index, weight)| {
                    let phase = index as f32 / WEIGHTS.len() as f32;
                    let wave = ((delta - phase).rem_euclid(1.0) * 2.0 - 1.0).abs();
                    div()
                        .w(rems(0.14))
                        .h(rems(0.25 + 0.65 * level * weight))
                        .rounded(radius)
                        .bg(color)
                        .opacity(0.35 + 0.65 * wave)
                }))
            },
        )
}

#[cfg(test)]
mod tests {
    use super::*;
    use gpui::{Context, Render, TestAppContext, VisualTestContext, px};

    struct VoiceProbe {
        state: VoiceState,
    }

    impl Render for VoiceProbe {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div()
                .w(px(420.))
                .h(px(160.))
                .child(VoiceControls::new("probe-voice", self.state).speakable(true))
        }
    }

    fn draw(cx: &mut VisualTestContext) {
        cx.update(|window, cx| window.draw(cx).clear(cx));
    }

    #[gpui::test]
    fn the_signal_field_exists_exactly_while_listening(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (probe, cx) = cx.add_window_view(|_, _| VoiceProbe {
            state: VoiceState::Listening { level: 0.6 },
        });
        let cx: &mut VisualTestContext = cx;
        draw(cx);
        assert!(
            cx.debug_bounds("voice-signal-probe-voice").is_some(),
            "listening must show the signal field"
        );

        probe.update(cx, |probe, cx| {
            probe.state = VoiceState::Idle;
            cx.notify();
        });
        draw(cx);
        assert!(
            cx.debug_bounds("voice-signal-probe-voice").is_none(),
            "leaving Listening must unmount the field, and its clock with it"
        );
    }

    #[gpui::test]
    fn reduced_motion_keeps_a_static_field(cx: &mut TestAppContext) {
        cx.update(crate::init);
        cx.update(|cx| cx.set_reduce_motion(true));
        let (_, cx) = cx.add_window_view(|_, _| VoiceProbe {
            state: VoiceState::Listening { level: 0.6 },
        });
        let cx: &mut VisualTestContext = cx;
        draw(cx);
        assert!(
            cx.debug_bounds("voice-signal-probe-voice").is_some(),
            "reduced motion keeps the static envelope as the meaningful mark"
        );
    }

    #[test]
    fn states_describe_themselves() {
        assert_eq!(VoiceState::Listening { level: 0.2 }.label(), "Listening");
        assert!(VoiceState::Listening { level: 0.2 }.is_listening());
        assert!(!VoiceState::Transcribing.is_listening());
    }
}