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>
185 lines
7.7 KiB
Rust
185 lines
7.7 KiB
Rust
//! One companion per data folder (spec 09 RT-14, RT-20): an exclusive `flock` on
|
|
//! `RUN/instance.lock`, a control socket `RUN/control.sock` for `show`, `stop` and `status`
|
|
//! (same user only, checked with `SO_PEERCRED`), and a `RUN/desktop.json` process marker used
|
|
//! by `capri stop` when the socket does not answer.
|
|
use std::io::Write;
|
|
use std::os::fd::AsRawFd;
|
|
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use anyhow::{bail, Context, Result};
|
|
use capri_core::Paths;
|
|
use serde_json::{json, Value};
|
|
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
|
use tokio::net::{UnixListener, UnixStream};
|
|
|
|
/// Answers one control request (`{"cmd": "show" | "stop" | "status" | "toggle"}`).
|
|
pub type Handler = Arc<dyn Fn(&str) -> Value + Send + Sync>;
|
|
|
|
/// Held for the companion's lifetime; dropping it releases the lock and removes the socket.
|
|
pub struct Instance {
|
|
lock: std::fs::File,
|
|
dir: PathBuf,
|
|
data: PathBuf,
|
|
}
|
|
|
|
pub enum Launch {
|
|
Owner(Instance),
|
|
/// Another Capri holds the lock for this data folder.
|
|
Running,
|
|
}
|
|
|
|
fn ensure_dir(dir: &Path) -> Result<()> {
|
|
std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir).with_context(|| format!("cannot create {}", dir.display()))?;
|
|
let meta = std::fs::symlink_metadata(dir)?;
|
|
if !meta.is_dir() || meta.permissions().mode() & 0o077 != 0 {
|
|
bail!("{} must be a private folder (mode 0700).", dir.display());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn try_lock(file: &std::fs::File) -> bool {
|
|
unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) == 0 }
|
|
}
|
|
|
|
fn open_lock(dir: &Path) -> Result<std::fs::File> {
|
|
ensure_dir(dir)?;
|
|
std::fs::OpenOptions::new().create(true).truncate(false).read(true).write(true).mode(0o600).custom_flags(libc::O_NOFOLLOW).open(dir.join("instance.lock")).context("instance lock")
|
|
}
|
|
|
|
/// Takes the instance lock, or reports that another Capri runs on this data folder.
|
|
pub fn acquire(paths: &Paths) -> Result<Launch> {
|
|
let dir = paths.run();
|
|
let lock = open_lock(&dir)?;
|
|
if !try_lock(&lock) {
|
|
return Ok(Launch::Running);
|
|
}
|
|
Ok(Launch::Owner(Instance { lock, dir, data: std::fs::canonicalize(&paths.data).unwrap_or_else(|_| paths.data.clone()) }))
|
|
}
|
|
|
|
/// `true` while some Capri holds the lock (checked without keeping it).
|
|
pub fn running(paths: &Paths) -> bool {
|
|
let Ok(lock) = open_lock(&paths.run()) else { return false };
|
|
if try_lock(&lock) {
|
|
unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_UN) };
|
|
return false;
|
|
}
|
|
true
|
|
}
|
|
|
|
/// Start time of `pid` in clock ticks since boot (`/proc/<pid>/stat` field 22), the identity
|
|
/// that makes a recycled pid detectable.
|
|
fn start_ticks(pid: u32) -> Option<u64> {
|
|
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
|
|
stat.rsplit_once(')')?.1.split_whitespace().nth(19)?.parse().ok()
|
|
}
|
|
|
|
impl Instance {
|
|
fn socket(&self) -> PathBuf {
|
|
self.dir.join("control.sock")
|
|
}
|
|
|
|
/// Writes the `desktop` marker and answers control requests until the runtime stops.
|
|
pub fn serve(&self, rt: &tokio::runtime::Handle, handler: Handler) -> Result<()> {
|
|
let pid = std::process::id();
|
|
let marker = json!({
|
|
"pid": pid,
|
|
"startedAt": start_ticks(pid).map(|t| t.to_string()),
|
|
"executable": std::env::current_exe().ok(),
|
|
"dataRoot": self.data,
|
|
"privateLogSchema": 1,
|
|
});
|
|
let path = self.dir.join("desktop.json");
|
|
let mut file = std::fs::OpenOptions::new().create(true).truncate(true).write(true).mode(0o600).custom_flags(libc::O_NOFOLLOW).open(&path)?;
|
|
file.write_all(marker.to_string().as_bytes())?;
|
|
|
|
let socket = self.socket();
|
|
// We hold the lock: a socket file left here is stale.
|
|
let _ = std::fs::remove_file(&socket);
|
|
let _guard = rt.enter();
|
|
let listener = UnixListener::bind(&socket).with_context(|| format!("cannot listen on {}", socket.display()))?;
|
|
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?;
|
|
let uid = unsafe { libc::getuid() };
|
|
rt.spawn(async move {
|
|
while let Ok((stream, _)) = listener.accept().await {
|
|
if !stream.peer_cred().is_ok_and(|c| c.uid() == uid) {
|
|
continue;
|
|
}
|
|
let handler = handler.clone();
|
|
tokio::spawn(async move {
|
|
let (read, mut write) = stream.into_split();
|
|
let mut line = String::new();
|
|
let mut reader = BufReader::new(read.take(4096));
|
|
let Ok(Ok(_)) = tokio::time::timeout(Duration::from_secs(5), reader.read_line(&mut line)).await else { return };
|
|
let cmd = serde_json::from_str::<Value>(&line).ok().and_then(|v| v["cmd"].as_str().map(str::to_string)).unwrap_or_default();
|
|
let reply = match cmd.as_str() {
|
|
"show" | "stop" | "status" | "toggle" => handler(&cmd),
|
|
_ => json!({"ok": false, "error": "Unknown command."}),
|
|
};
|
|
let _ = write.write_all(format!("{reply}\n").as_bytes()).await;
|
|
});
|
|
}
|
|
});
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl Drop for Instance {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_file(self.socket());
|
|
let _ = std::fs::remove_file(self.dir.join("desktop.json"));
|
|
unsafe { libc::flock(self.lock.as_raw_fd(), libc::LOCK_UN) };
|
|
}
|
|
}
|
|
|
|
/// Sends one command to the running companion; `Err` when it does not answer within 5 s.
|
|
pub async fn request(paths: &Paths, cmd: &str) -> Result<Value> {
|
|
let socket = paths.run().join("control.sock");
|
|
let exchange = async {
|
|
let mut stream = UnixStream::connect(&socket).await?;
|
|
stream.write_all(format!("{}\n", json!({ "cmd": cmd })).as_bytes()).await?;
|
|
let mut line = String::new();
|
|
BufReader::new(stream).read_line(&mut line).await?;
|
|
anyhow::Ok(serde_json::from_str::<Value>(&line)?)
|
|
};
|
|
match tokio::time::timeout(Duration::from_secs(5), exchange).await {
|
|
Ok(result) => result,
|
|
Err(_) => bail!("no answer within 5 s"),
|
|
}
|
|
}
|
|
|
|
/// Pid from the `desktop` marker, only while that process is still the one that wrote it.
|
|
pub fn marker_pid(paths: &Paths) -> Option<u32> {
|
|
let text = std::fs::read_to_string(paths.run().join("desktop.json")).ok().filter(|t| t.len() <= 65536)?;
|
|
let marker: Value = serde_json::from_str(&text).ok()?;
|
|
let pid = u32::try_from(marker["pid"].as_u64()?).ok().filter(|p| *p > 0)?;
|
|
let started: u64 = marker["startedAt"].as_str()?.parse().ok()?;
|
|
(start_ticks(pid) == Some(started)).then_some(pid)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn single_owner_and_control_socket() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let paths = Paths::under(dir.path().to_path_buf());
|
|
paths.ensure().unwrap();
|
|
let rt = tokio::runtime::Runtime::new().unwrap();
|
|
let Launch::Owner(owner) = acquire(&paths).unwrap() else { panic!("first launch owns the lock") };
|
|
assert!(matches!(acquire(&paths).unwrap(), Launch::Running));
|
|
assert!(running(&paths));
|
|
owner.serve(rt.handle(), Arc::new(|cmd| json!({"ok": true, "cmd": cmd}))).unwrap();
|
|
assert_eq!(rt.block_on(request(&paths, "status")).unwrap()["cmd"], "status");
|
|
assert_eq!(rt.block_on(request(&paths, "reboot")).unwrap()["ok"], false);
|
|
assert_eq!(marker_pid(&paths), Some(std::process::id()));
|
|
drop(owner);
|
|
assert!(!running(&paths));
|
|
assert!(rt.block_on(request(&paths, "show")).is_err());
|
|
assert_eq!(marker_pid(&paths), None);
|
|
}
|
|
}
|