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:21:40 +01:00
1 parent a2abf01280
commit 49349d6ecd
73 files changed
+4834 -517

No files matched your search

+31
View File
@@ -235,6 +235,23 @@ impl Awareness {
});
}
Desktop::X11(x) => {
// Screen lockers started directly (i3 key binding, xss-lock without logind)
// never tell logind: watch for their process.
let (emit4, cancel4, filter4) = (emit.clone(), cancel.clone(), filter.clone());
tokio::spawn(async move {
let mut locked = false;
while !cancel4.is_cancelled() {
let now = screen_locker_running();
if now != locked {
locked = now;
if !now {
filter4.lock().reset();
}
emit4(Event::new(if now { Kind::SessionLock } else { Kind::SessionUnlock }));
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
});
let (x, filter2, emit2, cancel2) = (x.clone(), filter.clone(), emit.clone(), cancel.clone());
tokio::spawn(async move {
while !cancel2.is_cancelled() {
@@ -298,6 +315,20 @@ fn active_window(x: &X11) -> Option<(u32, u32, bool)> {
Some((window, x.pid_of(window), fullscreen))
}
/// X11 screen lockers that do not report to logind.
const SCREEN_LOCKERS: [&str; 8] = ["i3lock", "i3lock-color", "xsecurelock", "slock", "xlock", "xtrlock", "physlock", "sxlock"];
/// A screen locker of this user is running.
pub fn screen_locker_running() -> bool {
use std::os::unix::fs::MetadataExt;
let uid = unsafe { libc::getuid() };
std::fs::read_dir("/proc").into_iter().flatten().flatten().any(|entry| {
entry.file_name().to_str().is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit()))
&& entry.metadata().is_ok_and(|m| m.uid() == uid)
&& std::fs::read_to_string(entry.path().join("comm")).is_ok_and(|comm| SCREEN_LOCKERS.contains(&comm.trim()))
})
}
fn spawn_idle<F, Fut>(cancel: CancellationToken, emit: Arc<impl Fn(Event) + Send + Sync + 'static>, probe: F)
where
F: Fn() -> Fut + Send + 'static,
+41 -7
View File
@@ -4,8 +4,9 @@
//! KDE: KWin `ScreenShot2` (`CaptureScreen`/`CaptureWindow`, raw pixels over a pipe). KWin only
//! answers executables whose installed `.desktop` file declares
//! `X-KDE-DBUS-Restricted-Interfaces=org.kde.KWin.ScreenShot2`; that is why `capri_linux/capture.py`
//! used Spectacle (a Python interpreter cannot be authorized). The Rust binary can be, see
//! [`kwin_desktop_entry`]; until then output captures fall back to Spectacle + crop.
//! used Spectacle (a Python interpreter cannot be authorized). The packaged `capri.desktop`
//! carries that key; other builds get a hidden per-user entry from [`ensure_kwin_authorization`].
//! When KWin still refuses, output captures fall back to Spectacle + crop.
//! i3/X11: `GetImage` on the root window (outputs) or the window drawable.
use std::collections::HashMap;
use std::io::Read;
@@ -127,12 +128,44 @@ async fn spectacle(state: &DesktopState, o: &Output) -> Result<RgbImage> {
}
/// The `.desktop` entry that authorizes the Capri binary for KWin ScreenShot2.
/// Install as `~/.local/share/applications/capri.desktop`; `Exec` must be the running binary.
/// `Exec` must be the running binary (quoted per the Desktop Entry spec when needed).
pub fn kwin_desktop_entry(exe: &std::path::Path) -> String {
format!(
"[Desktop Entry]\nType=Application\nName=Capri\nExec={}\nIcon=capri\nStartupWMClass=capri\nX-KDE-DBUS-Restricted-Interfaces=org.kde.KWin.ScreenShot2\n",
exe.display()
)
let path = exe.display().to_string();
let exec = if path.chars().any(|c| c.is_whitespace() || "\"'`$\\<>~|&;*?#()".contains(c)) {
format!("\"{}\"", path.chars().flat_map(|c| if "\"`$\\".contains(c) { vec!['\\', c] } else { vec![c] }).collect::<String>())
} else {
path
};
format!("[Desktop Entry]\nType=Application\nName=Capri\nExec={exec}\nIcon=capri\nStartupWMClass=capri\nX-KDE-DBUS-Restricted-Interfaces=org.kde.KWin.ScreenShot2\n")
}
/// Lets KWin answer ScreenShot2 (window capture) for this binary. `/usr/bin/capri` from the
/// package is covered by `/usr/share/applications/capri.desktop`; any other build (cargo, a
/// copy elsewhere) gets `~/.local/share/applications/capri-local.desktop` pointing at itself,
/// hidden from menus. Returns `true` when the entry was written or changed: KDE's service cache
/// is then refreshed (`kbuildsycoca6`), and KWin uses it from the next capture.
pub fn ensure_kwin_authorization() -> Result<bool> {
let exe = std::env::current_exe()?.canonicalize()?;
if exe == std::path::Path::new("/usr/bin/capri") && std::path::Path::new("/usr/share/applications/capri.desktop").is_file() {
return Ok(false);
}
let data = std::env::var_os("XDG_DATA_HOME")
.map(std::path::PathBuf::from)
.filter(|p| p.is_absolute())
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".local/share")))
.context("no home directory")?;
let file = data.join("applications").join("capri-local.desktop");
let entry = kwin_desktop_entry(&exe) + "NoDisplay=true\n";
if std::fs::read_to_string(&file).is_ok_and(|current| current == entry) {
return Ok(false);
}
std::fs::create_dir_all(file.parent().context("no parent")?)?;
let tmp = file.with_extension("desktop.tmp");
std::fs::write(&tmp, &entry)?;
std::fs::rename(&tmp, &file)?;
// KWin looks entries up through KDE's service cache.
let _ = std::process::Command::new("kbuildsycoca6").stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn();
Ok(true)
}
/// The monitor holding the foreground window, at the size of its desktop bounds:
@@ -199,5 +232,6 @@ mod tests {
let m = frame(&Fake, &NativeSource::Outputs(vec![o(0), o(1920)])).await.unwrap();
assert!(m.width() == 1280 && m.height() <= 720);
assert!(kwin_desktop_entry(std::path::Path::new("/usr/bin/capri")).contains("Exec=/usr/bin/capri\n"));
assert!(kwin_desktop_entry(std::path::Path::new("/home/a b/capri")).contains("Exec=\"/home/a b/capri\"\n"), "paths with spaces are quoted");
}
}
+17 -1
View File
@@ -24,9 +24,16 @@ impl Platform {
}
pub fn from_env(var: impl Fn(&str) -> Option<String>) -> Result<Self> {
if var("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty()) && var("XDG_CURRENT_DESKTOP").unwrap_or_default().to_uppercase().contains("KDE") {
let desktop = var("XDG_CURRENT_DESKTOP").unwrap_or_default();
let wayland = var("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty());
if wayland && desktop.to_uppercase().contains("KDE") {
return Ok(Self::Kde);
}
if wayland {
// GNOME, Sway, Hyprland…: XTest and X11 capture would only reach XWayland windows.
let name = if desktop.is_empty() { "This Wayland session".to_string() } else { desktop };
bail!("{name} is not supported for screen and computer control (KDE Plasma on Wayland or i3 on X11 only). Chat, voice and memory work normally.");
}
if var("DISPLAY").is_some_and(|v| !v.is_empty()) {
return Ok(Self::X11);
}
@@ -106,6 +113,13 @@ impl Desktop {
Ok(match Platform::detect()? {
Platform::Kde => Self::Kde(KWin::connect().await?),
Platform::X11 => {
// Window lists, focus and workspaces come from i3 IPC: other X11 window managers
// (Plasma X11, Xfce…) would fail at the first action.
if I3::connect().await.is_err() {
let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
let name = if desktop.is_empty() { "This X11 session".to_string() } else { format!("{desktop} on X11") };
bail!("{name} is not supported for screen and computer control: i3 is required on X11 (KDE Plasma is supported on Wayland). Chat, voice and memory work normally.");
}
let (conn, screen) = x11rb::connect(None)?;
let root = conn.setup().roots[screen].root;
Self::X11(Arc::new(X11 { conn, root }))
@@ -304,6 +318,8 @@ mod tests {
assert_eq!(Platform::from_env(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("XDG_CURRENT_DESKTOP", "KDE"), ("DISPLAY", ":0")])).unwrap(), Platform::Kde);
assert_eq!(Platform::from_env(env(&[("DISPLAY", ":0"), ("XDG_CURRENT_DESKTOP", "i3")])).unwrap(), Platform::X11);
assert!(Platform::from_env(env(&[])).is_err());
let gnome = Platform::from_env(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("XDG_CURRENT_DESKTOP", "GNOME"), ("DISPLAY", ":0")])).unwrap_err();
assert!(gnome.to_string().starts_with("GNOME is not supported"), "{gnome}");
}
#[test]
+67 -25
View File
@@ -7,6 +7,7 @@ use uuid::Uuid;
use crate::policy::{SourceEntry, SourceKind, UserGesture};
use crate::settings::{InitiativeSettings, Level, ResourceSettings, ScreenSettings};
use capri_core::i18n::t;
pub enum ScreenRequest {
Refresh,
@@ -14,6 +15,8 @@ pub enum ScreenRequest {
Start { source: Uuid, interval_ms: u64, duration_ms: u64, gesture: UserGesture },
Stop,
OpenFolder,
/// "Ask Capri" about the snapshot preview (spec 06 PER-04).
Ask { preview: Uuid, question: String },
}
/// Picker state kept by the app between frames.
@@ -21,6 +24,19 @@ pub enum ScreenRequest {
pub struct ScreenPanel {
pub sources: Vec<SourceEntry>,
pub selected: Option<Uuid>,
/// Last snapshot: preview id and PNG, shown until asked about or discarded (60 s lifetime).
pub preview: Option<(Uuid, Vec<u8>)>,
texture: Option<(Uuid, egui::TextureHandle)>,
pub question: String,
}
impl ScreenPanel {
/// Shows a new snapshot preview.
pub fn show_preview(&mut self, id: Uuid, png: Vec<u8>) {
self.preview = Some((id, png));
self.texture = None;
self.question.clear();
}
}
fn save<T: capri_core::Section>(store: &SettingsStore, value: &T) {
@@ -32,9 +48,9 @@ fn save<T: capri_core::Section>(store: &SettingsStore, value: &T) {
/// All three pages; `status` is `ScreenController::status` (capture + observation snapshot).
pub fn settings_ui(ui: &mut egui::Ui, store: &SettingsStore, panel: &mut ScreenPanel, status: &Value, initiative_status: &Value) -> Vec<ScreenRequest> {
let mut requests = vec![];
egui::CollapsingHeader::new("Screen snapshot").default_open(true).show(ui, |ui| requests = screen_page(ui, store, panel, status));
egui::CollapsingHeader::new("Initiative").show(ui, |ui| initiative_page(ui, store, initiative_status));
egui::CollapsingHeader::new("Resources").show(ui, |ui| resources_page(ui, store));
egui::CollapsingHeader::new(t("Screen snapshot")).default_open(true).show(ui, |ui| requests = screen_page(ui, store, panel, status));
egui::CollapsingHeader::new(t("Initiative")).show(ui, |ui| initiative_page(ui, store, initiative_status));
egui::CollapsingHeader::new(t("Resources")).show(ui, |ui| resources_page(ui, store));
requests
}
@@ -44,16 +60,16 @@ pub fn screen_page(ui: &mut egui::Ui, store: &SettingsStore, panel: &mut ScreenP
let mut s: ScreenSettings = store.section();
let (mut secs, mut mins) = (s.interval_ms / 1000, s.duration_ms as f64 / 60_000.0);
ui.add_enabled_ui(!running, |ui| {
ui.add(egui::Slider::new(&mut secs, 15..=300).text("Interval (seconds)"));
ui.add(egui::Slider::new(&mut mins, 0.5..=120.0).step_by(0.5).text("Duration (minutes)"));
egui::ComboBox::from_label("Source")
ui.add(egui::Slider::new(&mut secs, 15..=300).text(t("Interval (seconds)")));
ui.add(egui::Slider::new(&mut mins, 0.5..=120.0).step_by(0.5).text(t("Duration (minutes)")));
egui::ComboBox::from_label(t("Source"))
.selected_text(panel.selected.and_then(|id| panel.sources.iter().find(|e| e.id == id)).map_or("Choose a window or monitor…".into(), label))
.show_ui(ui, |ui| {
for e in &panel.sources {
ui.selectable_value(&mut panel.selected, Some(e.id), label(e));
}
});
if ui.button("Refresh sources").clicked() {
if ui.button(t("Refresh sources")).clicked() {
out.push(ScreenRequest::Refresh);
}
});
@@ -63,26 +79,52 @@ pub fn screen_page(ui: &mut egui::Ui, store: &SettingsStore, panel: &mut ScreenP
save(store, &s);
}
if running {
ui.label("Stop observation before changing its interval or duration.");
ui.label(t("Stop observation before changing its interval or duration."));
}
ui.horizontal(|ui| {
if let Some(id) = panel.selected.filter(|_| !running) {
if ui.button("Capture").clicked() {
if ui.button(t("Capture")).clicked() {
out.push(ScreenRequest::Capture(id, UserGesture::owner_clicked()));
}
if ui.button("Start observation").clicked() {
if ui.button(t("Start observation")).clicked() {
out.push(ScreenRequest::Start { source: id, interval_ms: s.interval_ms, duration_ms: s.duration_ms, gesture: UserGesture::owner_clicked() });
}
}
if (running || status["capture"]["active"] == true) && ui.button("Stop screen access").clicked() {
if (running || status["capture"]["active"] == true) && ui.button(t("Stop screen access")).clicked() {
out.push(ScreenRequest::Stop);
}
if ui.button("Open screenshots folder").clicked() {
if ui.button(t("Open screenshots folder")).clicked() {
out.push(ScreenRequest::OpenFolder);
}
});
if let Some((id, png)) = panel.preview.clone() {
ui.separator();
if panel.texture.as_ref().is_none_or(|(t, _)| *t != id)
&& let Ok(image) = image::load_from_memory(&png)
{
let rgba = image.thumbnail(640, 360).to_rgba8();
let color = egui::ColorImage::from_rgba_unmultiplied([rgba.width() as usize, rgba.height() as usize], rgba.as_raw());
panel.texture = Some((id, ui.ctx().load_texture("screen-preview", color, egui::TextureOptions::LINEAR)));
}
if let Some((_, texture)) = &panel.texture {
let size = texture.size_vec2();
let scale = (ui.available_width() / size.x).min(1.0);
ui.image((texture.id(), size * scale));
}
ui.label(t("Ask Capri about this snapshot (the image is used for one reply, then discarded):"));
ui.text_edit_singleline(&mut panel.question);
ui.horizontal(|ui| {
if ui.add_enabled(!panel.question.trim().is_empty(), egui::Button::new(t("Ask Capri"))).clicked() {
out.push(ScreenRequest::Ask { preview: id, question: panel.question.trim().to_string() });
panel.preview = None;
}
if ui.button(t("Discard")).clicked() {
panel.preview = None;
}
});
}
ui.label(observation_status(&status["observation"]));
ui.small("Observation stays on when this panel closes. OBS stops it immediately. Hiding Capri, locking the session or reaching the time limit also stops it. It never resumes automatically.");
ui.small(t("Observation stays on when this panel closes. OBS stops it immediately. Hiding Capri, locking the session or reaching the time limit also stops it. It never resumes automatically."));
out
}
@@ -131,19 +173,19 @@ pub fn initiative_page(ui: &mut egui::Ui, store: &SettingsStore, status: &Value)
});
ui.add_enabled_ui(s.level != Level::Off, |ui| {
let mut limit = s.hourly_limit.unwrap_or(s.limit() as u8);
if ui.add(egui::Slider::new(&mut limit, 1..=30).text("Comments per hour")).changed() {
if ui.add(egui::Slider::new(&mut limit, 1..=30).text(t("Comments per hour"))).changed() {
s.hourly_limit = Some(limit);
}
ui.checkbox(&mut s.spontaneous, "Spontaneous comments");
ui.checkbox(&mut s.return_reactions, "React when I come back");
ui.checkbox(&mut s.app_reactions, "React to media apps");
ui.checkbox(&mut s.quiet_hours_enabled, "Quiet hours");
ui.checkbox(&mut s.spontaneous, t("Spontaneous comments"));
ui.checkbox(&mut s.return_reactions, t("React when I come back"));
ui.checkbox(&mut s.app_reactions, t("React to media apps"));
ui.checkbox(&mut s.quiet_hours_enabled, t("Quiet hours"));
ui.add_enabled_ui(s.quiet_hours_enabled, |ui| {
ui.add(egui::Slider::new(&mut s.quiet_start, 0..=23).text("Quiet from"));
ui.add(egui::Slider::new(&mut s.quiet_end, 0..=23).text("Quiet until"));
ui.add(egui::Slider::new(&mut s.quiet_start, 0..=23).text(t("Quiet from")));
ui.add(egui::Slider::new(&mut s.quiet_end, 0..=23).text(t("Quiet until")));
});
let mut apps = s.excluded_apps.join(", ");
ui.label("Stay quiet while these apps are in front:");
ui.label(t("Stay quiet while these apps are in front:"));
if ui.text_edit_singleline(&mut apps).lost_focus() {
s.excluded_apps = apps.split(',').map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).collect();
}
@@ -155,20 +197,20 @@ pub fn initiative_page(ui: &mut egui::Ui, store: &SettingsStore, status: &Value)
let reason = status["reason"].as_str().unwrap_or("waiting").replace('_', " ");
let next = status["nextAt"].as_i64().filter(|t| *t > crate::now_ms()).and_then(chrono::DateTime::from_timestamp_millis).map(|t| format!(" · Next attempt: {}", t.with_timezone(&chrono::Local).format("%H:%M"))).unwrap_or_default();
ui.label(format!("Initiative status: {reason}{next}"));
ui.small("Supported media apps: VLC, mpv, Spotify, Celluloid, Haruna and Videos. Opening an app does not prove that anything is playing. Comments never control music, apps or files.");
ui.small(t("Supported media apps: VLC, mpv, Spotify, Celluloid, Haruna and Videos. Opening an app does not prove that anything is playing. Comments never control music, apps or files."));
}
pub fn resources_page(ui: &mut egui::Ui, store: &SettingsStore) {
let before: ResourceSettings = store.section();
let mut s = before.clone();
ui.checkbox(&mut s.memory_monitor, "Resource monitor");
ui.checkbox(&mut s.process_graphs, "Graphs and Capri process load");
ui.checkbox(&mut s.memory_monitor, t("Resource monitor"));
ui.checkbox(&mut s.process_graphs, t("Graphs and Capri process load"));
ui.horizontal(|ui| {
ui.selectable_value(&mut s.memory_style, "rings".into(), "Circles");
ui.selectable_value(&mut s.memory_style, "bars".into(), "Bars");
});
ui.horizontal(|ui| {
ui.label("Refresh every");
ui.label(t("Refresh every"));
for n in [3u8, 5, 10] {
ui.selectable_value(&mut s.memory_interval_seconds, n, format!("{n} s"));
}