CI / test (push) Has been cancelled
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>
127 lines
4.9 KiB
Rust
127 lines
4.9 KiB
Rust
//! Turn routing helpers (Capri `conversation-route.mjs`, `tool-loop.mjs`).
|
||
use std::collections::{HashMap, VecDeque};
|
||
use std::sync::LazyLock;
|
||
|
||
use regex::Regex;
|
||
use serde_json::Value;
|
||
use fingerprint_mod::fingerprint;
|
||
|
||
static GREETINGS: LazyLock<[Regex; 3]> = LazyLock::new(|| {
|
||
[
|
||
Regex::new(r"^(?:(?:hey|hi|hello|привет|здравствуй)[, ]+)?(?:capri|капри)[,! ]*(?:(?:how are you|как дела)[?!.]*)?$").unwrap(),
|
||
Regex::new(r"^(?:(?:say|скажи)\s+)?(?:hi|hello|hey|привет|здравствуй)(?:[, ]+(?:capri|капри))?(?:\s+briefly)?[?!.]*$").unwrap(),
|
||
Regex::new(r"^(?:bonjour|salut|coucou|hola|buenas|hallo|guten tag|olá|ola|oi|ciao|buongiorno|merhaba|你好|您好|こんにちは|안녕|안녕하세요|مرحبا)(?:[,,! ]*(?:capri|капри))?[?!.!。]*$").unwrap(),
|
||
]
|
||
});
|
||
|
||
/// Unambiguous social turn (greeting): answered without tools.
|
||
pub fn conversation_only(text: &str) -> bool {
|
||
if text.encode_utf16().count() > 100 {
|
||
return false;
|
||
}
|
||
let greeting = text.trim().to_lowercase(); // TODO: no NFKC normalization, so fullwidth greetings are missed
|
||
GREETINGS.iter().any(|r| r.is_match(&greeting))
|
||
}
|
||
|
||
/// Actions that only read state; repeating them identically three times means no progress.
|
||
const DISCOVERY: [&str; 4] = ["apps", "find_app", "status", "journal"];
|
||
|
||
/// Stops a turn whose tools make no progress (Capri `ToolProgressGuard`).
|
||
#[derive(Default)]
|
||
pub struct ToolProgressGuard {
|
||
reads: VecDeque<String>,
|
||
counts: HashMap<String, u32>,
|
||
failures: u32,
|
||
failed_action: String,
|
||
}
|
||
|
||
impl ToolProgressGuard {
|
||
/// Returns `Err` when the turn must stop with `CAPRI_TOOL_LOOP` (no detail: the caller maps it).
|
||
#[allow(clippy::result_unit_err)]
|
||
pub fn record(&mut self, tool: &str, args: &Value, result: &Value) -> Result<(), ()> {
|
||
if result["needsApproval"] == true || result["needsWindow"] == true {
|
||
return Ok(());
|
||
}
|
||
let action = args["action"].as_str().unwrap_or("");
|
||
if result["ok"] == false {
|
||
let key = format!("{tool}:{action}");
|
||
self.failures = if key == self.failed_action { self.failures + 1 } else { 1 };
|
||
self.failed_action = key;
|
||
return if self.failures >= 3 { Err(()) } else { Ok(()) };
|
||
}
|
||
self.failures = 0;
|
||
if result["ok"] != true {
|
||
return Ok(());
|
||
}
|
||
if !DISCOVERY.contains(&action) {
|
||
self.reads.clear();
|
||
self.counts.clear();
|
||
return Ok(());
|
||
}
|
||
let key = fingerprint(&[tool.into(), args.clone(), result.clone()]);
|
||
if !self.counts.contains_key(&key) {
|
||
if self.reads.len() >= 32
|
||
&& let Some(old) = self.reads.pop_front()
|
||
{
|
||
self.counts.remove(&old);
|
||
}
|
||
self.reads.push_back(key.clone());
|
||
}
|
||
let count = self.counts.entry(key).or_default();
|
||
*count += 1;
|
||
if *count >= 3 { Err(()) } else { Ok(()) }
|
||
}
|
||
}
|
||
|
||
mod fingerprint_mod {
|
||
use serde_json::Value;
|
||
|
||
/// Canonical JSON (sorted keys) used as an identity for repeated reads.
|
||
pub fn fingerprint(values: &[Value]) -> String {
|
||
fn canon(v: &Value) -> Value {
|
||
match v {
|
||
Value::Object(map) => {
|
||
let sorted: std::collections::BTreeMap<_, _> = map.iter().map(|(k, v)| (k.clone(), canon(v))).collect();
|
||
serde_json::to_value(sorted).unwrap()
|
||
}
|
||
Value::Array(items) => Value::Array(items.iter().map(canon).collect()),
|
||
other => other.clone(),
|
||
}
|
||
}
|
||
serde_json::to_string(&values.iter().map(canon).collect::<Vec<_>>()).unwrap()
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use serde_json::json;
|
||
|
||
#[test]
|
||
fn greetings() {
|
||
for yes in ["Salut Capri!", "hey capri, how are you?", "say hi", "Bonjour", "привет, капри"] {
|
||
assert!(conversation_only(yes), "{yes}");
|
||
}
|
||
for no in ["salut, ouvre firefox", "capri remind me in 5 minutes", "what time is it"] {
|
||
assert!(!conversation_only(no), "{no}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn guard_stops_repeated_failures_and_reads() {
|
||
let mut g = ToolProgressGuard::default();
|
||
let args = json!({"action": "list"});
|
||
let fail = json!({"ok": false});
|
||
assert!(g.record("filesystem_control", &args, &fail).is_ok());
|
||
assert!(g.record("filesystem_control", &args, &fail).is_ok());
|
||
assert!(g.record("filesystem_control", &args, &fail).is_err());
|
||
|
||
let mut g = ToolProgressGuard::default();
|
||
let status = json!({"action": "status"});
|
||
let ok = json!({"ok": true, "b": 1, "a": 2});
|
||
assert!(g.record("x", &status, &ok).is_ok());
|
||
assert!(g.record("x", &status, &json!({"a": 2, "b": 1, "ok": true})).is_ok());
|
||
assert!(g.record("x", &status, &ok).is_err());
|
||
}
|
||
}
|