Files
capri-core-rust/crates/capri/src/wiring.rs
T
nocodeandClaude Opus 5.5 49349d6ecd
CI / test (push) Has been cancelled
Linux port: first run, packaging, single instance, privacy and wiring
First run and backend
- The companion opens without Ollama or a model (OFFLINE / SETUP REQUIRED),
  opens Settings > Language model and picks the model up once downloaded.
- Model, provider and GPU changes apply without restarting (Ollama is
  restarted when launch settings change); no silent fallback from API mode.
- Fatal startup errors are shown in a window; the fallback avatar loads
  again; the shipped Capri artwork is used when nothing was imported.

Packaging and tooling
- packaging/arch/PKGBUILD, capri.desktop (KWin ScreenShot2 key), icons,
  artwork under /usr/share/capri/assets, Gitea Actions CI.
- xtask: `icons` and `release-check` (no private data or credentials).

Runtime
- One instance per data folder (flock + control socket): second launch
  shows the window; capri stop / restart / toggle / status (JSON, starts
  nothing) / doctor / setup / diagnostics export / purge.
- A foreign program on the Ollama port is refused; an Ollama left behind
  by Capri is replaced.

Privacy and security
- No raw Ollama log on disk; API keys are never saved in plaintext (old
  ones move to the keyring); refused credential notes are stored as
  [Credentials omitted]; launched apps get an allow-listed environment.

Fixes
- Stop/Escape silence the voice; saved voice effects apply to replies;
  settings_control glitch settings apply; distinct KWin cursor scripts;
  KDE window capture authorized for source builds; Linux wording.
- Voice pack references zipped with Windows separators are found.

Wired features
- Initiatives, request router, resource monitor, "clip that", questions
  about a snapshot, sleep mode, tap reactions, stopwatch, attachments,
  Internet mode button, voice-synced subtitles, wake visuals, dictation
  draft, tray switches, Spotify seek/shuffle/repeat; computer-control
  planner and classifier follow model switches and API mode.
- Approval cards: one shown, 8 queued, deduplicated, cancelled on stop,
  failure, lock or pause; one Application access switch.

Desktop
- Compositor detection (no black overlay on i3 without picom), i3lock
  detection, unsupported desktops reported at startup, screenshot-only
  control without AT-SPI, fontconfig fallbacks, translatable feature
  pages with French translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:21:40 +01:00

633 lines
30 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Builds the running companion: Ollama, model backend, engine, tools and memory.
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use capri_agent::engine::{Compactor, ContextHook, FastPath, TurnHook};
use capri_agent::Engine;
use capri_core::{Paths, Settings, SettingsStore};
use capri_llm::secrets::SecretStore;
use capri_llm::sections::ApiSection;
use capri_llm::server::{resolve_model, OllamaServer};
use capri_llm::{ChatRequest, LlmBackend, Message, Ollama, Options};
use capri_memory::{owner_note_request, MemoryHandle, NoteRequest};
use capri_tools::ToolEvent;
/// The Ollama server Capri runs; replaced in place when launch settings change.
pub type SharedServer = Arc<tokio::sync::Mutex<OllamaServer>>;
pub struct Companion {
pub server: SharedServer,
/// Client for the Capri Ollama address (stays valid across server restarts).
pub ollama: Ollama,
pub engine: Arc<Engine>,
pub memory: MemoryHandle,
pub tools: capri_tools::Tools,
pub store: Arc<SettingsStore>,
pub secrets: SecretStore,
pub voice: Option<capri_voice::VoiceHandle>,
pub desktop: crate::desktop::DesktopFeatures,
}
impl Companion {
/// Stops background services; call before the runtime shuts down.
pub async fn stop(self) {
if let Some(voice) = &self.voice {
voice.shutdown();
}
self.tools.time.close();
self.desktop.stop().await;
self.server.lock().await.shutdown().await;
}
}
/// Shows a startup problem in the companion, or on stderr in the terminal chat.
fn report(ui: &Option<capri_ui::UiHandle>, text: &str) {
match ui {
Some(ui) => ui.notice(text),
None => eprintln!("{text}"),
}
}
/// Capri's model aliases in its own store, rebuilt like Capri 1.0.4 did (after each server start).
async fn prepare_store(client: &Ollama, settings: &Settings, paths: &Paths) {
if settings.ollama_url.is_some() {
return;
}
if let Err(e) = capri_models::manage::ensure_native_alias(client, settings, &settings.models_dir(paths)).await {
tracing::warn!("Capri model alias: {e:#}");
}
let inference: capri_llm::sections::InferenceSection = settings.section();
if let Err(e) = capri_models::manage::ensure_embedding_alias(client, &inference.embedding_model).await {
tracing::warn!("memory model alias: {e:#}");
}
let router: capri_llm::RouterSection = settings.section();
if router.enabled
&& let Err(e) = capri_models::manage::ensure_router_alias(client, &router).await
{
tracing::debug!("request router alias: {e:#}");
}
}
/// The stopwatch shown in the header: the newest running one, else the newest paused one.
fn shown_stopwatch(rows: &[serde_json::Value]) -> Option<capri_ui::Stopwatch> {
let pick = |state: &str| rows.iter().filter(|r| r["kind"] == "stopwatch" && r["state"] == state).max_by_key(|r| r["createdAt"].as_i64().unwrap_or(0));
let row = pick("running").or_else(|| pick("paused"))?;
Some(capri_ui::Stopwatch {
title: row["title"].as_str().unwrap_or_default().to_string(),
elapsed: Duration::from_millis(row["elapsedMs"].as_f64().unwrap_or(0.0).max(0.0) as u64),
running: row["state"] == "running",
})
}
/// Indicator state: API mode does not need the local server.
fn backend_state(online: bool, model_ready: bool, local: bool) -> capri_ui::Backend {
match (local, online, model_ready) {
(false, _, _) | (true, true, true) => capri_ui::Backend::Ready,
(true, false, _) => capri_ui::Backend::Offline,
(true, true, false) => capri_ui::Backend::Setup,
}
}
const MODEL_MISSING: &str = "No language model is installed yet. Choose one in Settings › Language model and select Download.";
/// `ui`: the interface handle, or `None` in the terminal chat.
/// Ollama or the model being unavailable is reported, not fatal: the companion opens and
/// [`watch_model`] picks them up once they are ready.
pub async fn start(paths: &Paths, store: Arc<SettingsStore>, ui: Option<capri_ui::UiHandle>) -> Result<Companion> {
if let Err(e) = capri_computer::access::migrate_legacy_pause(&store) {
tracing::warn!("application access pause not migrated: {e:#}");
}
let settings = store.get();
let (server, online) = match OllamaServer::start_exclusive(&settings, paths).await {
Ok(server) => (server, true),
Err(e) => {
tracing::warn!("Ollama unavailable: {e:#}");
report(&ui, &format!("{e:#}"));
(OllamaServer::offline(&settings), false)
}
};
let ollama = server.client.clone();
if online {
prepare_store(&ollama, &settings, paths).await;
}
let resolved = if online { resolve_model(&ollama, &settings).await.ok() } else { None };
let model_ready = resolved.is_some();
let (model, capabilities) = resolved.unwrap_or_else(|| (settings.model.clone(), vec![]));
let secrets = SecretStore::open(&paths.data).await;
let backend = match LlmBackend::from_settings(&settings, &ollama, &secrets).await {
Ok(backend) => backend,
Err(text) => {
// Not silent: the owner chose API mode and must know the local model answers instead.
tracing::warn!("external AI provider unavailable, using the local model: {text}");
report(&ui, &format!("External AI provider unavailable: {text} The local model answers until it is fixed."));
LlmBackend::Local(ollama.clone())
}
};
if online && !model_ready && backend.is_local() {
report(&ui, MODEL_MISSING);
if let Some(ui) = &ui {
ui.command(capri_ui::Command::Settings(Some("models".into())));
}
}
if let Some(ui) = &ui {
ui.set_backend(backend_state(online, model_ready, backend.is_local()));
}
let (catalog, artwork_problem) = crate::load_catalog_checked(&settings);
if let Some(problem) = artwork_problem {
tracing::warn!("{problem}");
report(&ui, &problem);
}
let engine = Arc::new(Engine::new(paths.clone(), settings.clone(), backend, model.clone(), &capabilities, catalog)?);
if let Some(caps) = engine_backend_caps(&engine) {
tracing::info!("API capabilities: {caps:?}");
}
let memory = capri_memory::MemoryService::start(store.clone())?;
let (events, mut rx) = tokio::sync::mpsc::unbounded_channel::<ToolEvent>();
// Screen perception and computer control (local model on 127.0.0.1 only).
let local = capri_perception::llm::LocalModel::new(&settings.ollama_base_url(), &model, Some(capabilities.clone()), serde_json::json!({"num_ctx": settings.context_tokens})).ok();
let screen = crate::desktop::start_screen(paths, &engine, local.clone(), ui.clone()).await;
let external = crate::desktop::external(&store, screen.as_ref().map(|s| s.0.clone()));
let tools = capri_tools::tools(store.clone(), paths, events, external.clone())?;
tools.time.clone().spawn();
let desktop = match screen {
Some((screen, platform)) => crate::desktop::start_computer(paths, &store, &engine, platform, screen, local.clone(), external, ui.clone()).await,
None => crate::desktop::DesktopFeatures::default(),
};
let mut list = tools.list.clone();
list.extend(memory.tools());
list.extend(desktop.tools());
engine.set_tools(list);
// Explicit owner notes are answered without the model.
let notes_memory = memory.clone();
let notes_store = store.clone();
let fast: FastPath = Arc::new(move |text: &str| {
let lang = notes_store.get().language.conversation;
match owner_note_request(text) {
Some(NoteRequest::Save(note)) => Some(match notes_memory.save_note(&note) {
Ok(_) => capri_memory::notes::REPLY_SAVED.to_string(),
Err(_) => capri_memory::notes::reply_failed(&lang).to_string(),
}),
Some(NoteRequest::Refused) => Some(capri_memory::notes::reply_refused(&lang).to_string()),
None => notes_memory.recall_note(text),
}
});
engine.set_fast_path(fast);
// Request router: plain English small talk skips the action tools (spec 02 INF-66..68).
let (router_client, router_store) = (ollama.clone(), store.clone());
engine.set_classifier(Arc::new(move |text: String, context: Vec<String>| {
let router = capri_models::router::Router::new(router_client.clone(), router_store.section());
Box::pin(async move {
let refs: Vec<&str> = context.iter().map(String::as_str).collect();
let routing = router.classify(&text, &refs).await;
tracing::debug!(mode = ?routing.mode, reason = %routing.reason, ms = routing.elapsed_ms, "request routing");
routing.mode == capri_models::router::Mode::Fast
})
}));
engine.set_input_redactor(Arc::new(|text: &str| matches!(owner_note_request(text), Some(NoteRequest::Refused))));
// Brain excerpts and, in internet mode, web search results.
let weak = Arc::downgrade(&engine);
let context_memory = memory.clone();
let context_store = store.clone();
let context: ContextHook = Arc::new(move |text: String| {
let memory = context_memory.clone();
let engine = weak.upgrade();
let lang = context_store.get().language.conversation;
Box::pin(async move {
let Some(engine) = engine else { return String::new() };
let mut out = memory.knowledge_context(&text, !engine.label().starts_with("Local"));
if engine.internet() {
match capri_tools::web_context(&text, Some(&lang)).await {
Ok(web) => out.push_str(&web.text),
Err(e) => tracing::warn!("web search failed: {e:#}"),
}
}
out
})
});
engine.add_context(context);
let index_memory = memory.clone();
let after: TurnHook = Arc::new(move |messages, bytes| index_memory.on_session_messages(messages, bytes));
engine.set_after_turn(after);
// Long conversations are summarized with the local model.
let compact_client = ollama.clone();
let compact_memory = memory.clone();
let ctx = settings.context_tokens;
let compactor: Compactor = Arc::new(move |messages: Vec<Message>, previous: Option<String>| {
let client = compact_client.clone();
let memory = compact_memory.clone();
let model = model.clone();
Box::pin(async move {
let policy = capri_memory::compaction::context_policy(ctx, 2048);
let request = capri_memory::compaction::CompactRequest {
messages: &messages,
previous_summary: previous.as_deref(),
latest_unresolved_request: None,
max_input_chars: (ctx.saturating_sub(policy.summary_max_tokens) as usize) * 4,
max_summary_chars: policy.summary_max_tokens as usize * 4,
};
let summary = capri_memory::compaction::compact(request, |prompt: Vec<Message>| {
let client = client.clone();
let model = model.clone();
async move {
let request = ChatRequest {
model,
messages: prompt,
tools: vec![],
options: Options { num_ctx: ctx, temperature: 0.2, repeat_last_n: 64, num_predict: Some(policy.summary_max_tokens as i32), ..Default::default() },
keep_alive: -1,
stream: true,
think: Some(false),
};
let done = tokio::time::timeout(Duration::from_secs(120), client.chat(&request, |_| {})).await??;
Ok(done.content)
}
})
.await?;
memory.after_compaction();
Ok(summary)
})
});
engine.set_compactor(compactor);
// Settings changes apply from the next turn. Pausing Application access refuses waiting cards.
let mut changes = store.subscribe();
let live = Arc::downgrade(&engine);
let pause_ui = ui.clone();
let mut access = store.section::<capri_tools::ToolsSettings>().application_access;
tokio::spawn(async move {
while changes.changed().await.is_ok() {
let Some(engine) = live.upgrade() else { break };
let settings = changes.borrow_and_update().clone();
let now = settings.section::<capri_tools::ToolsSettings>().application_access;
if access && !now
&& let Some(ui) = &pause_ui
{
ui.cancel_approvals();
}
access = now;
engine.update_settings(settings);
}
});
// A failed or cancelled turn leaves no approval card behind.
if let Some(ui) = ui.clone() {
engine.add_observer(Arc::new(move |event: &capri_agent::TurnEvent| {
if matches!(event, capri_agent::TurnEvent::Cancelled { .. } | capri_agent::TurnEvent::Failed { .. }) {
ui.cancel_approvals();
}
}));
}
// Due reminders become desktop notifications; approved settings are applied.
let notice_ui = ui.clone();
let event_store = store.clone();
let clocks = tools.time.clone();
if let Some(ui) = &ui {
ui.set_stopwatch(shown_stopwatch(&clocks.snapshot()));
}
tokio::spawn(async move {
let ui = notice_ui;
while let Some(event) = rx.recv().await {
// Header stopwatch: follows every timer change (spec 06 PER-42).
if let (ToolEvent::TimeChanged, Some(ui)) = (&event, &ui) {
ui.set_stopwatch(shown_stopwatch(&clocks.snapshot()));
}
if let ToolEvent::Setting { name: "fullComputerAccess", value } = &event {
let enabled = *value == true;
let section = capri_computer::FullComputerAccess { enabled, drives: if enabled { vec!["/".into()] } else { vec![] } };
if let Err(e) = event_store.set_section(&section) {
tracing::warn!("full computer access not saved: {e:#}");
}
}
// `settings_control set glitch…`: the portrait effect setting of the companion.
if let ToolEvent::Setting { name: name @ ("glitchEnabled" | "glitchStrength"), value } = &event {
let mut appearance: capri_ui::UiSettings = event_store.section();
match *name {
"glitchEnabled" => appearance.glitch_enabled = *value == true,
_ => appearance.glitch_strength = value.as_u64().unwrap_or(appearance.glitch_strength as u64).min(100) as u32,
}
if let Err(e) = event_store.set_section(&appearance) {
tracing::warn!("glitch setting not saved: {e:#}");
}
}
if let (ToolEvent::OpenPanel(panel), Some(ui)) = (&event, &ui) {
ui.command(capri_ui::Command::Settings(Some((*panel).to_string())));
}
if let ToolEvent::TimeDue(item) = event {
if let Some(ui) = &ui {
ui.notice(capri_tools::reminder_speech(&item));
}
let (summary, body) = capri_tools::reminder_notification(&item, false);
if let Err(e) = capri_tools::notify(&summary, &body).await {
tracing::warn!("notification failed: {e:#}");
}
}
}
});
if let Some(ui) = &ui {
crate::attachments::install(&engine, ui);
}
let voice = ui.clone().map(|ui| start_voice(&engine, &store, ui));
// Sleep unloads the models (the microphone stays available); waking loads the model again.
if let Some(ui) = &ui {
let (rt, engine, voice, ollama) = (tokio::runtime::Handle::current(), engine.clone(), voice.clone(), ollama.clone());
ui.on_power(Arc::new(move |sleep: bool| {
let (engine, ollama) = (engine.clone(), ollama.clone());
if sleep {
engine.cancel();
if let Some(voice) = &voice {
voice.stop_speaking();
}
rt.spawn(async move {
for model in ollama.ps().await.unwrap_or_default() {
if let Err(e) = ollama.unload(&model.name).await {
tracing::warn!("{} not unloaded: {e}", model.name);
}
}
tracing::info!("asleep: models unloaded");
});
} else {
rt.spawn(async move {
if let Err(e) = engine.warm_up().await {
tracing::debug!("wake-up warm-up: {e:#}");
}
});
}
}));
}
let server: SharedServer = Arc::new(tokio::sync::Mutex::new(server));
// Screen descriptions and computer-control vision follow a model switch too.
let refresh: ModelListener = {
let (screen, control, base) = (desktop.screen.clone(), desktop.computer.as_ref().map(|c| c.control.clone()), local.clone());
Arc::new(move |model: &str, caps: &[String]| {
let Some(mut local) = base.clone() else { return };
local.model = model.to_string();
local.capabilities = Some(caps.to_vec());
let vision = Some(local).filter(capri_perception::llm::LocalModel::vision_available);
if let Some(screen) = &screen {
screen.set_model(vision.clone());
}
if let Some(control) = &control {
control.set_vision(vision);
}
})
};
tokio::spawn(watch_model(Arc::downgrade(&engine), store.clone(), server.clone(), paths.clone(), secrets.clone(), ui.clone(), capabilities, model_ready, refresh));
Ok(Companion { server, ollama, engine, memory, tools, store, secrets, voice, desktop })
}
/// Told the new local model and its capabilities after each switch.
type ModelListener = Arc<dyn Fn(&str, &[String]) + Send + Sync>;
/// Waits until no reply is running (switches are refused during a reply).
async fn idle(engine: &Engine) {
while engine.busy() {
tokio::time::sleep(Duration::from_millis(300)).await;
}
}
/// Applies model, provider and device changes without restarting Capri, and picks up Ollama
/// or the model once they become available (installed or downloaded after launch).
#[allow(clippy::too_many_arguments)]
async fn watch_model(
engine: std::sync::Weak<Engine>,
store: Arc<SettingsStore>,
server: SharedServer,
paths: Paths,
secrets: SecretStore,
ui: Option<capri_ui::UiHandle>,
mut local_capabilities: Vec<String>,
mut ready: bool,
on_model: ModelListener,
) {
let mut changes = store.subscribe();
let first = store.get();
let mut launch = OllamaServer::launch_key(&first, &paths);
let mut api: ApiSection = first.section();
let mut wanted = (first.model.clone(), first.upstream_model.clone());
let mut last_start = std::time::Instant::now();
loop {
tokio::select! {
changed = changes.changed() => if changed.is_err() { break },
// Health check: every 5 s while something is missing, every 30 s otherwise.
_ = tokio::time::sleep(Duration::from_secs(if ready { 30 } else { 5 })) => {}
}
let Some(engine) = engine.upgrade() else { break };
let settings = store.get();
let client = server.lock().await.client.clone();
// Launch settings (GPU, acceleration, port, model folder): restart the owned server.
// While Ollama is missing, retry starting it every 30 s (installed after launch).
let key = OllamaServer::launch_key(&settings, &paths);
let offline = client.version().await.is_err();
if offline {
// Ollama stopped or crashed: retried below, and the model is resolved again after.
ready = false;
}
let retry = offline && !ready && last_start.elapsed() >= Duration::from_secs(30);
if key != launch || retry {
idle(&engine).await;
let mut guard = server.lock().await;
guard.shutdown().await;
last_start = std::time::Instant::now();
match OllamaServer::start_exclusive(&settings, &paths).await {
Ok(started) => {
*guard = started;
drop(guard);
prepare_store(&client, &settings, &paths).await;
if key != launch {
report(&ui, "The local model server restarted with the new settings.");
}
}
Err(e) => {
*guard = OllamaServer::offline(&settings);
if key != launch || !offline {
report(&ui, &format!("{e:#}"));
}
}
}
launch = key;
}
// Model choice (Apply in Settings, a finished download): resolve and switch.
let names = (settings.model.clone(), settings.upstream_model.clone());
if names != wanted || !ready {
match resolve_model(&client, &settings).await {
Ok((model, capabilities)) => {
idle(&engine).await;
if engine.set_model(model.clone(), &capabilities).is_ok() {
on_model(&model, &capabilities);
if !ready || names != wanted {
tracing::info!(%model, "language model selected");
}
if !ready && engine.label().starts_with("Local") {
report(&ui, &format!("{model} is ready."));
}
local_capabilities = capabilities;
ready = true;
wanted = names;
}
}
Err(e) => {
if names != wanted && !offline {
report(&ui, &format!("{e:#}"));
}
ready = false;
wanted = names;
}
}
}
// External provider: switch backends, keeping the conversation.
let next: ApiSection = settings.section();
if next != api {
api = next;
let backend = match LlmBackend::from_settings(&settings, &client, &secrets).await {
Ok(backend) => backend,
Err(text) => {
report(&ui, &format!("External AI provider unavailable: {text} The local model answers until it is fixed."));
LlmBackend::Local(client.clone())
}
};
idle(&engine).await;
if let Err(text) = engine.set_backend(backend, &local_capabilities) {
report(&ui, &text);
}
}
if let Some(ui) = &ui {
let online = client.version().await.is_ok();
ui.set_backend(backend_state(online, ready, engine.label().starts_with("Local")));
}
}
}
/// Microphone to conversation, replies to speech, mouth and dance to the avatar.
fn start_voice(engine: &Arc<Engine>, store: &Arc<SettingsStore>, ui: capri_ui::UiHandle) -> capri_voice::VoiceHandle {
use capri_agent::TurnEvent;
use capri_voice::VoiceEvent;
let (voice, mut events) = capri_voice::VoiceHandle::start(store.clone());
let (mic, speaker_switch) = (voice.clone(), voice.clone());
ui.set_audio_controls(
Arc::new(move |on| mic.set_microphone(on).map_err(|e| format!("{e:#}"))),
Arc::new(move |on| speaker_switch.set_voice_enabled(on).map_err(|e| format!("{e:#}"))),
);
// Spoken cue on the first tap of a sequence, at most every 6 s (spec 03 AV-17, §6.3).
let cue_voice = voice.clone();
let cue_rt = tokio::runtime::Handle::current();
let next_cue = Arc::new(parking_lot::Mutex::new(std::time::Instant::now()));
ui.on_tap(Arc::new(move |_part: &str, tone: &str, count: u32| {
let now = std::time::Instant::now();
if count != 1 || *next_cue.lock() > now {
return;
}
let Some(language) = cue_voice.spoken_language() else { return };
let Some(cue) = capri_agent::reaction::spoken_cue(&language, tone, capri_agent::reaction::Mood::Neutral) else { return };
*next_cue.lock() = now + Duration::from_secs(6);
let voice = cue_voice.clone();
cue_rt.spawn(async move {
tokio::time::sleep(Duration::from_millis(420)).await;
voice.speak_line(cue);
});
}));
// Stop / Escape also silence a reply that is still being spoken after its turn ended.
let silence = voice.clone();
ui.on_stop_speech(Arc::new(move || silence.stop_speaking()));
// Set when the next turn comes from the microphone (follow-up listening applies).
let spoken = Arc::new(std::sync::atomic::AtomicBool::new(false));
let speaker = voice.clone();
let from_mic = spoken.clone();
engine.add_observer(Arc::new(move |event: &TurnEvent| match event {
TurnEvent::Started { turn_id, .. } => speaker.begin_turn(turn_id, from_mic.swap(false, std::sync::atomic::Ordering::Relaxed)),
TurnEvent::Delta { turn_id, text } => speaker.speak_delta(turn_id, text),
TurnEvent::Completed { turn_id, .. } | TurnEvent::Failed { turn_id, .. } => speaker.finish_turn(turn_id),
// Stop / Escape: silence now, never flush the rest or arm follow-up listening.
TurnEvent::Cancelled { .. } => speaker.stop_speaking(),
_ => {}
}));
let engine = Arc::downgrade(engine);
let wake_store = store.clone();
let mut listening_shown = false;
tokio::spawn(async move {
while let Some(event) = events.recv().await {
match event {
VoiceEvent::Submit { text, .. } => {
spoken.store(true, std::sync::atomic::Ordering::Relaxed);
ui.command(capri_ui::Command::Submit(text));
}
VoiceEvent::Interrupt => {
if let Some(engine) = engine.upgrade() {
engine.cancel();
}
}
VoiceEvent::Speaking { level, mouth, .. } => {
ui.set_speaking(level > 0.0);
ui.set_mouth_level(mouth as u8);
}
VoiceEvent::MusicState(music) => ui.set_music((music.playing && music.bpm > 0.0).then_some(music.bpm as f32)),
VoiceEvent::Error { message, .. } => ui.notice(message),
VoiceEvent::StopRequest => ui.set_microphone_on(false),
// "HEARD YOU", and bring Capri back from the tray when the owner allows it.
VoiceEvent::Wake { .. } => {
ui.set_wake(capri_ui::Wake::Heard);
if wake_store.section::<capri_ui::UiSettings>().restore_from_tray_on_wake {
ui.show();
}
}
// "I'M LISTENING" while a command is awaited (after the wake phrase, or always
// when no wake phrase is required); the microphone's own stop reason is shown.
VoiceEvent::Microphone(status) => {
use capri_voice::wake::GateState;
let listening = status.on && status.listening && matches!(status.wake_state, GateState::Command | GateState::Disabled);
if listening != listening_shown {
listening_shown = listening;
ui.set_wake(if listening { capri_ui::Wake::Listening } else { capri_ui::Wake::Off });
}
if let Some(error) = status.error {
ui.notice(error);
}
}
// Automatic sending off: the recognized text waits in the composer.
VoiceEvent::Transcript { text, is_final: true, auto_send: false, .. } if !text.trim().is_empty() => ui.command(capri_ui::Command::Draft(text)),
VoiceEvent::Subtitle { text, .. } => ui.command(capri_ui::Command::Subtitle(text)),
_ => {}
}
}
});
voice
}
fn engine_backend_caps(engine: &Engine) -> Option<String> {
let label = engine.label();
(!label.starts_with("Local")).then_some(label)
}
/// Settings pages owned by the feature crates, shown in the settings window.
pub fn settings_pages(companion: &Companion, rt: &tokio::runtime::Handle) -> Vec<capri_ui::SettingsPage> {
let page = |section: &str, title: &str, draw: Box<dyn FnMut(&mut egui::Ui) + Send>| capri_ui::SettingsPage { section: section.into(), title: title.into(), draw };
let store = companion.store.clone();
let tools_store = store.clone();
let time = companion.tools.time.clone();
let memory = companion.memory.clone();
let memory_store = store.clone();
let models = capri_models::ui::ModelsHandle::new(rt.clone(), store.clone(), companion.ollama.clone(), companion.secrets.clone());
let models_store = store.clone();
let mut pages = vec![
page("models", "Language model", Box::new(move |ui| capri_models::ui::settings_ui(ui, &models_store, &models))),
page("tools", "Applications and files", Box::new(move |ui| capri_tools::settings_ui(ui, &tools_store))),
page("timers", "Timers and reminders", Box::new(move |ui| capri_tools::timers_ui(ui, &time))),
page("memory", "Memory", Box::new(move |ui| capri_memory::settings_ui(ui, &memory_store, &memory))),
];
pages.extend(companion.desktop.pages(&store, rt));
if let Some(voice) = companion.voice.clone() {
let voice_store = store.clone();
pages.push(page("voice", "Voice and microphone", Box::new(move |ui| capri_voice::settings_ui(ui, &voice_store, &voice))));
}
pages
}