Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(host-core): expose computer use over computer.* RPC
vastsa91b3ccfd974e
diff --git a/crates/host-core/src/computer/backend.rs b/crates/host-core/src/computer/backend.rsindex 0c60932de..2f3a03f3b 100644--- a/crates/host-core/src/computer/backend.rs+++ b/crates/host-core/src/computer/backend.rs@@ -42,6 +42,10 @@ pub struct RawTarget {pub struct Measured {pub bounds: Rect,pub app_key: String,+ /// Live window title. Read by the backends that refresh a grant label; a+ /// title change alone never bumps the revision, because a document rename+ /// is not a different window.+ #[allow(dead_code)]pub title: String,}@@ -54,6 +58,10 @@ pub enum Dispatched {WindowEvent,}+/// Variants a given platform may never produce — `Elevated` is Windows-only,+/// `Unsupported` comes from the fallback — are kept so the contract is the+/// same everywhere and a port does not have to widen the enum.+#[allow(dead_code)]#[derive(Debug, Clone, PartialEq, Eq)]pub enum DesktopError {/// No backend on this platform, or no input path in this session type.@@ -120,13 +128,16 @@ pub trait Desktop: Send + Sync {}/// The backend every platform has: it exists so that an unimplemented platform-/// answers with a code instead of panicking or pretending to work.+/// answers with a code instead of panicking or pretending to work. On a+/// platform whose backend is built, nothing constructs it outside the tests.+#[allow(dead_code)]pub struct UnsupportedDesktop {platform: &'static str,reason: &'static str,}impl UnsupportedDesktop {+ #[allow(dead_code)]pub fn new(platform: &'static str, reason: &'static str) -> Self {Self { platform, reason }}diff --git a/crates/host-core/src/computer/mod.rs b/crates/host-core/src/computer/mod.rsindex 6844d5e9a..b92404625 100644--- a/crates/host-core/src/computer/mod.rs+++ b/crates/host-core/src/computer/mod.rs@@ -14,7 +14,7 @@pub mod backend;#[cfg(target_os = "macos")]mod macos;-mod policy;+pub mod policy;#[cfg(test)]mod tests;diff --git a/crates/host-core/src/computer/policy.rs b/crates/host-core/src/computer/policy.rsindex f044c78f6..5fdb7ec26 100644--- a/crates/host-core/src/computer/policy.rs+++ b/crates/host-core/src/computer/policy.rs@@ -11,7 +11,7 @@ use std::time::{Duration, Instant};use super::backend::{Desktop, Measured, RawTarget};use super::{ActResult, Action, ActionKind, Basis, CaptureMode, ComputerResult, Grant, GrantState,- InputPolicy, Inspection, Node, Point, Rect, Refusal, Target, TargetRefusal, MAX_ACTION_BUDGET,+ InputPolicy, Inspection, Node, Rect, Refusal, Target, TargetRefusal, MAX_ACTION_BUDGET,MAX_IDLE_EXPIRY, MAX_NODES, MAX_TEXT_CHARS, MIN_IDLE_EXPIRY,};@@ -424,21 +424,6 @@ pub fn act(})}-/// Where the overlay should draw the agent's cursor for this action, in screen-/// coordinates. Visualization only: a `None` here never blocks an action.-pub fn cursor_point(grant: &Grant, action: &Action, node_bounds: Option<Rect>) -> Option<Point> {- if let Some(bounds) = node_bounds {- return Some(Point {- x: bounds.x + bounds.width / 2.0,- y: bounds.y + bounds.height / 2.0,- });- }- action.point.map(|point| Point {- x: grant.bounds.x + point.x,- y: grant.bounds.y + point.y,- })-}-pub fn revoke(grant: &mut Grant, expired: bool) {grant.state = if expired {GrantState::Expireddiff --git a/crates/host-core/src/computer/tests.rs b/crates/host-core/src/computer/tests.rsindex 8d2df090f..74e91b1a2 100644--- a/crates/host-core/src/computer/tests.rs+++ b/crates/host-core/src/computer/tests.rs@@ -633,30 +633,6 @@ fn an_unsupported_platform_refuses_every_operation() {);}-#[test]-fn the_cursor_point_is_visualization_only() {- let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);- let grant = grant_for(&desktop, "w1");- // Element bounds win, because that is where the action actually lands.- let from_node = policy::cursor_point(- &grant,- &click_uid("0.1"),- Some(rect(10.0, 20.0, 100.0, 40.0)),- );- assert_eq!(from_node, Some(Point { x: 60.0, y: 40.0 }));- // A coordinate action draws at the window-relative point, offset to screen.- let action = Action {- kind: Some(ActionKind::Click),- point: Some(Point { x: 5.0, y: 6.0 }),- ..Action::default()- };- let from_point = policy::cursor_point(&grant, &action, None).expect("point");- assert_eq!(from_point.x, grant.bounds.x + 5.0);- assert_eq!(from_point.y, grant.bounds.y + 6.0);- // Neither: nothing to draw, and that is not an error.- assert_eq!(policy::cursor_point(&grant, &Action::default(), None), None);-}-#[test]fn a_grant_view_reports_expiry_without_persisting_it() {let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);diff --git a/crates/host-core/src/permissions.rs b/crates/host-core/src/permissions.rsindex 10cb225a1..a7c864a82 100644--- a/crates/host-core/src/permissions.rs+++ b/crates/host-core/src/permissions.rs@@ -120,7 +120,7 @@ impl PermissionManager {pub fn tool_risk_with_declared(tool_name: &str, declared: Option<&str>) -> Risk {match tool_name {"Read" | "Glob" | "Grep" | "ScheduledTaskList" | "TodoWrite" => Risk::Low,- "Write" | "Edit" | "Bash" | "GenerateImages" => Risk::High,+ "Write" | "Edit" | "Bash" | "GenerateImages" | "Computer" => Risk::High,name if name.starts_with("plugin_") => match declared {Some("low") => Risk::Low,Some("high") => Risk::High,diff --git a/crates/host-core/src/rpc/computer_rpc.rs b/crates/host-core/src/rpc/computer_rpc.rsnew file mode 100644index 000000000..73b8e0fb1--- /dev/null+++ b/crates/host-core/src/rpc/computer_rpc.rs@@ -0,0 +1,313 @@+//! `computer.*` RPC: the only way into the computer-use capability.+//!+//! Every method re-reads the live grant and the denylist from settings rather+//! than trusting anything in the request. The request may name a `grantId` and+//! a `sessionId`, and both are checked against the grant the host minted — a+//! caller cannot describe itself into authority it was not given.++use std::sync::Arc;+use std::time::{Duration, Instant};++use serde_json::{json, Value};+use tokio::sync::Mutex;++use crate::audit;+use crate::computer::{self, backend, policy, Action, CaptureMode, InputPolicy, Refusal};+use crate::state::AppState;++use super::{rpc_err, JsonRpcError};++fn refusal_err(refusal: Refusal) -> JsonRpcError {+ // 1006 is the host's "tool denied by policy" family; the public code is+ // what the caller branches on, and the message carries no window content.+ rpc_err(1006, refusal.message(), refusal.code())+}++fn invalid(message: &str) -> JsonRpcError {+ rpc_err(1002, message.to_string(), "INVALID_PARAMS")+}++fn string_param(params: &Value, key: &str) -> Option<String> {+ params+ .get(key)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_string)+}++/// Settings are the user's; the built-in credential denylist is not, so it is+/// added inside `Denylist` and cannot be removed by a settings write.+async fn denylist_from_settings(state: &Arc<Mutex<AppState>>) -> policy::Denylist {+ let st = state.lock().await;+ let stored = st.db.get_setting("app").ok().flatten();+ let entries = stored+ .as_ref()+ .and_then(|value| value.get("computerUse"))+ .and_then(|value| value.get("denylist"))+ .and_then(Value::as_array)+ .map(|items| {+ items+ .iter()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect::<Vec<_>>()+ })+ .unwrap_or_default();+ policy::Denylist::new(&entries)+}++async fn settings_enabled(state: &Arc<Mutex<AppState>>) -> bool {+ let st = state.lock().await;+ st.db+ .get_setting("app")+ .ok()+ .flatten()+ .as_ref()+ .and_then(|value| value.get("computerUse"))+ .and_then(|value| value.get("enabled"))+ .and_then(Value::as_bool)+ .unwrap_or(false)+}++fn audit_computer(state: &AppState, kind: &str, session_id: Option<&str>, payload: Value) {+ if let Err(error) = audit::append(&state.db, kind, session_id, payload) {+ tracing::warn!(%error, "computer-use audit append failed");+ }+}++pub(crate) async fn handle(+ state: Arc<Mutex<AppState>>,+ method: &str,+ params: Value,+) -> Result<Value, JsonRpcError> {+ let desktop = backend::active();+ match method {+ // Capabilities are readable while the feature is off: the settings page+ // has to be able to say "unsupported here" before anything is enabled.+ "computer.capabilities" => Ok(serde_json::to_value(desktop.capabilities())+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?),++ "computer.listTargets" => {+ if !settings_enabled(&state).await {+ return Err(refusal_err(Refusal::Disabled));+ }+ let denylist = denylist_from_settings(&state).await;+ let targets = policy::list_targets(desktop.as_ref(), &denylist).map_err(refusal_err)?;+ Ok(json!({ "targets": targets }))+ }++ "computer.grantCreate" => {+ if !settings_enabled(&state).await {+ return Err(refusal_err(Refusal::Disabled));+ }+ let target_id =+ string_param(¶ms, "targetId").ok_or_else(|| invalid("targetId is required"))?;+ let session_id = string_param(¶ms, "sessionId")+ .ok_or_else(|| invalid("sessionId is required"))?;+ let input_policy = match params.get("inputPolicy").and_then(Value::as_str) {+ Some("autonomous-in-scope") => InputPolicy::AutonomousInScope,+ Some("confirm-each") | None => InputPolicy::ConfirmEach,+ Some(_) => return Err(invalid("inputPolicy is invalid")),+ };+ let capture = match params.get("capture").and_then(Value::as_str) {+ Some("a11y-and-pixels") => CaptureMode::A11yAndPixels,+ Some("a11y-only") | None => CaptureMode::A11yOnly,+ Some(_) => return Err(invalid("capture is invalid")),+ };+ let action_budget = params+ .get("actionBudget")+ .and_then(Value::as_u64)+ .unwrap_or(computer::DEFAULT_ACTION_BUDGET as u64)+ .min(computer::MAX_ACTION_BUDGET as u64) as u32;+ let idle_expiry = params+ .get("idleExpiryMs")+ .and_then(Value::as_u64)+ .map(Duration::from_millis)+ .unwrap_or(computer::DEFAULT_IDLE_EXPIRY);+ let denylist = denylist_from_settings(&state).await;+ let now = Instant::now();++ let mut st = state.lock().await;+ let grant = policy::create_grant(+ desktop.as_ref(),+ st.computer_grant.as_ref(),+ &denylist,+ policy::GrantRequest {+ target_id,+ session_id: session_id.clone(),+ input_policy,+ capture,+ action_budget,+ idle_expiry,+ },+ now,+ );+ match grant {+ Ok(grant) => {+ let view = grant.view(now);+ audit_computer(+ &st,+ "computer.grant.created",+ Some(&session_id),+ json!({+ "grantId": view.grant_id,+ "appKey": view.app_key,+ "inputPolicy": view.input_policy,+ "capture": view.capture,+ "actionBudget": view.remaining_budget,+ }),+ );+ st.computer_grant = Some(grant);+ Ok(serde_json::to_value(view)+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?)+ }+ Err(refusal) => {+ audit_computer(+ &st,+ "computer.grant.refused",+ Some(&session_id),+ json!({ "code": refusal.code() }),+ );+ Err(refusal_err(refusal))+ }+ }+ }++ "computer.grantRevoke" => {+ let mut st = state.lock().await;+ let reason = string_param(¶ms, "reason").unwrap_or_else(|| "user".into());+ let Some(grant) = st.computer_grant.as_mut() else {+ // Revoking nothing is success: the caller's intent is satisfied.+ return Ok(json!({ "revoked": false }));+ };+ let grant_id = grant.grant_id.clone();+ let session_id = grant.session_id.clone();+ policy::revoke(grant, false);+ audit_computer(+ &st,+ "computer.grant.revoked",+ Some(&session_id),+ json!({ "grantId": grant_id, "reason": reason }),+ );+ st.computer_grant = None;+ Ok(json!({ "revoked": true }))+ }++ "computer.grantDescribe" => {+ let now = Instant::now();+ let mut st = state.lock().await;+ let Some(grant) = st.computer_grant.as_mut() else {+ return Ok(json!({ "grant": Value::Null }));+ };+ if grant.expired_at(now) {+ let view = grant.view(now);+ st.computer_grant = None;+ return Ok(json!({ "grant": view }));+ }+ Ok(json!({ "grant": grant.view(now) }))+ }++ "computer.inspect" => {+ let grant_id =+ string_param(¶ms, "grantId").ok_or_else(|| invalid("grantId is required"))?;+ let session_id = string_param(¶ms, "sessionId");+ let expected_revision = params+ .get("expectedRevision")+ .and_then(Value::as_u64)+ .map(|value| value as u32);+ let now = Instant::now();+ let mut st = state.lock().await;+ let grant = policy::usable_grant(+ st.computer_grant.as_mut(),+ &grant_id,+ session_id.as_deref(),+ now,+ )+ .map_err(refusal_err)?;+ let inspection = policy::inspect(desktop.as_ref(), grant, expected_revision, now)+ .map_err(refusal_err)?;+ Ok(serde_json::to_value(inspection)+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?)+ }++ "computer.act" => {+ let grant_id =+ string_param(¶ms, "grantId").ok_or_else(|| invalid("grantId is required"))?;+ let session_id = string_param(¶ms, "sessionId");+ let expected_revision = params+ .get("expectedRevision")+ .and_then(Value::as_u64)+ .map(|value| value as u32);+ let action: Action = serde_json::from_value(+ params+ .get("action")+ .cloned()+ .ok_or_else(|| invalid("action is required"))?,+ )+ .map_err(|error| invalid(&format!("action is invalid: {error}")))?;+ let now = Instant::now();+ let mut st = state.lock().await;+ let grant = policy::usable_grant(+ st.computer_grant.as_mut(),+ &grant_id,+ session_id.as_deref(),+ now,+ )+ .map_err(refusal_err)?;+ let owner = grant.session_id.clone();+ let app_key = grant.target.app_key.clone();+ let result = policy::act(desktop.as_ref(), grant, expected_revision, &action, now);+ match result {+ Ok(outcome) => {+ // The audit line records identity and shape, never content:+ // typed text appears as a length, and no pixels are stored.+ audit_computer(+ &st,+ "computer.act",+ Some(&owner),+ json!({+ "grantId": outcome.grant_id,+ "appKey": app_key,+ "action": action.kind.map(|kind| kind.as_str()),+ "uid": action.uid,+ "textLength": action.text.as_ref().map(|text| text.chars().count()),+ "dispatched": outcome.dispatched,+ "remainingBudget": outcome.remaining_budget,+ }),+ );+ if outcome.remaining_budget == 0 {+ st.computer_grant = None;+ }+ Ok(serde_json::to_value(outcome)+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?)+ }+ Err(refusal) => {+ audit_computer(+ &st,+ "computer.act.refused",+ Some(&owner),+ json!({+ "grantId": grant_id,+ "appKey": app_key,+ "action": action.kind.map(|kind| kind.as_str()),+ "code": refusal.code(),+ }),+ );+ // A refusal that ended the grant must not leave a dead one+ // behind for the next caller to trip over.+ if matches!(refusal, Refusal::ScopeViolation | Refusal::GrantExpired) {+ st.computer_grant = None;+ }+ Err(refusal_err(refusal))+ }+ }+ }++ _ => Err(rpc_err(+ -32601,+ format!("method not found: {method}"),+ "NOT_FOUND",+ )),+ }+}diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 7a04a9425..4a57f6025 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -1,3 +1,4 @@+mod computer_rpc;mod config_sync_rpc;mod file_batches;mod gen_ui;@@ -1967,6 +1968,10 @@ async fn handle_request(return file_batches::handle(state, method, params).await;}+ if method.starts_with("computer.") {+ return computer_rpc::handle(state, method, params).await;+ }+match method {"visualizations.readFragment" => gen_ui::read_fragment(state, params).await,"tools.remoteComplete" | "tools.workspaceExecute" | "tools.workspaceAbort" => {diff --git a/crates/host-core/src/state.rs b/crates/host-core/src/state.rsindex 4d2c30267..082c31aff 100644--- a/crates/host-core/src/state.rs+++ b/crates/host-core/src/state.rs@@ -93,6 +93,10 @@ pub struct AppState {/// Session-scoped Read/Edit snapshot store (ADR 0087). Interior mutex so/// tool execution does not hold the AppState lock.pub hashline: crate::tools::HashlineStore,+ /// The single active computer-use grant (ADR 0340). Process-local and+ /// never persisted: a restart must not hand a new process authority over+ /// the user's screen.+ pub computer_grant: Option<crate::computer::Grant>,}impl AppState {@@ -174,6 +178,7 @@ impl AppState {pending_bash_aborts: HashMap::new(),pending_tool_aborts: HashMap::new(),hashline: crate::tools::HashlineStore::new(),+ computer_grant: None,})}diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex fcd5c57f8..8396c2404 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -1278,7 +1278,10 @@ pub async fn execute_tool_with_file_lease(let result: Result<Value, hashline::ToolError> = match tool_name {// Authorize the desktop-owned image request through the normal host gate.// Only the trusted desktop runner performs the external call.- "GenerateImages" => Ok(serde_json::json!({ "authorized": true })),+ // Both run in Electron main after the host authorises them:+ // image generation needs a provider SDK, and computer use needs+ // a provider plus Chromium capture (ADR 0340).+ "GenerateImages" | "Computer" => Ok(serde_json::json!({ "authorized": true })),"Read" | "Glob" | "Grep" | "Write" | "Edit" => {run_file_tool(workspace,