Linux port: first run, packaging, single instance, privacy and wiring
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>
This commit is contained in:
nocodeandClaude Opus 5.5 committed 2026-11-12 20:15:49 +01:00
1 parent a2abf01280
commit 844435f21f
73 files changed
+4834 -517

No files matched your search

+272 -18
View File
@@ -31,6 +31,13 @@ const SETTLED_TOOLS_FALLBACK: &str = "The tool run finished, but no final summar
/// Answers a turn without the model (explicit owner notes). `Some(reply)` ends the turn.
pub type FastPath = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
/// Request router: `(text, up to 2 previous owner messages)` → `true` for plain small talk,
/// answered with dialogue-only instructions and no action tools (spec 02 INF-66).
pub type Classifier = Arc<dyn Fn(String, Vec<String>) -> Pin<Box<dyn Future<Output = bool> + Send>> + Send + Sync>;
/// `true` when the owner input must be stored as [`CREDENTIALS_OMITTED`].
pub type InputRedactor = Arc<dyn Fn(&str) -> bool + Send + Sync>;
/// Visible-history text of an input that carried credentials.
pub const CREDENTIALS_OMITTED: &str = "[Credentials omitted]";
/// Summarizes `messages` (oldest first) given the previous summary. Must call the model
/// without tools and fall back to an extractive summary itself.
pub type Compactor = Arc<dyn Fn(Vec<Message>, Option<String>) -> Pin<Box<dyn Future<Output = Result<String>> + Send>> + Send + Sync>;
@@ -93,8 +100,10 @@ pub struct Engine {
paths: Paths,
settings: Mutex<Settings>,
backend: Mutex<LlmBackend>,
model: String,
model: Mutex<String>,
capabilities: Mutex<Vec<String>>,
/// The local model's own capabilities, kept while an API is active.
local_caps: Mutex<Vec<String>>,
catalog: Arc<Catalog>,
session: Mutex<Session>,
journal: Mutex<Journal>,
@@ -105,7 +114,14 @@ pub struct Engine {
context: Mutex<Vec<ContextHook>>,
internet: AtomicBool,
fast_path: Mutex<Option<FastPath>>,
router: Mutex<Option<Router>>,
redact_input: Mutex<Option<InputRedactor>>,
classifier: Mutex<Option<Classifier>>,
/// Base64 images for the next owner message (attachments), consumed by it.
pending_images: Mutex<Vec<String>>,
/// Context text for the next owner message (what an attached snapshot shows), consumed by it.
pending_note: Mutex<String>,
/// Pre-model routes, tried in order; the first answer wins (clip command, computer tasks…).
routers: Mutex<Vec<Router>>,
reply_guard: Mutex<Option<ReplyGuard>>,
compactor: Mutex<Option<Compactor>>,
after_turn: Mutex<Option<TurnHook>>,
@@ -123,6 +139,8 @@ fn public_message(error: &TurnError) -> &'static str {
TurnError::Empty => "The response could not be completed. Check the local core or reconnect.",
TurnError::ToolLoop => "The action could not be completed after repeated attempts. Check Application access or try a larger language model.",
TurnError::ModelLoad => "The local model could not load. Free some memory or choose a smaller Qwen model, then try again.",
TurnError::ModelMissing => "No language model is installed yet. Download one in Settings › Language model, then try again.",
TurnError::Offline => "The local core is not running. Install Ollama (pacman -S ollama) or check Settings › Language model, then try again.",
TurnError::Llm(LlmError::Http { status: 401 | 403, .. }) => "The local core rejected authentication. Check its configuration.",
TurnError::Llm(LlmError::Http { status: 409 | 429, .. }) => "The local core is busy. Please wait and try again.",
TurnError::Llm(LlmError::Http { status: 500..=599, .. }) => "The local model could not finish this response. Please try again.",
@@ -135,6 +153,8 @@ enum TurnError {
Timeout,
Empty,
ModelLoad,
ModelMissing,
Offline,
ToolLoop,
Llm(LlmError),
Internal(#[allow(dead_code, reason = "read through Debug in the failure log")] anyhow::Error),
@@ -145,7 +165,8 @@ impl TurnError {
match self {
Self::Timeout => "CAPRI_TIMEOUT",
Self::Empty => "CAPRI_LLM_RESPONSE_EMPTY",
Self::ModelLoad => "CAPRI_MODEL_NOT_READY",
Self::ModelLoad | Self::ModelMissing => "CAPRI_MODEL_NOT_READY",
Self::Offline => "CAPRI_LLM_NETWORK_ERROR",
Self::ToolLoop => "CAPRI_TOOL_LOOP",
Self::Llm(e) => e.code(),
Self::Internal(_) => "CAPRI_INTERNAL",
@@ -217,8 +238,9 @@ impl Engine {
paths,
settings: Mutex::new(settings),
backend: Mutex::new(backend.into()),
model,
model: Mutex::new(model),
capabilities: Mutex::new(capabilities.to_vec()),
local_caps: Mutex::new(capabilities.to_vec()),
catalog,
session: Mutex::new(session),
journal: Mutex::new(journal),
@@ -229,7 +251,11 @@ impl Engine {
context: Mutex::new(vec![]),
internet: AtomicBool::new(false),
fast_path: Mutex::new(None),
router: Mutex::new(None),
redact_input: Mutex::new(None),
classifier: Mutex::new(None),
pending_images: Mutex::new(vec![]),
pending_note: Mutex::new(String::new()),
routers: Mutex::new(vec![]),
reply_guard: Mutex::new(None),
compactor: Mutex::new(None),
after_turn: Mutex::new(None),
@@ -260,8 +286,18 @@ impl Engine {
*self.fast_path.lock() = Some(hook);
}
pub fn set_classifier(&self, classifier: Classifier) {
*self.classifier.lock() = Some(classifier);
}
/// Owner inputs that must not be kept in the visible history (AG-02, AG-04).
pub fn set_input_redactor(&self, hook: InputRedactor) {
*self.redact_input.lock() = Some(hook);
}
/// Adds a pre-model route after the existing ones.
pub fn set_router(&self, router: Router) {
*self.router.lock() = Some(router);
self.routers.lock().push(router);
}
pub fn set_reply_guard(&self, guard: ReplyGuard) {
@@ -327,13 +363,27 @@ impl Engine {
*self.settings.lock() = settings;
}
pub fn model(&self) -> &str {
&self.model
pub fn model(&self) -> String {
self.model.lock().clone()
}
/// Switches the local model (after a download or a model change). The conversation is kept.
/// `capabilities` replace the current ones only while the local backend is active.
pub fn set_model(&self, model: String, capabilities: &[String]) -> Result<(), String> {
if self.busy() {
return Err("Wait for the current reply to finish.".into());
}
if self.backend.lock().is_local() {
*self.capabilities.lock() = capabilities.to_vec();
}
*self.local_caps.lock() = capabilities.to_vec();
*self.model.lock() = model;
Ok(())
}
/// `Local · <model>` or `API · <host> · <model>`.
pub fn label(&self) -> String {
self.backend.lock().label(&self.model)
self.backend.lock().label(&self.model())
}
/// Switches between the local model and an API connection. The conversation is kept.
@@ -343,6 +393,7 @@ impl Engine {
return Err("Wait for the current reply to finish.".into());
}
*self.capabilities.lock() = backend.api_capabilities().unwrap_or_else(|| local_capabilities.to_vec());
*self.local_caps.lock() = local_capabilities.to_vec();
*self.backend.lock() = backend;
Ok(())
}
@@ -351,6 +402,31 @@ impl Engine {
self.capabilities.lock().iter().any(|c| c == capability)
}
/// The backend the conversation uses now (local Ollama or an API), for auxiliary calls.
pub fn backend(&self) -> LlmBackend {
self.backend.lock().clone()
}
/// Capabilities of the local model (the active ones when the local backend is in use).
pub fn local_capabilities(&self) -> Vec<String> {
if self.backend.lock().is_local() { self.capabilities.lock().clone() } else { self.local_caps.lock().clone() }
}
/// Capability of the active model or API (`tools`, `vision`, `thinking`).
pub fn supports(&self, capability: &str) -> bool {
self.has(capability)
}
/// Images (base64) sent with the next owner message; a context hook may call this.
pub fn attach_images(&self, images: Vec<String>) {
self.pending_images.lock().extend(images);
}
/// Context text added to the next owner message only (e.g. which screen a snapshot shows).
pub fn attach_note(&self, note: &str) {
self.pending_note.lock().push_str(note);
}
pub fn catalog(&self) -> &Arc<Catalog> {
&self.catalog
}
@@ -385,7 +461,7 @@ impl Engine {
pub async fn warm_up(&self) -> Result<()> {
let keep_alive = self.settings.lock().keep_alive;
let backend = self.backend.lock().clone();
tokio::time::timeout(self.deadlines.load, backend.load(&self.model, keep_alive))
tokio::time::timeout(self.deadlines.load, backend.load(&self.model(), keep_alive))
.await
.map_err(|_| anyhow::anyhow!("The model took too long to load."))??;
Ok(())
@@ -397,6 +473,122 @@ impl Engine {
Some(AvatarRef { id: id.into(), pose: frame.pose.clone(), expression: frame.expression.clone() })
}
/// A short line Capri says on her own (tap reaction, initiative): one model call without
/// tools or history. `clean` filters the raw text; a kept line is stored as an assistant
/// message (`origin` = `{"kind": …}`) and emitted like a turn so it is shown and spoken.
/// `Ok(None)`: the model gave nothing usable. `Err`: a reply is running or the model failed.
pub async fn say(&self, system: String, user: String, origin: serde_json::Value, clean: impl Fn(&str) -> Option<String>, emit: impl Fn(TurnEvent) + Send + Sync) -> Result<Option<String>, String> {
let cancel = {
let mut active = self.active.lock();
if active.is_some() {
return Err("A reply is already in progress.".into());
}
let token = CancellationToken::new();
*active = Some(token.clone());
token
};
let result = self.say_inner(system, user, origin, clean, &cancel, emit).await;
*self.active.lock() = None;
result
}
async fn say_inner(&self, system: String, user: String, origin: serde_json::Value, clean: impl Fn(&str) -> Option<String>, cancel: &CancellationToken, emit: impl Fn(TurnEvent) + Send + Sync) -> Result<Option<String>, String> {
let settings = self.settings.lock().clone();
let backend = self.backend.lock().clone();
let request = ChatRequest {
model: self.model(),
messages: vec![Message::new("system", system), Message::new("user", user)],
tools: vec![],
options: Options {
num_ctx: backend.context_tokens(&settings).min(4096),
temperature: settings.temperature,
repeat_last_n: settings.repeat_last_n,
num_gpu: (settings.acceleration == "cpu").then_some(0),
num_thread: settings.cpu_threads,
num_predict: Some(96),
},
keep_alive: settings.keep_alive,
stream: true,
think: self.has("thinking").then_some(false),
};
let call = tokio::time::timeout(self.deadlines.load + self.deadlines.first_text, backend.chat(&request, |_| {}));
let done = tokio::select! {
_ = cancel.cancelled() => return Ok(None),
done = call => match done {
Ok(Ok(done)) => done,
Ok(Err(e)) => return Err(e.to_string()),
Err(_) => return Err("Capri took too long to respond.".into()),
},
};
if !done.tool_calls.is_empty() || done.done_reason.as_deref() == Some("length") {
return Ok(None);
}
let Some(line) = clean(&done.content) else { return Ok(None) };
let turn_id = uuid::Uuid::new_v4().to_string();
let mut extra = serde_json::Map::new();
extra.insert("origin".into(), origin);
let message = JournalMessage {
id: uuid::Uuid::new_v4().to_string(),
turn_id: turn_id.clone(),
role: "assistant".into(),
text: line.clone(),
status: "complete".into(),
created_at: now(),
avatar: None,
follow_up: Some(false),
extra,
};
self.journal.lock().put(message).map_err(|e| e.to_string())?;
let observers = self.observers.lock().clone();
let send = |event: TurnEvent| {
for observer in &observers {
observer(&event);
}
emit(event);
};
send(TurnEvent::Started { turn_id: turn_id.clone(), text: String::new() });
send(TurnEvent::Delta { turn_id: turn_id.clone(), text: line.clone() });
send(TurnEvent::Completed { turn_id, text: line.clone() });
Ok(Some(line))
}
/// Keeps a line Capri said on her own (initiative) in the visible history and the model
/// session, so later replies know it was said. `label` describes its origin for the model.
pub fn record_line(&self, turn_id: &str, text: &str, avatar: Option<&str>, origin: serde_json::Value, label: &str) -> Result<()> {
let mut extra = serde_json::Map::new();
extra.insert("origin".into(), origin);
self.journal.lock().put(JournalMessage {
id: uuid::Uuid::new_v4().to_string(),
turn_id: turn_id.into(),
role: "assistant".into(),
text: text.into(),
status: "complete".into(),
created_at: now(),
avatar: avatar.and_then(|id| self.avatar_ref(id)),
follow_up: Some(false),
extra,
})?;
let content = if label.is_empty() { text.to_string() } else { format!("[{label}] {text}") };
self.session.lock().append(Some(turn_id), &[("assistant", Message::new("assistant", content))])?;
Ok(())
}
/// Sends a recorded line to the observers (voice, approval cleanup) like a finished turn.
pub fn announce(&self, turn_id: &str, text: &str, avatar: Option<&str>) {
let observers = self.observers.lock().clone();
let mut events = vec![TurnEvent::Started { turn_id: turn_id.into(), text: String::new() }];
if let Some(id) = avatar {
events.push(TurnEvent::Avatar { turn_id: turn_id.into(), id: id.into(), follow_up: false });
}
events.push(TurnEvent::Delta { turn_id: turn_id.into(), text: text.into() });
events.push(TurnEvent::Completed { turn_id: turn_id.into(), text: text.into() });
for event in &events {
for observer in &observers {
observer(event);
}
}
}
/// Runs one owner turn. `Err` is a validation message shown to the owner without starting a turn.
pub async fn submit(&self, text: &str, emit: impl Fn(TurnEvent) + Send + Sync) -> Result<(), String> {
let text = text.trim();
@@ -456,17 +648,23 @@ impl Engine {
for hook in hooks {
context.push_str(&hook(text.to_string()).await);
}
Message::new("user", format!("{text}{}{context}", prompt::envelope(&state)))
context.push_str(&std::mem::take(&mut *self.pending_note.lock()));
let mut message = Message::new("user", format!("{text}{}{context}", prompt::envelope(&state)));
message.images = std::mem::take(&mut *self.pending_images.lock());
message
}
async fn run(&self, text: &str, cancel: &CancellationToken, emit: &(impl Fn(TurnEvent) + Send + Sync)) -> Result<()> {
let turn_id = uuid::Uuid::new_v4().to_string();
let created = now();
// A refused credential note is answered, but its text is never stored or echoed.
let redactor = self.redact_input.lock().clone();
let shown = if redactor.is_some_and(|r| r(text)) { CREDENTIALS_OMITTED } else { text };
let user = JournalMessage {
id: uuid::Uuid::new_v4().to_string(),
turn_id: turn_id.clone(),
role: "user".into(),
text: text.into(),
text: shown.into(),
status: "complete".into(),
created_at: created.clone(),
avatar: None,
@@ -479,7 +677,7 @@ impl Engine {
journal.put(user)?;
journal.put(reply.clone())?;
}
emit(TurnEvent::Started { turn_id: turn_id.clone(), text: text.into() });
emit(TurnEvent::Started { turn_id: turn_id.clone(), text: shown.into() });
let fast = self.fast_path.lock().clone();
if let Some(answer) = fast.and_then(|f| f(text)) {
@@ -495,8 +693,8 @@ impl Engine {
return Ok(());
}
let router = self.router.lock().clone();
if let Some(router) = router {
let routers = self.routers.lock().clone();
for router in routers {
let routed = router(text.to_string(), turn_id.clone(), cancel.clone()).await;
if cancel.is_cancelled() {
reply.status = "interrupted".into();
@@ -519,7 +717,18 @@ impl Engine {
}
}
let (mode, tools) = self.tool_mode(text);
let (mut mode, mut tools) = self.tool_mode(text);
let classifier = self.classifier.lock().clone();
if mode == PromptMode::Tools
&& let Some(classify) = classifier
{
// The two owner messages before this one (this one is already in the journal).
let mut context: Vec<String> = self.journal.lock().messages.iter().rev().filter(|m| m.role == "user").skip(1).take(2).map(|m| m.text.clone()).collect();
context.reverse();
if classify(text.to_string(), context).await {
(mode, tools) = (PromptMode::Dialogue, vec![]);
}
}
let user_message = self.user_message(text, mode).await;
let mut output = Output::new(&self.catalog);
let mut calls: Vec<ToolCallRecord> = Vec::new();
@@ -604,8 +813,10 @@ impl Engine {
let settings = self.settings.lock().clone();
let backend = self.backend.lock().clone();
// Model preparation has its own deadline so a cold load is not counted as "no text".
match tokio::time::timeout(self.deadlines.load, backend.load(&self.model, settings.keep_alive)).await {
match tokio::time::timeout(self.deadlines.load, backend.load(&self.model(), settings.keep_alive)).await {
Ok(Ok(())) => {}
Ok(Err(LlmError::Http { status: 404, .. })) => return Err(TurnError::ModelMissing),
Ok(Err(LlmError::Network { .. })) => return Err(TurnError::Offline),
Ok(Err(e)) => {
tracing::warn!("model load failed: {e}");
return Err(TurnError::ModelLoad);
@@ -633,7 +844,7 @@ impl Engine {
let mut settled_retry = false;
for _ in 0..MAX_MODEL_CALLS {
let request = ChatRequest {
model: self.model.clone(),
model: self.model(),
messages: messages.clone(),
tools: if settled_retry { vec![] } else { specs.clone() },
options: Options {
@@ -912,6 +1123,40 @@ mod tests {
engine.submit("salut capri", |_| {}).await.unwrap();
let last: serde_json::Value = serde_json::from_slice(&server.received_requests().await.unwrap().last().unwrap().body).unwrap();
assert!(last.get("tools").is_none());
// So does the request router's small-talk decision, which sees the earlier owner messages.
let seen = Arc::new(Mutex::new(vec![]));
let context = seen.clone();
engine.set_classifier(Arc::new(move |_text: String, previous: Vec<String>| {
*context.lock() = previous;
Box::pin(async { true })
}));
engine.submit("tell me a joke", |_| {}).await.unwrap();
let last: serde_json::Value = serde_json::from_slice(&server.received_requests().await.unwrap().last().unwrap().body).unwrap();
assert!(last.get("tools").is_none());
assert_eq!(seen.lock().last().map(String::as_str), Some("salut capri"));
}
#[tokio::test]
async fn say_stores_and_emits_a_filtered_line() {
let server = MockServer::start().await;
Mock::given(method("POST")).and(path("/api/chat"))
.respond_with(ResponseTemplate::new(200).set_body_string(line("*Hey*, easy on the hand! 😄", false) + &line("", true))).mount(&server).await;
let dir = tempfile::tempdir().unwrap();
let engine = Engine::new(Paths::under(dir.path().to_path_buf()), Settings::default(), Ollama::new(server.uri()), "m".into(), &[], Arc::new(Catalog::fallback())).unwrap();
let seen = Arc::new(Mutex::new(vec![]));
let observed = seen.clone();
engine.add_observer(Arc::new(move |e: &TurnEvent| observed.lock().push(format!("{e:?}"))));
let events = Mutex::new(vec![]);
let said = engine.say("sys".into(), "user".into(), serde_json::json!({"kind": "avatar-click"}), crate::reaction::clean_line, |e| events.lock().push(e)).await.unwrap();
assert_eq!(said.as_deref(), Some("Hey, easy on the hand!"));
assert!(matches!(events.lock().last(), Some(TurnEvent::Completed { text, .. }) if text == "Hey, easy on the hand!"));
assert_eq!(seen.lock().len(), 3, "the voice observer gets the line too");
let stored = engine.history().pop().unwrap();
assert_eq!((stored.role.as_str(), stored.extra["origin"]["kind"].as_str()), ("assistant", Some("avatar-click")));
assert!(!engine.busy());
// A line the filter rejects is neither stored nor shown.
assert_eq!(engine.say("s".into(), "u".into(), serde_json::json!({}), |_| None, |_| {}).await.unwrap(), None);
assert_eq!(engine.history().len(), 1);
}
#[tokio::test]
@@ -937,6 +1182,15 @@ mod tests {
assert!(matches!(events.into_inner().last().unwrap(), TurnEvent::Completed { text, .. } if text == "Done."));
let calls = server.received_requests().await.unwrap().len();
assert_eq!(calls, 0, "a note never reaches the model");
// A refused credential note is answered but never kept in the visible history.
engine.set_input_redactor(Arc::new(|t: &str| t.contains("password")));
engine.set_fast_path(Arc::new(|t: &str| t.starts_with("remember that").then(|| "I can’t save passwords.".to_string())));
let started = Mutex::new(String::new());
engine.submit("remember that my password is hunter22", |e| if let TurnEvent::Started { text, .. } = e { *started.lock() = text }).await.unwrap();
assert_eq!(*started.lock(), CREDENTIALS_OMITTED);
assert!(engine.history().iter().all(|m| !m.text.contains("hunter22")));
let transcript = std::fs::read_to_string(dir.path().join("data/desktop/transcript.json")).unwrap();
assert!(!transcript.contains("hunter22") && transcript.contains(CREDENTIALS_OMITTED));
let long = "x".repeat(600);
for _ in 0..3 {
engine.submit(&long, |_| {}).await.unwrap();