capri: add desktop module
This commit is contained in:
1 file changed
+472
@@ -0,0 +1,472 @@
|
|||||||
|
//! Screen perception and computer control wiring (`capri-perception`, `capri-computer`):
|
||||||
|
//! the screen controller and its per-turn context, the `desktop_control` / `workflow_control`
|
||||||
|
//! tools, the indicator overlay, awareness-driven revocation and their settings pages.
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use capri_agent::tools::{StateProvider, Tool};
|
||||||
|
use capri_agent::{Engine, TurnEvent};
|
||||||
|
use capri_computer::{access, a11y, native::Native, planner::Planner, Backends, ComputerControl, DesktopControl, Indicator, WorkflowControl};
|
||||||
|
use capri_core::{Paths, SettingsStore};
|
||||||
|
use capri_perception::llm::LocalModel;
|
||||||
|
use capri_perception::observation::HostState;
|
||||||
|
use capri_perception::platform::{process, Desktop};
|
||||||
|
use capri_perception::policy::StopReason;
|
||||||
|
use capri_perception::ScreenController;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use serde_json::json;
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct DesktopFeatures {
|
||||||
|
pub screen: Option<Arc<ScreenController>>,
|
||||||
|
pub computer: Option<Arc<DesktopControl>>,
|
||||||
|
pub awareness: Option<capri_perception::awareness::Awareness>,
|
||||||
|
pub ui: Option<capri_ui::UiHandle>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The computer-control indicator drawn by `capri-ui` on every monitor, with the real pointer
|
||||||
|
/// fed to its reticle (KDE: persistent KWin script; X11: pointer query every 33 ms).
|
||||||
|
struct UiIndicator {
|
||||||
|
ui: Option<capri_ui::UiHandle>,
|
||||||
|
desktop: Desktop,
|
||||||
|
store: Arc<SettingsStore>,
|
||||||
|
feed: Mutex<Option<CancellationToken>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `capri_linux/cursor.py`: reports the real cursor (XWayland only sees it over X11 windows).
|
||||||
|
const CURSOR_SCRIPT: &str = r#"
|
||||||
|
let last = 0;
|
||||||
|
function report() {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - last < 16) return;
|
||||||
|
last = now;
|
||||||
|
const p = workspace.cursorPos;
|
||||||
|
callDBus("%NAME%", "/", "org.capri.Report", "Report", "%TAG%\n" + Math.round(p.x) + "," + Math.round(p.y));
|
||||||
|
}
|
||||||
|
workspace.cursorPosChanged.connect(report);
|
||||||
|
report();
|
||||||
|
"#;
|
||||||
|
const CURSOR_PLUGIN: &str = "capri-cursor";
|
||||||
|
|
||||||
|
impl UiIndicator {
|
||||||
|
async fn start_feed(&self, ui: capri_ui::UiHandle) {
|
||||||
|
let cancel = CancellationToken::new();
|
||||||
|
if let Some(old) = self.feed.lock().replace(cancel.clone()) {
|
||||||
|
old.cancel();
|
||||||
|
}
|
||||||
|
match &self.desktop {
|
||||||
|
Desktop::Kde(kwin) => match kwin.persistent(CURSOR_PLUGIN, CURSOR_SCRIPT).await {
|
||||||
|
Ok(mut reports) => {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let report = tokio::select! { _ = cancel.cancelled() => break, r = reports.recv() => r };
|
||||||
|
let Some(report) = report else { break };
|
||||||
|
if let Some((x, y)) = report.split_once(',').and_then(|(x, y)| Some((x.trim().parse::<f32>().ok()?, y.trim().parse::<f32>().ok()?))) {
|
||||||
|
ui.set_control_pointer(Some([x, y]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(e) => tracing::warn!("cursor feed unavailable: {e:#}"),
|
||||||
|
},
|
||||||
|
Desktop::X11(x) => {
|
||||||
|
let x = x.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while !cancel.is_cancelled() {
|
||||||
|
if let Ok((px, py, _)) = x.pointer() {
|
||||||
|
ui.set_control_pointer(Some([px as f32, py as f32]));
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(33)).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Indicator for UiIndicator {
|
||||||
|
async fn show(&self, caption: &str) -> Result<()> {
|
||||||
|
let ui = self.ui.clone().ok_or_else(|| anyhow::anyhow!("No desktop interface"))?;
|
||||||
|
let state = self.desktop.state(false).await?;
|
||||||
|
let monitors = state.outputs.iter().map(|o| [o.rect.x as f32, o.rect.y as f32, o.rect.width as f32, o.rect.height as f32]).collect();
|
||||||
|
let a: access::ComputerAppearance = self.store.section();
|
||||||
|
ui.set_control_pointer(Some([state.cursor.0 as f32, state.cursor.1 as f32]));
|
||||||
|
ui.set_control_overlay(Some(capri_ui::ControlOverlay { caption: caption.into(), monitors, effects: a.enabled, intensity: a.intensity.min(100) as f32, blackwall: a.theme == "blackwall", cursor: a.cursor }));
|
||||||
|
self.start_feed(ui.clone()).await;
|
||||||
|
let end = Instant::now() + Duration::from_secs(5);
|
||||||
|
while !ui.control_overlay_visible() {
|
||||||
|
anyhow::ensure!(Instant::now() < end, "Computer control indicator did not become visible.");
|
||||||
|
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
async fn hide(&self) {
|
||||||
|
if let Some(t) = self.feed.lock().take() {
|
||||||
|
t.cancel();
|
||||||
|
}
|
||||||
|
if let Desktop::Kde(kwin) = &self.desktop {
|
||||||
|
kwin.unload(CURSOR_PLUGIN).await;
|
||||||
|
}
|
||||||
|
if let Some(ui) = &self.ui {
|
||||||
|
ui.set_control_overlay(None);
|
||||||
|
ui.set_control_pointer(None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn visible(&self) -> bool {
|
||||||
|
self.ui.as_ref().is_some_and(|ui| ui.control_overlay_visible())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `trash` scopes come from the file tools' folder grants.
|
||||||
|
struct Scopes(capri_tools::files::Access);
|
||||||
|
|
||||||
|
impl capri_computer::tool::FileScopes for Scopes {
|
||||||
|
fn target(&self, scope_id: &str, path: &str) -> Result<std::path::PathBuf> {
|
||||||
|
Ok(self.0.target(scope_id, path, true)?.path)
|
||||||
|
}
|
||||||
|
fn is_installation(&self, scope_id: &str) -> bool {
|
||||||
|
self.0.scope(scope_id, false).is_ok_and(|s| self.0.is_installation(&s))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Live values for `capri-tools` (`settings_control status`, file scopes).
|
||||||
|
pub fn external(store: &Arc<SettingsStore>, screen: Option<Arc<ScreenController>>) -> StateProvider {
|
||||||
|
let store = store.clone();
|
||||||
|
Arc::new(move || json!({"fullComputerAccess": access::allowed(&store), "screenObservation": screen.as_ref().is_some_and(|s| s.observation_active())}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the screen controller. `None` outside KDE Plasma / X11.
|
||||||
|
pub async fn start_screen(paths: &Paths, engine: &Arc<Engine>, local: Option<LocalModel>) -> Option<(Arc<ScreenController>, Desktop)> {
|
||||||
|
let desktop = match Desktop::connect().await {
|
||||||
|
Ok(d) => d,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("screen and computer control unavailable: {e:#}");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let weak = Arc::downgrade(engine);
|
||||||
|
let host = Arc::new(move || HostState { busy: weak.upgrade().is_some_and(|e| e.busy()), ..Default::default() });
|
||||||
|
let screen = ScreenController::new(Arc::new(desktop.clone()), host, paths.data.clone(), paths.state());
|
||||||
|
screen.set_model(local.filter(LocalModel::vision_available));
|
||||||
|
// Per turn: fresh foreground analysis while observing, then the observation block.
|
||||||
|
let ctx_screen = screen.clone();
|
||||||
|
engine.add_context(Arc::new(move |text: String| {
|
||||||
|
let screen = ctx_screen.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
screen.prepare_turn(&text, &CancellationToken::new()).await;
|
||||||
|
screen.observation_context(&text)
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
let state_screen = screen.clone();
|
||||||
|
engine.add_state(Arc::new(move || state_screen.state_json()));
|
||||||
|
tracing::info!("screen perception ready ({:?}, vision {})", desktop.platform(), screen.vision_available());
|
||||||
|
Some((screen, desktop))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds computer control and its tools; awareness revokes screen and control on lock/suspend.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub async fn start_computer(paths: &Paths, store: &Arc<SettingsStore>, engine: &Arc<Engine>, desktop: Desktop, screen: Arc<ScreenController>, local: Option<LocalModel>, external: StateProvider, ui: Option<capri_ui::UiHandle>) -> DesktopFeatures {
|
||||||
|
let mut out = DesktopFeatures { screen: Some(screen.clone()), ui: ui.clone(), ..Default::default() };
|
||||||
|
let computer = async {
|
||||||
|
let local = local.clone().ok_or_else(|| anyhow::anyhow!("computer control needs the local model on 127.0.0.1"))?;
|
||||||
|
let (backends, _) = Backends::connect(&paths.data).await?;
|
||||||
|
let native = Arc::new(Native { windows: backends.windows.clone(), input: backends.input.clone(), a11y: Arc::new(a11y::Atspi::connect().await?), allowed: Arc::new(|pid| process::allowed(pid, 0)) });
|
||||||
|
let allowed = {
|
||||||
|
let s = store.clone();
|
||||||
|
Arc::new(move || access::allowed(&s))
|
||||||
|
};
|
||||||
|
let indicator = Arc::new(UiIndicator { ui: ui.clone(), desktop: desktop.clone(), store: store.clone(), feed: Mutex::default() });
|
||||||
|
let control = ComputerControl::new(native.clone(), backends.escape.clone(), indicator, Some(Arc::new(desktop.clone())), allowed);
|
||||||
|
control.set_vision(Some(local.clone()).filter(LocalModel::vision_available));
|
||||||
|
let appearance: access::ComputerAppearance = store.section();
|
||||||
|
control.pointer_duration.store(appearance.pointer_duration.min(1000) as u64, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
let browsers: Vec<String> = capri_tools::catalog().into_iter().filter(|a| capri_computer::apps::BROWSERS.iter().any(|b| a.id.to_lowercase().contains(b))).map(|a| a.name).collect();
|
||||||
|
let files: Option<Arc<dyn capri_computer::tool::FileScopes>> = capri_tools::files::Access::new(store.clone(), paths, external).ok().map(|a| Arc::new(Scopes(a)) as _);
|
||||||
|
let lang_store = store.clone();
|
||||||
|
let tool = DesktopControl::new(store.clone(), native, control.clone(), Planner::new(Arc::new(local.clone()), browsers), files, Arc::new(move || lang_store.get().language.conversation))?;
|
||||||
|
anyhow::Ok((tool, control, local))
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
install_reply_guard(engine, store);
|
||||||
|
match computer {
|
||||||
|
Ok((tool, control, local)) => {
|
||||||
|
install_router(engine, store, &tool, local, ui.clone());
|
||||||
|
if let Some(ui) = &ui {
|
||||||
|
// Input pulses and control phases drive the overlay effects.
|
||||||
|
let (mut steps, ui1) = (control.events.subscribe(), ui.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut last = 0;
|
||||||
|
while steps.changed().await.is_ok() {
|
||||||
|
let n = steps.borrow_and_update()["steps"].as_u64().unwrap_or(0);
|
||||||
|
if n > last {
|
||||||
|
ui1.control_pulse();
|
||||||
|
}
|
||||||
|
last = n;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let (mut phases, ui2) = (tool.agent().progress.subscribe(), ui.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while phases.changed().await.is_ok() {
|
||||||
|
let phase = phases.borrow_and_update()["phase"].as_str().unwrap_or("").to_string();
|
||||||
|
ui2.control_phase(&phase);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let rt = tokio::runtime::Handle::current();
|
||||||
|
if let Some(ui) = &ui {
|
||||||
|
let stop = control.clone();
|
||||||
|
let rt = rt.clone();
|
||||||
|
ui.on_stop_control(Arc::new(move || {
|
||||||
|
let stop = stop.clone();
|
||||||
|
rt.spawn(async move { stop.stop(true).await });
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
let turns = control.clone();
|
||||||
|
engine.add_observer(Arc::new(move |event: &TurnEvent| {
|
||||||
|
if let TurnEvent::Completed { turn_id, .. } | TurnEvent::Failed { turn_id, .. } | TurnEvent::Cancelled { turn_id } = event {
|
||||||
|
let (control, turn) = (turns.clone(), turn_id.clone());
|
||||||
|
rt.spawn(async move { control.turn_ended(&turn).await });
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
tracing::info!("computer control ready ({:?})", desktop.platform());
|
||||||
|
out.computer = Some(tool);
|
||||||
|
}
|
||||||
|
Err(e) => tracing::warn!("computer control unavailable: {e:#}"),
|
||||||
|
}
|
||||||
|
// Lock, suspend and display changes revoke screen access and stop control (never resumed).
|
||||||
|
match capri_perception::awareness::Awareness::start(desktop, vec![]).await {
|
||||||
|
Ok((awareness, mut events)) => {
|
||||||
|
let control = out.computer.as_ref().map(|c| c.control.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
|
use capri_perception::awareness::Kind;
|
||||||
|
while let Some(event) = events.recv().await {
|
||||||
|
let reason = match event.map(|e| e.kind) {
|
||||||
|
None => {
|
||||||
|
screen.topology_changed();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Some(Kind::SessionLock) => StopReason::ScreenLocked,
|
||||||
|
Some(Kind::PowerSuspend) => StopReason::SystemSuspended,
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
screen.discard(reason);
|
||||||
|
if let Some(c) = &control {
|
||||||
|
c.stop(true).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
tracing::info!("desktop awareness active");
|
||||||
|
out.awareness = Some(awareness);
|
||||||
|
}
|
||||||
|
Err(e) => tracing::warn!("desktop awareness unavailable: {e:#}"),
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DesktopFeatures {
|
||||||
|
pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
|
||||||
|
match &self.computer {
|
||||||
|
Some(c) => vec![c.clone() as Arc<dyn Tool>, Arc::new(WorkflowControl(c.clone()))],
|
||||||
|
None => vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn stop(&self) {
|
||||||
|
if let Some(c) = &self.computer {
|
||||||
|
c.control.stop(true).await;
|
||||||
|
}
|
||||||
|
if let Some(s) = &self.screen {
|
||||||
|
s.discard(StopReason::Cancelled);
|
||||||
|
}
|
||||||
|
if let Some(a) = &self.awareness {
|
||||||
|
a.stop().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Screen snapshot, Initiative, Resources, Computer control and Workflows pages.
|
||||||
|
pub fn pages(&self, store: &Arc<SettingsStore>, rt: &tokio::runtime::Handle) -> Vec<capri_ui::SettingsPage> {
|
||||||
|
let page = |section: &str, title: &str, draw: Box<dyn FnMut(&mut egui::Ui) + Send>| capri_ui::SettingsPage { section: section.into(), title: title.into(), draw };
|
||||||
|
let mut pages = vec![];
|
||||||
|
if let Some(screen) = self.screen.clone() {
|
||||||
|
let (store, rt) = (store.clone(), rt.clone());
|
||||||
|
let panel = Arc::new(Mutex::new(capri_perception::ui::ScreenPanel::default()));
|
||||||
|
pages.push(page(
|
||||||
|
"screen",
|
||||||
|
"Screen snapshot",
|
||||||
|
Box::new(move |ui| {
|
||||||
|
let status = screen.status.borrow().clone();
|
||||||
|
let requests = capri_perception::ui::screen_page(ui, &store, &mut panel.lock(), &status);
|
||||||
|
for request in requests {
|
||||||
|
let (screen, panel) = (screen.clone(), panel.clone());
|
||||||
|
rt.spawn(async move {
|
||||||
|
use capri_perception::ui::ScreenRequest;
|
||||||
|
let result = match request {
|
||||||
|
ScreenRequest::Refresh => screen.discover().await.map(|list| panel.lock().sources = list),
|
||||||
|
ScreenRequest::Capture(id, gesture) => screen.capture_snapshot(id, gesture).await.map(|_| ()),
|
||||||
|
ScreenRequest::Start { source, interval_ms, duration_ms, gesture } => screen.start_observation(source, interval_ms, duration_ms, gesture).await,
|
||||||
|
ScreenRequest::Stop => {
|
||||||
|
screen.stop();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
ScreenRequest::OpenFolder => match screen.screenshots_folder() {
|
||||||
|
Ok(dir) => capri_perception::clip::open_with_default(&dir).await,
|
||||||
|
Err(e) => Err(e),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if let Err(e) = result {
|
||||||
|
tracing::warn!("screen: {e:#}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let s = store.clone();
|
||||||
|
pages.push(page("initiative", "Initiative", Box::new(move |ui| capri_perception::ui::initiative_page(ui, &s, &serde_json::Value::Null))));
|
||||||
|
let s = store.clone();
|
||||||
|
pages.push(page("resources", "Resources", Box::new(move |ui| capri_perception::ui::resources_page(ui, &s))));
|
||||||
|
if let Some(computer) = self.computer.clone() {
|
||||||
|
let (s, rt, ui_handle) = (store.clone(), rt.clone(), self.ui.clone());
|
||||||
|
let workflows = computer.clone();
|
||||||
|
let wrt = rt.clone();
|
||||||
|
pages.push(page(
|
||||||
|
"computer",
|
||||||
|
"Computer control",
|
||||||
|
Box::new(move |ui| {
|
||||||
|
for request in capri_computer::ui::computer_page(ui, &s, &computer) {
|
||||||
|
let (s, computer, approvals) = (s.clone(), computer.clone(), ui_handle.clone());
|
||||||
|
rt.spawn(async move { run_request(request, &s, &computer, approvals).await });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
let s = store.clone();
|
||||||
|
let approvals = self.ui.clone();
|
||||||
|
pages.push(page(
|
||||||
|
"workflows",
|
||||||
|
"Task training",
|
||||||
|
Box::new(move |ui| {
|
||||||
|
for request in capri_computer::ui::workflows_page(ui, &workflows) {
|
||||||
|
let (s, computer, approvals) = (s.clone(), workflows.clone(), approvals.clone());
|
||||||
|
wrt.spawn(async move { run_request(request, &s, &computer, approvals).await });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
pages
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Computer requests run on the host before any model turn.
|
||||||
|
fn install_router(engine: &Arc<Engine>, store: &Arc<SettingsStore>, tool: &Arc<DesktopControl>, local: LocalModel, ui: Option<capri_ui::UiHandle>) {
|
||||||
|
// The owner's previous message (references such as "sur firefox"), from the turn events.
|
||||||
|
// (previous, current) owner messages with their time (ms).
|
||||||
|
type Owner = (Option<(String, i64)>, Option<(String, i64)>);
|
||||||
|
let owner: Arc<Mutex<Owner>> = Arc::default();
|
||||||
|
let seen = owner.clone();
|
||||||
|
engine.add_observer(Arc::new(move |event: &TurnEvent| {
|
||||||
|
if let TurnEvent::Started { text, .. } = event {
|
||||||
|
let mut o = seen.lock();
|
||||||
|
o.0 = o.1.take();
|
||||||
|
o.1 = Some((text.clone(), capri_perception::now_ms()));
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
let previous: capri_computer::route::PreviousOwner = Arc::new(move || owner.lock().0.clone());
|
||||||
|
let approvals: Arc<dyn capri_agent::tools::Approvals> = match ui {
|
||||||
|
Some(ui) => Arc::new(ui),
|
||||||
|
None => Arc::new(capri_agent::tools::DenyAll),
|
||||||
|
};
|
||||||
|
let router = Arc::new(capri_computer::route::ComputerRouter::new(tool.clone(), store.clone(), local, approvals, previous));
|
||||||
|
let weak = Arc::downgrade(engine);
|
||||||
|
let lang_store = store.clone();
|
||||||
|
engine.set_router(Arc::new(move |text: String, turn: String, cancel: CancellationToken| {
|
||||||
|
let router = router.clone();
|
||||||
|
let engine = weak.upgrade();
|
||||||
|
let internet = engine.as_ref().is_some_and(|e| e.internet());
|
||||||
|
let settings = lang_store.get();
|
||||||
|
Box::pin(async move {
|
||||||
|
let summary = router.route(&text, &turn, internet, &cancel).await?;
|
||||||
|
let model = engine.map(|e| e.model().to_string()).unwrap_or_else(|| settings.model.clone());
|
||||||
|
Some(translate_summary(summary, &settings, &model).await)
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Computer control reports in English; the owner reads the conversation language.
|
||||||
|
async fn translate_summary(summary: String, settings: &capri_core::Settings, model: &str) -> String {
|
||||||
|
let code = settings.language.conversation.as_str();
|
||||||
|
if code == "en" || summary.trim().is_empty() {
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
let language = if code == "custom" {
|
||||||
|
settings.language.custom_conversation.clone()
|
||||||
|
} else {
|
||||||
|
capri_core::persona::languages().iter().find(|l| l.id == code).map_or_else(|| code.to_string(), |l| l.name.clone())
|
||||||
|
};
|
||||||
|
let request = capri_llm::ChatRequest {
|
||||||
|
model: model.to_string(),
|
||||||
|
messages: vec![
|
||||||
|
capri_llm::Message::new("system", format!("Translate the user's status message into {language}. Keep every fact, name, number and URL. Output only the translation, as plain text.")),
|
||||||
|
capri_llm::Message::new("user", summary.clone()),
|
||||||
|
],
|
||||||
|
tools: vec![],
|
||||||
|
options: capri_llm::Options { num_ctx: 2048, temperature: 0.1, repeat_last_n: 64, num_predict: Some(256), ..Default::default() },
|
||||||
|
keep_alive: settings.keep_alive,
|
||||||
|
stream: true,
|
||||||
|
think: Some(false),
|
||||||
|
};
|
||||||
|
let client = capri_llm::Ollama::new(settings.ollama_base_url());
|
||||||
|
match tokio::time::timeout(std::time::Duration::from_secs(20), client.chat(&request, |_| {})).await {
|
||||||
|
Ok(Ok(done)) if !done.content.trim().is_empty() => capri_agent::stream::plain_dialogue_text(done.content.trim()),
|
||||||
|
other => {
|
||||||
|
tracing::warn!("computer summary not translated: {:?}", other.map(|r| r.map(|d| d.content.len())));
|
||||||
|
summary
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Receipts for verified mutations; a reply claiming an action that no tool performed
|
||||||
|
/// gets an explicit correction.
|
||||||
|
fn install_reply_guard(engine: &Arc<Engine>, store: &Arc<SettingsStore>) {
|
||||||
|
const ACTION_TOOLS: [&str; 7] = ["desktop_control", "application_control", "filesystem_control", "spotify_control", "workflow_control", "time_control", "settings_control"];
|
||||||
|
let store = store.clone();
|
||||||
|
engine.set_reply_guard(Arc::new(move |reply: &str, calls: &[capri_agent::engine::ToolCallRecord]| {
|
||||||
|
let mut receipts: Vec<String> = vec![];
|
||||||
|
for (name, args, result) in calls {
|
||||||
|
if let Some(r) = capri_tools::factual_action_reply(name, args, result).map(|r| capri_ui::i18n::t(&r))
|
||||||
|
&& !receipts.contains(&r)
|
||||||
|
&& !reply.contains(&r)
|
||||||
|
{
|
||||||
|
receipts.push(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !receipts.is_empty() {
|
||||||
|
return Some(receipts.into_iter().take(8).collect::<Vec<_>>().join(" "));
|
||||||
|
}
|
||||||
|
let actions = calls.iter().filter(|(n, _, r)| ACTION_TOOLS.contains(&n.as_str()) && r["ok"] == true).count();
|
||||||
|
let lang = store.get().language.conversation;
|
||||||
|
capri_computer::route::unbacked_action_claim(reply, actions).then(|| capri_computer::route::no_action_text(&lang).to_string())
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_request(request: capri_computer::ui::ComputerRequest, store: &Arc<SettingsStore>, computer: &Arc<DesktopControl>, approvals: Option<capri_ui::UiHandle>) {
|
||||||
|
use capri_computer::ui::ComputerRequest;
|
||||||
|
match request {
|
||||||
|
ComputerRequest::EnableFullAccess => {
|
||||||
|
let Some(ui) = approvals else { return };
|
||||||
|
let ru = store.get().language.conversation == "ru";
|
||||||
|
access::configure(store, &ui, true, ru).await;
|
||||||
|
}
|
||||||
|
ComputerRequest::Stop => {
|
||||||
|
computer.control.stop(true).await;
|
||||||
|
}
|
||||||
|
ComputerRequest::RunWorkflow(id) => {
|
||||||
|
if let Err(e) = computer.workflows.run(&computer.control, &id, &Default::default()).await {
|
||||||
|
tracing::warn!("workflow: {e:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user