The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(computer): make browser tasks runnable and diagnosable on the hosted route
Shanu29817a2d94d2
diff --git a/.env.example b/.env.exampleindex 38eec596ea..4d6622ca29 100644--- a/.env.example+++ b/.env.example@@ -140,6 +140,16 @@ OPENHUMAN_TEMPERATURE=0.7# ---------------------------------------------------------------------------# [optional] Default: 0OPENHUMAN_BROWSER_ALLOW_ALL=0+# [optional] Trace TinyComputer runs, as `[computer] trace = true` does: every+# browser task records its decisions and keeps its full report, and desktop+# commands are traced, under <workspace>/state/computer/. Reports hold page+# text. Default: 0+OPENHUMAN_COMPUTER_TRACE=0+# [optional] TinyComputer's own debug journal, read by the module inside this+# process: every Jev call with its latency, and the wall time of each decision,+# action and step, written under this directory (1 = ./.jev-journal). Read it+# with tinycomputer's `jev_journal` example. Off when unset.+# TINYCOMPUTER_JEV_JOURNAL=# [optional] Default: 0OPENHUMAN_LOG_PROMPTS=0# [optional] Enable reasoning modediff --git a/crates/openhuman-core/src/config/schema/computer.rs b/crates/openhuman-core/src/config/schema/computer.rsindex 76ce224ecf..683c1e31a6 100644--- a/crates/openhuman-core/src/config/schema/computer.rs+++ b/crates/openhuman-core/src/config/schema/computer.rs@@ -45,6 +45,11 @@ pub struct ComputerConfig {/// How many times one task may be rescued; `0` turns rescue off and/// `None` keeps the module's default (5, also its maximum).pub max_rescues: Option<u32>,+ /// Record every decision of a browser task and keep each task's full+ /// report, and trace desktop commands, under `<workspace>/state/computer/`.+ /// Off by default: reports hold page text. `OPENHUMAN_COMPUTER_TRACE=1`+ /// turns it on for one run without editing the config.+ pub trace: bool,}#[cfg(test)]diff --git a/crates/openhuman-core/src/modules/browser.rs b/crates/openhuman-core/src/modules/browser.rsindex 0786aa4189..3bc18bc3d3 100644--- a/crates/openhuman-core/src/modules/browser.rs+++ b/crates/openhuman-core/src/modules/browser.rs@@ -20,6 +20,21 @@ use crate::config::Config;pub const MODULE_ID: &str = super::desktop::MODULE_ID;+/// What the agent is told when TinyComputer finds no Chrome. The module looks+/// in its own cache, the standard install locations, and the Puppeteer and+/// Playwright caches, so a Chrome kept anywhere else (`~/Applications`, the+/// Desktop) needs its path set. Left without this, an agent tried to install+/// a browser itself (`npx agent-browser install`, then `sudo`).+pub(crate) const CHROME_NOT_FOUND_HINT: &str = "Chrome was not found. Ask the user to set \+ the full path to the Chrome program under Connections > Computer Control > Browser > \+ Chrome path (for example /Applications/Google Chrome.app/Contents/MacOS/Google Chrome), \+ then try again. Do not install or download a browser yourself.";++/// Whether a module error or task failure says Chrome could not be found.+pub(crate) fn chrome_not_found(text: &str) -> bool {+ text.to_ascii_lowercase().contains("chrome not found")+}+#[derive(Debug, thiserror::Error)]pub enum BrowserCallError {#[error("TinyComputer browser unavailable: {0}")]@@ -55,10 +70,12 @@ impl BrowserCallError {.and_then(serde_json::Value::as_str).map(|name| name.rsplit('.').next().unwrap_or(name).to_owned()).unwrap_or_else(|| error.code.clone());- Self::Bus {- name,- message: error.message.clone(),- }+ let message = if chrome_not_found(&error.message) {+ format!("{} {CHROME_NOT_FOUND_HINT}", error.message)+ } else {+ error.message.clone()+ };+ Self::Bus { name, message }}}diff --git a/crates/openhuman-core/src/modules/browser_task.rs b/crates/openhuman-core/src/modules/browser_task.rsindex 0a89a6854d..0eae2e4b99 100644--- a/crates/openhuman-core/src/modules/browser_task.rs+++ b/crates/openhuman-core/src/modules/browser_task.rs@@ -67,6 +67,7 @@ pub fn start_request(config: &Config, task: &BrowserTask) -> StartTaskRequest {max_rescues: config.computer.max_rescues,..TaskBudget::default()},+ trace: super::computer_config::tracing_enabled(config),..StartTaskRequest::default()}}@@ -89,7 +90,7 @@ pub async fn start(config: &Config, task: &BrowserTask) -> Result<TaskView, Stri"[browser-task] starting");let view: TaskView = call(config, methods::START_TASK, request, true).await?;- follow(config, view).await+ settle(config, view).await}/// Answer a paused task and follow it again.@@ -100,7 +101,7 @@ pub async fn start(config: &Config, task: &BrowserTask) -> Result<TaskView, Stripub async fn resume(config: &Config, request: ContinueTaskRequest) -> Result<TaskView, String> {tracing::debug!(task = %request.id, approve = ?request.approve, "[browser-task] continuing");let view: TaskView = call(config, methods::CONTINUE_TASK, request, true).await?;- follow(config, view).await+ settle(config, view).await}/// Keep following a task that was still running when the last call returned.@@ -119,7 +120,7 @@ pub async fn wait(config: &Config, id: TaskId) -> Result<TaskView, String> {false,).await?;- follow(config, view).await+ settle(config, view).await}/// Cancel a task.@@ -140,15 +141,38 @@ pub async fn cancel(config: &Config, id: TaskId) -> Result<TaskView, String> {////// Returns a module or transport error.pub async fn report(config: &Config, id: TaskId) -> Result<TaskReport, String> {+ report_with(config, id, false).await+}++/// The task's record, with every Jev exchange when `trace` is set and the+/// task was started with `StartTask.trace`. A traced report can run to+/// megabytes, so only the tracing path asks for it.+///+/// # Errors+///+/// Returns a module or transport error.+pub(crate) async fn report_with(+ config: &Config,+ id: TaskId,+ trace: bool,+) -> Result<TaskReport, String> {call(config,methods::TASK_REPORT,- TaskReportRequest { id, trace: false },+ TaskReportRequest { id, trace },true,).await}+/// Follow `view` until it stops or the host deadline passes, then record+/// how it stopped (see [`super::browser_task_report`]).+async fn settle(config: &Config, view: TaskView) -> Result<TaskView, String> {+ let view = follow(config, view).await?;+ super::browser_task_report::record(config, &view).await;+ Ok(view)+}+async fn follow(config: &Config, mut view: TaskView) -> Result<TaskView, String> {let deadline = Instant::now() + Duration::from_secs(config.browser.task_timeout_secs.max(1));while matches!(view.status, tinycomputer_bus::agent::TaskStatus::Running) {diff --git a/crates/openhuman-core/src/modules/browser_task_report.rs b/crates/openhuman-core/src/modules/browser_task_report.rsnew file mode 100644index 0000000000..1bc9e3fdda--- /dev/null+++ b/crates/openhuman-core/src/modules/browser_task_report.rs@@ -0,0 +1,235 @@+//! What the host keeps from a browser task once it stops: a content-free+//! summary in the log when the task stopped short (failed, or needs a person+//! or a plan), and — with tracing on — the module's full report under+//! `<workspace>/state/computer/tasks/`.+//!+//! A report holds page text (step notes, records and, when traced, every Jev+//! exchange), so it is written only to the workspace and never logged: the+//! log gets counts, the failed step's position and kind, and the module's own+//! one-line reason.++use std::collections::VecDeque;+use std::path::PathBuf;+use std::sync::{Mutex, OnceLock};+use std::time::{SystemTime, UNIX_EPOCH};++use tinycomputer_bus::agent::{RescueOutcome, TaskReport, TaskStatus, TaskView};+use tinycomputer_bus::flow::StepOutcome;++use crate::config::Config;++#[cfg(test)]+#[path = "browser_task_report_tests.rs"]+mod tests;++/// How many stopped tasks are remembered, so a view followed again does not+/// record the same stop twice.+const REMEMBERED: usize = 64;+/// The most characters of a failure reason written to the log.+const REASON_CHARS: usize = 240;++/// Records `view` once per task and state: a log summary when it stopped+/// short, and the full report on disk when tracing is on and it settled.+/// Never fails the caller; a report that cannot be fetched is only logged.+pub(crate) async fn record(config: &Config, view: &TaskView) {+ let traced = super::computer_config::tracing_enabled(config);+ if !worth_recording(&view.status, traced) || !first_time(view) {+ return;+ }+ let report = match super::browser_task::report_with(config, view.id.clone(), traced).await {+ Ok(report) => report,+ Err(error) => {+ tracing::warn!(task = %view.id, %error, "[browser-task] report unavailable");+ return;+ }+ };+ if stopped_short(&view.status) {+ let summary = Summary::of(&view.status, &report);+ tracing::warn!(+ task = %view.id,+ state = status_name(&view.status),+ step = ?summary.failed_step,+ kind = summary.failed_kind.unwrap_or("-"),+ steps = summary.steps,+ jev_calls = summary.jev_calls,+ actions = summary.actions,+ rescues = summary.rescues,+ recovered = summary.recovered,+ reason = %reason(&view.status),+ "[browser-task] task stopped short"+ );+ }+ if traced {+ write(config, &report).await;+ }+}++/// A task that ended without doing what it was asked.+fn stopped_short(status: &TaskStatus) -> bool {+ matches!(+ status,+ TaskStatus::Failed { .. } | TaskStatus::NeedsHuman { .. } | TaskStatus::NeedsPlan { .. }+ )+}++fn worth_recording(status: &TaskStatus, traced: bool) -> bool {+ stopped_short(status) || (traced && !matches!(status, TaskStatus::Running))+}++/// Whether this task has not been recorded in this state yet.+fn first_time(view: &TaskView) -> bool {+ static SEEN: OnceLock<Mutex<VecDeque<String>>> = OnceLock::new();+ let key = format!(+ "{}|{}|{:.3}",+ view.id,+ status_name(&view.status),+ view.progress+ );+ let mut seen = SEEN+ .get_or_init(Mutex::default)+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if seen.contains(&key) {+ return false;+ }+ if seen.len() == REMEMBERED {+ seen.pop_front();+ }+ seen.push_back(key);+ true+}++fn status_name(status: &TaskStatus) -> &'static str {+ match status {+ TaskStatus::Running => "running",+ TaskStatus::NeedsInput { .. } => "needs_input",+ TaskStatus::NeedsApproval { .. } => "needs_approval",+ TaskStatus::Checkpoint { .. } => "checkpoint",+ TaskStatus::NeedsHuman { .. } => "needs_human",+ TaskStatus::NeedsPlan { .. } => "needs_plan",+ TaskStatus::Done { .. } => "done",+ TaskStatus::Failed { .. } => "failed",+ TaskStatus::Cancelled => "cancelled",+ }+}++/// The module's own reason for stopping, cut to [`REASON_CHARS`].+fn reason(status: &TaskStatus) -> String {+ let reason = match status {+ TaskStatus::Failed { reason, .. } | TaskStatus::NeedsHuman { reason, .. } => {+ reason.as_str()+ }+ TaskStatus::NeedsPlan { .. } => "no planner is configured",+ _ => "",+ };+ reason.chars().take(REASON_CHARS).collect()+}++/// The counts a stopped task is logged with; nothing a page showed.+#[derive(Debug, PartialEq, Eq)]+struct Summary {+ steps: usize,+ jev_calls: u64,+ actions: usize,+ rescues: usize,+ recovered: usize,+ failed_step: Option<usize>,+ failed_kind: Option<&'static str>,+}++impl Summary {+ fn of(status: &TaskStatus, report: &TaskReport) -> Self {+ let failed_step = match status {+ TaskStatus::Failed { step, .. } => *step,+ _ => None,+ };+ Self {+ steps: report.steps.len(),+ jev_calls: report+ .steps+ .iter()+ .map(|step| u64::from(step.jev_calls))+ .sum(),+ actions: report.steps.iter().map(|step| step.actions.len()).sum(),+ rescues: report.rescues.len(),+ recovered: report+ .rescues+ .iter()+ .filter(|rescue| rescue.outcome == RescueOutcome::Recovered)+ .count(),+ failed_step,+ failed_kind: report+ .steps+ .iter()+ .rev()+ .find(|step| step.outcome == StepOutcome::Failed)+ .map(|step| kind_name(&step.kind)),+ }+ }+}++/// A step kind as the log may show it: one of the flow grammar's own words,+/// never free text.+fn kind_name(kind: &str) -> &'static str {+ const KINDS: &[&str] = &[+ "open",+ "browse",+ "do",+ "enter",+ "choose",+ "read",+ "extract",+ "pick",+ "verify",+ "wait_for",+ "if",+ "repeat_until",+ "stop_before",+ ];+ KINDS+ .iter()+ .find(|known| kind.eq_ignore_ascii_case(known))+ .copied()+ .unwrap_or("other")+}++/// Where a report of task `id`, recorded at `millis`, is written.+fn report_path(config: &Config, id: &str, millis: u128) -> PathBuf {+ let id: String = id+ .chars()+ .filter(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))+ .collect();+ super::computer_config::trace_dir(config)+ .join("tasks")+ .join(format!("{millis}-{id}.json"))+}++async fn write(config: &Config, report: &TaskReport) {+ let millis = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map_or(0, |elapsed| elapsed.as_millis());+ let path = report_path(config, &report.view.id.0, millis);+ let bytes = match serde_json::to_vec_pretty(report) {+ Ok(bytes) => bytes,+ Err(error) => {+ tracing::warn!(%error, "[browser-task] report not serializable");+ return;+ }+ };+ if let Some(dir) = path.parent() {+ if let Err(error) = tokio::fs::create_dir_all(dir).await {+ tracing::warn!(%error, "[browser-task] report directory unavailable");+ return;+ }+ }+ match tokio::fs::write(&path, &bytes).await {+ Ok(()) => tracing::info!(+ task = %report.view.id,+ path = %path.display(),+ bytes = bytes.len(),+ exchanges = report.trace.len(),+ "[browser-task] report written"+ ),+ Err(error) => tracing::warn!(%error, "[browser-task] report not written"),+ }+}diff --git a/crates/openhuman-core/src/modules/browser_task_report_tests.rs b/crates/openhuman-core/src/modules/browser_task_report_tests.rsnew file mode 100644index 0000000000..423c79bd2c--- /dev/null+++ b/crates/openhuman-core/src/modules/browser_task_report_tests.rs@@ -0,0 +1,167 @@+//! A stopped task is summarised without page content, recorded once per+//! state, and its full report is written inside the workspace.++use super::*;+use serde_json::{json, Value};++fn view(id: &str, status: Value, progress: f32) -> TaskView {+ serde_json::from_value(json!({+ "id": id,+ "status": status,+ "summary": "searching",+ "progress": progress,+ "next": []+ }))+ .unwrap()+}++fn failed() -> Value {+ json!({+ "state": "failed",+ "step": 2,+ "reason": "the last three actions changed nothing on screen",+ "hint": "",+ "recoverable": true+ })+}++fn report(view: &TaskView) -> TaskReport {+ serde_json::from_value(json!({+ "view": view,+ "steps": [+ {"path": "0", "kind": "browse", "text": "open the site", "outcome": "done",+ "turns": 0, "jev_calls": 0, "actions": [], "loops": [], "note": ""},+ {"path": "1", "kind": "enter", "text": "type Asha", "outcome": "done",+ "turns": 2, "jev_calls": 14, "actions": [{"action": "fill", "ok": true}],+ "loops": [], "note": ""},+ {"path": "2", "kind": "do", "text": "search for trains", "outcome": "failed",+ "turns": 3, "jev_calls": 21,+ "actions": [{"action": "click", "ok": true}, {"action": "click", "ok": false}],+ "loops": [], "note": "nothing changed"}+ ],+ "records": {},+ "artifacts": [],+ "learned": [],+ "trace": [],+ "rescues": [+ {"step": 2, "failure": "nothing changed", "reason": "timed out", "outcome": "gave_up"}+ ]+ }))+ .unwrap()+}++#[test]+fn a_task_that_stopped_short_is_summarised_with_counts_not_page_text() {+ let view = view("t-summary", failed(), 0.33);+ let summary = Summary::of(&view.status, &report(&view));+ assert_eq!(+ summary,+ Summary {+ steps: 3,+ jev_calls: 35,+ actions: 3,+ rescues: 1,+ recovered: 0,+ failed_step: Some(2),+ failed_kind: Some("do"),+ }+ );+}++#[test]+fn only_a_task_that_stopped_short_or_a_traced_settled_one_is_recorded() {+ let done = view(+ "t-done",+ json!({"state": "done", "answer": "found", "records": {}}),+ 1.0,+ );+ let running = view("t-running", json!({"state": "running"}), 0.5);+ let human = view(+ "t-human",+ json!({"state": "needs_human", "reason": "log in"}),+ 0.5,+ );+ let plan = view("t-plan", json!({"state": "needs_plan", "guide": "…"}), 0.0);+ let failed = view("t-failed", failed(), 0.3);++ assert!(worth_recording(&failed.status, false));+ assert!(worth_recording(&human.status, false));+ assert!(worth_recording(&plan.status, false));+ assert!(!worth_recording(&done.status, false));+ assert!(worth_recording(&done.status, true));+ assert!(!worth_recording(&running.status, true));+}++#[test]+fn the_same_stop_is_recorded_once() {+ let first = view("t-dedupe", failed(), 0.33);+ assert!(first_time(&first));+ assert!(+ !first_time(&first),+ "followed again, it is not recorded twice"+ );+ let later = view("t-dedupe", failed(), 0.66);+ assert!(first_time(&later), "a later stop of the same task is new");+}++#[test]+fn the_logged_reason_is_the_modules_own_line_cut_short() {+ let long = "x".repeat(500);+ let status: TaskStatus = serde_json::from_value(json!({+ "state": "failed", "step": null, "reason": long, "hint": "", "recoverable": false+ }))+ .unwrap();+ assert_eq!(reason(&status).chars().count(), REASON_CHARS);+ let plan: TaskStatus =+ serde_json::from_value(json!({"state": "needs_plan", "guide": "write a flow"})).unwrap();+ assert_eq!(reason(&plan), "no planner is configured");+ assert_eq!(reason(&TaskStatus::Cancelled), "");+}++#[test]+fn a_step_kind_outside_the_flow_grammar_is_logged_as_other() {+ assert_eq!(kind_name("DO"), "do");+ assert_eq!(kind_name("stop_before"), "stop_before");+ assert_eq!(kind_name("<b>Pay</b>"), "other");+}++#[test]+fn a_report_path_stays_in_the_workspace_and_names_the_task_safely() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.workspace_dir = dir.path().join("workspace");+ let path = report_path(&config, "t-1/../etc", 42);+ assert_eq!(+ path,+ config+ .workspace_dir+ .join("state")+ .join("computer")+ .join("tasks")+ .join("42-t-1etc.json")+ );+}++#[tokio::test]+async fn a_traced_report_is_written_whole_into_the_workspace() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.workspace_dir = dir.path().join("workspace");+ let view = view("t-write", failed(), 0.33);+ let report = report(&view);+ write(&config, &report).await;+ let tasks = super::super::computer_config::trace_dir(&config).join("tasks");+ let written = std::fs::read_dir(&tasks)+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .collect::<Vec<_>>();+ assert_eq!(written.len(), 1, "{written:?}");+ let name = written[0]+ .file_name()+ .unwrap()+ .to_string_lossy()+ .into_owned();+ assert!(name.ends_with("-t-write.json"), "{name}");+ let back: TaskReport = serde_json::from_slice(&std::fs::read(&written[0]).unwrap()).unwrap();+ assert_eq!(back, report);+}diff --git a/crates/openhuman-core/src/modules/browser_task_tests.rs b/crates/openhuman-core/src/modules/browser_task_tests.rsindex ccf1bceb0f..f18842f3d1 100644--- a/crates/openhuman-core/src/modules/browser_task_tests.rs+++ b/crates/openhuman-core/src/modules/browser_task_tests.rs@@ -30,6 +30,13 @@ fn start_request_confines_the_task_to_the_browser_under_host_policy() {assert_eq!(request.budget.max_rescues, Some(2));}+#[test]+fn a_traced_host_asks_the_module_to_record_every_decision() {+ let mut config = Config::default();+ config.computer.trace = true;+ assert!(start_request(&config, &task()).trace);+}+#[tokio::test]async fn start_refuses_a_task_without_origins() {let mut empty = task();diff --git a/crates/openhuman-core/src/modules/browser_tests.rs b/crates/openhuman-core/src/modules/browser_tests.rsindex 2f1fc68e01..60e98620d5 100644--- a/crates/openhuman-core/src/modules/browser_tests.rs+++ b/crates/openhuman-core/src/modules/browser_tests.rs@@ -131,6 +131,27 @@ fn failed_reply_without_a_name_falls_back_to_the_code() {));}+#[test]+fn a_missing_chrome_tells_the_agent_where_the_user_sets_its_path() {+ let response: DesktopResponse = serde_json::from_value(serde_json::json!({+ "version": "2.5",+ "ok": false,+ "command": "browser-open-session",+ "error": {+ "code": "BROWSER_UNAVAILABLE",+ "message": "browser unavailable: Chrome not found. Checked: - System Chrome installations",+ "details": {"name": "ai.tinyhumans.tinycomputer.Browser.Error.BrowserUnavailable"}+ }+ }))+ .unwrap();+ let error = BrowserCallError::from_response(&response).to_string();+ assert!(error.starts_with("BrowserUnavailable: browser unavailable: Chrome not found"));+ assert!(error.contains("Chrome path"), "{error}");+ assert!(error.contains("Do not install"), "{error}");+ assert!(chrome_not_found("CHROME NOT FOUND"));+ assert!(!chrome_not_found("Chrome launch timed out"));+}+#[test]fn fresh_profile_is_the_default() {let config = Config::default();diff --git a/crates/openhuman-core/src/modules/computer_config.rs b/crates/openhuman-core/src/modules/computer_config.rsindex 0c6643dc31..5064a569c2 100644--- a/crates/openhuman-core/src/modules/computer_config.rs+++ b/crates/openhuman-core/src/modules/computer_config.rs@@ -9,6 +9,9 @@//! - `planner` — the planner, rescue and output models: through the//! TinyHumans proxy when signed in, else the user's OpenRouter key.//! - `browser` — the Chrome executable the user picked, if any.+//! - `trace_path` — where desktop commands are traced, when tracing is on.++use std::path::PathBuf;use serde_json::{json, Map, Value};@@ -56,6 +59,15 @@ fn jev(config: &Config, hosted: Option<&str>) -> Option<Value> {}}+/// The model the TinyHumans gateway runs the planner, rescue and output+/// roles on when the user picked none. The module's own defaults are+/// OpenRouter ids (`anthropic/claude-sonnet-5`, `openai/gpt-6-luna`) that the+/// gateway refuses ("Model … is not available"), so a signed-in task failed+/// before its first step; the gateway's reasoning tier can outlast its+/// request timeout on a rescue (HTTP 504). A direct OpenRouter key keeps the+/// module's defaults.+pub const HOSTED_REASONING_MODEL: &str = "agentic-v1";+fn planner(config: &Config, hosted: Option<&str>) -> Option<Value> {let mut planner = match hosted {Some(api_key) => json!({@@ -69,17 +81,44 @@ fn planner(config: &Config, hosted: Option<&str>) -> Option<Value> {}};let computer = &config.computer;- for (key, value) in [- ("model", &computer.planner_model),- ("rescue_model", &computer.rescue_model),+ let fallback = hosted.map(|_| HOSTED_REASONING_MODEL);+ for (key, chosen) in [+ ("model", computer.planner_model.as_deref()),+ ("rescue_model", computer.rescue_model.as_deref()),+ ("output_model", None),] {- if let Some(model) = value {+ let chosen = chosen.map(str::trim).filter(|model| !model.is_empty());+ if let Some(model) = chosen.or(fallback) {planner[key] = json!(model);}}Some(planner)}+/// The environment switch that turns tracing on for one run.+pub const TRACE_ENV: &str = "OPENHUMAN_COMPUTER_TRACE";++/// Whether TinyComputer runs are traced: `[computer] trace`, or+/// `OPENHUMAN_COMPUTER_TRACE=1` in the environment.+#[must_use]+pub fn tracing_enabled(config: &Config) -> bool {+ tracing_enabled_with(config, std::env::var(TRACE_ENV).ok().as_deref())+}++fn tracing_enabled_with(config: &Config, env: Option<&str>) -> bool {+ config.computer.trace+ || matches!(+ env.map(str::trim),+ Some("1" | "true" | "TRUE" | "yes" | "YES")+ )+}++/// Where traces and task reports are written: `<workspace>/state/computer`.+#[must_use]+pub fn trace_dir(config: &Config) -> PathBuf {+ config.workspace_dir.join("state").join("computer")+}+/// Build the module configuration for `config`.#[must_use]pub fn module_config(config: &Config) -> Value {@@ -94,11 +133,23 @@ pub fn module_config(config: &Config) -> Value {if let Some(executable) = config.browser.chrome_path.as_ref() {out.insert("browser".into(), json!({ "executable": executable }));}+ let traced = tracing_enabled(config);+ if traced {+ let dir = trace_dir(config);+ if let Err(error) = std::fs::create_dir_all(&dir) {+ tracing::warn!(%error, "[computer] trace directory unavailable");+ }+ out.insert(+ "trace_path".into(),+ json!(dir.join("desktop-trace.jsonl").to_string_lossy()),+ );+ }tracing::debug!(decision_model = config.computer.decision_model.as_str(),jev = out.contains_key("jev"),planner = out.contains_key("planner"),hosted = hosted.is_some(),+ traced,"[computer] module config built");Value::Object(out)diff --git a/crates/openhuman-core/src/modules/computer_config_tests.rs b/crates/openhuman-core/src/modules/computer_config_tests.rsindex 55d1c22b19..78db732eb1 100644--- a/crates/openhuman-core/src/modules/computer_config_tests.rs+++ b/crates/openhuman-core/src/modules/computer_config_tests.rs@@ -37,9 +37,24 @@ fn signed_in_host_routes_jev_and_planner_through_tinyhumans() {assert!(value["planner"]["sdk_name"].is_string());assert_eq!(value["planner"]["rescue_model"], "openai/gpt-6-luna-pro");assert_eq!(value["planner"]["model"], "anthropic/claude-sonnet-5");+ // The output shaper has no setting; the gateway runs it on its own model.+ assert_eq!(value["planner"]["output_model"], HOSTED_REASONING_MODEL);assert_eq!(billing_route(&config), "hosted");}+#[test]+fn signed_in_host_runs_unchosen_roles_on_a_model_the_gateway_serves() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = config_in(dir.path());+ api_key::store_api_key(&config, "th_test_backend").unwrap();+ // A blank choice is no choice.+ config.computer.rescue_model = Some(" ".into());+ let value = module_config(&config);+ for role in ["model", "rescue_model", "output_model"] {+ assert_eq!(value["planner"][role], HOSTED_REASONING_MODEL, "{role}");+ }+}+#[test]fn byok_host_uses_openrouter_for_both() {let dir = tempfile::tempdir().unwrap();@@ -49,7 +64,10 @@ fn byok_host_uses_openrouter_for_both() {assert_eq!(value["jev"]["provider"], "open_router");assert_eq!(value["planner"]["provider"], "open_router");assert_eq!(value["planner"]["api_key"], "or_test_direct");- assert!(value["planner"].get("rescue_model").is_none());+ // OpenRouter serves the module's own defaults, so none is sent.+ for role in ["model", "rescue_model", "output_model"] {+ assert!(value["planner"].get(role).is_none(), "{role}");+ }assert_eq!(billing_route(&config), "direct_openrouter");}@@ -78,6 +96,33 @@ fn open_jev_and_sage_use_their_own_keys() {assert_eq!(billing_route(&config), "sage");}+#[test]+fn tracing_is_off_unless_the_config_or_the_environment_turns_it_on() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = config_in(dir.path());+ assert!(!tracing_enabled_with(&config, None));+ assert!(!tracing_enabled_with(&config, Some("0")));+ assert!(tracing_enabled_with(&config, Some("1")));+ assert!(tracing_enabled_with(&config, Some(" true ")));+ config.computer.trace = true;+ assert!(tracing_enabled_with(&config, None));+}++#[test]+fn a_traced_host_gives_the_module_a_desktop_trace_path_in_the_workspace() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = config_in(dir.path());+ config.computer.trace = true;+ let value = module_config(&config);+ let expected = trace_dir(&config).join("desktop-trace.jsonl");+ assert_eq!(value["trace_path"], json!(expected.to_string_lossy()));+ assert!(+ trace_dir(&config).is_dir(),+ "the trace directory is created"+ );+ assert!(expected.starts_with(&config.workspace_dir));+}+#[test]fn chrome_path_is_the_module_browser_executable() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rsindex 696ded9df9..3f80ce1289 100644--- a/crates/openhuman-core/src/modules/mod.rs+++ b/crates/openhuman-core/src/modules/mod.rs@@ -42,6 +42,7 @@pub mod boot;pub mod browser;pub mod browser_task;+mod browser_task_report;pub mod computer;pub mod computer_config;pub mod connectors;diff --git a/crates/openhuman-core/src/modules/schemas.rs b/crates/openhuman-core/src/modules/schemas.rsindex 0848aad26a..1f0604b72e 100644--- a/crates/openhuman-core/src/modules/schemas.rs+++ b/crates/openhuman-core/src/modules/schemas.rs@@ -159,6 +159,18 @@ pub fn schemas(function: &str) -> ControllerSchema {}}+/// What the settings page's Chrome check shows when Chrome would not start:+/// where to fix a missing Chrome, or else the module's own reason.+fn readiness_error(detail: &str) -> String {+ if super::browser::chrome_not_found(detail) {+ "Chrome was not found. Set Chrome path below to the Chrome program (for example \+ /Applications/Google Chrome.app/Contents/MacOS/Google Chrome), save, and test again."+ .to_owned()+ } else {+ format!("Chrome could not start: {detail}")+ }+}+fn handle_browser_check_readiness(_params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let mut config = config_rpc::load_config_with_timeout().await?;@@ -185,9 +197,9 @@ fn handle_browser_check_readiness(_params: Map<String, Value>) -> ControllerFutu"error": if closed { None } else { Some("Chrome session could not close cleanly") }}),)}- Ok(Err(_)) => Ok(+ Ok(Err(error)) => Ok(serde_json::json!({"module_ready": true, "chrome_ready": false,- "error": "Chrome could not start; check browser settings and allowed websites"}),+ "error": readiness_error(&error.to_string())}),),Err(_) => Ok(serde_json::json!({"module_ready": true, "chrome_ready": false,diff --git a/crates/openhuman-core/src/modules/schemas_tests.rs b/crates/openhuman-core/src/modules/schemas_tests.rsindex ed365dfac1..663c834e97 100644--- a/crates/openhuman-core/src/modules/schemas_tests.rs+++ b/crates/openhuman-core/src/modules/schemas_tests.rs@@ -67,3 +67,16 @@ async fn computer_status_handler_returns_serialized_status() {assert!(status.get("decision_model").is_some());}++#[test]+fn the_chrome_check_says_where_to_fix_a_missing_chrome() {+ let missing = super::readiness_error(+ "BrowserUnavailable: browser unavailable: Chrome not found. Checked: …",+ );+ assert!(missing.starts_with("Chrome was not found."), "{missing}");+ assert!(missing.contains("Chrome path"), "{missing}");+ assert_eq!(+ super::readiness_error("Bus: launch timed out"),+ "Chrome could not start: Bus: launch timed out"+ );+}diff --git a/crates/openhuman-core/src/tools/impl/browser/browser.rs b/crates/openhuman-core/src/tools/impl/browser/browser.rsindex 523fd09f6c..5edd81add7 100644--- a/crates/openhuman-core/src/tools/impl/browser/browser.rs+++ b/crates/openhuman-core/src/tools/impl/browser/browser.rs@@ -26,7 +26,7 @@ use std::{sync::{Arc, Mutex as StdMutex},time::Instant,};-use task_actions::{approve_task_action, parse_action, required, task_inputs};+use task_actions::{approve_task_action, host_hint, parse_action, required, task_inputs};use tinycomputer_bus::agent::{ContinueTaskRequest, TaskId, TaskStatus, TaskView};use tinycomputer_bus::browser::{Action, DownloadState, DownloadWaitRequest, NavigateRequest, ReadRequest, SessionId,@@ -311,6 +311,9 @@ impl BrowserTool {/// token that only `confirm_pending` (through the host gate) can spend.async fn report(&self, view: TaskView) -> anyhow::Result<Value> {let mut output = serde_json::to_value(&view)?;+ if let Some(hint) = host_hint(&view) {+ output["host_hint"] = json!(hint);+ }if let TaskStatus::NeedsApproval { action, target, .. } = &view.status {let token = uuid::Uuid::new_v4().to_string();*self.pending.lock().await = Some(Pending {diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_computer_tests.rs b/crates/openhuman-core/src/tools/impl/browser/browser_computer_tests.rsindex d6d3c04ac4..7d3d1541fd 100644--- a/crates/openhuman-core/src/tools/impl/browser/browser_computer_tests.rs+++ b/crates/openhuman-core/src/tools/impl/browser/browser_computer_tests.rs@@ -413,3 +413,24 @@ async fn task_rejects_a_malformed_flow_before_the_module() {.unwrap_err();assert!(error.to_string().contains("Invalid flow"), "{error}");}++#[test]+fn a_task_that_found_no_chrome_tells_the_agent_to_ask_for_its_path() {+ let failed = |reason: &str| -> TaskView {+ serde_json::from_value(json!({+ "id": "t-1",+ "status": {"state": "failed", "step": null, "reason": reason,+ "hint": "", "recoverable": true},+ "summary": "failed",+ "progress": 0.0,+ "next": []+ }))+ .unwrap()+ };+ let hint = host_hint(&failed("browser unavailable: Chrome not found. Checked: …"));+ assert_eq!(hint, Some(crate::modules::browser::CHROME_NOT_FOUND_HINT));+ assert_eq!(+ host_hint(&failed("the last three actions changed nothing")),+ None+ );+}diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_task_actions.rs b/crates/openhuman-core/src/tools/impl/browser/browser_task_actions.rsindex 72f653540f..552ff5cf3b 100644--- a/crates/openhuman-core/src/tools/impl/browser/browser_task_actions.rs+++ b/crates/openhuman-core/src/tools/impl/browser/browser_task_actions.rs@@ -5,8 +5,24 @@ use crate::security::approval::{ApprovalGate, GateOutcome};use serde_json::{json, Value};use sha2::{Digest, Sha256};use std::collections::BTreeMap;+use tinycomputer_bus::agent::{TaskStatus, TaskView};use tinycomputer_bus::browser::{Action, LocateBy, Locator, ScrollDirection, Target, WaitState};+/// What the host adds to a task report the agent cannot act on alone: a+/// task that failed because Chrome was not found says where the user sets+/// its path, rather than leaving the agent to install a browser.+pub(super) fn host_hint(view: &TaskView) -> Option<&'static str> {+ match &view.status {+ TaskStatus::Failed { reason, hint, .. }+ if crate::modules::browser::chrome_not_found(reason)+ || crate::modules::browser::chrome_not_found(hint) =>+ {+ Some(crate::modules::browser::CHROME_NOT_FOUND_HINT)+ }+ _ => None,+ }+}+pub(super) fn task_inputs(args: &Value) -> anyhow::Result<BTreeMap<String, String>> {args["inputs"].as_object().map_or_else(|| Ok(BTreeMap::new()),