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
Split browser site memory under the file-size limit
Shanub9f5e3af0297
diff --git a/crates/openhuman-core/src/modules/browser_sites.rs b/crates/openhuman-core/src/modules/browser_sites.rsindex 0af24b731c..dd33aa63e2 100644--- a/crates/openhuman-core/src/modules/browser_sites.rs+++ b/crates/openhuman-core/src/modules/browser_sites.rs@@ -27,10 +27,8 @@//! `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::collections::{BTreeMap, 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::atomic::{AtomicU64, Ordering};@@ -41,11 +39,13 @@ 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 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.@@ -443,66 +443,6 @@ pub async fn forget(config: &Config, site: Option<&str>) -> std::io::Result<usizOk(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) {@@ -607,119 +547,6 @@ fn holds(text: &str, facts: &[String]) -> bool {.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. Whether the file holds the change, or there was none; a-/// failure is logged, never raised.-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.-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.-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>> {diff --git a/crates/openhuman-core/src/modules/browser_sites/store.rs b/crates/openhuman-core/src/modules/browser_sites/store.rsnew file mode 100644index 0000000000..d29c21466c--- /dev/null+++ b/crates/openhuman-core/src/modules/browser_sites/store.rs@@ -0,0 +1,192 @@+//! 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.rsnew file mode 100644index 0000000000..d1bf63af6e--- /dev/null+++ b/crates/openhuman-core/src/modules/browser_sites_store_tests.rs@@ -0,0 +1,212 @@+//! 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.rsindex e747089b04..d88427489b 100644--- a/crates/openhuman-core/src/modules/browser_sites_tests.rs+++ b/crates/openhuman-core/src/modules/browser_sites_tests.rs@@ -400,110 +400,6 @@ async fn a_paused_task_is_followed_until_it_ends() {end(&config, "t-unknown", done(), None).await;}-#[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 an_id_the_module_gives_another_task_is_not_learned_from() {let dir = tempfile::tempdir().unwrap();@@ -666,53 +562,6 @@ async fn a_saved_plan_the_module_refuses_is_forgotten_and_the_task_planned_afresassert_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();@@ -729,60 +578,6 @@ async fn a_switch_in_settings_reaches_tools_built_before_it() {assert!(apply(&config, &order, &mut request).await.is_some());}-#[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 = super::super::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 = super::super::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"- );-}-#[tokio::test]async fn a_refused_plan_that_cannot_be_forgotten_still_counts_as_reused() {let dir = tempfile::tempdir().unwrap();@@ -870,3 +665,6 @@ async fn a_task_of_another_workspace_or_an_earlier_setup_is_not_taken_for_this_oend(&second, "t-shared", done(), Some(finished("t-shared"))).await;assert!(site_path(&second, "shop.test").exists());}++#[path = "browser_sites_store_tests.rs"]+mod store;