//! `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; /// What the presence indicator reports about the model backend. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Backend { /// The model answers. #[default] Ready, /// The local model server does not answer (Ollama missing or stopped). Offline, /// The server answers but no language model is installed (first run). Setup, } /// 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); fn remove(&self, name: &str); /// Names shown as chips under the composer. fn names(&self) -> Vec; } /// 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; /// Sleep (`true`) or wake (`false`): the app unloads or reloads the models (spec 10 ORC-06). pub type PowerHook = Arc; /// `isSleepCommand` (spec 10 ORC-06): the whole message asks Capri to go to sleep. pub fn is_sleep_command(text: &str) -> bool { let mut t = text.trim().to_lowercase().replace(['’', '‘'], "'"); t = t.trim_end_matches(['.', '!', '?', '…', ' ']).to_string(); for prefix in ["hey ", "эй "] { if let Some(rest) = t.strip_prefix(prefix) { t = rest.trim_start().to_string(); } } for name in ["capri", "капри"] { if let Some(rest) = t.strip_prefix(name) { t = rest.trim_start_matches([',', ':', '!', ' ']).to_string(); } } for polite in ["please ", "пожалуйста, ", "пожалуйста "] { if let Some(rest) = t.strip_prefix(polite) { t = rest.to_string(); } } for polite in [", please", " please", ", пожалуйста", " пожалуйста"] { if let Some(rest) = t.strip_suffix(polite) { t = rest.to_string(); } } let t = t.trim(); const PHRASES: [&str; 18] = [ "sleep", "go to sleep", "you can sleep", "you can go to sleep", "time to sleep", "time to go to sleep", "it's time to sleep", "it's time to go to sleep", "it is time to sleep", "it is time to go to sleep", "take a nap", "get some rest", "иди спать", "иди поспи", "ложись спать", "пора спать", "тебе пора спать", "отдыхай", ]; PHRASES.contains(&t) || ["можешь идти спать", "можешь поспать", "можешь отдохнуть"].contains(&t) } #[derive(Debug)] pub enum Command { Show, Hide, /// Show when hidden, hide when shown (`capri toggle`, bound to a key by the owner). Toggle, ToggleFocus, Settings(Option), Teleport, Return, ResetPosition, AlwaysOnTop(bool), Avatar(AvatarCommand), Notice(String), /// Send this text as an owner message, exactly like the composer (spoken input). Submit(String), /// Recognized speech to review before sending (automatic sending off): fills the composer. Draft(String), /// Sleep (`true`, unload the models) or wake up (`false`). Sleep(bool), /// Tray switches: microphone, spoken replies, internet mode. ToggleMicrophone, ToggleVoice, ToggleInternet, /// Plays a cue preset (`spark`, `pulse`…) or a sound file (`file:`). Sound(String), /// A line Capri says on her own (initiative): shown like a reply, with its expression. Line { text: String, avatar: Option }, /// The sentence Capri starts speaking: the reply page follows the voice. Subtitle(String), Quit, } /// One approval card. Only the first card of `State::cards` is shown and can be answered; /// the others wait their turn (`MAX_QUEUED`), each with a fresh lifetime when shown. pub(crate) struct Card { pub id: u64, pub request: Approval, /// When the card became the shown one (the danger delay counts from here). pub created: Instant, pub expires: Instant, /// Every waiting caller: an identical request joins the existing card. pub replies: Vec>, } /// Cards waiting behind the shown one (spec 08 TL-05: one pending + 8 queued). pub const MAX_QUEUED: usize = 8; #[derive(Default)] pub(crate) struct State { pub mouth: u8, pub speaking: bool, pub music_bpm: Option, pub sleeping: bool, pub wake: Wake, pub wake_at: Option, pub backend: Backend, pub stopwatch: Option<(Stopwatch, Instant)>, pub commands: VecDeque, pub cards: Vec, next_id: u64, pub attachments: Option>, pub tap_hook: Option, /// Tray checkboxes: (detached, focus mode, always on top). pub tray: (bool, bool, bool), /// Tray switches: (microphone, spoken replies, internet mode); `None` = no voice controls. pub tray_switches: (Option<(bool, bool)>, bool), /// Computer-control indicator: one click-through overlay per monitor while `Some`. pub overlay: Option, /// Set by the shell once every overlay window was drawn. pub overlay_drawn: bool, pub stop_hook: Option>, pub power: Option, /// Compact resource line under the header (`RAM 42% · CPU 12% · GPU 3.1/8 GB`). pub resources: Option, /// Silences Capri's voice (Stop button, Escape). pub stop_speech: Option>, /// Microphone and spoken-reply switches (header buttons). pub audio: Option, /// 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, } /// 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 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, pub ctx: OnceLock, } #[derive(Clone, Default)] pub struct UiHandle(pub(crate) Arc); 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) { 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_resource_line(&self, line: Option) { if self.0.state.lock().resources != line { self.with(|s| s.resources = line); } } /// Capri's voice is playing (read by the initiative gates). pub fn speaking(&self) -> bool { self.0.state.lock().speaking } pub fn sleeping(&self) -> bool { self.0.state.lock().sleeping } pub fn set_sleeping(&self, sleeping: bool) { self.with(|s| s.sleeping = sleeping); } pub fn on_power(&self, hook: PowerHook) { self.with(|s| s.power = Some(hook)); } /// Puts Capri to sleep or wakes her: shown at once, models unloaded/reloaded by the app. pub fn request_sleep(&self, sleep: bool) { let hook = { let mut s = self.0.state.lock(); if s.sleeping == sleep { return; } s.sleeping = sleep; s.power.clone() }; if sleep { self.cancel_approvals(); } if let Some(hook) = hook { hook(sleep); } if let Some(ctx) = self.0.ctx.get() { ctx.request_repaint(); } } 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) { self.with(|s| s.stopwatch = stopwatch.map(|w| (w, Instant::now()))); } pub fn set_attachments(&self, hook: Arc) { self.with(|s| s.attachments = Some(hook)); } pub fn on_tap(&self, hook: TapHook) { self.with(|s| s.tap_hook = Some(hook)); } /// Backend state shown by the presence indicator (`OFFLINE`, `SETUP REQUIRED`). pub fn set_backend(&self, backend: Backend) { self.with(|s| s.backend = backend); } /// Error notice in the companion. pub fn notice(&self, text: impl Into) { 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) { 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_speech(&self, hook: Arc) { self.with(|s| s.stop_speech = Some(hook)); } /// Silences the voice now (no effect when nothing is spoken). pub(crate) fn stop_speech(&self) { let hook = self.0.state.lock().stop_speech.clone(); if let Some(stop) = hook { stop(); } } pub fn on_stop_control(&self, hook: Arc) { 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 { self.0.state.lock().commands.drain(..).collect() } /// Answers the shown card from the UI. pub(crate) fn answer(&self, id: u64, accepted: bool) { self.with(|s| { let Some(card) = s.cards.first() else { return }; if card.id != id { return; } // The danger delay is enforced here, not only by a disabled button. if accepted && card.request.kind == DANGER_KIND && card.created.elapsed() < DANGER_DELAY { return; } let card = s.cards.remove(0); let accepted = accepted && Instant::now() < card.expires; for reply in card.replies { let _ = reply.send(accepted); } Self::promote(s); }); } /// Refuses every shown and queued card: Stop, Escape, a cancelled or failed turn, screen /// lock, Application access paused, quit (spec 08 TL-05 `cancel()` triggers). pub fn cancel_approvals(&self) { self.with(|s| { for card in s.cards.drain(..) { for reply in card.replies { let _ = reply.send(false); } } }); } /// The next queued card becomes the shown one with its own full lifetime. fn promote(s: &mut State) { if let Some(next) = s.cards.first_mut() { next.created = Instant::now(); next.expires = next.created + next.request.timeout; } } /// Refuses the shown card once its time is over. fn expire(&self) { self.with(|s| { if s.cards.first().is_some_and(|c| Instant::now() >= c.expires) { for reply in s.cards.remove(0).replies { let _ = reply.send(false); } Self::promote(s); } }); } /// Drops cards whose callers all went away (their turn was cancelled). fn forget_abandoned(&self) { self.with(|s| { let first = s.cards.first().map(|c| c.id); for card in &mut s.cards { card.replies.retain(|r| !r.is_closed()); } s.cards.retain(|c| !c.replies.is_empty()); if s.cards.first().map(|c| c.id) != first { Self::promote(s); } }); } } /// Removes the caller's card when `confirm` is dropped before an answer (cancelled turn). struct Abandon(UiHandle); impl Drop for Abandon { fn drop(&mut self) { self.0.forget_abandoned(); } } #[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 { // Declared first so it drops last, after the receiver: the sender then reads as closed. let _abandon = Abandon(self.clone()); let (tx, mut rx) = oneshot::channel(); let mut queued = true; self.with(|s| { let same = |c: &Card| c.request.kind == request.kind && c.request.title == request.title && c.request.detail == request.detail; if let Some(card) = s.cards.iter_mut().find(|c| same(c)) { card.replies.push(tx); return; } if s.cards.len() > MAX_QUEUED { queued = false; // "Too many pending permission requests." return; } s.next_id += 1; let now = Instant::now(); // A queued card gets its lifetime when it is shown (see `promote`). let expires = if s.cards.is_empty() { now + request.timeout } else { now + Duration::from_secs(86_400) }; s.cards.push(Card { id: s.next_id, request, created: now, expires, replies: vec![tx] }); }); if !queued { return false; } loop { match tokio::time::timeout(Duration::from_millis(200), &mut rx).await { Ok(answer) => return answer.unwrap_or(false), Err(_) => self.expire(), } } } } #[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); } #[test] fn sleep_commands() { for yes in ["sleep", "Go to sleep.", "Hey Capri, take a nap please", "capri: you can go to sleep!", "It’s time to sleep", "Капри, иди спать", "пожалуйста, отдыхай"] { assert!(is_sleep_command(yes), "{yes}"); } for no in ["sleep well tonight", "I want to sleep", "how do I sleep better?", "remind me to sleep at 11"] { assert!(!is_sleep_command(no), "{no}"); } } #[tokio::test] async fn approval_queue_dedupe_cap_and_cancel() { let ui = UiHandle::new(); let ask = |a: Approval| { let ui = ui.clone(); tokio::spawn(async move { ui.confirm(a).await }) }; let count = |ui: &UiHandle| ui.0.state.lock().cards.len(); let first = ask(approval(5000)); let same = ask(approval(5000)); while count(&ui) == 0 || ui.0.state.lock().cards[0].replies.len() < 2 { tokio::task::yield_now().await; } assert_eq!(count(&ui), 1, "an identical request joins the shown card"); let queued: Vec<_> = (0..MAX_QUEUED).map(|i| ask(Approval { detail: format!("/tmp/{i}"), ..approval(5000) })).collect(); while count(&ui) < 1 + MAX_QUEUED { tokio::task::yield_now().await; } assert!(!ui.confirm(Approval { detail: "/tmp/one-too-many".into(), ..approval(5000) }).await, "the queue is full"); // Only the shown card can be answered; both callers get the answer. let second = ui.0.state.lock().cards[1].id; ui.answer(second, true); assert_eq!(count(&ui), 1 + MAX_QUEUED); let shown = ui.0.state.lock().cards[0].id; ui.answer(shown, true); assert!(first.await.unwrap() && same.await.unwrap()); // Stop refuses everything left. ui.cancel_approvals(); for waiter in queued { assert!(!waiter.await.unwrap()); } assert_eq!(count(&ui), 0); // A caller that goes away (cancelled turn) leaves no card behind. let gone = ask(approval(5000)); while count(&ui) == 0 { tokio::task::yield_now().await; } gone.abort(); let _ = gone.await; assert_eq!(count(&ui), 0); } }