capri-perception: add screen module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent eebd2c6d94
commit 995de6352f
1 file changed
+419
+419
View File
@@ -0,0 +1,419 @@
//! `ScreenController`: one owner of the capture grant, the observation lease, previews and
//! clips. UI buttons call it with a [`UserGesture`]; the chat turn calls [`ScreenController::prepare_turn`]
//! and reads [`ScreenController::observation_context`] / [`ScreenController::state_json`].
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::{anyhow, bail, ensure, Result};
use parking_lot::Mutex;
use serde_json::{json, Value};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
use crate::capture::{self, Capturer, NativeSource};
use crate::clip::{LastScreenshot, ScreenshotFiles};
use crate::imaging;
use crate::llm::{LocalModel, ModelError, SCREEN_VISION_REQUIRED};
use crate::observation::{self, HostState, ScreenContext, ScreenObservation, Source};
use crate::policy::{CapturePolicy, Grant, Mode, SourceEntry, SourceKind, StopReason, UserGesture};
struct Preview {
png: Vec<u8>,
source: Source,
captured_at: i64,
created: Instant,
}
pub struct ScreenController {
capturer: Arc<dyn Capturer>,
model: Mutex<Option<LocalModel>>,
policy: Mutex<CapturePolicy>,
observation: Mutex<ScreenObservation>,
host: Arc<dyn Fn() -> HostState + Send + Sync>,
previews: Mutex<HashMap<Uuid, Preview>>,
files: ScreenshotFiles,
state_dir: PathBuf,
last_screenshot: Mutex<Option<LastScreenshot>>,
last_context: Mutex<Option<ScreenContext>>,
watch: Mutex<Option<CancellationToken>>,
/// Latest `screen.status` + `screen.observation` for the UI (REC/OBS indicator).
pub status: tokio::sync::watch::Sender<Value>,
}
fn source_of(g: &Grant) -> Source {
Source { kind: g.kind, label: g.label.clone() }
}
impl ScreenController {
/// `data_root` holds `screenshots/`, `state_dir` holds `last-screenshot.json`.
pub fn new(capturer: Arc<dyn Capturer>, host: Arc<dyn Fn() -> HostState + Send + Sync>, data_root: PathBuf, state_dir: PathBuf) -> Arc<Self> {
let files = ScreenshotFiles::new(&data_root);
let last = files.load_receipt(&state_dir);
Arc::new(Self {
capturer,
model: Mutex::new(None),
policy: Mutex::new(CapturePolicy::new(Arc::new(Instant::now))),
observation: Mutex::new(ScreenObservation::new(crate::now_ms)),
host,
previews: Mutex::default(),
files,
state_dir,
last_screenshot: Mutex::new(last),
last_context: Mutex::default(),
watch: Mutex::default(),
status: tokio::sync::watch::Sender::new(Value::Null),
})
}
/// The vision model (set at startup; `None` = vision unavailable).
pub fn set_model(&self, model: Option<LocalModel>) {
*self.model.lock() = model;
}
fn model(&self) -> Result<LocalModel> {
self.model.lock().clone().filter(LocalModel::vision_available).ok_or_else(|| anyhow!(SCREEN_VISION_REQUIRED))
}
pub fn vision_available(&self) -> bool {
self.model().is_ok()
}
fn publish(&self) {
let host = (self.host)();
self.status.send_replace(json!({"capture": self.policy.lock().snapshot(), "observation": self.observation.lock().snapshot(host)}));
}
/// Source picker list (pixel-free).
pub async fn discover(&self) -> Result<Vec<SourceEntry>> {
self.stop_watch();
let state = self.capturer.state().await?;
let list = self.policy.lock().discover(&state);
self.publish();
Ok(list)
}
async fn grant(&self, token: Uuid, mode: Mode, gesture: UserGesture) -> Result<Grant> {
let state = self.capturer.state().await?;
let id = {
let mut p = self.policy.lock();
p.renew(token, &state)?;
p.prepare(token, mode)?
};
let grant = self.policy.lock().start(id, gesture, &state);
self.publish();
grant
}
/// One-shot snapshot ("Capture"): returns a preview id and the PNG to show. The grant ends here.
pub async fn capture_snapshot(&self, token: Uuid, gesture: UserGesture) -> Result<(Uuid, Vec<u8>)> {
let grant = self.grant(token, Mode::OneShot, gesture).await?;
let frame = capture::frame(self.capturer.as_ref(), &grant.native).await;
self.policy.lock().release(grant.id, StopReason::Completed);
self.publish();
let png = imaging::encode_png(&frame.map_err(|_| anyhow!("The selected source could not be captured. Select it again; camera access stays off."))?)?;
let id = Uuid::new_v4();
self.previews.lock().insert(id, Preview { png: png.clone(), source: source_of(&grant), captured_at: crate::now_ms(), created: Instant::now() });
Ok((id, png))
}
/// "Ask Capri" on a preview: consumes it (<= 60 s old). Build the turn with `visual::messages`.
pub fn take_preview(&self, id: Uuid) -> Result<(Vec<u8>, Source, i64)> {
self.model()?;
let p = self.previews.lock().remove(&id).filter(|p| p.created.elapsed() <= Duration::from_secs(60)).ok_or_else(|| anyhow!("Take a new snapshot first"))?;
imaging::valid_snapshot(&p.png)?;
Ok((p.png, p.source, p.captured_at))
}
/// Panel closed: previews are discarded.
pub fn close_panel(&self) {
self.previews.lock().clear();
}
/// "Start observation": bounded watch lease and the background tick loop.
pub async fn start_observation(self: &Arc<Self>, token: Uuid, interval_ms: u64, duration_ms: u64, gesture: UserGesture) -> Result<()> {
self.model()?;
let grant = self.grant(token, Mode::watch(interval_ms, duration_ms)?, gesture).await?;
// First frame within 10 s, else the lease is released.
let first = tokio::time::timeout(Duration::from_secs(10), capture::frame(self.capturer.as_ref(), &grant.native)).await;
if !matches!(first, Ok(Ok(_))) {
self.policy.lock().release(grant.id, StopReason::SourceUnavailable);
self.publish();
bail!("The selected source could not be observed. Choose it again.");
}
self.observation.lock().start(grant.id, source_of(&grant), crate::now_ms() + duration_ms as i64, interval_ms as i64);
let cancel = CancellationToken::new();
if let Some(old) = self.watch.lock().replace(cancel.clone()) {
old.cancel();
}
tokio::spawn(self.clone().watch_loop(grant.id, cancel));
self.publish();
Ok(())
}
async fn active(&self, id: Uuid) -> Option<Grant> {
if let Some(g) = self.policy.lock().check_active(id, None) {
return Some(g);
}
let state = self.capturer.state().await.ok();
self.policy.lock().check_active(id, state.as_ref())
}
async fn watch_loop(self: Arc<Self>, id: Uuid, cancel: CancellationToken) {
let mut failures = 0;
loop {
let monitors = self.policy.lock().grant().is_some_and(|g| g.kind == SourceKind::Monitors);
let pause = if monitors || failures > 0 { 5 } else { 2 };
tokio::select! { _ = cancel.cancelled() => break, _ = tokio::time::sleep(Duration::from_secs(pause)) => {} }
let Some(grant) = self.active(id).await else { break };
match self.tick(&grant, &cancel).await {
Ok(()) => failures = 0,
Err(_) => {
failures += 1;
if failures >= 3 {
tracing::info!("Screen observation stopped after 3 failed updates");
self.policy.lock().release(id, StopReason::SourceUnavailable);
break;
}
}
}
self.publish();
}
self.observation.lock().stop();
self.publish();
}
async fn tick(&self, grant: &Grant, cancel: &CancellationToken) -> Result<()> {
let frame = capture::frame(self.capturer.as_ref(), &grant.native).await?;
let signature = imaging::signature(&frame);
let host = (self.host)();
if !self.observation.lock().sample(grant.id, signature.clone(), host) {
return Ok(());
}
let Some((generation, token)) = self.observation.lock().begin_background(grant.id, &signature, host) else { return Ok(()) };
let png = imaging::encode_png(&frame)?;
let model = self.model()?;
let result = tokio::select! {
_ = cancel.cancelled() => Err(ModelError::Cancelled),
r = observation::describe(&model, &png, grant.kind, None, Duration::from_secs(12), &token) => r,
};
let ok = result.is_ok() || matches!(result, Err(ModelError::Cancelled));
if self.active(grant.id).await.is_some() {
self.observation.lock().finish_background(grant.id, generation, signature, result, crate::now_ms(), (self.host)());
}
ensure!(ok, "Screen update skipped");
Ok(())
}
/// A fresh frame from the active watch lease (Ask Capri while observing, clips).
pub async fn observed_frame(&self) -> Result<(Vec<u8>, Source)> {
let id = self.policy.lock().grant().filter(|g| matches!(g.mode, Mode::Watch { .. })).map(|g| g.id).ok_or_else(|| anyhow!("Screen access is off"))?;
let grant = self.active(id).await.ok_or_else(|| anyhow!("Selected source is unavailable"))?;
let frame = tokio::time::timeout(Duration::from_secs(4), capture::frame(self.capturer.as_ref(), &grant.native)).await.map_err(|_| anyhow!("Selected source is unavailable"))??;
ensure!(self.policy.lock().grant().is_some_and(|g| g.id == id), "Screen access is off");
Ok((imaging::encode_png(&frame)?, source_of(&grant)))
}
/// Per chat turn: fresh foreground analysis when observing. A failure never fails the
/// turn and never substitutes an older scene. Cancellation of the turn propagates as `None`.
pub async fn prepare_turn(&self, question: &str, cancel: &CancellationToken) -> Option<ScreenContext> {
let context = self.prepare_inner(question, cancel).await;
*self.last_context.lock() = context.clone();
self.publish();
context
}
async fn prepare_inner(&self, question: &str, cancel: &CancellationToken) -> Option<ScreenContext> {
let id = self.observation.lock().session_id()?;
let model = self.model().ok()?;
let fallback = || Some(ScreenContext { active: true, current: false, observation: None });
let Ok((png, source)) = self.observed_frame().await else {
return self.observation.lock().session_id().filter(|s| *s == id).and_then(|_| fallback());
};
let token = self.observation.lock().begin_foreground(id).ok()?;
let result = tokio::select! {
_ = cancel.cancelled() => Err(ModelError::Cancelled),
r = observation::describe(&model, &png, source.kind, Some(question), Duration::from_secs(20), &token) => r,
};
if cancel.is_cancelled() {
return None;
}
let ok = result.is_ok();
let context = self.observation.lock().finish_foreground(id, result, crate::now_ms());
if ok { context } else { self.observation.lock().session_id().filter(|s| *s == id).and_then(|_| fallback()) }
}
/// Text appended to this turn's context.
pub fn observation_context(&self, question: &str) -> String {
observation::observation_text(self.last_context.lock().as_ref(), question)
}
/// `StateProvider` fields: `screenObservation`, `screenVisionAvailable` (only when false),
/// `previousScreenshotSaved`.
pub fn state_json(&self) -> Value {
let mut v = json!({
"screenObservation": self.observation.lock().context().is_some_and(|c| c.active),
"previousScreenshotSaved": self.last_screenshot.lock().is_some(),
});
if !self.vision_available() {
v["screenVisionAvailable"] = json!(false);
}
v
}
pub fn observation_active(&self) -> bool {
self.observation.lock().context().is_some()
}
/// Owner activity (typing, microphone, sending, playback).
pub fn activity(&self) {
self.observation.lock().activity();
}
fn stop_watch(&self) {
if let Some(t) = self.watch.lock().take() {
t.cancel();
}
self.observation.lock().stop();
}
/// Stop button / tray "Stop screen observation".
pub fn stop(&self) {
self.stop_watch();
self.policy.lock().stop(StopReason::Cancelled);
self.previews.lock().clear();
self.publish();
}
/// Hide, lock, suspend, model sleep, quit: everything off; nothing resumes automatically.
pub fn discard(&self, reason: StopReason) {
self.stop_watch();
self.policy.lock().clear(reason);
self.previews.lock().clear();
*self.last_context.lock() = None;
self.publish();
}
pub fn topology_changed(&self) {
self.policy.lock().topology_changed();
if self.policy.lock().grant().is_none() {
self.stop_watch();
}
self.publish();
}
/// "Clip that": reuse a file for the same command id; else the active watch lease
/// (never a fallback) or, without a capture, the monitor of the foreground window at native
/// resolution. Returns the saved path; the app plays the shutter and says [`crate::clip::CLIPPED`].
pub async fn clip(&self, command_id: Uuid, locked: bool) -> Result<PathBuf> {
ensure!(!locked, "The session is locked");
let id = command_id.to_string();
if let Some(path) = self.files.saved(&id)? {
return Ok(path);
}
let has_capture = self.policy.lock().grant().is_some();
let (png, source) = if has_capture {
let (png, s) = self.observed_frame().await?;
(png, json!({"kind": s.kind, "label": s.label}))
} else {
let (image, _) = tokio::time::timeout(Duration::from_secs(15), capture::active_display(self.capturer.as_ref())).await.map_err(|_| anyhow!("Capture timed out"))??;
(imaging::encode_png(&image)?, json!({"kind": "monitor", "label": "Active display"}))
};
let path = self.files.save(&id, &png)?;
let receipt = self.files.receipt(&id, crate::now_ms(), source);
if let Err(e) = ScreenshotFiles::store_receipt(&self.state_dir, &receipt) {
tracing::warn!("Screenshot receipt not saved: {e}");
}
*self.last_screenshot.lock() = Some(receipt);
Ok(path)
}
pub fn screenshots_folder(&self) -> Result<PathBuf> {
self.files.folder()
}
/// Status snapshot for diagnostics (no labels).
pub fn diagnostics(&self) -> Value {
self.policy.lock().diagnostics()
}
/// The grant source kind/label of an active capture, for the REC/OBS indicator.
pub fn indicator(&self) -> Option<(SourceKind, String, bool)> {
self.policy.lock().grant().map(|g| (g.kind, g.label.clone(), matches!(g.mode, Mode::Watch { .. })))
}
#[doc(hidden)]
pub fn native_of_grant(&self) -> Option<NativeSource> {
self.policy.lock().grant().map(|g| g.native.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::imaging::Rect;
use crate::platform::{DesktopState, DesktopWindow, Output};
use async_trait::async_trait;
use image::RgbImage;
struct Fake {
window: Mutex<bool>,
}
#[async_trait]
impl Capturer for Fake {
async fn state(&self) -> Result<DesktopState> {
let w = DesktopWindow { id: "5".into(), title: "Editor".into(), rect: Rect { x: 0, y: 0, width: 640, height: 480 }, active: true, output: "A".into(), ..Default::default() };
Ok(DesktopState { windows: if *self.window.lock() { vec![w] } else { vec![] }, outputs: vec![Output { name: "A".into(), rect: Rect { x: 0, y: 0, width: 800, height: 600 } }], cursor: (0, 0) })
}
async fn window(&self, _: &DesktopWindow) -> Result<RgbImage> {
Ok(RgbImage::new(640, 480))
}
async fn output(&self, o: &Output, _: bool) -> Result<RgbImage> {
Ok(RgbImage::new(o.rect.width, o.rect.height))
}
}
fn controller() -> (Arc<ScreenController>, tempfile::TempDir, Arc<Fake>) {
let dir = tempfile::tempdir().unwrap();
let fake = Arc::new(Fake { window: Mutex::new(true) });
let state = dir.path().join("desktop");
std::fs::create_dir(&state).unwrap();
let c = ScreenController::new(fake.clone(), Arc::new(HostState::default), dir.path().to_path_buf(), state);
(c, dir, fake)
}
#[tokio::test]
async fn snapshot_preview_and_clip() {
let (c, _dir, _) = controller();
let list = c.discover().await.unwrap();
let (preview, png) = c.capture_snapshot(list[0].id, UserGesture::owner_clicked()).await.unwrap();
assert_eq!(imaging::png_dimensions(&png, 3 << 20, 1280, 720).unwrap(), (640, 480));
assert!(c.take_preview(preview).is_err(), "vision unavailable without a model");
assert_eq!(c.status.borrow()["capture"]["phase"], "off", "one-shot grant released");
assert_eq!(c.state_json(), json!({"screenObservation": false, "previousScreenshotSaved": false, "screenVisionAvailable": false}));
let id = Uuid::new_v4();
let path = c.clip(id, false).await.unwrap();
assert_eq!(c.clip(id, false).await.unwrap(), path, "replay reuses the file");
assert_eq!(c.state_json()["previousScreenshotSaved"], true);
assert!(c.clip(Uuid::new_v4(), true).await.is_err());
}
#[tokio::test]
async fn observation_lifecycle_and_source_loss() {
let (c, _dir, fake) = controller();
c.set_model(Some(LocalModel::new("http://127.0.0.1:9", "m", None, json!({})).unwrap()));
let list = c.discover().await.unwrap();
c.start_observation(list[0].id, 15_000, 60_000, UserGesture::owner_clicked()).await.unwrap();
assert!(c.observation_active());
assert_eq!(c.state_json()["screenObservation"], true);
let (png, source) = c.observed_frame().await.unwrap();
assert!(imaging::valid_snapshot(&png).is_ok() && source.label == "Editor");
assert!(c.clip(Uuid::new_v4(), false).await.is_ok(), "clips use the active lease");
c.discard(StopReason::ScreenLocked);
assert!(!c.observation_active());
assert!(c.observed_frame().await.is_err(), "nothing resumes after a lock");
*fake.window.lock() = false;
assert!(c.discover().await.unwrap().iter().all(|e| e.kind != SourceKind::Window));
}
}