capri-ui: add hooks module
This commit is contained in:
1 file changed
+360
@@ -0,0 +1,360 @@
|
||||
//! `UiHandle`: the thread-safe surface other crates use to drive the shell (voice mouth level,
|
||||
//! music, sleep, wake feedback, stopwatch, notices, movement commands) and the exact,
|
||||
//! temporary approval cards behind `capri_agent::tools::Approvals`.
|
||||
use std::collections::VecDeque;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use capri_agent::tools::{Approval, Approvals};
|
||||
use eframe::egui;
|
||||
use parking_lot::Mutex;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
pub use crate::dock::AvatarCommand;
|
||||
|
||||
/// Wake-word feedback.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Wake {
|
||||
#[default]
|
||||
Off,
|
||||
/// Microphone open and waiting for speech: "I'M LISTENING".
|
||||
Listening,
|
||||
/// The wake word was heard: "HEARD YOU" for 900 ms.
|
||||
Heard,
|
||||
}
|
||||
|
||||
/// Selected stopwatch shown in the header; the time service owns the clock.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Stopwatch {
|
||||
pub title: String,
|
||||
pub elapsed: Duration,
|
||||
pub running: bool,
|
||||
}
|
||||
|
||||
/// Composer attachments, owned by the attachments feature.
|
||||
pub trait Attachments: Send + Sync {
|
||||
/// Files dropped on Capri's windows.
|
||||
fn add(&self, files: Vec<PathBuf>);
|
||||
fn remove(&self, name: &str);
|
||||
/// Names shown as chips under the composer.
|
||||
fn names(&self) -> Vec<String>;
|
||||
}
|
||||
|
||||
/// Called on every awake tap with (part, tone, count in the sequence, 1..=11): spoken cues and
|
||||
/// the model reaction at count 10 belong to the voice/engine side.
|
||||
pub type TapHook = Arc<dyn Fn(&str, &str, u32) + Send + Sync>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Command {
|
||||
Show,
|
||||
Hide,
|
||||
ToggleFocus,
|
||||
Settings(Option<String>),
|
||||
Teleport,
|
||||
Return,
|
||||
ResetPosition,
|
||||
AlwaysOnTop(bool),
|
||||
Avatar(AvatarCommand),
|
||||
Notice(String),
|
||||
/// Send this text as an owner message, exactly like the composer (spoken input).
|
||||
Submit(String),
|
||||
Quit,
|
||||
}
|
||||
|
||||
pub(crate) struct Card {
|
||||
pub id: u64,
|
||||
pub request: Approval,
|
||||
pub created: Instant,
|
||||
pub expires: Instant,
|
||||
pub reply: Option<oneshot::Sender<bool>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct State {
|
||||
pub mouth: u8,
|
||||
pub speaking: bool,
|
||||
pub music_bpm: Option<f32>,
|
||||
pub sleeping: bool,
|
||||
pub wake: Wake,
|
||||
pub wake_at: Option<Instant>,
|
||||
pub stopwatch: Option<(Stopwatch, Instant)>,
|
||||
pub commands: VecDeque<Command>,
|
||||
pub cards: Vec<Card>,
|
||||
next_id: u64,
|
||||
pub attachments: Option<Arc<dyn Attachments>>,
|
||||
pub tap_hook: Option<TapHook>,
|
||||
/// Tray checkboxes: (detached, focus mode, always on top).
|
||||
pub tray: (bool, bool, bool),
|
||||
/// Computer-control indicator: one click-through overlay per monitor while `Some`.
|
||||
pub overlay: Option<ControlOverlay>,
|
||||
/// Set by the shell once every overlay window was drawn.
|
||||
pub overlay_drawn: bool,
|
||||
pub stop_hook: Option<Arc<dyn Fn() + Send + Sync>>,
|
||||
/// Microphone and spoken-reply switches (header buttons).
|
||||
pub audio: Option<AudioControls>,
|
||||
/// Real pointer (desktop pixels) and its recent positions for the overlay reticle.
|
||||
pub control_pointer: Option<[f32; 2]>,
|
||||
pub control_trail: VecDeque<([f32; 2], Instant)>,
|
||||
/// Control phase (`observing`, `planning`, `acting`, `verifying`...) and last input pulse.
|
||||
pub control_phase: String,
|
||||
pub control_pulse: Option<Instant>,
|
||||
}
|
||||
|
||||
/// Indicator request from computer control: caption and monitor rectangles (desktop pixels).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ControlOverlay {
|
||||
pub caption: String,
|
||||
pub monitors: Vec<[f32; 4]>,
|
||||
/// Decorative edge effects (border and caption are always drawn).
|
||||
pub effects: bool,
|
||||
/// 0..=100 (Capri: amount = intensity / 50).
|
||||
pub intensity: f32,
|
||||
/// `blackwall` palette instead of `capri`.
|
||||
pub blackwall: bool,
|
||||
/// Reticle and trail at the real pointer.
|
||||
pub cursor: bool,
|
||||
}
|
||||
|
||||
/// Approval kind whose confirm button needs `DANGER_DELAY` (enforced in `answer`, not only in the UI).
|
||||
pub const DANGER_KIND: &str = "settings.fullComputerAccess";
|
||||
pub const DANGER_DELAY: Duration = Duration::from_secs(3);
|
||||
|
||||
/// `set(on)` returns an error text to show when the switch could not be applied.
|
||||
pub type Switch = Arc<dyn Fn(bool) -> Result<(), String> + Send + Sync>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AudioControls {
|
||||
pub microphone: Switch,
|
||||
pub voice: Switch,
|
||||
pub microphone_on: bool,
|
||||
pub voice_on: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Shared {
|
||||
pub state: Mutex<State>,
|
||||
pub ctx: OnceLock<egui::Context>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct UiHandle(pub(crate) Arc<Shared>);
|
||||
|
||||
impl UiHandle {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Shows the microphone and voice buttons. Both start off, like Capri at every launch.
|
||||
pub fn set_audio_controls(&self, microphone: Switch, voice: Switch) {
|
||||
self.with(|s| s.audio = Some(AudioControls { microphone, voice, microphone_on: false, voice_on: false }));
|
||||
}
|
||||
|
||||
pub(crate) fn with_audio(&self, f: impl FnOnce(&mut AudioControls)) {
|
||||
self.with(|s| {
|
||||
if let Some(a) = s.audio.as_mut() {
|
||||
f(a);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Reflects a microphone change made elsewhere (spoken "microphone off", device error).
|
||||
pub fn set_microphone_on(&self, on: bool) {
|
||||
self.with(|s| {
|
||||
if let Some(a) = s.audio.as_mut() {
|
||||
a.microphone_on = on;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn with(&self, f: impl FnOnce(&mut State)) {
|
||||
f(&mut self.0.state.lock());
|
||||
if let Some(ctx) = self.0.ctx.get() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Mouth opening while Capri speaks: 0 closed, 1 small, 2 round, 3 wide.
|
||||
pub fn set_mouth_level(&self, level: u8) {
|
||||
let level = level.min(3);
|
||||
if self.0.state.lock().mouth != level {
|
||||
self.with(|s| s.mouth = level);
|
||||
}
|
||||
}
|
||||
|
||||
/// Voice playback state: drives the SPEAKING status and the speech clip.
|
||||
pub fn set_speaking(&self, speaking: bool) {
|
||||
self.with(|s| {
|
||||
s.speaking = speaking;
|
||||
if !speaking {
|
||||
s.mouth = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Music dance: `Some(bpm)` while music is heard with a usable tempo.
|
||||
pub fn set_music(&self, bpm: Option<f32>) {
|
||||
self.with(|s| s.music_bpm = bpm.filter(|b| (40.0..=240.0).contains(b)));
|
||||
}
|
||||
|
||||
/// Sleep visuals: closed eyes, `Zzz` caption, silent taps.
|
||||
pub fn set_sleeping(&self, sleeping: bool) {
|
||||
self.with(|s| s.sleeping = sleeping);
|
||||
}
|
||||
|
||||
pub fn set_wake(&self, wake: Wake) {
|
||||
self.with(|s| {
|
||||
s.wake = wake;
|
||||
s.wake_at = Some(Instant::now());
|
||||
});
|
||||
}
|
||||
|
||||
pub fn set_stopwatch(&self, stopwatch: Option<Stopwatch>) {
|
||||
self.with(|s| s.stopwatch = stopwatch.map(|w| (w, Instant::now())));
|
||||
}
|
||||
|
||||
pub fn set_attachments(&self, hook: Arc<dyn Attachments>) {
|
||||
self.with(|s| s.attachments = Some(hook));
|
||||
}
|
||||
|
||||
pub fn on_tap(&self, hook: TapHook) {
|
||||
self.with(|s| s.tap_hook = Some(hook));
|
||||
}
|
||||
|
||||
/// Error notice in the companion.
|
||||
pub fn notice(&self, text: impl Into<String>) {
|
||||
self.command(Command::Notice(text.into()));
|
||||
}
|
||||
|
||||
/// Runs a movement command (see [`crate::avatar_command`]); the reply is shown as a notice-free bubble.
|
||||
pub fn avatar_command(&self, command: AvatarCommand) {
|
||||
self.command(Command::Avatar(command));
|
||||
}
|
||||
|
||||
/// Restores the companion (tray, second launch, wake word).
|
||||
pub fn show(&self) {
|
||||
self.command(Command::Show);
|
||||
}
|
||||
|
||||
/// Shows (`Some`) or removes the computer-control indicator overlays.
|
||||
pub fn set_control_overlay(&self, overlay: Option<ControlOverlay>) {
|
||||
self.with(|s| {
|
||||
s.overlay_drawn = false;
|
||||
s.overlay = overlay;
|
||||
});
|
||||
}
|
||||
|
||||
/// Real pointer position for the overlay reticle (desktop pixels).
|
||||
pub fn set_control_pointer(&self, point: Option<[f32; 2]>) {
|
||||
let mut s = self.0.state.lock();
|
||||
if let (Some(old), Some(new)) = (s.control_pointer, point)
|
||||
&& old != new
|
||||
{
|
||||
s.control_trail.push_back((old, Instant::now()));
|
||||
if s.control_trail.len() > 12 {
|
||||
s.control_trail.pop_front();
|
||||
}
|
||||
}
|
||||
s.control_pointer = point;
|
||||
}
|
||||
|
||||
/// An input was sent: brief pulse of the reticle and edges.
|
||||
pub fn control_pulse(&self) {
|
||||
self.with(|s| s.control_pulse = Some(Instant::now()));
|
||||
}
|
||||
|
||||
pub fn control_phase(&self, phase: &str) {
|
||||
self.with(|s| s.control_phase = phase.to_string());
|
||||
}
|
||||
|
||||
/// True once the requested overlays have been drawn on every monitor.
|
||||
pub fn control_overlay_visible(&self) -> bool {
|
||||
let s = self.0.state.lock();
|
||||
s.overlay.is_some() && s.overlay_drawn
|
||||
}
|
||||
|
||||
/// Called by the "Stop computer control" button.
|
||||
pub fn on_stop_control(&self, hook: Arc<dyn Fn() + Send + Sync>) {
|
||||
self.with(|s| s.stop_hook = Some(hook));
|
||||
}
|
||||
|
||||
pub fn command(&self, command: Command) {
|
||||
self.with(|s| s.commands.push_back(command));
|
||||
}
|
||||
|
||||
pub(crate) fn take_commands(&self) -> Vec<Command> {
|
||||
self.0.state.lock().commands.drain(..).collect()
|
||||
}
|
||||
|
||||
/// Answers a card from the UI.
|
||||
pub(crate) fn answer(&self, id: u64, accepted: bool) {
|
||||
self.with(|s| {
|
||||
if let Some(i) = s.cards.iter().position(|c| c.id == id) {
|
||||
// The danger delay is enforced here, not only by a disabled button.
|
||||
if accepted && s.cards[i].request.kind == DANGER_KIND && s.cards[i].created.elapsed() < DANGER_DELAY {
|
||||
return;
|
||||
}
|
||||
let mut card = s.cards.remove(i);
|
||||
if let Some(reply) = card.reply.take() {
|
||||
let _ = reply.send(accepted && Instant::now() < card.expires);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Approvals for UiHandle {
|
||||
/// Shows an exact, temporary card; anything but an explicit accept before expiry is a refusal.
|
||||
async fn confirm(&self, request: Approval) -> bool {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let timeout = request.timeout;
|
||||
let mut id = 0;
|
||||
self.with(|s| {
|
||||
s.next_id += 1;
|
||||
id = s.next_id;
|
||||
s.cards.push(Card { id, request, created: Instant::now(), expires: Instant::now() + timeout, reply: Some(tx) });
|
||||
});
|
||||
let accepted = matches!(tokio::time::timeout(timeout, rx).await, Ok(Ok(true)));
|
||||
self.with(|s| s.cards.retain(|c| c.id != id));
|
||||
accepted
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn approval(ms: u64) -> Approval {
|
||||
Approval { kind: "file.trash".into(), title: "Move to trash?".into(), detail: "/tmp/x".into(), timeout: Duration::from_millis(ms) }
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn approvals_accept_refuse_expire() {
|
||||
let ui = UiHandle::new();
|
||||
let waiter = { let ui = ui.clone(); tokio::spawn(async move { ui.confirm(approval(5000)).await }) };
|
||||
while ui.0.state.lock().cards.is_empty() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
let id = ui.0.state.lock().cards[0].id;
|
||||
ui.answer(id, true);
|
||||
assert!(waiter.await.unwrap());
|
||||
assert!(ui.0.state.lock().cards.is_empty());
|
||||
// Expiry counts as a refusal and removes the card.
|
||||
assert!(!ui.confirm(approval(20)).await);
|
||||
assert!(ui.0.state.lock().cards.is_empty());
|
||||
// Full computer access cannot be accepted before 3 s.
|
||||
let waiter = { let ui = ui.clone(); tokio::spawn(async move { ui.confirm(Approval { kind: DANGER_KIND.into(), ..approval(5000) }).await }) };
|
||||
while ui.0.state.lock().cards.is_empty() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
let id = ui.0.state.lock().cards[0].id;
|
||||
ui.answer(id, true);
|
||||
assert_eq!(ui.0.state.lock().cards.len(), 1, "an early accept is ignored");
|
||||
ui.answer(id, false);
|
||||
assert!(!waiter.await.unwrap());
|
||||
ui.set_mouth_level(9);
|
||||
assert_eq!(ui.0.state.lock().mouth, 3);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user