Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(desktop): run scoped Jev tasks in one call

Steven Enamakelc645b527d9fc
diff --git a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md
index 857ddb8b16..0b9b0030e5 100644
--- a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md
+++ b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md
@@ -4,7 +4,7 @@ Take the first branch that applies:
1. **Answerable without tools**: reply. Small talk, simple Q&A, general knowledge.
1b. **Needs a capability you do not see listed**: `tool_search` with the intent in plain words before delegating or declining; if nothing comes back, say so.
-Desktop control, when enabled, is available through `tool_search`.
+Desktop control: `tool_search` finds it. Plan one bounded task; `desktop_goal` loops internally to visible success.
2. **Needs a connected service's own data or actions** (inbox, messages, calendar, docs, tickets, "send/check X"): `tool_search` for the action ("send an email", "list calendar events"), then call what it returns. No sub-agent runs it for you, and an announced search never runs: emit it. Use the live service even when memory could plausibly answer. A service being connected is not a reason to touch it: general knowledge, web/news lookups, headlines, date/time, math, and anything public on the web (a public repository, a product page, docs) never go to a service; those are `web_fetch` / `web_search_tool` / `research` work. Reach for a toolkit only for the user's own account data or actions on it. Not connected? Raise a connect card with `composio_connect`: the list shows what is connected, not what is connectable, so never refuse from it or send the user to settings, and never paste OAuth URLs. If the connect call reports the toolkit unavailable, relay its message; that is the only honest refusal.
3. **Solvable with a direct tool**: do it yourself. `web_search_tool` and `web_fetch` for a fact or a page, `memory_recall` and `memory_store` for the user's own facts, `shell` plus `apply_patch` for repository work. Keep code work end-to-end: edit and verify in the same turn; never delegate merely because a task touches a repository.
4. **Needs a specialist**: the specialists you can call are in your tool list with their own descriptions. **Capabilities not in your tool list** names the ones a skill holds; reach those through `use_skill`. Workers return only their result; carry out any `## Handoff Plan` they return yourself, under the approval gate.
diff --git a/crates/openhuman-core/src/desktop/control/WORKFLOW.md b/crates/openhuman-core/src/desktop/control/WORKFLOW.md
index 1132807a46..85de86f8b7 100644
--- a/crates/openhuman-core/src/desktop/control/WORKFLOW.md
+++ b/crates/openhuman-core/src/desktop/control/WORKFLOW.md
@@ -5,6 +5,6 @@ description: Inspect and control native desktop apps when Desktop is enabled in
# Desktop control
-Use `tool_search` to discover `desktop_*` tools. Begin with `desktop_list_apps` and `desktop_list_windows`; if the app has no visible window, use `desktop_launch` to activate it. Take a skeleton `desktop_snapshot`, then use `desktop_find` or a deeper snapshot to select a snapshot-qualified element ref. After an action, observe the app again and verify the visible result.
+Use `tool_search` to discover `desktop_*` tools. Begin with `desktop_list_apps` and `desktop_list_windows`; if the app has no visible window, use `desktop_launch` to activate it. Use the exact `window_id` from `desktop_list_windows` in `desktop_snapshot` and `desktop_goal` to bind both to the same native window; an exact `window` title may also be supplied. Inspect a skeleton `desktop_snapshot` to obtain exact accessible target names, descriptions, or `native_id.value`, and the completion condition. Plan one bounded task, then call `desktop_goal` once: state the app and goal, enumerate allowed mutating operations and exact targets, supply any text in `text_slots` keyed by the target's exact name, description, or `native_id.value`, and give one or more positive `success` predicates using the same target identifier. A missing element in a bounded snapshot does not prove absence. If a target has no accessible name, use its observed native AX identifier when available; otherwise inspect further without broadening the target scope. The module executes and verifies multiple actions inside this one call. Read its `verified`, `stop`, and final observation before reporting completion.
-If a ref is stale, take a fresh snapshot. If Accessibility is denied, ask the user to grant it to the process running OpenHuman. Desktop goals have small action and model-call limits. With desktop approvals off (the default), the core continues a confirmation stop through the module's one-use handle; the module reobserves and validates the target before acting. If the operator enables desktop approvals, wait for their decision in Connections before using `desktop_continue_goal`. Never claim an action succeeded from a timeout or a model decision alone.
+If a ref is stale, take a fresh snapshot. If Accessibility is denied, ask the user to grant it to the process running OpenHuman. Desktop goals have action, model-call, and elapsed-time limits. With desktop approvals off (the default), the module runs in-scope actions without stopping for per-action approval. If the operator enables desktop approvals and the module returns a pending action, wait for their decision in Connections before using `desktop_continue_goal`. If `verified` is false, use the returned evidence to replan or explain the blocker; do not replay an uncertain action. Never claim success from a timeout or a model decision alone.
diff --git a/crates/openhuman-core/src/desktop/control/tools.rs b/crates/openhuman-core/src/desktop/control/tools.rs
index d5d327fb27..ac73a7732c 100644
--- a/crates/openhuman-core/src/desktop/control/tools.rs
+++ b/crates/openhuman-core/src/desktop/control/tools.rs
@@ -1,15 +1,16 @@
//! Deferred desktop tools. Only their names and descriptions enter discovery.
-use std::future::Future;
use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{json, Value};
use tinydesktop_bus::{
- names, DesktopResponse, FindRequest, LaunchRequest, ListAppsRequest, ListWindowsRequest,
- RefRequest, SnapshotRequest, TypeRequest,
+ names, FindRequest, LaunchRequest, ListAppsRequest, ListWindowsRequest, RefRequest,
+ RunGoalRequest, SnapshotRequest, TypeRequest, VisiblePredicate,
+};
+use tinytools::{
+ PermissionLevel, Tool, ToolCallOptions, ToolExposure, ToolResult, ToolRunContext, ToolTimeout,
};
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolExposure, ToolResult, ToolRunContext};
use crate::config::Config;
@@ -45,72 +46,96 @@ fn required(args: &Value, key: &str) -> anyhow::Result<String> {
.ok_or_else(|| anyhow::anyhow!("missing required parameter: {key}"))
}
-fn confirmation_id(response: &DesktopResponse) -> Result<Option<String>, String> {
- if !response.ok {
- return Ok(None);
- }
- let Some(data) = response.data.as_ref() else {
- return Ok(None);
- };
- if data.get("stop").and_then(Value::as_str) != Some("confirmation_required") {
- return Ok(None);
- }
- data.get("confirmation_id")
- .and_then(Value::as_str)
- .filter(|id| !id.is_empty())
- .map(str::to_owned)
- .map(Some)
- .ok_or_else(|| {
- "desktop goal requested confirmation without a continuation handle".to_owned()
- })
+fn optional_string(args: &Value, key: &str) -> anyhow::Result<Option<String>> {
+ args.get(key).map(|_| required(args, key)).transpose()
}
-/// The module owns remaining action/model budgets and revalidates a one-use
-/// target against a fresh snapshot on every continuation. The host adds a hard
-/// eight-confirmation ceiling so a module bug cannot hold this tool forever.
-async fn advance_goal_confirmations<F, Fut>(
- mut response: DesktopResponse,
- approvals_enabled: bool,
- mut continue_with: F,
-) -> Result<DesktopResponse, String>
-where
- F: FnMut(String, bool) -> Fut,
- Fut: Future<Output = Result<DesktopResponse, String>>,
-{
- if approvals_enabled {
- return Ok(response);
- }
- for _ in 0..8 {
- let Some(id) = confirmation_id(&response)? else {
- return Ok(response);
- };
- tracing::info!(
- "[desktop] continuing module-confirmed action under approvals-disabled policy"
- );
- response = continue_with(id, true).await?;
- }
- if let Some(id) = confirmation_id(&response)? {
- let executed = response
- .data
- .as_ref()
- .and_then(|data| data.get("turns"))
- .and_then(Value::as_array)
- .map_or(0, Vec::len);
- let cancelled = continue_with(id, false).await.map_err(|error| {
- format!(
- "desktop goal reached the confirmation continuation limit after {executed} \
- executed action(s); cancellation delivery is uncertain: {error}"
+fn snapshot_request(args: &Value) -> anyhow::Result<SnapshotRequest> {
+ Ok(SnapshotRequest {
+ app: args.get("app").and_then(Value::as_str).map(str::to_owned),
+ window_id: optional_string(args, "window_id")?,
+ skeleton: args
+ .get("skeleton")
+ .and_then(Value::as_bool)
+ .unwrap_or(true),
+ root_ref: args
+ .get("root_ref")
+ .and_then(Value::as_str)
+ .map(str::to_owned),
+ max_depth: args
+ .get("max_depth")
+ .and_then(Value::as_u64)
+ .map(|n| n.clamp(1, 12) as u8),
+ ..SnapshotRequest::default()
+ })
+}
+
+fn goal_request(args: &Value, approvals_enabled: bool) -> anyhow::Result<Value> {
+ let app = required(args, "app")?;
+ let goal = required(args, "goal")?;
+ let operations = args
+ .get("allowed_operations")
+ .and_then(Value::as_array)
+ .filter(|operations| !operations.is_empty())
+ .ok_or_else(|| anyhow::anyhow!("desktop_goal requires allowed_operations"))?;
+ let targets = args
+ .get("allowed_targets")
+ .and_then(Value::as_array)
+ .filter(|targets| {
+ !targets.is_empty()
+ && targets.iter().all(|target| {
+ target
+ .as_str()
+ .is_some_and(|name| !name.trim().is_empty())
+ })
+ })
+ .ok_or_else(|| {
+ anyhow::anyhow!(
+ "needs_inspection: supply allowed_targets using exact accessible names, descriptions, or native AX identifiers from desktop_snapshot or desktop_find"
)
})?;
- if !cancelled.ok {
- return Err(format!(
- "desktop goal reached the confirmation continuation limit after {executed} \
- executed action(s); module refused cancellation"
- ));
+ let success = args
+ .get("success")
+ .and_then(Value::as_array)
+ .filter(|predicates| !predicates.is_empty())
+ .ok_or_else(|| anyhow::anyhow!("desktop_goal requires a visible success predicate"))?;
+ let mut request = json!({
+ "app": app,
+ "goal": goal,
+ "include_values": false,
+ "require_confirmations": approvals_enabled,
+ "max_steps": args.get("max_steps").and_then(Value::as_u64).unwrap_or(12).clamp(1, 20),
+ "max_model_calls": args.get("max_model_calls").and_then(Value::as_u64).unwrap_or(24).clamp(1, 40),
+ "max_elapsed_ms": args.get("max_elapsed_ms").and_then(Value::as_u64).unwrap_or(120_000).clamp(1_000, 300_000),
+ "success": success,
+ "text_slots": args.get("text_slots").cloned().unwrap_or_else(|| json!({})),
+ "allowed_operations": operations,
+ "allowed_targets": targets,
+ });
+ if let Some(window) = args.get("window") {
+ request["window"] = window.clone();
+ }
+ if let Some(window_id) = optional_string(args, "window_id")? {
+ request["window_id"] = json!(window_id);
+ }
+ // Decode through the shared contract before dispatch, so malformed
+ // predicates and operation names fail without reaching the native module.
+ let request: RunGoalRequest = serde_json::from_value(request)?;
+ if !request.success.iter().all(|predicate| match predicate {
+ VisiblePredicate::NamePresent { name } => !name.trim().is_empty(),
+ VisiblePredicate::ValueEquals { name, .. } => !name.trim().is_empty(),
+ VisiblePredicate::ValueContains { name, value } => {
+ !name.trim().is_empty() && !value.trim().is_empty()
+ }
+ VisiblePredicate::StateContains { name, state } => {
+ !name.trim().is_empty() && !state.trim().is_empty()
}
- return Ok(cancelled);
+ }) {
+ anyhow::bail!(
+ "desktop_goal success predicates require nonblank names, state tokens, and value_contains fragments"
+ );
}
- Ok(response)
+ Ok(serde_json::to_value(request)?)
}
#[async_trait]
@@ -136,7 +161,7 @@ impl Tool for DesktopTool {
DesktopToolKind::Snapshot => "Inspect an app's accessibility tree and obtain snapshot-qualified element refs.",
DesktopToolKind::Find => "Find a desktop accessibility element by role and name, returning a ref.",
DesktopToolKind::Act => "Act on a desktop element ref: click, focus, type, check, uncheck, expand, or collapse.",
- DesktopToolKind::Goal => "Run a bounded Jev-guided desktop goal. Search for desktop tools before use; consequential actions require confirmation.",
+ DesktopToolKind::Goal => "Run one scoped, bounded Jev desktop task through its internal observe-act-verify loop. Supply a visible success predicate; discover via tool_search.",
DesktopToolKind::ContinueGoal => "Resume a desktop goal after the user approved its exact pending action in Connections.",
}
}
@@ -169,6 +194,21 @@ impl Tool for DesktopTool {
)
}
+ fn timeout_policy(&self, args: &Value) -> ToolTimeout {
+ match self.kind {
+ DesktopToolKind::Goal => {
+ let budget_ms = args
+ .get("max_elapsed_ms")
+ .and_then(Value::as_u64)
+ .unwrap_or(120_000)
+ .clamp(1_000, 300_000);
+ ToolTimeout::Millis(budget_ms + 30_000)
+ }
+ DesktopToolKind::ContinueGoal => ToolTimeout::Millis(330_000),
+ _ => ToolTimeout::Inherit,
+ }
+ }
+
fn parameters_schema(&self) -> Value {
match self.kind {
DesktopToolKind::Apps => json!({"type":"object","properties":{}}),
@@ -178,7 +218,7 @@ impl Tool for DesktopTool {
"app":{"type":"string","description":"Application name, e.g. Spotify or TextEdit"}},
"required":["app"],"additionalProperties":false}),
DesktopToolKind::Snapshot => json!({"type":"object","properties":{
- "app":{"type":"string"}, "skeleton":{"type":"boolean"},
+ "app":{"type":"string"}, "window_id":{"type":"string","minLength":1,"description":"Exact window ID from desktop_list_windows"}, "skeleton":{"type":"boolean"},
"root_ref":{"type":"string"}, "max_depth":{"type":"integer","minimum":1,"maximum":12}}}),
DesktopToolKind::Find => json!({"type":"object","properties":{
"app":{"type":"string"},"role":{"type":"string"},"name":{"type":"string"},
@@ -189,11 +229,21 @@ impl Tool for DesktopTool {
"text":{"type":"string","description":"Required for type"}},
"required":["operation","ref_id"]}),
DesktopToolKind::Goal => json!({"type":"object","properties":{
- "app":{"type":"string"},"goal":{"type":"string"},
- "text":{"type":"array","items":{"type":"string"}},
- "max_steps":{"type":"integer","minimum":1,"maximum":8},
- "max_model_calls":{"type":"integer","minimum":1,"maximum":16}},
- "required":["app","goal"]}),
+ "app":{"type":"string","description":"Native app to control"},
+ "window":{"type":"string","description":"Optional exact title of an observed app window"},
+ "window_id":{"type":"string","minLength":1,"description":"Optional exact window ID from desktop_list_windows; binds actions and verification to that native window"},
+ "goal":{"type":"string","description":"One bounded desktop task; describe the intended visible result"},
+ "allowed_operations":{"type":"array","minItems":1,"items":{"type":"string","enum":["CLICK","TYPE_TEXT","CHECK","UNCHECK","EXPAND","COLLAPSE","SCROLL"]},"description":"Mutating operations Jev may execute; enumerate those needed for this task"},
+ "allowed_targets":{"type":"array","minItems":1,"items":{"type":"string"},"description":"Exact accessible name, description, or native_id.value from desktop_snapshot or desktop_find for each action target"},
+ "text_slots":{"type":"object","additionalProperties":{"type":"string"},"description":"Prepared text keyed by the target's exact accessible name, description, or native_id.value"},
+ "success":{"type":"array","minItems":1,"items":{"type":"object","properties":{
+ "kind":{"type":"string","enum":["name_present","value_equals","value_contains","state_contains"]},
+ "name":{"type":"string","description":"Exact accessible name, description, or native_id.value from the snapshot"},"value":{"type":"string"},"state":{"type":"string"}},
+ "required":["kind","name"]},"description":"All predicates must match a fresh accessibility observation before completion"},
+ "max_steps":{"type":"integer","minimum":1,"maximum":20},
+ "max_model_calls":{"type":"integer","minimum":1,"maximum":40},
+ "max_elapsed_ms":{"type":"integer","minimum":1000,"maximum":300000}},
+ "required":["app","goal","allowed_operations","allowed_targets","success"],"additionalProperties":false}),
DesktopToolKind::ContinueGoal => json!({"type":"object","properties":{
"confirmation_id":{"type":"string","description":"One-use handle approved by the user in Connections"}},
"required":["confirmation_id"]}),
@@ -248,6 +298,7 @@ impl Tool for DesktopTool {
return Ok(ToolResult::error("Desktop Accessibility permission is not granted. Enable it in system settings and retry."));
}
let mut goal_identity = None;
+ let mut approvals_enabled = true;
let (member, request) = match self.kind {
DesktopToolKind::Apps => (
names::methods::LIST_APPS,
@@ -266,22 +317,7 @@ impl Tool for DesktopTool {
(names::methods::LAUNCH, serde_json::to_value(request)?)
}
DesktopToolKind::Snapshot => {
- let request = SnapshotRequest {
- app: args.get("app").and_then(Value::as_str).map(str::to_owned),
- skeleton: args
- .get("skeleton")
- .and_then(Value::as_bool)
- .unwrap_or(true),
- root_ref: args
- .get("root_ref")
- .and_then(Value::as_str)
- .map(str::to_owned),
- max_depth: args
- .get("max_depth")
- .and_then(Value::as_u64)
- .map(|n| n.clamp(1, 12) as u8),
- ..SnapshotRequest::default()
- };
+ let request = snapshot_request(&args)?;
(names::methods::SNAPSHOT, serde_json::to_value(request)?)
}
DesktopToolKind::Find => {
@@ -337,60 +373,38 @@ impl Tool for DesktopTool {
(required(&args, "app")?, required(&args, "goal")?, None)
};
goal_identity = Some((app.clone(), goal.clone()));
- let mut request = json!({"app":app,"goal":goal,
- "text":args.get("text").cloned().unwrap_or_else(|| json!([])),
- "include_values":false,
- "max_steps":args.get("max_steps").and_then(Value::as_u64).unwrap_or(6).clamp(1,8),
- "max_model_calls":args.get("max_model_calls").and_then(Value::as_u64).unwrap_or(12).clamp(1,16)});
+ let mut request = if continuation.is_some() {
+ json!({"app":app,"goal":goal})
+ } else {
+ let live_config = match crate::config::rpc::load_config_with_timeout().await {
+ Ok(config) => config,
+ Err(error) => {
+ return Ok(ToolResult::error(format!(
+ "Desktop approval setting is unavailable: {error}"
+ )))
+ }
+ };
+ approvals_enabled = live_config.desktop.approvals_enabled;
+ goal_request(&args, approvals_enabled)?
+ };
if let Some(continuation) = continuation {
request["continuation"] = continuation;
}
(names::methods::RUN_GOAL, request)
}
};
- let goal_action = matches!(
- self.kind,
- DesktopToolKind::Goal | DesktopToolKind::ContinueGoal
- );
- let approvals_enabled = if goal_action {
- let live_config = match crate::config::rpc::load_config_with_timeout().await {
- Ok(config) => config,
- Err(error) => {
- return Ok(ToolResult::error(format!(
- "Desktop approval setting is unavailable: {error}"
- )))
- }
- };
- live_config.desktop.approvals_enabled
- } else {
- true
- };
let reply = crate::modules::desktop::call(&self.config, member, request).await;
- let reply = if goal_action {
- match reply {
- Ok(response) => {
- let config = Arc::clone(&self.config);
- advance_goal_confirmations(response, approvals_enabled, move |id, approve| {
- let config = Arc::clone(&config);
- async move {
- crate::modules::desktop::call(
- &config,
- names::methods::RUN_GOAL,
- json!({"continuation":{"id":id,"approve":approve}}),
- )
- .await
- }
- })
- .await
- }
- Err(error) => Err(error),
- }
- } else {
- reply
- };
match reply {
Ok(response) if response.ok => {
let data = response.data.unwrap_or(Value::Null);
+ if matches!(self.kind, DesktopToolKind::Goal)
+ && !approvals_enabled
+ && data.get("stop").and_then(Value::as_str) == Some("confirmation_required")
+ {
+ return Ok(ToolResult::error(
+ "Desktop module unexpectedly requested confirmation during an approvals-disabled task.",
+ ));
+ }
if let Some((app, goal)) = goal_identity.filter(|_| approvals_enabled) {
if data.get("stop").and_then(Value::as_str) == Some("confirmation_required") {
let Some(thread_id) = thread_id else {
diff --git a/crates/openhuman-core/src/desktop/control/tools_tests.rs b/crates/openhuman-core/src/desktop/control/tools_tests.rs
index aae748d3d2..435a10fa49 100644
--- a/crates/openhuman-core/src/desktop/control/tools_tests.rs
+++ b/crates/openhuman-core/src/desktop/control/tools_tests.rs
@@ -1,5 +1,4 @@
use super::*;
-use tinydesktop_bus::DesktopError;
#[test]
fn desktop_arguments_reject_missing_or_blank_required_values() {
@@ -55,15 +54,43 @@ fn raw_ref_action_requires_a_snapshot_ref_and_declares_a_write_effect() {
assert!(schema["properties"].get("env").is_none());
}
+#[test]
+fn snapshot_can_bind_the_window_listed_by_desktop() {
+ let tool = DesktopTool::new(Arc::new(Config::default()), DesktopToolKind::Snapshot);
+ assert_eq!(tool.exposure(), ToolExposure::Deferred);
+ assert!(tool.parameters_schema()["properties"]
+ .get("window_id")
+ .is_some());
+ let request = snapshot_request(&json!({"app":"TextEdit","window_id":"w-515619"})).unwrap();
+ assert_eq!(request.app.as_deref(), Some("TextEdit"));
+ assert_eq!(request.window_id.as_deref(), Some("w-515619"));
+ assert!(snapshot_request(&json!({"window_id":" "})).is_err());
+}
+
#[test]
fn goal_and_continuation_have_distinct_required_inputs() {
let config = Arc::new(Config::default());
let goal = DesktopTool::new(config.clone(), DesktopToolKind::Goal);
let continuation = DesktopTool::new(config, DesktopToolKind::ContinueGoal);
- assert_eq!(goal.parameters_schema()["required"], json!(["app", "goal"]));
+ assert_eq!(
+ goal.parameters_schema()["required"],
+ json!([
+ "app",
+ "goal",
+ "allowed_operations",
+ "allowed_targets",
+ "success"
+ ])
+ );
assert!(goal.parameters_schema()["properties"]
.get("confirmation_id")
.is_none());
+ assert!(
+ !goal.parameters_schema()["properties"]["success"]["items"]["properties"]["kind"]["enum"]
+ .as_array()
+ .unwrap()
+ .contains(&json!("name_absent"))
+ );
assert_eq!(
continuation.parameters_schema()["required"],
json!(["confirmation_id"])
@@ -74,159 +101,80 @@ fn goal_and_continuation_have_distinct_required_inputs() {
assert!(super::super::confirmation::take_approved("unknown", Some("thread-a")).is_err());
}
-#[tokio::test]
-async fn approvals_off_continues_one_use_handle_and_reports_module_result() {
- assert!(!Config::default().desktop.approvals_enabled);
- let called = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let observed = Arc::clone(&called);
- let initial = DesktopResponse::ok(
- "run-goal",
- json!({
- "stop":"confirmation_required", "confirmation_id":"once"
- }),
- );
- let result = advance_goal_confirmations(initial, false, move |id, approve| {
- let observed = Arc::clone(&observed);
- async move {
- assert_eq!(id, "once");
- assert!(approve);
- observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- Ok(DesktopResponse::ok(
- "run-goal",
- json!({
- "stop":"stale_target", "turns":[], "metrics":{"calls":1}
- }),
- ))
- }
- })
- .await
- .unwrap();
- assert_eq!(called.load(std::sync::atomic::Ordering::SeqCst), 1);
- assert_eq!(result.data.unwrap()["stop"], "stale_target");
-}
-
-#[tokio::test]
-async fn approvals_on_returns_pending_without_self_approval() {
- let initial = DesktopResponse::ok(
- "run-goal",
- json!({
- "stop":"confirmation_required", "confirmation_id":"once"
- }),
+#[test]
+fn goal_request_carries_scoped_task_and_disables_confirmations() {
+ let args = json!({
+ "app":"TextEdit", "window":"Untitled", "window_id":"w-515619",
+ "goal":"Enter a disposable marker",
+ "allowed_operations":["TYPE_TEXT"], "allowed_targets":["Text Entry Area"],
+ "text_slots":{"Text Entry Area":"desktop-test-42"},
+ "success":[{"kind":"value_equals","name":"Text Entry Area","value":"desktop-test-42"}],
+ "max_steps":3, "max_model_calls":5, "max_elapsed_ms":20_000
+ });
+ let request = goal_request(&args, false).unwrap();
+ assert_eq!(request["require_confirmations"], false);
+ assert_eq!(request["window"], "Untitled");
+ assert_eq!(request["window_id"], "w-515619");
+ let goal = DesktopTool::new(Arc::new(Config::default()), DesktopToolKind::Goal);
+ assert!(goal.parameters_schema()["properties"]
+ .get("window_id")
+ .is_some());
+ assert_eq!(request["allowed_operations"], json!(["TYPE_TEXT"]));
+ assert_eq!(request["allowed_targets"], json!(["Text Entry Area"]));
+ assert_eq!(request["text_slots"]["Text Entry Area"], "desktop-test-42");
+ assert_eq!(request["success"], args["success"]);
+ assert_eq!(request["max_elapsed_ms"], 20_000);
+ assert!(request["continuation"].is_null());
+ assert_eq!(
+ goal_request(&args, true).unwrap()["require_confirmations"],
+ true
);
- let result = advance_goal_confirmations(initial, true, |_id, _approve| async {
- panic!("manual approval mode must never auto-continue")
- })
- .await
- .unwrap();
- assert_eq!(result.data.unwrap()["confirmation_id"], "once");
-}
-
-#[tokio::test]
-async fn a_missing_confirmation_handle_never_triggers_an_action() {
- let malformed = DesktopResponse::ok("run-goal", json!({"stop":"confirmation_required"}));
- let error = advance_goal_confirmations(malformed, false, |_id, _approve| async {
- panic!("a missing handle must not reach the desktop module")
- })
- .await
- .unwrap_err();
- assert!(error.contains("without a continuation handle"));
-
- let failure = DesktopResponse::err("run-goal", DesktopError::new("PERM_DENIED", "denied"));
- let returned = advance_goal_confirmations(failure.clone(), false, |_id, _approve| async {
- panic!("a failed goal must not be continued")
- })
- .await
- .unwrap();
- assert_eq!(returned, failure);
+ assert!(goal_request(&json!({"app":"TextEdit","goal":"type"}), false).is_err());
+ let without_targets = json!({"app":"TextEdit","goal":"type", "allowed_operations":["TYPE_TEXT"],
+ "success":[{"kind":"name_present","name":"Text Entry Area"}]});
+ assert!(goal_request(&without_targets, false)
+ .unwrap_err()
+ .to_string()
+ .contains("needs_inspection"));
+ let mut blank_target = without_targets.clone();
+ blank_target["allowed_targets"] = json!([" "]);
+ assert!(goal_request(&blank_target, false).is_err());
+ let mut blank_window = args.clone();
+ blank_window["window_id"] = json!(" ");
+ assert!(goal_request(&blank_window, false).is_err());
+ let malformed = json!({"app":"TextEdit","goal":"type", "allowed_operations":["TYPE_TEXT"],
+ "allowed_targets":["Text Entry Area"],
+ "success":[{"kind":"value_contains","name":"Text Entry Area"}]});
+ assert!(goal_request(&malformed, false).is_err());
+ for predicate in [
+ json!({"kind":"name_absent","name":"Play"}),
+ json!({"kind":"name_present","name":" "}),
+ json!({"kind":"value_contains","name":"Text Entry Area","value":""}),
+ json!({"kind":"value_equals","name":"","value":"marker"}),
+ json!({"kind":"state_contains","name":"Play","state":" "}),
+ ] {
+ let mut request = args.clone();
+ request["success"] = json!([predicate]);
+ assert!(goal_request(&request, false).is_err());
+ }
+ let mut cleared = args.clone();
+ cleared["success"] = json!([{"kind":"value_equals","name":"Text Entry Area","value":""}]);
+ assert!(goal_request(&cleared, false).is_ok());
}
-#[tokio::test]
-async fn continuation_ceiling_returns_cancelled_result_with_all_executed_turns() {
- let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let seen = Arc::clone(&calls);
- let initial = DesktopResponse::ok(
- "run-goal",
- json!({
- "stop":"confirmation_required", "confirmation_id":"id-0", "turns":[]
- }),
+#[test]
+fn goal_timeout_outlives_the_module_loop_budget() {
+ let goal = DesktopTool::new(Arc::new(Config::default()), DesktopToolKind::Goal);
+ assert_eq!(
+ goal.timeout_policy(&json!({})),
+ ToolTimeout::Millis(150_000)
);
- let result = advance_goal_confirmations(initial, false, move |id, approve| {
- let seen = Arc::clone(&seen);
- async move {
- let index = seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- assert_eq!(id, format!("id-{index}"));
- if approve {
- Ok(DesktopResponse::ok(
- "run-goal",
- json!({
- "stop":"confirmation_required",
- "confirmation_id":format!("id-{}", index + 1),
- "turns":vec![Value::Null; index + 1],
- "metrics":{"calls":index + 1}
- }),
- ))
- } else {
- assert_eq!(index, 8);
- Ok(DesktopResponse::ok(
- "run-goal",
- json!({
- "stop":"cancelled", "turns":vec![Value::Null; 8],
- "metrics":{"calls":8}
- }),
- ))
- }
- }
- })
- .await
- .unwrap();
- assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 9);
- let data = result.data.unwrap();
- assert_eq!(data["stop"], "cancelled");
- assert_eq!(data["turns"].as_array().unwrap().len(), 8);
- assert_eq!(data["metrics"]["calls"], 8);
-}
-
-#[tokio::test]
-async fn continuation_ceiling_reports_uncertain_cancellation_delivery() {
- let initial = DesktopResponse::ok(
- "run-goal",
- json!({"stop":"confirmation_required", "confirmation_id":"once", "turns":[]}),
+ assert_eq!(
+ goal.timeout_policy(&json!({"max_elapsed_ms":300_000})),
+ ToolTimeout::Millis(330_000)
);
- let result = advance_goal_confirmations(initial, false, |_id, approve| async move {
- if approve {
- Ok(DesktopResponse::ok(
- "run-goal",
- json!({"stop":"confirmation_required", "confirmation_id":"once", "turns":[null]}),
- ))
- } else {
- Err("connection lost".to_owned())
- }
- })
- .await;
- let error = result.unwrap_err();
- assert!(error.contains("continuation limit"));
- assert!(error.contains("cancellation delivery is uncertain: connection lost"));
-}
-
-#[tokio::test]
-async fn continuation_ceiling_rejects_a_module_that_refuses_cancellation() {
- let initial = DesktopResponse::ok(
- "run-goal",
- json!({"stop":"confirmation_required", "confirmation_id":"once"}),
+ assert_eq!(
+ goal.timeout_policy(&json!({"max_elapsed_ms":999_999})),
+ ToolTimeout::Millis(330_000)
);
- let result = advance_goal_confirmations(initial, false, |_id, approve| async move {
- if approve {
- Ok(DesktopResponse::ok(
- "run-goal",
- json!({"stop":"confirmation_required", "confirmation_id":"once"}),
- ))
- } else {
- Ok(DesktopResponse::err(
- "run-goal",
- DesktopError::new("CANCEL_FAILED", "not cancelled"),
- ))
- }
- })
- .await;
- assert!(result.unwrap_err().contains("module refused cancellation"));
}
diff --git a/crates/openhuman-core/src/modules/desktop.rs b/crates/openhuman-core/src/modules/desktop.rs
index c7757b303e..890fe48785 100644
--- a/crates/openhuman-core/src/modules/desktop.rs
+++ b/crates/openhuman-core/src/modules/desktop.rs
@@ -120,6 +120,16 @@ async fn call_with_proxy<Request: Serialize + Send>(
member: &str,
request: Request,
) -> Result<DesktopResponse, String> {
+ // RunGoal enforces its own shorter elapsed-time budget (at most five
+ // minutes). Keep the bus deadline beyond that budget so the caller gets a
+ // structured stop and partial execution evidence instead of a transport
+ // timeout after TinyBus's default 30 seconds.
+ let goal_proxy = (member == names::methods::RUN_GOAL).then(|| {
+ proxy
+ .clone()
+ .with_timeout(std::time::Duration::from_secs(330))
+ });
+ let proxy = goal_proxy.as_ref().unwrap_or(proxy);
let response = if member == names::methods::RUN_GOAL || member == names::methods::RESOLVE_INTENT
{
proxy
diff --git a/scripts/debug/desktop-live.mjs b/scripts/debug/desktop-live.mjs
index 9cffb9498d..dedfca4691 100644
--- a/scripts/debug/desktop-live.mjs
+++ b/scripts/debug/desktop-live.mjs
@@ -2,20 +2,21 @@
/**
* Opt-in core-only desktop smoke test against an already-running local core.
*
- * Prepare a disposable TextEdit document first for the textedit scenario. Set
- * `[agent] tool_dispatcher = "native"` in the isolated config for an OpenRouter
- * model that supports structured tool calls. Start the core with an
- * isolated OPENHUMAN_WORKSPACE, an operator-supplied OPENHUMAN_CORE_TOKEN (so it
- * writes no core.token file), and OPENROUTER_API_KEY when no TinyHumans session
- * is present. Then run:
+ * Prepare the disposable TextEdit document `desktop-e2e-noapproval.txt` first
+ * for the textedit scenario. Use native tool dispatch for an OpenRouter model
+ * that supports structured tool calls. Point --workspace at the running core's
+ * actual workspace; a live signed-in profile works without changing its auth.
+ * Supply the core bearer in OPENHUMAN_CORE_TOKEN and, if needed, a live
+ * OPENROUTER_API_KEY. Then run:
*
* node scripts/debug/desktop-live.mjs --live --workspace "$OPENHUMAN_WORKSPACE" \
* --model 'openai/gpt-4.1-mini' --rpc-url http://127.0.0.1:7788/rpc
*
* The script prints only method names and counts. It never prints a prompt,
* transcript body, credential, accessibility value, or the random test marker.
- * It makes three bounded orchestrator turns: discover/list apps, type into the
- * disposable document through Jev, and read the value back through accessibility.
+ * The Calculator scenario makes one orchestrator turn and requires the goal
+ * to complete multiple actions through one Jev call. The other scenarios make
+ * bounded discovery, goal, and independent-readback turns.
* Clean up the disposable document after the run.
*/
@@ -57,7 +58,9 @@ const openRouterKey = process.env.OPENROUTER_API_KEY;
const approveDisposable = process.argv.includes('--approve-disposable');
const localOfflineSession = process.argv.includes('--local-offline-session');
const scenario = option('--scenario', 'textedit');
-if (!['textedit', 'spotify', 'spotify_pause'].includes(scenario)) fail('--scenario must be textedit, spotify, or spotify_pause');
+if (!['textedit', 'spotify', 'spotify_pause', 'calculator'].includes(scenario)) {
+ fail('--scenario must be textedit, spotify, spotify_pause, or calculator');
+}
if (!workspace || !model || !token) {
fail('Set --workspace, --model, and OPENHUMAN_CORE_TOKEN.');
}
@@ -189,7 +192,43 @@ console.log(`desktop: module=${status.module_state}, accessibility=${status.acce
if (!status.jev_ready) fail('No Jev credential is available to the core.');
if (status.approvals_enabled !== false) fail('Live no-prompt run requires desktop approvals disabled.');
-const appName = scenario === 'textedit' ? 'TextEdit' : 'Spotify';
+const appName = scenario === 'textedit' ? 'TextEdit' : scenario === 'calculator' ? 'Calculator' : 'Spotify';
+if (scenario === 'calculator') {
+ const transcript = await turn('single-turn',
+ 'In the native Calculator app, compute 12 + 34 and verify that the displayed result is 46. ' +
+ 'Use tool_search to discover desktop tools, launch Calculator, and inspect its accessibility snapshot. ' +
+ 'Then make exactly one desktop_goal call. Give it a bounded goal, the exact current window scope, ' +
+ 'CLICK as the only allowed mutation, exact target labels from the snapshot, and a value_equals or ' +
+ 'value_contains success predicate for the result display using its exact accessibility label. ' +
+ 'Allow up to 12 actions, 24 Jev decisions and 120 seconds. Do not use desktop_act. ' +
+ 'The Jev loop should do the calculator steps itself; do not make another desktop_goal call for each key. ' +
+ 'After the goal, read a fresh desktop_snapshot and report whether 46 is visible.');
+ const observedCalls = calls(transcript);
+ if (!observedCalls.includes('tool_search') || !observedCalls.includes('desktop_launch') ||
+ !observedCalls.includes('desktop_goal') || !observedCalls.includes('desktop_snapshot')) {
+ fail(`single-turn: missing desktop discovery, launch, goal or snapshot; saw ${observedCalls.join(', ')}`);
+ }
+ if (observedCalls.filter((name) => name === 'desktop_goal').length !== 1) {
+ fail('single-turn: expected exactly one desktop_goal call');
+ }
+ const goal = toolOutput(transcript, 'desktop_goal');
+ if (goal?.verified !== true || !Array.isArray(goal.turns) || goal.turns.length < 2) {
+ fail(`single-turn: goal did not verify a multi-action result (stop=${goal?.stop ?? 'missing'}, steps=${goal?.turns?.length ?? 0})`);
+ }
+ const snapshot = toolOutput(transcript, 'desktop_snapshot');
+ if (!JSON.stringify(snapshot ?? '').includes('46')) {
+ fail('single-turn: independent Calculator snapshot did not contain result 46');
+ }
+ const pending = await rpc('openhuman.desktop_pending');
+ const generic = await rpc('openhuman.approval_list_pending');
+ const genericRows = Array.isArray(generic) ? generic : generic?.result;
+ if ((Array.isArray(pending) && pending.length > 0) || !Array.isArray(genericRows) || genericRows.length > 0) {
+ fail('single-turn: an approval remained pending');
+ }
+ console.log(`single-turn: one desktop_goal call, ${goal.turns.length} actions, verified result 46, no pending approvals`);
+ console.log('PASS: Calculator task completed through one orchestrator turn and one Jev goal call.');
+ process.exit(0);
+}
let transcript = await turn('discover',
`List the running desktop applications on this computer. Discover desktop tools with tool_search first, then call the matching desktop tool. Report only whether ${appName} is running.`);
let names = calls(transcript);
@@ -204,17 +243,29 @@ names = calls(transcript);
if (!names.includes('desktop_launch')) fail(`windows: desktop_launch was not called; saw ${names.join(', ')}`);
if (!names.includes('desktop_list_windows')) fail(`windows: desktop_list_windows was not called; saw ${names.join(', ')}`);
console.log('windows: desktop_launch -> desktop_list_windows observed');
+const listedWindows = toolOutput(transcript, 'desktop_list_windows');
+const activeWindow = Array.isArray(listedWindows)
+ ? listedWindows.find((window) => window.title === 'desktop-e2e-noapproval.txt' && window.accessible)
+ : null;
+if (scenario === 'textedit' && (!activeWindow?.title || !activeWindow?.id)) {
+ fail('windows: disposable TextEdit test document is not available');
+}
transcript = await turn('goal', scenario !== 'textedit'
- ? `In the running Spotify desktop app, ${scenario === 'spotify_pause' ? 'pause playback' : 'play the current track if paused'}. Use tool_search to find desktop_goal and run it with max_steps 4 and max_model_calls 8. Verify the player shows a ${scenario === 'spotify_pause' ? 'Play' : 'Pause'} control. Do not change playlists or account settings.`
+ ? `In the running Spotify desktop app, ${scenario === 'spotify_pause' ? 'pause playback' : 'play the current track if paused'}. Use tool_search to find desktop_goal and run it with max_steps 4 and max_model_calls 8. Supply a name_present success predicate for the ${scenario === 'spotify_pause' ? 'Play' : 'Pause'} control using its exact accessibility name. Do not change playlists or account settings.`
: `In the already open disposable TextEdit document, append this exact marker: ${marker}. ` +
- 'Use tool_search to find desktop_goal. Pass the marker as the first value in its text array, and run the bounded goal with max_steps 4 and max_model_calls 8. Do not save or close the document.');
+ `The just-inspected disposable document is titled ${JSON.stringify(activeWindow.title)} and its editable field has the exact native AX identifier "First Text View". ` +
+ `Use tool_search to find desktop_goal, then call it once with app TextEdit, window ${JSON.stringify(activeWindow.title)}, window_id ${JSON.stringify(activeWindow.id)}, ` +
+ 'allowed_operations [TYPE_TEXT], allowed_targets [First Text View], a text_slots entry keyed First Text View ' +
+ 'containing the marker, and a value_contains success predicate with name First Text View and value equal to the marker. ' +
+ 'Set max_steps 4 and max_model_calls 8. Let the goal tool make its own fresh observation. Do not save or close the document.');
names = calls(transcript);
if (!names.includes('desktop_goal')) fail(`goal: desktop_goal was not called; saw ${names.join(', ')}`);
const goalResult = toolOutput(transcript, 'desktop_goal');
if (!goalResult || !Array.isArray(goalResult.turns) || goalResult.turns.length < 1) {
fail('goal: no desktop action was executed; an observed app state alone is insufficient');
}
+if (goalResult.verified !== true) fail(`goal: result was not independently verified (stop=${goalResult.stop})`);
console.log(`goal: stop=${goalResult.stop}, executed_steps=${goalResult.turns.length}, jev_calls=${goalResult.metrics?.calls ?? 0}`);
const pending = await rpc('openhuman.desktop_pending');
@@ -244,7 +295,7 @@ if (Array.isArray(pending) && pending.length > 0) {
const beforeVerify = transcript.length;
transcript = await turn('verify', scenario !== 'textedit'
? `Read the full accessibility snapshot of the Spotify player using desktop_snapshot with skeleton false. Do not change playback. Report whether a ${scenario === 'spotify_pause' ? 'Play' : 'Pause'} control is visible.`
- : 'Read the full accessibility snapshot of the current TextEdit document using desktop_snapshot with skeleton false. Do not change the document.');
+ : `Read the full accessibility snapshot of TextEdit window_id ${JSON.stringify(activeWindow.id)} using desktop_snapshot with skeleton false. Do not change the document.`);
const verifyRecords = transcript.slice(beforeVerify);
names = calls(verifyRecords);
if (!names.includes('desktop_snapshot')) fail(`verify: desktop_snapshot was not called; saw ${names.join(', ')}`);
diff --git a/vendor/tinydesktop b/vendor/tinydesktop
index cab323a2bf..40723470cb 160000
--- a/vendor/tinydesktop
+++ b/vendor/tinydesktop
@@ -1 +1 @@
-Subproject commit cab323a2bf92da0a52d1a77665076ef7ada89ee4
+Subproject commit 40723470cbb8dfbdc01e6e210ca3bb5788511f87