capri-perception: add policy module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent e6cdad4387
commit 04a399ef9b
1 file changed
+384
+384
View File
@@ -0,0 +1,384 @@
//! Capture consent: opaque source tokens, a single gesture-bound grant
//! (armed 10 s, single use), watch leases, expiry and revocation. Fails closed: a missing
//! source is never replaced by another window or monitor.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::{bail, ensure, Result};
use serde::Serialize;
use serde_json::{json, Value};
use uuid::Uuid;
use crate::capture::NativeSource;
use crate::platform::DesktopState;
/// Proof that the owner clicked or pressed a key in Capri's own UI. Construct it only inside
/// such an event handler; no IPC, D-Bus, tool or model path may create one.
#[derive(Debug)]
pub struct UserGesture {
_private: (),
}
impl UserGesture {
pub fn owner_clicked() -> Self {
Self { _private: () }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SourceKind {
Window,
Monitor,
Monitors,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
OneShot,
Watch { interval: Duration, duration: Duration },
}
impl Mode {
pub fn watch(interval_ms: u64, duration_ms: u64) -> Result<Self> {
ensure!((15_000..=300_000).contains(&interval_ms) && (30_000..=7_200_000).contains(&duration_ms), "Invalid screen capture mode");
Ok(Self::Watch { interval: Duration::from_millis(interval_ms), duration: Duration::from_millis(duration_ms) })
}
fn name(&self) -> &'static str {
match self {
Self::OneShot => "one-shot",
Self::Watch { .. } => "watch",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum StopReason {
Cancelled,
Completed,
Expired,
FrameChanged,
SourceUnavailable,
CompanionHidden,
ScreenLocked,
SystemSuspended,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Phase {
Armed,
Capturing,
}
/// UI list entry: never a native id.
#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct SourceEntry {
pub id: Uuid,
pub label: String,
#[serde(rename = "type")]
pub kind: SourceKind,
}
struct Entry {
key: String,
label: String,
kind: SourceKind,
native: NativeSource,
expires: Instant,
}
#[derive(Clone, Debug)]
pub struct Grant {
pub id: Uuid,
pub token: Uuid,
pub kind: SourceKind,
pub label: String,
pub native: NativeSource,
pub mode: Mode,
pub phase: Phase,
pub expires: Instant,
checked: Instant,
}
pub type Clock = Arc<dyn Fn() -> Instant + Send + Sync>;
pub struct CapturePolicy {
clock: Clock,
catalog: HashMap<Uuid, Entry>,
pub epoch: u64,
grant: Option<Grant>,
last_stop: Option<Value>,
}
fn key_of(native: &NativeSource) -> String {
match native {
NativeSource::Window(w) => format!("window:{}", w.id),
NativeSource::Output(o) => format!("screen:{}", o.name),
NativeSource::Outputs(list) => format!("monitors:{}", list.iter().map(|o| format!("{}@{},{},{}x{}", o.name, o.rect.x, o.rect.y, o.rect.width, o.rect.height)).collect::<Vec<_>>().join(";")),
}
}
fn clean_label(s: &str) -> String {
let s: String = s.chars().filter(|c| !c.is_control()).take(160).collect();
if s.trim().is_empty() { "Selected source".into() } else { s }
}
/// Native sources currently available, from a pixel-free desktop listing.
pub fn sources(state: &DesktopState) -> Vec<(NativeSource, String, SourceKind)> {
let mut out: Vec<_> = state
.windows
.iter()
.filter(|w| !w.minimized && !w.title.trim().is_empty() && w.rect.width > 0 && w.rect.height > 0)
.take(200)
.map(|w| (NativeSource::Window(w.clone()), clean_label(&w.title), SourceKind::Window))
.collect();
out.extend(state.outputs.iter().map(|o| (NativeSource::Output(o.clone()), clean_label(&o.name), SourceKind::Monitor)));
let mut outputs = state.outputs.clone();
let unique = outputs.iter().map(|o| &o.name).collect::<std::collections::HashSet<_>>().len() == outputs.len();
if (2..=8).contains(&outputs.len()) && unique && outputs.iter().all(|o| o.rect.width > 0 && o.rect.height > 0) {
outputs.sort_by_key(|o| (o.rect.y, o.rect.x));
out.push((NativeSource::Outputs(outputs), "All monitors".into(), SourceKind::Monitors));
}
out
}
impl CapturePolicy {
pub fn new(clock: Clock) -> Self {
Self { clock, catalog: HashMap::new(), epoch: 0, grant: None, last_stop: None }
}
fn now(&self) -> Instant {
(self.clock)()
}
/// Refreshes the source list (stops any capture). Tokens survive identical sources.
pub fn discover(&mut self, state: &DesktopState) -> Vec<SourceEntry> {
self.epoch += 1;
self.stop(StopReason::Cancelled);
let old: HashMap<(String, String), Uuid> = self.catalog.drain().map(|(id, e)| ((e.key, e.label), id)).collect();
let expires = self.now() + Duration::from_secs(30);
let mut list = Vec::new();
for (native, label, kind) in sources(state) {
let key = key_of(&native);
let id = old.get(&(key.clone(), label.clone())).copied().unwrap_or_else(Uuid::new_v4);
list.push(SourceEntry { id, label: label.clone(), kind });
self.catalog.insert(id, Entry { key, label, kind, native, expires });
}
list
}
/// Before every prepare: the token's exact source must still exist.
pub fn renew(&mut self, token: Uuid, state: &DesktopState) -> Result<()> {
let now = self.now();
let entry = self.catalog.get(&token).filter(|e| e.expires > now);
let Some(entry) = entry else { bail!("Choose an available screen source again") };
let current = sources(state).into_iter().find(|(n, l, _)| key_of(n) == entry.key && *l == entry.label);
let Some((native, ..)) = current else {
self.catalog.remove(&token);
bail!("The selected source is no longer available")
};
let e = self.catalog.get_mut(&token).expect("checked above");
e.native = native;
e.expires = now + Duration::from_secs(30);
Ok(())
}
/// Arms a grant for 10 s; any previous capture stops.
pub fn prepare(&mut self, token: Uuid, mode: Mode) -> Result<Uuid> {
let now = self.now();
let entry = self.catalog.get(&token).filter(|e| e.expires > now);
let Some(entry) = entry else { bail!("Choose an available screen source again") };
let grant = Grant {
id: Uuid::new_v4(),
token,
kind: entry.kind,
label: entry.label.clone(),
native: entry.native.clone(),
mode,
phase: Phase::Armed,
expires: now + Duration::from_secs(10),
checked: now,
};
self.stop(StopReason::Cancelled);
let id = grant.id;
self.grant = Some(grant);
Ok(id)
}
/// Consumes an armed grant with the owner's gesture. The exact source must be present in
/// `state` (no fallback); otherwise the grant stops with `source-unavailable`.
pub fn start(&mut self, id: Uuid, _gesture: UserGesture, state: &DesktopState) -> Result<Grant> {
let now = self.now();
let Some(g) = self.grant.as_mut().filter(|g| g.id == id && g.phase == Phase::Armed && g.expires > now) else { bail!("Screen access is off") };
let key = key_of(&g.native);
let Some((native, ..)) = sources(state).into_iter().find(|(n, ..)| key_of(n) == key) else {
self.stop(StopReason::SourceUnavailable);
bail!("The selected source could not be captured. Select it again; camera access stays off.")
};
g.native = native;
g.phase = Phase::Capturing;
g.checked = now;
if let Mode::Watch { duration, .. } = g.mode {
g.expires = now + duration;
}
Ok(g.clone())
}
pub fn grant(&self) -> Option<&Grant> {
self.grant.as_ref()
}
/// Current capturing, unexpired grant with this id. With `state`, re-validates the source
/// (cached 4 s for single sources); a vanished source stops the grant.
pub fn check_active(&mut self, id: Uuid, state: Option<&DesktopState>) -> Option<Grant> {
let now = self.now();
let g = self.grant.as_ref().filter(|g| g.id == id && g.phase == Phase::Capturing)?;
if g.expires <= now {
self.stop(StopReason::Expired);
return None;
}
if g.kind != SourceKind::Monitors && now.duration_since(g.checked) < Duration::from_secs(4) {
return Some(g.clone());
}
let state = state?;
let key = key_of(&g.native);
match sources(state).into_iter().find(|(n, ..)| key_of(n) == key) {
Some((native, ..)) => {
let g = self.grant.as_mut().expect("checked above");
g.native = native;
g.checked = now;
Some(g.clone())
}
None => {
self.stop(StopReason::SourceUnavailable);
None
}
}
}
/// Stops only the capture with this id (a stale id cannot cancel a newer capture).
pub fn release(&mut self, id: Uuid, reason: StopReason) -> bool {
if self.grant.as_ref().is_some_and(|g| g.id == id) {
self.stop(reason);
return true;
}
false
}
pub fn stop(&mut self, reason: StopReason) {
if let Some(g) = self.grant.take() {
let record = json!({"reason": reason, "at": crate::now_ms(), "mode": g.mode.name()});
tracing::info!("Capri screen capture stopped: {record}");
self.last_stop = Some(record);
}
}
/// Hide, lock, suspend, sleep, quit: forget the catalog and stop.
pub fn clear(&mut self, reason: StopReason) {
self.epoch += 1;
self.catalog.clear();
self.stop(reason);
}
/// Display added/removed/changed: "All monitors" tokens die, a monitor-set capture stops.
pub fn topology_changed(&mut self) {
self.catalog.retain(|_, e| e.kind != SourceKind::Monitors);
if self.grant.as_ref().is_some_and(|g| g.kind == SourceKind::Monitors) {
self.stop(StopReason::SourceUnavailable);
}
}
/// `screen.status` (no native ids; `diagnostics` additionally drops the label).
pub fn snapshot(&self) -> Value {
let now = self.now();
let g = self.grant.as_ref();
json!({
"schemaVersion": 1,
"active": g.is_some_and(|g| g.phase == Phase::Capturing && g.expires > now),
"armed": g.is_some_and(|g| g.phase == Phase::Armed),
"phase": g.map_or("off", |g| if g.phase == Phase::Armed { "armed" } else { "capturing" }),
"source": g.map(|g| g.label.clone()),
"allMonitors": g.is_some_and(|g| g.kind == SourceKind::Monitors),
"mode": g.map(|g| g.mode.name()),
"camera": false, "audio": false, "savesImages": false,
})
}
pub fn diagnostics(&self) -> Value {
let mut v = self.snapshot();
v["source"] = Value::Null;
v["lastStop"] = self.last_stop.clone().unwrap_or(Value::Null);
v
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::imaging::Rect;
use crate::platform::{DesktopWindow, Output};
use parking_lot::Mutex;
fn clock() -> (Clock, Arc<Mutex<Instant>>) {
let t = Arc::new(Mutex::new(Instant::now()));
let c = t.clone();
(Arc::new(move || *c.lock()), t)
}
fn state(with_window: bool) -> DesktopState {
let o = |n: &str, x| Output { name: n.into(), rect: Rect { x, y: 0, width: 1920, height: 1080 } };
let w = DesktopWindow { id: "7".into(), title: "Editor".into(), rect: Rect { x: 0, y: 0, width: 800, height: 600 }, ..Default::default() };
DesktopState { windows: if with_window { vec![w] } else { vec![] }, outputs: vec![o("B", 1920), o("A", 0)], cursor: (0, 0) }
}
#[test]
fn tokens_grants_and_failures() {
let (c, t) = clock();
let mut p = CapturePolicy::new(c);
let list = p.discover(&state(true));
assert_eq!(list.len(), 4, "window, two monitors, all monitors");
assert_eq!(p.discover(&state(true)), list, "tokens stable across refresh");
let window = list[0].id;
p.renew(window, &state(true)).unwrap();
let g = p.prepare(window, Mode::OneShot).unwrap();
let g2 = p.prepare(window, Mode::watch(30_000, 60_000).unwrap()).unwrap();
assert!(!p.release(g, StopReason::Cancelled), "stale release cannot cancel a newer grant");
let grant = p.start(g2, UserGesture::owner_clicked(), &state(true)).unwrap();
assert!(p.start(g2, UserGesture::owner_clicked(), &state(true)).is_err(), "second request denied");
assert_eq!(p.snapshot()["active"], true);
assert_eq!(p.diagnostics()["source"], Value::Null);
*t.lock() += Duration::from_secs(5);
assert!(p.check_active(grant.id, Some(&state(false))).is_none(), "window loss: no monitor fallback");
assert_eq!(p.diagnostics()["lastStop"]["reason"], "source-unavailable");
let id = p.prepare(window, Mode::OneShot).unwrap();
*t.lock() += Duration::from_secs(11);
assert!(p.start(id, UserGesture::owner_clicked(), &state(true)).is_err(), "expired arm denied");
assert!(Mode::watch(1_000, 60_000).is_err());
}
#[test]
fn monitor_sets_and_expiry() {
let (c, t) = clock();
let mut p = CapturePolicy::new(c);
let list = p.discover(&state(true));
let all = list.iter().find(|e| e.kind == SourceKind::Monitors).unwrap();
let g = p.prepare(all.id, Mode::watch(15_000, 30_000).unwrap()).unwrap();
let grant = p.start(g, UserGesture::owner_clicked(), &state(true)).unwrap();
match &grant.native {
NativeSource::Outputs(o) => assert_eq!(o[0].name, "A", "sorted by geometry"),
_ => panic!(),
}
p.topology_changed();
assert!(p.grant().is_none());
let w = p.discover(&state(true))[0].id;
let g = p.prepare(w, Mode::watch(15_000, 30_000).unwrap()).unwrap();
p.start(g, UserGesture::owner_clicked(), &state(true)).unwrap();
*t.lock() += Duration::from_secs(31);
assert!(p.check_active(g, None).is_none());
assert_eq!(p.diagnostics()["lastStop"]["reason"], "expired");
}
}