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
Keep what finished browser tasks learn about a site for the next task there
Shanua4dfbcded1ca
diff --git a/crates/openhuman-core/src/config/ops/ui.rs b/crates/openhuman-core/src/config/ops/ui.rsindex c54070f43f..59f3a96557 100644--- a/crates/openhuman-core/src/config/ops/ui.rs+++ b/crates/openhuman-core/src/config/ops/ui.rs@@ -21,6 +21,7 @@ pub struct BrowserSettingsPatch {pub download_dir: Option<String>,pub max_task_steps: Option<usize>,pub task_timeout_secs: Option<u64>,+ pub learn_from_tasks: Option<bool>,}#[derive(Debug, Clone, Default)]@@ -117,8 +118,16 @@ pub async fn apply_browser_settings(}browser.task_timeout_secs = timeout;}+ if let Some(learn) = update.learn_from_tasks {+ browser.learn_from_tasks = learn;+ }config.browser = browser;config.save().await.map_err(|e| e.to_string())?;+ // Tools built before the switch hold the config they were built with.+ #[cfg(feature = "modules")]+ if let Some(learn) = update.learn_from_tasks {+ crate::modules::browser_sites::note_switch(&config.workspace_dir, learn);+ }let snapshot = snapshot_config_json(config)?;Ok(Outcome::new(snapshot,diff --git a/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs b/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rsindex 74345d57d4..50df4cc713 100644--- a/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs+++ b/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs@@ -444,6 +444,32 @@ async fn apply_browser_settings_updates_enabled_flag() {assert!(cfg.browser.enabled);}+#[tokio::test]+async fn apply_browser_settings_switches_learning_from_tasks() {+ let tmp = tempdir().unwrap();+ let mut cfg = tmp_config(&tmp);+ assert!(cfg.browser.learn_from_tasks, "on by default");++ apply_browser_settings(+ &mut cfg,+ BrowserSettingsPatch {+ learn_from_tasks: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("apply");+ assert!(!cfg.browser.learn_from_tasks);++ apply_browser_settings(&mut cfg, BrowserSettingsPatch::default())+ .await+ .expect("apply");+ assert!(+ !cfg.browser.learn_from_tasks,+ "left as it was when not named"+ );+}+#[tokio::test]async fn apply_browser_settings_updates_backend() {let tmp = tempdir().unwrap();diff --git a/crates/openhuman-core/src/config/schema/tools/browser.rs b/crates/openhuman-core/src/config/schema/tools/browser.rsindex e44854020e..823f33f1ad 100644--- a/crates/openhuman-core/src/config/schema/tools/browser.rs+++ b/crates/openhuman-core/src/config/schema/tools/browser.rs@@ -86,6 +86,12 @@ pub struct BrowserConfig {pub max_task_steps: usize,#[serde(default = "default_task_timeout_secs")]pub task_timeout_secs: u64,+ /// Keep, per site, the plan a finished browser task ran and the elements+ /// it found, and hand them to the next task there+ /// (`modules::browser_sites`). Kept in the workspace only, never in the+ /// agent's memory.+ #[serde(default = "default_true")]+ pub learn_from_tasks: bool,}fn default_viewport_width() -> u32 {@@ -136,6 +142,7 @@ impl Default for BrowserConfig {download_dir: None,max_task_steps: default_max_task_steps(),task_timeout_secs: default_task_timeout_secs(),+ learn_from_tasks: true,}}}diff --git a/crates/openhuman-core/src/config/schemas/controllers/agent.rs b/crates/openhuman-core/src/config/schemas/controllers/agent.rsindex 6a8fee84cf..bfdaea7fae 100644--- a/crates/openhuman-core/src/config/schemas/controllers/agent.rs+++ b/crates/openhuman-core/src/config/schemas/controllers/agent.rs@@ -105,6 +105,7 @@ pub(super) fn handle_update_browser_settings(params: Map<String, Value>) -> Contdownload_dir: update.download_dir,max_task_steps: update.max_task_steps,task_timeout_secs: update.task_timeout_secs,+ learn_from_tasks: update.learn_from_tasks,};to_json(config_rpc::load_and_apply_browser_settings(patch).await?)})diff --git a/crates/openhuman-core/src/config/schemas/helpers.rs b/crates/openhuman-core/src/config/schemas/helpers.rsindex 9c00bbf1d5..4c024ec53b 100644--- a/crates/openhuman-core/src/config/schemas/helpers.rs+++ b/crates/openhuman-core/src/config/schemas/helpers.rs@@ -99,6 +99,7 @@ pub(super) struct BrowserSettingsUpdate {pub(super) download_dir: Option<String>,pub(super) max_task_steps: Option<usize>,pub(super) task_timeout_secs: Option<u64>,+ pub(super) learn_from_tasks: Option<bool>,}#[derive(Debug, Deserialize)]diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/agent.rs b/crates/openhuman-core/src/config/schemas/schema_defs/agent.rsindex 888c4ef84a..06d88e9046 100644--- a/crates/openhuman-core/src/config/schemas/schema_defs/agent.rs+++ b/crates/openhuman-core/src/config/schemas/schema_defs/agent.rs@@ -130,6 +130,10 @@ pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {optional_string("download_dir", "Absolute permitted download folder; empty clears."),optional_number("max_task_steps", "Maximum Jev task steps (1-100)."),optional_number("task_timeout_secs", "Browser task timeout in seconds (5-600)."),+ optional_bool(+ "learn_from_tasks",+ "Keep the plan and elements a finished browser task used on a site, for the next task there.",+ ),],outputs: vec![json_output("snapshot", "Updated config snapshot.")],}),diff --git a/crates/openhuman-core/src/modules/browser_sites.rs b/crates/openhuman-core/src/modules/browser_sites.rsnew file mode 100644index 0000000000..0aa64eb173--- /dev/null+++ b/crates/openhuman-core/src/modules/browser_sites.rs@@ -0,0 +1,702 @@+//! What browser tasks learn about a site, kept for its next task.+//!+//! TinyComputer returns, with every finished task, the plan it ran+//! (`TaskReport.flow`) and the elements its steps found+//! (`TaskReport.learned`), and takes both back on `StartTask`: a ready `flow`+//! skips planning, and `memory` lets a step confirm a remembered element with+//! one yes/no question instead of searching the page for it. The module keeps+//! nothing between tasks; the host keeps it here, per site, in+//! `<workspace>/state/computer/sites/<site>.json`, readable by its owner+//! alone.+//!+//! - Only a task that finished (`done`, or stopped at its payment checkpoint)+//! teaches anything.+//! - A plan is reused only for the same goal, with the same facts, on the+//! same site. It is kept only when its run needed no rescue and its steps+//! hold no fact value the goal does not. A task that fails, or needs a+//! rescue, on a reused plan forgets it, and so does a module that refuses+//! it, the task then being planned afresh.+//! - An element whose name, key or place holds a fact value, however the+//! module spells it, or whose name reads like page text rather than a+//! control's label, is not kept.+//! - What no finished run has used for 30 days is dropped, and a site's file+//! goes 30 days after it last changed.+//!+//! Nothing here reaches the agent's memory or its prompts: plans and elements+//! go to the module alone. `browser.learn_from_tasks` turns learning off, and+//! `modules.browser_forget_sites` forgets one site or every site, also for+//! tasks still running there.++use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};+use std::future::Future;+#[cfg(unix)]+use std::os::unix::fs::PermissionsExt;+use std::path::{Path, PathBuf};+use std::pin::Pin;+use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};+use std::time::{SystemTime, UNIX_EPOCH};++use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use tinycomputer_bus::agent::{StartTaskRequest, TaskId, TaskReport, TaskStatus, TaskView};+use tinycomputer_bus::{Flow, GroundingHint};+use tokio::io::AsyncWriteExt;++use super::browser_task::BrowserTask;+use crate::config::Config;++/// Most elements kept per site; the oldest go first.+const MAX_HINTS: usize = 50;+/// Most plans kept per site; the one finished on longest ago goes first.+const MAX_PLANS: usize = 20;+/// How long a plan or an element is kept without a finished run using it,+/// and a site's file without a change.+const KEEP_SECS: u64 = 30 * 24 * 60 * 60;+/// Longest element name kept: a longer one is page text, not a label.+const MAX_NAME_CHARS: usize = 80;+/// Shortest fact value looked for: a shorter one (a count, an initial) is in+/// too many labels to tell anything.+const MIN_FACT_CHARS: usize = 3;+/// How many started tasks are followed at once; the oldest is let go first.+const FOLLOWED: usize = 64;+/// Largest site file read: anything bigger was not written here.+const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;++/// A pending `TaskReport` call.+type ReportFetch<'a> = Pin<Box<dyn Future<Output = Result<TaskReport, String>> + Send + 'a>>;++/// What finished tasks left about one site.+#[derive(Debug, Default, Clone, Serialize, Deserialize)]+struct SiteMemory {+ #[serde(default)]+ plans: Vec<SavedPlan>,+ #[serde(default)]+ hints: Vec<SavedHint>,+}++/// A plan that reached a goal.+#[derive(Debug, Clone, Serialize, Deserialize)]+struct SavedPlan {+ /// The goal it reached, as [`goal_key`] spells it.+ goal: String,+ /// The facts it ran with, as [`facts_id`] spells them.+ #[serde(default)]+ facts_id: String,+ flow: Flow,+ /// When a run last finished on it, in seconds since the epoch.+ ok_at: u64,+ /// How many finished runs it served.+ runs: u32,+}++/// An element a finished task's step found.+#[derive(Debug, Clone, Serialize, Deserialize)]+struct SavedHint {+ hint: GroundingHint,+ /// When a finished run last found it, in seconds since the epoch.+ ok_at: u64,+}++/// A started task, followed for what it may teach once it ends.+#[derive(Debug, Clone)]+pub(crate) struct Following {+ /// The workspace whose site files it teaches.+ workspace: PathBuf,+ site: String,+ goal: String,+ facts_id: String,+ /// Whether it runs a plan saved here, forgotten if the run fails on it.+ reused_plan: bool,+ /// Its fact values, lower-cased and as words, none of which may be kept.+ facts: Vec<String>,+}++impl Following {+ /// Whether the task runs a plan saved for its goal and facts.+ pub(crate) fn reuses_plan(&self) -> bool {+ self.reused_plan+ }+}++/// The site `url` belongs to: its host, lower-cased and without a leading+/// `www.`; `None` for an address that is not `http(s)` or names no plain+/// host.+#[must_use]+pub fn site_of(url: &str) -> Option<String> {+ let parsed = url::Url::parse(url.trim()).ok()?;+ if !matches!(parsed.scheme(), "http" | "https") {+ return None;+ }+ site_named(parsed.host_str()?)+}++/// `host` as a site name, or `None` when it is not a plain host name.+fn site_named(host: &str) -> Option<String> {+ let host = host.trim().to_ascii_lowercase();+ let host = host.strip_prefix("www.").unwrap_or(&host);+ let plain = !host.is_empty()+ && !host.starts_with('.')+ && host+ .chars()+ .all(|character| character.is_ascii_alphanumeric() || matches!(character, '.' | '-'));+ plain.then(|| host.to_owned())+}++/// A goal as plans are matched by: lower-cased, its whitespace collapsed.+fn goal_key(goal: &str) -> String {+ goal.split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+ .to_lowercase()+}++/// `facts`, names and values, as one digest, so a site file holds no value.+/// A plan is reused only with the facts it ran with: one chosen by a value+/// (a size, a city) never meets another, and none it reads goes unsupplied.+fn facts_id(facts: &BTreeMap<String, String>) -> String {+ let bytes = serde_json::to_vec(facts).unwrap_or_default();+ hex::encode(Sha256::digest(bytes))+}++/// `text` as the module keys a step by: its words, lower-cased, with+/// anything between them turned to single spaces.+fn words(text: &str) -> String {+ text.to_lowercase()+ .chars()+ .map(|character| {+ if character.is_alphanumeric() {+ character+ } else {+ ' '+ }+ })+ .collect::<String>()+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+}++/// The fact values worth looking for, lower-cased, each also as its words:+/// the module keys a step by its text with the values filled in, so+/// `[email protected]` is kept as `asha r example com`.+fn fact_values<'a>(values: impl IntoIterator<Item = &'a String>) -> Vec<String> {+ let mut found = Vec::new();+ for value in values {+ let value = value.trim().to_lowercase();+ let spelled = words(&value);+ for form in [value, spelled] {+ if form.chars().count() >= MIN_FACT_CHARS && !found.contains(&form) {+ found.push(form);+ }+ }+ }+ found+}++fn now() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map_or(0, |elapsed| elapsed.as_secs())+}++/// Records that Browser settings switched learning on or off for+/// `workspace`. A tool keeps the config it was built with, and a channel's+/// agent is built once, so the switch outranks that config.+pub(crate) fn note_switch(workspace: &Path, on: bool) {+ switched().insert(workspace.to_path_buf(), on);+}++/// Whether tasks under `config` learn: the latest switch in Browser+/// settings, else `browser.learn_from_tasks`.+fn learning(config: &Config) -> bool {+ switched()+ .get(&config.workspace_dir)+ .copied()+ .unwrap_or(config.browser.learn_from_tasks)+}++/// Fills `request` from what finished tasks on `task`'s site left: the plan+/// saved for its goal and facts, unless the caller brought a flow of its own,+/// and the elements found there. Returns the task to follow, or `None` when+/// learning is off or the task names no site.+pub(crate) async fn apply(+ config: &Config,+ task: &BrowserTask,+ request: &mut StartTaskRequest,+) -> Option<Following> {+ sweep(config, now()).await;+ if !learning(config) {+ return None;+ }+ let site = task.site.clone()?;+ let goal = goal_key(&task.goal);+ let facts_id = facts_id(&task.facts);+ let memory = load(config, &site, now()).await;+ let mut reused_plan = false;+ if request.flow.is_none() {+ if let Some(plan) = memory+ .plans+ .iter()+ .find(|plan| plan.serves(&goal, &facts_id))+ {+ request.flow = Some(plan.flow.clone());+ reused_plan = true;+ }+ }+ request.memory = memory+ .hints+ .iter()+ .map(|saved| saved.hint.clone())+ .collect();+ tracing::debug!(+ reused_plan,+ hints = request.memory.len(),+ "[browser-sites] applied what the site's finished tasks left"+ );+ Some(Following {+ workspace: config.workspace_dir.clone(),+ site,+ goal,+ facts_id,+ reused_plan,+ facts: fact_values(task.facts.values()),+ })+}++/// Follows task `id` until it ends, to learn from how it did; with `None`,+/// follows no task by that id. The module numbers its tasks afresh each time+/// it is set up again, so an id can come back for another task.+pub(crate) fn follow(id: &TaskId, following: Option<Following>) {+ let mut followed = followed();+ followed.retain(|(known, _)| known != id);+ if let Some(following) = following {+ followed.push_back((id.clone(), following));+ }+ while followed.len() > FOLLOWED {+ followed.pop_front();+ }+}++/// Adds `inputs`, the values a paused task `id` is given, to the values it+/// may not keep.+pub(crate) fn note_inputs(id: &TaskId, inputs: &BTreeMap<String, String>) {+ if inputs.is_empty() {+ return;+ }+ let mut followed = followed();+ if let Some((_, following)) = followed.iter_mut().find(|(known, _)| known == id) {+ for value in fact_values(inputs.values()) {+ if !following.facts.contains(&value) {+ following.facts.push(value);+ }+ }+ }+}++/// Forgets the saved plan `following` was to reuse, which the module refused,+/// so the task is planned afresh.+pub(crate) async fn refused(config: &Config, following: &mut Following) {+ let plan_of: &Following = following;+ update(config, &plan_of.site, |memory| {+ memory.forget_plan(plan_of);+ true+ })+ .await;+ following.reused_plan = false;+ tracing::debug!("[browser-sites] forgot a saved plan the module refused");+}++/// Learns from a followed task that has ended: what it found and the plan it+/// ran when it finished, or that the plan it reused failed. A task still+/// running or paused stays followed.+pub(crate) async fn learn(config: &Config, view: &TaskView) {+ learn_with(config, view, |id| {+ Box::pin(super::browser_task::report_with(config, id, false))+ })+ .await;+}++/// [`learn`] with the module's `TaskReport` call passed in as `fetch`.+async fn learn_with<'a>(+ config: &'a Config,+ view: &TaskView,+ fetch: impl FnOnce(TaskId) -> ReportFetch<'a>,+) {+ match &view.status {+ TaskStatus::Done { .. } | TaskStatus::Checkpoint { .. } => {+ let Some(following) = followed_as(&view.id) else {+ return;+ };+ if !learning(config) {+ stop_following(&view.id);+ return;+ }+ match fetch(view.id.clone()).await {+ Ok(report) => {+ let learned = now();+ let mut kept = false;+ update(config, &following.site, |memory| {+ // Still followed, under the save lock: a Forget that+ // came while the report was fetched holds.+ kept = stop_following(&view.id).is_some();+ if kept {+ memory.learn(&following, &report, learned);+ }+ kept+ })+ .await;+ tracing::debug!(+ task = %view.id,+ kept,+ found = report.learned.len(),+ rescues = report.rescues.len(),+ "[browser-sites] learned from a finished task"+ );+ }+ Err(error) => {+ stop_following(&view.id);+ tracing::warn!(task = %view.id, %error, "[browser-sites] report unavailable; nothing learned");+ }+ }+ }+ TaskStatus::Failed { .. } => {+ let Some(following) = stop_following(&view.id) else {+ return;+ };+ if following.reused_plan {+ update(config, &following.site, |memory| {+ memory.forget_plan(&following);+ true+ })+ .await;+ tracing::debug!(task = %view.id, "[browser-sites] forgot a reused plan that failed");+ }+ }+ TaskStatus::Cancelled | TaskStatus::NeedsPlan { .. } => {+ stop_following(&view.id);+ }+ _ => {}+ }+}++/// Forgets what was learned about `site` (a host or an address), or about+/// every site when `None`, also by the tasks still running there. Returns how+/// many sites were forgotten.+///+/// # Errors+///+/// Returns an I/O error when a site's file exists and cannot be removed.+pub async fn forget(config: &Config, site: Option<&str>) -> std::io::Result<usize> {+ let site = match site {+ Some(named) => match site_of(named).or_else(|| site_named(named)) {+ Some(site) => Some(site),+ None => return Ok(0),+ },+ None => None,+ };+ let _saving = saving().lock().await;+ // A task still running there would write it all back when it ends.+ followed().retain(|(_, following)| {+ following.workspace != config.workspace_dir+ || site.as_ref().is_some_and(|site| *site != following.site)+ });+ let Some(site) = site else {+ return forget_every_site(&sites_dir(config)).await;+ };+ let path = site_path(config, &site);+ // A copy set aside as unreadable holds the same site's data.+ let set_aside = remove(&path.with_extension("json.corrupt")).await?;+ remove(&path.with_extension("json.tmp")).await?;+ let kept = remove(&path).await?;+ Ok(usize::from(kept || set_aside))+}++/// Removes every file in `dir`, returning how many sites they held.+async fn forget_every_site(dir: &Path) -> std::io::Result<usize> {+ let mut entries = match tokio::fs::read_dir(dir).await {+ Ok(entries) => entries,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),+ Err(error) => return Err(error),+ };+ let mut forgotten = BTreeSet::new();+ while let Some(entry) = entries.next_entry().await? {+ if entry.file_type().await?.is_file() {+ let name = entry.file_name().to_string_lossy().into_owned();+ if let Some(site) = name+ .strip_suffix(".json")+ .or_else(|| name.strip_suffix(".json.corrupt"))+ {+ forgotten.insert(site.to_owned());+ }+ remove(&entry.path()).await?;+ }+ }+ Ok(forgotten.len())+}++/// Removes the file at `path`, returning whether there was one.+async fn remove(path: &Path) -> std::io::Result<bool> {+ match tokio::fs::remove_file(path).await {+ Ok(()) => Ok(true),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),+ Err(error) => Err(error),+ }+}++/// Removes the site files nothing changed for `KEEP_SECS` before `now`:+/// every entry in them has expired, as has a copy set aside or a write left+/// behind.+async fn sweep(config: &Config, now: u64) {+ let _saving = saving().lock().await;+ let Ok(mut entries) = tokio::fs::read_dir(sites_dir(config)).await else {+ return;+ };+ while let Ok(Some(entry)) = entries.next_entry().await {+ let Ok(metadata) = entry.metadata().await else {+ continue;+ };+ let changed = metadata+ .modified()+ .ok()+ .and_then(|at| at.duration_since(UNIX_EPOCH).ok())+ .map_or(now, |since| since.as_secs());+ if metadata.is_file() && changed.saturating_add(KEEP_SECS) <= now {+ match remove(&entry.path()).await {+ Ok(_) => {+ tracing::debug!("[browser-sites] removed a site file unchanged for 30 days")+ }+ Err(error) => tracing::warn!(%error, "[browser-sites] old site file not removed"),+ }+ }+ }+}++impl SiteMemory {+ /// Drops what no finished run has used since `now - KEEP_SECS`.+ fn expire(&mut self, now: u64) {+ let fresh = |ok_at: u64| ok_at.saturating_add(KEEP_SECS) > now;+ self.plans.retain(|plan| fresh(plan.ok_at));+ self.hints.retain(|saved| fresh(saved.ok_at));+ }++ /// Keeps what `following`'s finished run, reported in `report`, found,+ /// and the plan it ran when it needed no rescue; forgets a reused plan+ /// that did.+ fn learn(&mut self, following: &Following, report: &TaskReport, now: u64) {+ for hint in &report.learned {+ if !keepable_hint(hint, &following.facts) {+ continue;+ }+ self.hints+ .retain(|saved| !(saved.hint.app == hint.app && saved.hint.key == hint.key));+ self.hints.push(SavedHint {+ hint: hint.clone(),+ ok_at: now,+ });+ }+ let excess = self.hints.len().saturating_sub(MAX_HINTS);+ self.hints.drain(..excess);+ if !report.rescues.is_empty() {+ if following.reused_plan {+ self.forget_plan(following);+ }+ return;+ }+ let Some(flow) = report+ .flow+ .as_ref()+ .filter(|flow| keepable_plan(flow, following))+ else {+ return;+ };+ let runs = self+ .plans+ .iter()+ .find(|plan| plan.serves(&following.goal, &following.facts_id))+ .map_or(0, |plan| plan.runs);+ self.forget_plan(following);+ self.plans.push(SavedPlan {+ goal: following.goal.clone(),+ facts_id: following.facts_id.clone(),+ flow: flow.clone(),+ ok_at: now,+ runs: runs.saturating_add(1),+ });+ self.plans.sort_by_key(|plan| plan.ok_at);+ let excess = self.plans.len().saturating_sub(MAX_PLANS);+ self.plans.drain(..excess);+ }++ /// Forgets the plan saved for `following`'s goal and facts.+ fn forget_plan(&mut self, following: &Following) {+ self.plans+ .retain(|plan| !plan.serves(&following.goal, &following.facts_id));+ }+}++impl SavedPlan {+ /// Whether it is the plan saved for `goal` with the facts `facts_id`.+ fn serves(&self, goal: &str, facts_id: &str) -> bool {+ self.goal == goal && self.facts_id == facts_id+ }+}++/// Whether `hint` may be kept: its name reads like a control's label, and+/// neither it, its key, nor its place holds one of `facts`.+fn keepable_hint(hint: &GroundingHint, facts: &[String]) -> bool {+ let name = hint.name.as_deref().unwrap_or_default();+ let mut texts = [name, hint.key.as_str()]+ .into_iter()+ .chain(hint.path.iter().map(String::as_str));+ name.chars().count() <= MAX_NAME_CHARS && !texts.any(|text| holds(text, facts))+}++/// Whether `flow` may be reused for its goal: it holds no fact value the+/// goal does not, which another task with the same goal could change.+fn keepable_plan(flow: &Flow, following: &Following) -> bool {+ let Ok(text) = serde_json::to_string(flow) else {+ return false;+ };+ let foreign: Vec<String> = following+ .facts+ .iter()+ .filter(|fact| !holds(&following.goal, std::slice::from_ref(*fact)))+ .cloned()+ .collect();+ !holds(&text, &foreign)+}++/// Whether `text`, as written or as its words, holds any of `facts`.+fn holds(text: &str, facts: &[String]) -> bool {+ let written = text.to_lowercase();+ let spelled = words(text);+ facts+ .iter()+ .any(|fact| written.contains(fact.as_str()) || spelled.contains(fact.as_str()))+}++fn sites_dir(config: &Config) -> PathBuf {+ super::computer_config::trace_dir(config).join("sites")+}++fn site_path(config: &Config, site: &str) -> PathBuf {+ sites_dir(config).join(format!("{site}.json"))+}++/// `site`'s memory as of `now`. A missing file is an empty memory; a file+/// that cannot be read as one is set aside as `<site>.json.corrupt` and+/// treated as empty.+async fn load(config: &Config, site: &str, now: u64) -> SiteMemory {+ let path = site_path(config, site);+ let read = match tokio::fs::metadata(&path).await {+ Ok(metadata) if metadata.len() <= MAX_FILE_BYTES => tokio::fs::read(&path).await,+ Ok(_) => Err(std::io::Error::other("larger than a site file can be")),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ return SiteMemory::default();+ }+ Err(error) => Err(error),+ };+ let parsed = read.and_then(|bytes| {+ serde_json::from_slice::<SiteMemory>(&bytes).map_err(std::io::Error::other)+ });+ match parsed {+ Ok(mut memory) => {+ memory.expire(now);+ memory+ }+ Err(error) => {+ tracing::warn!(%error, "[browser-sites] unreadable site file set aside");+ let _set_aside = tokio::fs::rename(&path, path.with_extension("json.corrupt")).await;+ SiteMemory::default()+ }+ }+}++/// Loads `site`'s memory and lets `change` change it, one update at a time,+/// writing it back when `change` says it did; a memory left empty removes+/// the file. A failure is logged, never raised.+async fn update(config: &Config, site: &str, change: impl FnOnce(&mut SiteMemory) -> bool) {+ let _saving = saving().lock().await;+ let mut memory = load(config, site, now()).await;+ if !change(&mut memory) {+ return;+ }+ let path = site_path(config, site);+ let written = if memory.plans.is_empty() && memory.hints.is_empty() {+ remove(&path).await.map(|_removed| ())+ } else {+ save(&path, &memory).await+ };+ if let Err(error) = written {+ tracing::warn!(%error, "[browser-sites] site memory not saved");+ }+}++/// Writes `memory` to `path` through a temporary file, in a directory and a+/// file only their owner can read: plans and elements tell where a person+/// browses.+async fn save(path: &Path, memory: &SiteMemory) -> std::io::Result<()> {+ let bytes = serde_json::to_vec_pretty(memory).map_err(std::io::Error::other)?;+ if let Some(dir) = path.parent() {+ tokio::fs::create_dir_all(dir).await?;+ #[cfg(unix)]+ tokio::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).await?;+ }+ let staged = path.with_extension("json.tmp");+ let mut options = tokio::fs::OpenOptions::new();+ options.write(true).create(true).truncate(true);+ #[cfg(unix)]+ options.mode(0o600);+ let mut file = options.open(&staged).await?;+ #[cfg(unix)]+ file.set_permissions(std::fs::Permissions::from_mode(0o600))+ .await?;+ file.write_all(&bytes).await?;+ file.flush().await?;+ drop(file);+ tokio::fs::rename(&staged, path).await+}++/// Serializes changes to site files across tasks.+fn saving() -> &'static tokio::sync::Mutex<()> {+ static SAVING: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();+ SAVING.get_or_init(|| tokio::sync::Mutex::new(()))+}++/// Learning switched in Browser settings since the process started, by+/// workspace.+fn switched() -> MutexGuard<'static, HashMap<PathBuf, bool>> {+ static SWITCHED: OnceLock<Mutex<HashMap<PathBuf, bool>>> = OnceLock::new();+ SWITCHED+ .get_or_init(|| Mutex::new(HashMap::new()))+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+}++/// The tasks being followed, oldest first.+fn followed() -> MutexGuard<'static, VecDeque<(TaskId, Following)>> {+ static FOLLOWING: OnceLock<Mutex<VecDeque<(TaskId, Following)>>> = OnceLock::new();+ FOLLOWING+ .get_or_init(|| Mutex::new(VecDeque::new()))+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+}++/// What task `id` is followed for, if it is.+fn followed_as(id: &TaskId) -> Option<Following> {+ followed()+ .iter()+ .find(|(known, _)| known == id)+ .map(|(_, following)| following.clone())+}++/// Stops following task `id`, returning what it was followed for.+fn stop_following(id: &TaskId) -> Option<Following> {+ let mut followed = followed();+ let index = followed.iter().position(|(known, _)| known == id)?;+ followed.remove(index).map(|(_, following)| following)+}++#[cfg(test)]+#[path = "browser_sites_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/modules/browser_sites_tests.rs b/crates/openhuman-core/src/modules/browser_sites_tests.rsnew file mode 100644index 0000000000..808ffe3256--- /dev/null+++ b/crates/openhuman-core/src/modules/browser_sites_tests.rs@@ -0,0 +1,717 @@+//! A finished browser task leaves its plan and the elements it found for the+//! next task on the same site, the plan only for the same goal and facts;+//! nothing that holds a fact, reads like page text, needed a rescue, or+//! failed when reused is kept, and none of it outlives its use, the learning+//! switch, or a request to forget.++use super::*;+use serde_json::{json, Value};+use std::time::Duration;++/// A config whose workspace is inside `dir`, learning on.+fn workspace_config(dir: &tempfile::TempDir) -> Config {+ let mut config = Config::default();+ config.workspace_dir = dir.path().join("workspace");+ config+}++/// A task on `shop.test` for `goal`, typing the name "Asha Raina".+fn task(goal: &str) -> BrowserTask {+ BrowserTask {+ goal: goal.into(),+ facts: BTreeMap::from([("name".into(), "Asha Raina".into())]),+ origins: vec!["https://.shop.test".into()],+ max_actions: 40,+ flow: None,+ site: Some("shop.test".into()),+ }+}++fn view(id: &str, status: Value) -> TaskView {+ serde_json::from_value(json!({+ "id": id, "status": status, "summary": "", "progress": 1.0, "next": []+ }))+ .unwrap()+}++fn done() -> Value {+ json!({"state": "done", "answer": "ordered", "records": {}})+}++fn failed() -> Value {+ json!({"state": "failed", "step": 2, "reason": "nothing changed", "hint": "", "recoverable": true})+}++fn flow(steps: Value) -> Value {+ json!({"app": "browser", "steps": steps})+}++fn hint(key: &str, name: &str) -> Value {+ json!({"app": "browser", "key": key, "role": "button", "name": name, "path": ["main", "product"]})+}++/// A report of `view` that ran `flow`, found `learned`, and took `rescues`.+fn report(view: &TaskView, flow: Value, learned: Value, rescues: Value) -> TaskReport {+ serde_json::from_value(json!({+ "view": view, "flow": flow, "steps": [], "records": {}, "artifacts": [],+ "learned": learned, "trace": [], "rescues": rescues+ }))+ .unwrap()+}++/// A rescue that put a step in place of the failed one.+fn rescue() -> Value {+ json!([{"step": 1, "failure": "covered", "reason": "a size comes first",+ "steps": ["choose a size"], "covers": 0, "outcome": "recovered"}])+}++/// Starts `task` as the host would: the request, what the site left, and the+/// task followed as `id`.+async fn start(config: &Config, task: &BrowserTask, id: &str) -> StartTaskRequest {+ let mut request = super::super::browser_task::start_request(config, task);+ follow(&TaskId::new(id), apply(config, task, &mut request).await);+ request+}++/// A change that leaves one element in a site's memory.+fn keep_one(memory: &mut SiteMemory) -> bool {+ memory.hints.push(SavedHint {+ hint: serde_json::from_value(hint("search", "Search")).unwrap(),+ ok_at: now(),+ });+ true+}++/// A report of `id` finishing on a one-step plan with one element found.+fn finished(id: &str) -> TaskReport {+ report(+ &view(id, done()),+ flow(json!(["a"])),+ json!([hint("a", "A")]),+ json!([]),+ )+}++/// Ends task `id` in `status`, its report being `reported`.+async fn end(config: &Config, id: &str, status: Value, reported: Option<TaskReport>) {+ let ended = view(id, status);+ learn_with(config, &ended, move |_| {+ Box::pin(async move { reported.ok_or_else(|| "no report".to_owned()) })+ })+ .await;+}++#[test]+fn a_site_is_its_host_without_www() {+ assert_eq!(+ site_of("https://www.Amazon.in/s?k=x").as_deref(),+ Some("amazon.in")+ );+ assert_eq!(+ site_of(" http://shop.test:8080/cart ").as_deref(),+ Some("shop.test")+ );+ assert_eq!(site_of("file:///tmp/page.html"), None);+ assert_eq!(site_of("https://[::1]/"), None);+ assert_eq!(site_of("not an address"), None);+ assert_eq!(site_named(".hidden"), None);+}++#[test]+fn goals_are_matched_whatever_their_case_and_spacing() {+ assert_eq!(+ goal_key(" Order MILK\non shop.test "),+ "order milk on shop.test"+ );+}++#[tokio::test]+async fn a_finished_task_leaves_its_plan_and_elements_for_the_next_task_there() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");+ let first = start(&config, &order, "t-plan-1").await;+ assert!(first.flow.is_none(), "nothing saved yet");+ assert_eq!(first.memory.len(), 0);++ let ran = flow(json!([{"browse": "https://shop.test"}, "add milk to the cart"]));+ let found = json!([+ hint("add milk to the cart", "Add to cart"),+ hint("deliver", "Deliver to Asha Raina"),+ hint("read", &"long page text ".repeat(10)),+ ]);+ let finished = view("t-plan-1", done());+ end(+ &config,+ "t-plan-1",+ done(),+ Some(report(&finished, ran.clone(), found, json!([]))),+ )+ .await;++ let second = start(&config, &order, "t-plan-2").await;+ assert_eq!(serde_json::to_value(second.flow.unwrap()).unwrap(), ran);+ let names: Vec<_> = second.memory.iter().map(|hint| hint.name.clone()).collect();+ assert_eq!(+ names,+ [Some("Add to cart".to_owned())],+ "no fact, no page text"+ );++ // Another goal on the same site gets the elements, not the plan.+ let other = start(+ &config,+ &task("Start at https://shop.test. Order eggs"),+ "t-plan-3",+ )+ .await;+ assert!(other.flow.is_none());+ assert_eq!(other.memory.len(), 1);+}++#[tokio::test]+async fn a_plan_that_needed_a_rescue_or_holds_a_fact_is_not_kept() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");+ let ran = flow(json!(["add milk to the cart"]));++ start(&config, &order, "t-rescued").await;+ let finished = view("t-rescued", done());+ let rescued = report(+ &finished,+ ran.clone(),+ json!([hint("add", "Add")]),+ rescue(),+ );+ end(&config, "t-rescued", done(), Some(rescued)).await;+ let next = start(&config, &order, "t-after-rescue").await;+ assert!(next.flow.is_none(), "a rescued run's plan is not kept");+ assert_eq!(next.memory.len(), 1, "its elements are");++ // A plan typing a fact the goal does not name could type the wrong one.+ let typed = flow(json!([{"enter": {"name": "Asha Raina"}}]));+ let finished = view("t-after-rescue", done());+ end(+ &config,+ "t-after-rescue",+ done(),+ Some(report(&finished, typed.clone(), json!([]), json!([]))),+ )+ .await;+ assert!(start(&config, &order, "t-fact").await.flow.is_none());++ // Named in the goal, the same value is part of what the plan is for.+ let named = task("Start at https://shop.test. Book a table for Asha Raina");+ start(&config, &named, "t-named").await;+ let finished = view("t-named", done());+ end(+ &config,+ "t-named",+ done(),+ Some(report(&finished, typed, json!([]), json!([]))),+ )+ .await;+ assert!(start(&config, &named, "t-named-again").await.flow.is_some());+}++#[tokio::test]+async fn a_plan_is_reused_only_with_the_facts_it_ran_with() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order a shirt");+ start(&config, &order, "t-facts-1").await;+ // Chosen by the size fact, not typed from it: only its facts may rerun it.+ let ran = flow(json!(["choose Medium", "add the shirt to the cart"]));+ let finished = view("t-facts-1", done());+ end(+ &config,+ "t-facts-1",+ done(),+ Some(report(+ &finished,+ ran,+ json!([hint("add", "Add to bag")]),+ json!([]),+ )),+ )+ .await;++ let mut larger = order.clone();+ larger.facts.insert("size".into(), "L".into());+ let request = start(&config, &larger, "t-facts-2").await;+ assert!(request.flow.is_none(), "other facts plan afresh");+ assert_eq!(request.memory.len(), 1, "and still get the site's elements");+ end(&config, "t-facts-2", failed(), None).await;+ assert!(start(&config, &order, "t-facts-3").await.flow.is_some());+ let saved = std::fs::read_to_string(site_path(&config, "shop.test")).unwrap();+ assert!(!saved.contains("Asha Raina"), "facts are kept as a digest");+}++#[tokio::test]+async fn a_reused_plan_that_fails_or_needs_a_rescue_is_forgotten() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");+ let ran = flow(json!(["add milk to the cart"]));+ let save = |id: &'static str| {+ let config = config.clone();+ let ran = ran.clone();+ let order = order.clone();+ async move {+ start(&config, &order, id).await;+ let finished = view(id, done());+ end(+ &config,+ id,+ done(),+ Some(report(&finished, ran, json!([]), json!([]))),+ )+ .await;+ }+ };++ save("t-save-1").await;+ assert!(start(&config, &order, "t-reuse-fails").await.flow.is_some());+ end(&config, "t-reuse-fails", failed(), None).await;+ assert!(+ start(&config, &order, "t-replan").await.flow.is_none(),+ "forgotten"+ );++ end(&config, "t-replan", failed(), None).await;+ save("t-save-2").await;+ start(&config, &order, "t-reuse-rescued").await;+ let finished = view("t-reuse-rescued", done());+ end(+ &config,+ "t-reuse-rescued",+ done(),+ Some(report(&finished, ran.clone(), json!([]), rescue())),+ )+ .await;+ assert!(start(&config, &order, "t-replan-2").await.flow.is_none());+}++#[tokio::test]+async fn a_flow_the_caller_brings_is_never_replaced() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");+ start(&config, &order, "t-own-1").await;+ let finished = view("t-own-1", done());+ end(+ &config,+ "t-own-1",+ done(),+ Some(report(&finished, flow(json!(["a"])), json!([]), json!([]))),+ )+ .await;++ let mut own = order.clone();+ own.flow = Some(serde_json::from_value(flow(json!(["b"]))).unwrap());+ let request = start(&config, &own, "t-own-2").await;+ assert_eq!(+ serde_json::to_value(request.flow.unwrap()).unwrap(),+ flow(json!(["b"]))+ );+ // Failing on its own flow does not forget the saved one.+ end(&config, "t-own-2", failed(), None).await;+ assert!(start(&config, &order, "t-own-3").await.flow.is_some());+}++#[tokio::test]+async fn with_learning_off_nothing_is_handed_over_or_kept() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");+ start(&config, &order, "t-switch").await;+ config.browser.learn_from_tasks = false;+ let finished = view("t-switch", done());+ end(+ &config,+ "t-switch",+ done(),+ Some(report(+ &finished,+ flow(json!(["a"])),+ json!([hint("a", "A")]),+ json!([]),+ )),+ )+ .await;+ let mut request = super::super::browser_task::start_request(&config, &order);+ assert!(apply(&config, &order, &mut request).await.is_none());+ config.browser.learn_from_tasks = true;+ let request = start(&config, &order, "t-switch-on").await;+ assert!(request.flow.is_none());+ assert_eq!(request.memory.len(), 0);+ // A task with no site learns nothing either.+ let mut nowhere = order.clone();+ nowhere.site = None;+ let mut request = super::super::browser_task::start_request(&config, &nowhere);+ assert!(apply(&config, &nowhere, &mut request).await.is_none());+}++#[tokio::test]+async fn a_paused_task_is_followed_until_it_ends() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");+ start(&config, &order, "t-paused").await;+ end(+ &config,+ "t-paused",+ json!({"state": "needs_human", "reason": "sign in"}),+ None,+ )+ .await;+ let finished = view("t-paused", done());+ end(+ &config,+ "t-paused",+ done(),+ Some(report(&finished, flow(json!(["a"])), json!([]), json!([]))),+ )+ .await;+ assert!(start(&config, &order, "t-paused-next").await.flow.is_some());++ // A cancelled task, or one whose report cannot be had, teaches nothing.+ end(+ &config,+ "t-paused-next",+ json!({"state": "cancelled"}),+ None,+ )+ .await;+ let other = task("Start at https://shop.test. Order eggs");+ start(&config, &other, "t-no-report").await;+ end(&config, "t-no-report", done(), None).await;+ assert!(start(&config, &other, "t-no-report-next")+ .await+ .flow+ .is_none());+ // Ending a task nobody follows does nothing.+ end(&config, "t-unknown", done(), None).await;+}++#[test]+fn old_entries_go_and_limits_hold() {+ let order = task("Order milk");+ let following = Following {+ workspace: PathBuf::from("/nowhere"),+ site: "shop.test".into(),+ goal: goal_key(&order.goal),+ facts_id: facts_id(&order.facts),+ reused_plan: false,+ facts: fact_values(order.facts.values()),+ };+ let finished = view("t-limits", done());+ let found: Vec<Value> = (0..MAX_HINTS + 5)+ .map(|index| hint(&format!("step {index}"), &format!("Button {index}")))+ .collect();+ let mut memory = SiteMemory::default();+ memory.learn(+ &following,+ &report(&finished, flow(json!(["a"])), json!(found), json!([])),+ 100,+ );+ assert_eq!(memory.hints.len(), MAX_HINTS);+ assert_eq!(memory.hints[0].hint.key, "step 5", "the oldest went first");+ for index in 0..MAX_PLANS + 2 {+ let goal = Following {+ goal: format!("goal {index}"),+ ..following.clone()+ };+ let at = 200 + u64::try_from(index).unwrap();+ memory.learn(+ &goal,+ &report(&finished, flow(json!(["a"])), json!([]), json!([])),+ at,+ );+ }+ assert_eq!(memory.plans.len(), MAX_PLANS);+ assert!(memory+ .plans+ .iter()+ .all(|plan| plan.goal != "goal 0" && plan.goal != "goal 1"));+ memory.expire(100 + KEEP_SECS);+ assert_eq!(memory.hints.len(), 0, "unused for 30 days");+ assert_eq!(memory.plans.len(), MAX_PLANS);+}++#[tokio::test]+async fn an_unreadable_site_file_is_set_aside_and_files_stay_private() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let path = site_path(&config, "shop.test");+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(&path, b"{not json").unwrap();+ assert_eq!(load(&config, "shop.test", now()).await.plans.len(), 0);+ assert!(path.with_extension("json.corrupt").exists());++ update(&config, "shop.test", keep_one).await;+ #[cfg(unix)]+ {+ let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777;+ assert_eq!(mode(&path), 0o600);+ assert_eq!(mode(path.parent().unwrap()), 0o700);+ }+}++#[tokio::test]+async fn forgetting_removes_one_site_or_every_site() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ assert_eq!(+ forget(&config, None).await.unwrap(),+ 0,+ "nothing learned yet"+ );+ for site in ["shop.test", "books.test"] {+ update(&config, site, keep_one).await;+ }+ let staged = site_path(&config, "shop.test").with_extension("json.tmp");+ std::fs::write(&staged, b"{").unwrap();+ assert_eq!(+ forget(&config, Some("https://www.shop.test/cart"))+ .await+ .unwrap(),+ 1+ );+ assert!(!staged.exists(), "a write left behind goes too");+ assert_eq!(+ forget(&config, Some("shop.test")).await.unwrap(),+ 0,+ "already gone"+ );+ assert_eq!(forget(&config, Some("not a host!")).await.unwrap(), 0);+ // A copy set aside as unreadable is the same site's data, counted once.+ let set_aside = |site: &str| site_path(&config, site).with_extension("json.corrupt");+ std::fs::write(set_aside("books.test"), b"{").unwrap();+ std::fs::write(set_aside("maps.test"), b"{").unwrap();+ assert_eq!(forget(&config, Some("maps.test")).await.unwrap(), 1);+ assert!(!set_aside("maps.test").exists());+ std::fs::write(set_aside("maps.test"), b"{").unwrap();+ assert_eq!(forget(&config, None).await.unwrap(), 2);+ assert!(!site_path(&config, "books.test").exists());+ assert!(!set_aside("books.test").exists());+}++#[tokio::test]+async fn an_id_the_module_gives_another_task_is_not_learned_from() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");+ start(&config, &order, "t-again").await;+ // Set up again, the module numbers its tasks afresh, and a task with no+ // site takes the same id.+ let mut elsewhere = order.clone();+ elsewhere.site = None;+ start(&config, &elsewhere, "t-again").await;+ end(&config, "t-again", done(), Some(finished("t-again"))).await;+ let next = start(&config, &order, "t-again-next").await;+ assert!(next.flow.is_none());+ assert_eq!(next.memory.len(), 0);+}++#[tokio::test]+async fn forgetting_holds_for_tasks_still_running() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");++ // Paused for an approval when the person forgets every site.+ start(&config, &order, "t-forgot-paused").await;+ forget(&config, None).await.unwrap();+ end(+ &config,+ "t-forgot-paused",+ done(),+ Some(finished("t-forgot-paused")),+ )+ .await;+ assert!(!site_path(&config, "shop.test").exists());++ // Forgotten while its report was being fetched.+ start(&config, &order, "t-forgot-fetching").await;+ let config_ref = &config;+ learn_with(&config, &view("t-forgot-fetching", done()), move |_| {+ Box::pin(async move {+ forget(config_ref, Some("shop.test")).await.unwrap();+ Ok(finished("t-forgot-fetching"))+ })+ })+ .await;+ assert!(!site_path(&config, "shop.test").exists());++ // Forgetting another site leaves a task here followed.+ start(&config, &order, "t-forgot-other").await;+ forget(&config, Some("books.test")).await.unwrap();+ end(+ &config,+ "t-forgot-other",+ done(),+ Some(finished("t-forgot-other")),+ )+ .await;+ assert!(start(&config, &order, "t-forgot-next").await.flow.is_some());+}++#[tokio::test]+async fn values_are_found_however_the_module_spells_them() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let mut signup = task("Start at https://shop.test. Sign up");+ signup+ .facts+ .insert("email".into(), "[email protected]".into());+ signup.facts.insert("born".into(), "1990-05-12".into());+ start(&config, &signup, "t-spelled").await;+ // A value given when the paused task resumes is not kept either.+ note_inputs(+ &TaskId::new("t-spelled"),+ &BTreeMap::from([("phone".into(), "98-7654-3210".into())]),+ );+ let found = json!([+ hint("type asha r example com into the email box", "Email"),+ {"app": "browser", "key": "pick the day", "role": "button", "name": "12", "path": ["1990 05 12"]},+ hint("enter 98 7654 3210", "Phone"),+ hint("press sign up", "Sign up"),+ ]);+ let ended = view("t-spelled", done());+ end(+ &config,+ "t-spelled",+ done(),+ Some(report(&ended, flow(json!(["a"])), found, json!([]))),+ )+ .await;+ let next = start(&config, &signup, "t-spelled-next").await;+ let keys: Vec<_> = next.memory.iter().map(|hint| hint.key.as_str()).collect();+ assert_eq!(keys, ["press sign up"]);+}++#[tokio::test]+async fn a_saved_plan_the_module_refuses_is_forgotten_and_the_task_planned_afresh() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");+ start(&config, &order, "t-refused-1").await;+ end(+ &config,+ "t-refused-1",+ done(),+ Some(finished("t-refused-1")),+ )+ .await;+ let refusal =+ || "browser task StartTask failed [INVALID_FLOW]: step 1 is not a step".to_owned();++ // A transport error is not a refusal: the plan stays.+ let error = super::super::browser_task::begin(&config, &order, |_| {+ Box::pin(async {+ Err::<TaskView, _>("browser task StartTask failed: bus closed".to_owned())+ })+ })+ .await+ .unwrap_err();+ assert!(error.contains("bus closed"));++ let sent = Mutex::new(Vec::new());+ let started = super::super::browser_task::begin(&config, &order, |request| {+ let carried = request.flow.is_some();+ sent.lock().unwrap().push(carried);+ Box::pin(async move {+ if carried {+ Err(refusal())+ } else {+ Ok(view("t-refused-2", json!({"state": "running"})))+ }+ })+ })+ .await+ .unwrap();+ assert_eq!(started.id, TaskId::new("t-refused-2"));+ assert_eq!(*sent.lock().unwrap(), [true, false], "sent again unplanned");+ assert!(+ start(&config, &order, "t-refused-3").await.flow.is_none(),+ "forgotten"+ );++ // A flow the caller brought, refused, is the caller's to fix.+ let mut own = order.clone();+ own.flow = Some(serde_json::from_value(flow(json!(["b"]))).unwrap());+ let calls = Mutex::new(0);+ let error = super::super::browser_task::begin(&config, &own, |_| {+ *calls.lock().unwrap() += 1;+ Box::pin(async move { Err::<TaskView, _>(refusal()) })+ })+ .await+ .unwrap_err();+ assert!(error.contains("INVALID_FLOW"));+ assert_eq!(*calls.lock().unwrap(), 1);+}++#[tokio::test]+async fn files_unchanged_for_30_days_go_and_an_emptied_site_leaves_none() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ for site in ["old.test", "new.test"] {+ update(&config, site, keep_one).await;+ }+ let old = site_path(&config, "old.test");+ let stale = [+ old.clone(),+ old.with_extension("json.corrupt"),+ old.with_extension("json.tmp"),+ ];+ let month_ago = SystemTime::now() - Duration::from_secs(KEEP_SECS + 60);+ for path in &stale {+ std::fs::write(path, b"{}").unwrap();+ std::fs::File::options()+ .write(true)+ .open(path)+ .unwrap()+ .set_modified(month_ago)+ .unwrap();+ }+ // Any task's start sweeps, one on no site included.+ let mut nowhere = task("Read the news");+ nowhere.site = None;+ let mut request = super::super::browser_task::start_request(&config, &nowhere);+ assert!(apply(&config, &nowhere, &mut request).await.is_none());+ assert!(stale.iter().all(|path| !path.exists()));+ assert!(site_path(&config, "new.test").exists());++ // A reused plan that fails, the site's only entry, leaves no file.+ let order = task("Start at https://shop.test. Order milk");+ start(&config, &order, "t-only").await;+ let ended = view("t-only", done());+ end(+ &config,+ "t-only",+ done(),+ Some(report(&ended, flow(json!(["a"])), json!([]), json!([]))),+ )+ .await;+ assert!(start(&config, &order, "t-only-again").await.flow.is_some());+ end(&config, "t-only-again", failed(), None).await;+ assert!(!site_path(&config, "shop.test").exists());+}++#[tokio::test]+async fn a_switch_in_settings_reaches_tools_built_before_it() {+ let dir = tempfile::tempdir().unwrap();+ let config = workspace_config(&dir);+ let order = task("Start at https://shop.test. Order milk");+ start(&config, &order, "t-switched").await;+ note_switch(&config.workspace_dir, false);+ end(&config, "t-switched", done(), Some(finished("t-switched"))).await;+ assert!(!site_path(&config, "shop.test").exists(), "kept nothing");+ let mut request = super::super::browser_task::start_request(&config, &order);+ assert!(apply(&config, &order, &mut request).await.is_none());++ note_switch(&config.workspace_dir, true);+ assert!(apply(&config, &order, &mut request).await.is_some());+}diff --git a/crates/openhuman-core/src/modules/browser_task.rs b/crates/openhuman-core/src/modules/browser_task.rsindex 0eae2e4b99..b2006de404 100644--- a/crates/openhuman-core/src/modules/browser_task.rs+++ b/crates/openhuman-core/src/modules/browser_task.rs@@ -9,6 +9,8 @@//! surfaces as `needs_approval` and only `ContinueTask.approve` releases.use std::collections::BTreeMap;+use std::future::Future;+use std::pin::Pin;use std::time::{Duration, Instant};use serde::{de::DeserializeOwned, Serialize};@@ -24,6 +26,9 @@ use crate::config::Config;#[path = "browser_task_tests.rs"]mod tests;+/// A pending `StartTask` call.+pub(crate) type Started<'a> = Pin<Box<dyn Future<Output = Result<TaskView, String>> + Send + 'a>>;+/// The longest one `AwaitTask` long-poll asks for. The module caps it at 60s.const AWAIT_SLICE_MS: u64 = 30_000;/// The bus deadline for one call; beyond the longest long-poll.@@ -44,6 +49,10 @@ pub struct BrowserTask {/// A flow to run instead of having the module plan one from `goal`, such/// as a plan saved from an earlier run. `goal` then explains it.pub flow: Option<tinycomputer_bus::Flow>,+ /// The site the task starts on, from its starting address+ /// ([`super::browser_sites::site_of`]): what it learns is kept under it,+ /// and what earlier tasks there learned is handed to it.+ pub site: Option<String>,}/// Build the `StartTask` request for a browser-only task under host policy.@@ -79,18 +88,52 @@ pub fn start_request(config: &Config, task: &BrowserTask) -> StartTaskRequest {////// Returns a module, transport, or task error without page content.pub async fn start(config: &Config, task: &BrowserTask) -> Result<TaskView, String> {+ let view = begin(config, task, |request| {+ Box::pin(call(config, methods::START_TASK, request, true))+ })+ .await?;+ settle(config, view).await+}++/// Hands `task` to the module through `send`, its `StartTask` call, with what+/// earlier tasks on its site left (see [`super::browser_sites`]), and follows+/// the task for what it may teach. A saved plan the module refuses is+/// forgotten, and the task is sent again to be planned afresh.+///+/// # Errors+///+/// Returns a module, transport, or task error without page content.+pub(crate) async fn begin<'a>(+ config: &'a Config,+ task: &BrowserTask,+ send: impl Fn(StartTaskRequest) -> Started<'a>,+) -> Result<TaskView, String> {if task.origins.is_empty() {return Err("a browser task needs at least one allowed origin".to_owned());}- let request = start_request(config, task);+ let mut request = start_request(config, task);+ let mut following = super::browser_sites::apply(config, task, &mut request).await;tracing::debug!(origins = task.origins.len(),max_actions = task.max_actions,saved_flow = task.flow.is_some(),+ learning = following.is_some(),"[browser-task] starting");- let view: TaskView = call(config, methods::START_TASK, request, true).await?;- settle(config, view).await+ let view = match send(request.clone()).await {+ Err(error) if refused_flow(&error) => match following.as_mut() {+ Some(reusing) if reusing.reuses_plan() => {+ tracing::warn!(%error, "[browser-task] the module refused a saved plan; planning afresh");+ super::browser_sites::refused(config, reusing).await;+ request.flow = None;+ send(request).await?+ }+ _ => return Err(error),+ },+ sent => sent?,+ };+ super::browser_sites::follow(&view.id, following);+ Ok(view)}/// Answer a paused task and follow it again.@@ -100,6 +143,7 @@ pub async fn start(config: &Config, task: &BrowserTask) -> Result<TaskView, Stri/// Returns a module, transport, or task error.pub async fn resume(config: &Config, request: ContinueTaskRequest) -> Result<TaskView, String> {tracing::debug!(task = %request.id, approve = ?request.approve, "[browser-task] continuing");+ super::browser_sites::note_inputs(&request.id, &request.inputs);let view: TaskView = call(config, methods::CONTINUE_TASK, request, true).await?;settle(config, view).await}@@ -130,7 +174,9 @@ pub async fn wait(config: &Config, id: TaskId) -> Result<TaskView, String> {/// Returns a module or transport error.pub async fn cancel(config: &Config, id: TaskId) -> Result<TaskView, String> {tracing::debug!(task = %id, "[browser-task] cancelling");- call(config, methods::CANCEL_TASK, TaskRef { id }, false).await+ let view: TaskView = call(config, methods::CANCEL_TASK, TaskRef { id }, false).await?;+ super::browser_sites::learn(config, &view).await;+ Ok(view)}/// The task's record: its steps, what it collected, and every rescue. Page@@ -166,10 +212,12 @@ pub(crate) async fn report_with(}/// Follow `view` until it stops or the host deadline passes, then record-/// how it stopped (see [`super::browser_task_report`]).+/// how it stopped (see [`super::browser_task_report`]) and learn from it+/// once it has ended (see [`super::browser_sites`]).async fn settle(config: &Config, view: TaskView) -> Result<TaskView, String> {let view = follow(config, view).await?;super::browser_task_report::record(config, &view).await;+ super::browser_sites::learn(config, &view).await;Ok(view)}@@ -217,6 +265,12 @@ async fn call<Request: Serialize + Send, Reply: DeserializeOwned>(unwrap_response(member, response)}+/// Whether `error`, as [`unwrap_response`] spells it, is the module refusing+/// the flow a task was handed.+fn refused_flow(error: &str) -> bool {+ error.contains("[INVALID_FLOW]")+}+fn unwrap_response<Reply>(member: &str, response: AgentResponse<Reply>) -> Result<Reply, String> {match (response.ok, response.data, response.error) {(true, Some(data), _) => Ok(data),diff --git a/crates/openhuman-core/src/modules/browser_task_tests.rs b/crates/openhuman-core/src/modules/browser_task_tests.rsindex c662c34136..9762d4a77e 100644--- a/crates/openhuman-core/src/modules/browser_task_tests.rs+++ b/crates/openhuman-core/src/modules/browser_task_tests.rs@@ -9,6 +9,7 @@ fn task() -> BrowserTask {origins: vec!["https://.example.com".into()],max_actions: 12,flow: None,+ site: None,}}@@ -46,6 +47,36 @@ async fn start_refuses_a_task_without_origins() {assert!(error.contains("allowed origin"), "{error}");}+#[test]+fn only_the_module_refusing_a_flow_reads_as_a_refused_flow() {+ let refused: AgentResponse<u32> = AgentResponse {+ ok: false,+ data: None,+ error: Some(AgentError::new(+ "INVALID_FLOW",+ "step 2 is not a step",+ "fix the flow",+ true,+ )),+ };+ assert!(refused_flow(+ &unwrap_response("StartTask", refused).unwrap_err()+ ));+ let other: AgentResponse<u32> = AgentResponse {+ ok: false,+ data: None,+ error: Some(AgentError::new(+ "PLANNER_UNAVAILABLE",+ "no planner",+ "configure one",+ false,+ )),+ };+ assert!(!refused_flow(+ &unwrap_response("StartTask", other).unwrap_err()+ ));+}+#[test]fn unwrap_response_returns_data_or_the_structured_error() {let ok = AgentResponse {diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rsindex 3f80ce1289..62b4d6369f 100644--- a/crates/openhuman-core/src/modules/mod.rs+++ b/crates/openhuman-core/src/modules/mod.rs@@ -29,7 +29,8 @@//! - [`registry`] — the compiled-in set of loadable modules and their digests.//! - [`documents`] — the host half of the `tinydocs` module's three operations.//! - [`browser`] and [`browser_task`] — TinyComputer browser members and tasks-//! without linking the browser engine into the core.+//! without linking the browser engine into the core; [`browser_sites`] keeps+//! what finished tasks learned about each site for the next task there.//! - [`wallet`] — the host half of the `tinywallet` module, which builds and//! assembles transactions while the signing key stays in this process.//! - [`host`] — the module broker, connection and loader.@@ -41,6 +42,7 @@pub mod boot;pub mod browser;+pub(crate) mod browser_sites;pub mod browser_task;mod browser_task_report;pub mod computer;diff --git a/crates/openhuman-core/src/modules/schemas.rs b/crates/openhuman-core/src/modules/schemas.rsindex 1f0604b72e..091ff202b4 100644--- a/crates/openhuman-core/src/modules/schemas.rs+++ b/crates/openhuman-core/src/modules/schemas.rs@@ -24,6 +24,7 @@ pub fn all_controller_schemas() -> Vec<ControllerSchema> {schemas("status"),schemas("load"),schemas("browser_check_readiness"),+ schemas("browser_forget_sites"),schemas("computer_status"),]}@@ -46,6 +47,10 @@ pub fn all_registered_controllers() -> Vec<RegisteredController> {schema: schemas("browser_check_readiness"),handler: handle_browser_check_readiness,},+ RegisteredController {+ schema: schemas("browser_forget_sites"),+ handler: handle_browser_forget_sites,+ },RegisteredController {schema: schemas("computer_status"),handler: handle_computer_status,@@ -127,6 +132,23 @@ pub fn schemas(function: &str) -> ControllerSchema {},],},+ "browser_forget_sites" => ControllerSchema {+ namespace: "modules",+ function: "browser_forget_sites",+ description: "Forget what finished browser tasks learned about one site, or about every site.",+ inputs: vec![FieldSchema {+ name: "site",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "The site's host or an address on it; omit to forget every site.",+ required: false,+ }],+ outputs: vec![FieldSchema {+ name: "forgotten",+ ty: TypeSchema::U64,+ comment: "How many sites were forgotten.",+ required: true,+ }],+ },"computer_status" => ControllerSchema {namespace: "modules",function: "computer_status",@@ -209,6 +231,32 @@ fn handle_browser_check_readiness(_params: Map<String, Value>) -> ControllerFutu})}+fn handle_browser_forget_sites(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ // A blank or non-text site must not read as "every site".+ let site = match params.get("site") {+ None | Some(Value::Null) => None,+ Some(Value::String(site)) if !site.trim().is_empty() => Some(site.trim().to_owned()),+ Some(_) => {+ return Err(+ "`site` must name a site (a host or an address); omit it to forget every site"+ .to_owned(),+ )+ }+ };+ let config = config_rpc::load_config_with_timeout().await?;+ let forgotten = super::browser_sites::forget(&config, site.as_deref())+ .await+ .map_err(|error| format!("could not forget learned site data: {error}"))?;+ tracing::info!(+ forgotten,+ all = site.is_none(),+ "[browser-sites] forgot learned site data"+ );+ Ok(serde_json::json!({ "forgotten": forgotten }))+ })+}+fn handle_computer_status(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let load = params.get("load").and_then(Value::as_bool).unwrap_or(false);diff --git a/crates/openhuman-core/src/modules/schemas_tests.rs b/crates/openhuman-core/src/modules/schemas_tests.rsindex 663c834e97..57c79208c0 100644--- a/crates/openhuman-core/src/modules/schemas_tests.rs+++ b/crates/openhuman-core/src/modules/schemas_tests.rs@@ -68,6 +68,34 @@ async fn computer_status_handler_returns_serialized_status() {assert!(status.get("decision_model").is_some());}+#[tokio::test]+async fn forgetting_sites_reports_how_many_went() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = crate::config::Config::default();+ config.workspace_dir = dir.path().join("workspace");+ let sites = crate::modules::computer_config::trace_dir(&config).join("sites");+ std::fs::create_dir_all(&sites).unwrap();+ for site in ["shop.test", "books.test"] {+ std::fs::write(sites.join(format!("{site}.json")), b"{}").unwrap();+ }+ let ctx = CoreContext::for_test_with_config(DomainSet::full(), config);++ let (one, every) = CoreContext::scope(ctx, async {+ let mut one = Map::new();+ one.insert(+ "site".to_string(),+ Value::String("https://www.shop.test/cart".to_string()),+ );+ let one = super::handle_browser_forget_sites(one).await;+ (one, super::handle_browser_forget_sites(Map::new()).await)+ })+ .await;++ assert_eq!(one.unwrap()["forgotten"], 1);+ assert_eq!(every.unwrap()["forgotten"], 1);+ assert!(!sites.join("books.test.json").exists());+}+#[test]fn the_chrome_check_says_where_to_fix_a_missing_chrome() {let missing = super::readiness_error(@@ -80,3 +108,15 @@ fn the_chrome_check_says_where_to_fix_a_missing_chrome() {"Chrome could not start: Bus: launch timed out");}++#[tokio::test]+async fn a_blank_or_unreadable_site_forgets_nothing() {+ for site in [Value::String(" ".to_string()), Value::from(7)] {+ let mut params = Map::new();+ params.insert("site".to_string(), site);+ let error = super::handle_browser_forget_sites(params)+ .await+ .unwrap_err();+ assert!(error.contains("must name a site"), "{error}");+ }+}diff --git a/crates/openhuman-core/src/tools/impl/browser/browser.rs b/crates/openhuman-core/src/tools/impl/browser/browser.rsindex 5edd81add7..b3ad52abbe 100644--- a/crates/openhuman-core/src/tools/impl/browser/browser.rs+++ b/crates/openhuman-core/src/tools/impl/browser/browser.rs@@ -243,6 +243,9 @@ impl BrowserTool {async fn task(&self, args: &Value) -> anyhow::Result<Value> {let mut goal = required(args, "goal")?.to_owned();+ let site = args["url"]+ .as_str()+ .and_then(crate::modules::browser_sites::site_of);let origins = match args["url"].as_str().filter(|url| !url.trim().is_empty()) {Some(url) => {self.client.check_url(url)?;@@ -267,6 +270,7 @@ impl BrowserTool {origins,max_actions: u32::try_from(self.max_steps).unwrap_or(u32::MAX),flow,+ site,};let view = crate::modules::browser_task::start(self.client.config(), &task).awaitdiff --git a/tests/computer_bali_live_e2e.rs b/tests/computer_bali_live_e2e.rsindex 7bcd2baa4e..d959220c85 100644--- a/tests/computer_bali_live_e2e.rs+++ b/tests/computer_bali_live_e2e.rs@@ -165,6 +165,7 @@ async fn books_a_bali_flight_up_to_the_payment_page() {} else {Some(serde_json::from_str(&plan_text).expect("saved flow"))},+ site: None,};let minutes = std::env::var("COMPUTER_E2E_MINUTES").ok()