Skip to content

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

feat(browser): add browser sites module with persistent store

Steven Enamakel161130bd9346
diff --git a/crates/openhuman-core/src/config/ops/ui.rs b/crates/openhuman-core/src/config/ops/ui.rs
index 59f3a96557..6ef6de8b00 100644
--- a/crates/openhuman-core/src/config/ops/ui.rs
+++ b/crates/openhuman-core/src/config/ops/ui.rs
@@ -126,7 +126,7 @@ pub async fn apply_browser_settings(
// 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);
+ crate::modules::site_memory_host::note_switch(&config.workspace_dir, learn);
}
let snapshot = snapshot_config_json(config)?;
Ok(Outcome::new(
diff --git a/crates/openhuman-core/src/modules/browser_sites.rs b/crates/openhuman-core/src/modules/browser_sites.rs
deleted file mode 100644
index dd33aa63e2..0000000000
--- a/crates/openhuman-core/src/modules/browser_sites.rs
+++ /dev/null
@@ -1,590 +0,0 @@
-//! 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, HashMap, VecDeque};
-use std::future::Future;
-use std::path::{Path, PathBuf};
-use std::pin::Pin;
-use std::sync::atomic::{AtomicU64, Ordering};
-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 self::store::{forget_every_site, load, remove, saving, site_path, sites_dir, sweep, update};
-use super::browser_task::BrowserTask;
-use crate::config::Config;
-
-mod store;
-
-/// 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 {
- /// Tells this following from any other under the same task id: the
- /// module numbers its tasks afresh each time it is set up again.
- token: u64,
- /// 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;
- }
- // A plain host name, nothing a path could be built from.
- let site = site_named(task.site.as_deref()?)?;
- 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"
- );
- static TOKENS: AtomicU64 = AtomicU64::new(1);
- Some(Following {
- token: TOKENS.fetch_add(1, Ordering::Relaxed),
- workspace: config.workspace_dir.clone(),
- site,
- goal,
- facts_id,
- reused_plan,
- facts: fact_values(task.facts.values()),
- })
-}
-
-/// Follows task `id` of `config`'s workspace until it ends, to learn from
-/// how it did; with `None`, follows no task by that id there. 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(config: &Config, id: &TaskId, following: Option<Following>) {
- let mut followed = followed();
- followed
- .retain(|(known, existing)| !(known == id && existing.workspace == config.workspace_dir));
- if let Some(following) = following {
- followed.push_back((id.clone(), following));
- }
- while followed.len() > FOLLOWED {
- followed.pop_front();
- }
-}
-
-/// Which following of task `id` in `config`'s workspace is under way, to be
-/// handed to [`learn`] once the task is seen to have ended: a view of an
-/// earlier task by the same id then learns nothing.
-pub(crate) fn token_of(config: &Config, id: &TaskId) -> Option<u64> {
- followed_as(config, id).map(|following| following.token)
-}
-
-/// Adds `inputs`, the values a paused task `id` is given, to the values it
-/// may not keep.
-pub(crate) fn note_inputs(config: &Config, id: &TaskId, inputs: &BTreeMap<String, String>) {
- if inputs.is_empty() {
- return;
- }
- let mut followed = followed();
- if let Some((_, following)) = followed
- .iter_mut()
- .find(|(known, following)| known == id && following.workspace == config.workspace_dir)
- {
- 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. When the site file cannot be changed, the
-/// task still counts as reusing it, and a failure forgets it then.
-pub(crate) async fn refused(config: &Config, following: &mut Following) {
- let plan_of: &Following = following;
- let forgotten = update(config, &plan_of.site, |memory| {
- memory.forget_plan(plan_of);
- true
- })
- .await;
- if forgotten {
- 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. `token`
-/// ([`token_of`]) names the following the view belongs to, taken before the
-/// task was last waited on; a view of another task by the same id learns
-/// nothing. A task still running or paused stays followed.
-pub(crate) async fn learn(config: &Config, view: &TaskView, token: Option<u64>) {
- learn_with(config, view, token, |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,
- token: Option<u64>,
- fetch: impl FnOnce(TaskId) -> ReportFetch<'a>,
-) {
- let Some(token) = token else {
- return;
- };
- match &view.status {
- TaskStatus::Done { .. } | TaskStatus::Checkpoint { .. } => {
- let Some(following) =
- followed_as(config, &view.id).filter(|following| following.token == token)
- else {
- return;
- };
- if !learning(config) {
- stop_following(config, &view.id, token);
- return;
- }
- match fetch(view.id.clone()).await {
- Ok(report) => {
- let learned = now();
- let mut kept = false;
- update(config, &following.site, |memory| {
- // Still followed and learning, under the save lock: a
- // Forget, or learning switched off, while the report
- // was fetched holds.
- kept =
- stop_following(config, &view.id, token).is_some() && learning(config);
- 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(config, &view.id, token);
- tracing::warn!(task = %view.id, %error, "[browser-sites] report unavailable; nothing learned");
- }
- }
- }
- TaskStatus::Failed { .. } => {
- let Some(following) = stop_following(config, &view.id, token) 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(config, &view.id, token);
- }
- _ => {}
- }
-}
-
-/// 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))
-}
-
-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()))
-}
-
-/// 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` of `config`'s workspace is followed for, if it is.
-fn followed_as(config: &Config, id: &TaskId) -> Option<Following> {
- followed()
- .iter()
- .find(|(known, following)| known == id && following.workspace == config.workspace_dir)
- .map(|(_, following)| following.clone())
-}
-
-/// Stops the following `token` of task `id` in `config`'s workspace,
-/// returning what the task was followed for; another following of that id
-/// is left alone.
-fn stop_following(config: &Config, id: &TaskId, token: u64) -> Option<Following> {
- let mut followed = followed();
- let index = followed.iter().position(|(known, following)| {
- known == id && following.workspace == config.workspace_dir && following.token == token
- })?;
- 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/store.rs b/crates/openhuman-core/src/modules/browser_sites/store.rs
deleted file mode 100644
index d29c21466c..0000000000
--- a/crates/openhuman-core/src/modules/browser_sites/store.rs
+++ /dev/null
@@ -1,192 +0,0 @@
-//! Site files: where each site's memory is kept, reading one back, writing a
-//! change through a temporary file within its size limit, and removing what
-//! is forgotten or unchanged for 30 days.
-
-use std::collections::BTreeSet;
-#[cfg(unix)]
-use std::os::unix::fs::PermissionsExt;
-use std::path::{Path, PathBuf};
-use std::sync::OnceLock;
-use std::time::UNIX_EPOCH;
-
-use tokio::io::AsyncWriteExt;
-
-use super::{now, SiteMemory, KEEP_SECS, MAX_FILE_BYTES};
-use crate::config::Config;
-
-/// Removes every file in `dir`, returning how many sites they held.
-pub(super) 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.
-pub(super) 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.
-pub(super) 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"),
- }
- }
- }
-}
-
-pub(super) fn sites_dir(config: &Config) -> PathBuf {
- crate::modules::computer_config::trace_dir(config).join("sites")
-}
-
-pub(super) 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.
-pub(super) 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. Whether the file holds the change, or there was none; a
-/// failure is logged, never raised.
-pub(super) async fn update(
- config: &Config,
- site: &str,
- change: impl FnOnce(&mut SiteMemory) -> bool,
-) -> bool {
- let _saving = saving().lock().await;
- let mut memory = load(config, site, now()).await;
- if !change(&mut memory) {
- return true;
- }
- let path = site_path(config, site);
- let written = if memory.plans.is_empty() && memory.hints.is_empty() {
- remove(&path).await.map(|_removed| ())
- } else {
- match fitted(&mut memory) {
- Ok(bytes) => save(&path, &bytes).await,
- Err(error) => Err(error),
- }
- };
- if let Err(error) = &written {
- tracing::warn!(%error, "[browser-sites] site memory not saved");
- }
- written.is_ok()
-}
-
-/// `memory` serialized within `MAX_FILE_BYTES`, its oldest plans and then its
-/// oldest elements dropped until it fits: a larger file is set aside unread
-/// by the next [`load`], with all it held.
-pub(super) fn fitted(memory: &mut SiteMemory) -> std::io::Result<Vec<u8>> {
- loop {
- let bytes = serde_json::to_vec_pretty(memory).map_err(std::io::Error::other)?;
- let fits = u64::try_from(bytes.len()).is_ok_and(|length| length <= MAX_FILE_BYTES);
- if fits {
- return Ok(bytes);
- }
- if memory.plans.is_empty() {
- if memory.hints.is_empty() {
- return Ok(bytes);
- }
- memory.hints.remove(0);
- } else {
- memory.plans.remove(0);
- }
- }
-}
-
-/// Writes `bytes` 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, bytes: &[u8]) -> std::io::Result<()> {
- 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.
-pub(super) fn saving() -> &'static tokio::sync::Mutex<()> {
- static SAVING: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
- SAVING.get_or_init(|| tokio::sync::Mutex::new(()))
-}
diff --git a/crates/openhuman-core/src/modules/browser_sites_store_tests.rs b/crates/openhuman-core/src/modules/browser_sites_store_tests.rs
deleted file mode 100644
index d1bf63af6e..0000000000
--- a/crates/openhuman-core/src/modules/browser_sites_store_tests.rs
+++ /dev/null
@@ -1,212 +0,0 @@
-//! Site files: entries that expire and the limits a site's memory keeps,
-//! an unreadable file set aside, forgetting one site or every site, the
-//! 30-day sweep, and the size a file may grow to.
-
-use super::*;
-#[cfg(unix)]
-use std::os::unix::fs::PermissionsExt;
-
-#[test]
-fn old_entries_go_and_limits_hold() {
- let order = task("Order milk");
- let following = Following {
- token: 0,
- 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 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 = crate::modules::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_site_that_is_no_plain_host_names_no_file() {
- let dir = tempfile::tempdir().unwrap();
- let config = workspace_config(&dir);
- for site in ["../outside", "a/b", "..", "", ".hidden"] {
- let mut odd = task("Start at https://shop.test. Order milk");
- odd.site = Some(site.to_owned());
- let mut request = crate::modules::browser_task::start_request(&config, &odd);
- assert!(apply(&config, &odd, &mut request).await.is_none(), "{site}");
- }
- // Spelled another way, a host is still its site.
- let mut spelled = task("Start at https://shop.test. Order milk");
- spelled.site = Some("WWW.Shop.Test".to_owned());
- let mut request = crate::modules::browser_task::start_request(&config, &spelled);
- let following = apply(&config, &spelled, &mut request).await.unwrap();
- assert_eq!(following.site, "shop.test");
-}
-
-#[tokio::test]
-async fn a_site_file_stays_within_its_size_limit() {
- let dir = tempfile::tempdir().unwrap();
- let config = workspace_config(&dir);
- let order = task("Start at https://shop.test. Order milk");
- start(&config, &order, "t-small").await;
- end(&config, "t-small", done(), Some(finished("t-small"))).await;
- let eggs = task("Start at https://shop.test. Order eggs");
- start(&config, &eggs, "t-big").await;
- let huge = flow(json!(
- ["x".repeat(usize::try_from(MAX_FILE_BYTES).unwrap())]
- ));
- let ended = view("t-big", done());
- end(
- &config,
- "t-big",
- done(),
- Some(report(&ended, huge, json!([hint("b", "B")]), json!([]))),
- )
- .await;
-
- let path = site_path(&config, "shop.test");
- assert!(std::fs::metadata(&path).unwrap().len() <= MAX_FILE_BYTES);
- let memory = load(&config, "shop.test", now()).await;
- assert!(
- !path.with_extension("json.corrupt").exists(),
- "read back, not set aside"
- );
- assert_eq!(memory.hints.len(), 2, "the elements are kept");
- assert_eq!(
- memory.plans.len(),
- 0,
- "the oldest plans went first, then the one too large on its own"
- );
-}
diff --git a/crates/openhuman-core/src/modules/browser_sites_tests.rs b/crates/openhuman-core/src/modules/browser_sites_tests.rs
deleted file mode 100644
index d88427489b..0000000000
--- a/crates/openhuman-core/src/modules/browser_sites_tests.rs
+++ /dev/null
@@ -1,670 +0,0 @@
-//! 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(
- config,
- &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);
- let token = token_of(config, &TaskId::new(id));
- learn_with(config, &ended, token, 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;
-}
-
-#[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;
- let token = token_of(&config, &TaskId::new("t-forgot-fetching"));
- learn_with(
- &config,
- &view("t-forgot-fetching", done()),
- token,
- 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(
- &config,
- &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 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());
-}
-
-#[tokio::test]
-async fn a_refused_plan_that_cannot_be_forgotten_still_counts_as_reused() {
- let dir = tempfile::tempdir().unwrap();
- let config = workspace_config(&dir);
- let order = task("Start at https://shop.test. Order milk");
- start(&config, &order, "t-locked").await;
- end(&config, "t-locked", done(), Some(finished("t-locked"))).await;
- let mut request = super::super::browser_task::start_request(&config, &order);
- let mut reusing = apply(&config, &order, &mut request).await.unwrap();
- assert!(reusing.reuses_plan());
-
- // A directory where the site file is written through: the write fails.
- let staged = site_path(&config, "shop.test").with_extension("json.tmp");
- std::fs::create_dir(&staged).unwrap();
- refused(&config, &mut reusing).await;
- assert!(
- reusing.reuses_plan(),
- "still reused, so a failure on it forgets it"
- );
- std::fs::remove_dir(&staged).unwrap();
- refused(&config, &mut reusing).await;
- assert!(!reusing.reuses_plan());
- let mut request = super::super::browser_task::start_request(&config, &order);
- assert!(!apply(&config, &order, &mut request)
- .await
- .unwrap()
- .reuses_plan());
-}
-
-#[tokio::test]
-async fn learning_switched_off_while_a_report_is_fetched_keeps_nothing() {
- let dir = tempfile::tempdir().unwrap();
- let config = workspace_config(&dir);
- let order = task("Start at https://shop.test. Order milk");
- start(&config, &order, "t-switch-mid").await;
- let id = TaskId::new("t-switch-mid");
- let workspace = config.workspace_dir.clone();
- learn_with(
- &config,
- &view("t-switch-mid", done()),
- token_of(&config, &id),
- move |_| {
- Box::pin(async move {
- note_switch(&workspace, false);
- Ok(finished("t-switch-mid"))
- })
- },
- )
- .await;
- assert!(!site_path(&config, "shop.test").exists());
- assert!(token_of(&config, &id).is_none(), "no longer followed");
-}
-
-#[tokio::test]
-async fn a_task_of_another_workspace_or_an_earlier_setup_is_not_taken_for_this_one() {
- let (one, two) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
- let (first, second) = (workspace_config(&one), workspace_config(&two));
- let order = task("Start at https://shop.test. Order milk");
- let shared = TaskId::new("t-shared");
- // The same id, in two workspaces.
- start(&first, &order, "t-shared").await;
- start(&second, &order, "t-shared").await;
- end(&first, "t-shared", done(), Some(finished("t-shared"))).await;
- assert!(site_path(&first, "shop.test").exists());
- assert!(!site_path(&second, "shop.test").exists());
- assert!(token_of(&second, &shared).is_some(), "still followed there");
-
- // A view of an earlier task by that id, once the module, set up again,
- // gave it to a newer task.
- let earlier = token_of(&second, &shared);
- start(
- &second,
- &task("Start at https://shop.test. Order eggs"),
- "t-shared",
- )
- .await;
- learn_with(&second, &view("t-shared", done()), earlier, |_| {
- Box::pin(async { Ok::<_, String>(finished("t-shared")) })
- })
- .await;
- assert!(
- !site_path(&second, "shop.test").exists(),
- "the earlier view learns nothing"
- );
- end(&second, "t-shared", done(), Some(finished("t-shared"))).await;
- assert!(site_path(&second, "shop.test").exists());
-}
-
-#[path = "browser_sites_store_tests.rs"]
-mod store;
diff --git a/crates/openhuman-core/src/modules/browser_task_tests.rs b/crates/openhuman-core/src/modules/browser_task_tests.rs
index d0d2af4b70..03e82523df 100644
--- a/crates/openhuman-core/src/modules/browser_task_tests.rs
+++ b/crates/openhuman-core/src/modules/browser_task_tests.rs
@@ -1,6 +1,5 @@
use super::*;
use serde_json::json;
-use tinycomputer_bus::agent::AgentError;
fn task() -> BrowserTask {
BrowserTask {
@@ -78,47 +77,30 @@ async fn start_refuses_a_task_without_origins() {
}
#[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,
- )),
+fn the_module_is_told_the_site_only_while_learning_is_on() {
+ let workspace = tempfile::tempdir().unwrap();
+ let mut config = Config {
+ workspace_dir: workspace.path().to_path_buf(),
+ ..Config::default()
};
- assert!(!refused_flow(
- &unwrap_response("StartTask", other).unwrap_err()
- ));
- // Only the code counts, not a message that quotes it.
- let quoted: AgentResponse<u32> = AgentResponse {
- ok: false,
- data: None,
- error: Some(AgentError::new(
- "PLANNER_UNAVAILABLE",
- "[INVALID_FLOW] was the last answer",
- "configure one",
- false,
- )),
- };
- assert!(!refused_flow(
- &unwrap_response("StartTask", quoted).unwrap_err()
- ));
+ config.browser.learn_from_tasks = true;
+ let mut on_a_site = task();
+ on_a_site.site = Some("shop.test".to_owned());
+
+ assert_eq!(
+ start_request(&config, &on_a_site).site.as_deref(),
+ Some("shop.test")
+ );
+ // A switch in Browser settings outranks the config a tool was built with.
+ super::super::site_memory_host::note_switch(workspace.path(), false);
+ assert_eq!(start_request(&config, &on_a_site).site, None);
+ super::super::site_memory_host::note_switch(workspace.path(), true);
+ assert_eq!(
+ start_request(&config, &on_a_site).site.as_deref(),
+ Some("shop.test")
+ );
+ // A task that names no site hands the module none.
+ assert_eq!(start_request(&config, &task()).site, None);
}
#[test]
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index cb9d6c13f7..fb34ece6e3 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -29,8 +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; [`browser_sites`] keeps
-//! what finished tasks learned about each site for the next task there, and
+//! without linking the browser engine into the core; [`site_memory_host`] serves
+//! where the module keeps what finished tasks learned about each site, and
//! [`profile_claim`] asks the module to claim the persistent Chrome profile
//! for a browser about to start.
//! - [`wallet`] — the host half of the `tinywallet` module, which builds and
@@ -47,8 +47,6 @@ pub mod boot;
#[cfg(feature = "modules")]
pub mod browser;
#[cfg(feature = "modules")]
-pub(crate) mod browser_sites;
-#[cfg(feature = "modules")]
pub mod browser_task;
#[cfg(feature = "modules")]
mod browser_task_report;
@@ -86,7 +84,7 @@ pub mod search;
#[cfg(feature = "modules")]
mod search_path;
#[cfg(feature = "modules")]
-mod site_memory_host;
+pub(crate) mod site_memory_host;
mod source;
#[cfg(feature = "modules")]
mod storage_grant_tinychannels;
diff --git a/crates/openhuman-core/src/modules/schemas.rs b/crates/openhuman-core/src/modules/schemas.rs
index 795bef7143..93d385239d 100644
--- a/crates/openhuman-core/src/modules/schemas.rs
+++ b/crates/openhuman-core/src/modules/schemas.rs
@@ -253,7 +253,7 @@ fn handle_browser_forget_sites(params: Map<String, Value>) -> ControllerFuture {
};
let config = config_rpc::load_config_with_timeout().await?;
crate::core::runtime::components::require_config(&config, "computer")?;
- let forgotten = super::browser_sites::forget(&config, site.as_deref())
+ let forgotten = super::site_memory_host::forget(&config, site.as_deref())
.await
.map_err(|error| format!("could not forget learned site data: {error}"))?;
tracing::info!(
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser.rs b/crates/openhuman-core/src/tools/impl/browser/browser.rs
index 06e2009101..364c1c4847 100644
--- a/crates/openhuman-core/src/tools/impl/browser/browser.rs
+++ b/crates/openhuman-core/src/tools/impl/browser/browser.rs
@@ -256,7 +256,7 @@ impl BrowserTool {
let mut goal = required(args, "goal")?.to_owned();
let site = args["url"]
.as_str()
- .and_then(crate::modules::browser_sites::site_of);
+ .and_then(crate::modules::site_memory_host::site_of);
let origins = match args["url"].as_str().filter(|url| !url.trim().is_empty()) {
Some(url) => {
self.client.check_url(url)?;