Skip to content

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

fix(browser): claim the persistent profile until its Chrome holds it

Shanua7334b71a85b
diff --git a/crates/openhuman-core/src/modules/README.md b/crates/openhuman-core/src/modules/README.md
index 90d752a5e9..bbeff29dc7 100644
--- a/crates/openhuman-core/src/modules/README.md
+++ b/crates/openhuman-core/src/modules/README.md
@@ -218,7 +218,7 @@ download, its `dlopen`, or its resident memory.
| [`computer.rs`](computer.rs) | `tinycomputer` | `status` for the Computer settings page: lifecycle state, configured routes, and optionally what the module reports through `Describe`. |
| [`browser.rs`](browser.rs) | `tinycomputer` | `BrowserClient` for the `Browser*` members, over the desktop proxy, plus the shared website policy: "Allow all" (the list's `*`) lets the browser open any public site, private and local addresses still refused. |
| [`browser_task.rs`](browser_task.rs) | `tinycomputer` | Browser tasks over `StartTask` / `AwaitTask` / `ContinueTask`: `start`, `wait`, `resume`, `cancel`, `report`. The host keeps the policy (surfaces, origins, action budget, approvals) and sends Browser Control's Chrome path, and in persistent mode its profile folder, with every task, read from the settings each time. A refusal or failure that says Chrome is missing, or that its path names no Chrome, tells the agent where the user sets that path. |
-| [`browser_profile.rs`](browser_profile.rs) | `tinycomputer` | Whether a running Chrome holds the persistent profile folder, by the lock Chrome keeps there (`SingletonLock`, or `lockfile` on Windows). Chrome lets one browser at a time use a profile, so a task waits up to 5 s for one closing on it, then runs in a fresh profile. |
+| [`browser_profile.rs`](browser_profile.rs) | `tinycomputer` | Whether a running Chrome holds the persistent profile folder, by the lock Chrome keeps there (`SingletonLock`, or `lockfile` on Windows). Chrome lets one browser at a time use a profile, so a task waits up to 5 s for one closing on it, then runs in a fresh profile. A browser of this process claims the folder before it starts, as Chrome locks it only once started, so two starting together never both take it. |
| [`browser_task_report.rs`](browser_task_report.rs) | `tinycomputer` | What is kept when a task stops: a content-free log summary, and with tracing on the full report under `<workspace>/state/computer/tasks/`. |
| [`browser_sites.rs`](browser_sites.rs), [`browser_sites/store.rs`](browser_sites/store.rs) | `tinycomputer` | Per-site memory of plans and elements learned by finished tasks, in `<workspace>/state/computer/sites/<site>.json`, with 30-day expiry. Fed back on `StartTask`; never reaches the agent's memory or prompts. |
| [`connectors.rs`](connectors.rs) | `tinyconnectors` | `proxy`, `call`, `call_stateless`, `call_bare`, `reconcile_route_if_loaded`. Builds the route configuration (signed-in backend or the user's own Composio key) and reconciles it on every call so sign-out reaches the module. |
diff --git a/crates/openhuman-core/src/modules/browser.rs b/crates/openhuman-core/src/modules/browser.rs
index 53e89e0076..3141163f99 100644
--- a/crates/openhuman-core/src/modules/browser.rs
+++ b/crates/openhuman-core/src/modules/browser.rs
@@ -204,12 +204,19 @@ impl BrowserClient {
} else {
None
};
- fresh_if_held(&mut options, super::browser_profile::SESSION_PROFILE_WAIT).await;
+ let claimed =
+ claim_profile(&mut options, super::browser_profile::SESSION_PROFILE_WAIT).await;
options.download_dir = browser.download_dir.clone();
options.default_timeout_ms = browser.task_timeout_secs.saturating_mul(1000);
options.allowed_origins =
origin.map_or_else(|| self.browser_origins(), |origin| vec![origin]);
- self.call(names::methods::OPEN_SESSION, options).await
+ let opened = self.call(names::methods::OPEN_SESSION, options).await;
+ // An open session's Chrome holds the profile itself; one that did
+ // not open holds nothing.
+ if let Some(profile) = claimed {
+ super::browser_profile::release(&profile);
+ }
+ opened
}
/// Open a session bound to the host tree of an explicit destination.
@@ -481,21 +488,25 @@ fn parsed_browser_url(raw: &str) -> Result<url::Url, BrowserCallError> {
.map_err(|_| BrowserCallError::Policy("invalid URL".into()))
}
-/// Leaves `options` its persistent profile only when no other Chrome holds
-/// it within `wait`. Chrome lets one browser at a time use a profile folder:
-/// a second one hands its window to the first and exits, and a session in
-/// one conversation found the profile held by another conversation's
-/// browser, or a task's. Such a session uses a fresh profile instead.
-async fn fresh_if_held(options: &mut SessionOptions, wait: std::time::Duration) {
- let Some(profile) = options.user_data_dir.clone() else {
- return;
- };
- if !super::browser_profile::free_within(std::path::Path::new(&profile), wait).await {
- tracing::warn!(
- "[browser] another Chrome holds the persistent profile; this session uses a fresh profile"
- );
- options.user_data_dir = None;
- }
+/// Claims `options`' persistent profile for the session's browser, or leaves
+/// it a fresh profile when another browser still holds the folder after
+/// `wait`; the folder it claimed. Chrome lets one browser at a time use a
+/// profile folder: a second one hands its window to the first and exits, and
+/// a session in one conversation found the profile held by another
+/// conversation's browser, or a task's.
+async fn claim_profile(
+ options: &mut SessionOptions,
+ wait: std::time::Duration,
+) -> Option<std::path::PathBuf> {
+ let profile = std::path::PathBuf::from(options.user_data_dir.as_ref()?);
+ if super::browser_profile::claim_within(&profile, wait).await {
+ return Some(profile);
+ }
+ tracing::warn!(
+ "[browser] another browser holds the persistent profile; this session uses a fresh profile"
+ );
+ options.user_data_dir = None;
+ None
}
fn browser_allow_all() -> bool {
diff --git a/crates/openhuman-core/src/modules/browser_profile.rs b/crates/openhuman-core/src/modules/browser_profile.rs
index 2f0544c007..58413b6abf 100644
--- a/crates/openhuman-core/src/modules/browser_profile.rs
+++ b/crates/openhuman-core/src/modules/browser_profile.rs
@@ -1,5 +1,5 @@
-//! Whether a running Chrome holds a profile folder, and waiting a moment for
-//! one that is closing to let it go.
+//! Whether a running Chrome holds a profile folder, and claiming one for a
+//! browser about to start.
//!
//! Chrome lets one browser at a time use a profile folder: a second one
//! started on it hands its window to the first and exits, so a browser task
@@ -8,9 +8,17 @@
//! Chrome that is closing (the one the task before it closes as it ends), a
//! session up to [`SESSION_PROFILE_WAIT`], and otherwise each runs in a fresh
//! profile.
+//!
+//! Chrome takes the folder's lock only once it has started, so two browsers
+//! starting together would each find the folder free. A browser of this
+//! process therefore claims the folder first ([`claim_within`]), and the
+//! claim stands until its Chrome holds the folder itself. Claims are this
+//! process's own; between processes, Chrome's lock is the only arbiter.
-use std::path::Path;
-use std::time::Duration;
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::{LazyLock, Mutex, PoisonError};
+use std::time::{Duration, Instant};
/// How long a task waits for the Chrome holding its persistent profile to
/// let it go before it runs in a fresh profile instead.
@@ -25,6 +33,15 @@ pub(crate) const SESSION_PROFILE_WAIT: Duration = Duration::from_secs(1);
/// How often the profile is looked at while waiting.
const PROFILE_POLL: Duration = Duration::from_millis(250);
+/// How long a claim stands while its Chrome has not taken the folder's lock:
+/// well past the time a browser takes to start. A session's Chrome starts
+/// before its open returns, a task's as the task starts, beside its planning.
+const CLAIM_GRACE: Duration = Duration::from_secs(30);
+
+/// The profile folders browsers of this process may still be starting on,
+/// with when each was claimed.
+static CLAIMS: LazyLock<Mutex<HashMap<PathBuf, Instant>>> = LazyLock::new(Mutex::default);
+
/// Whether a running Chrome holds the profile folder `path`, by the lock it
/// keeps there: on macOS and Linux a `SingletonLock` link naming the host and
/// the process holding it, on Windows a `lockfile` held open. A link naming
@@ -64,12 +81,14 @@ fn held_by(target: &str) -> bool {
system.process(pid).is_some()
}
-/// Waits up to `wait` for no Chrome to hold the profile folder `path`;
-/// whether it is free.
-pub(crate) async fn free_within(path: &Path, wait: Duration) -> bool {
+/// Claims the profile folder `path` for a browser about to start, waiting up
+/// to `wait` for no Chrome, and no other browser of this process starting on
+/// it, to hold it; whether it was claimed. The claim stands until that
+/// browser's Chrome holds the folder, [`release`], or [`CLAIM_GRACE`] passes.
+pub(crate) async fn claim_within(path: &Path, wait: Duration) -> bool {
let deadline = tokio::time::Instant::now() + wait;
loop {
- if !in_use(path) {
+ if claim(path) {
return true;
}
if tokio::time::Instant::now() >= deadline {
@@ -79,6 +98,34 @@ pub(crate) async fn free_within(path: &Path, wait: Duration) -> bool {
}
}
+/// Claims `path` when neither a Chrome nor a claim holds it; whether it did.
+fn claim(path: &Path) -> bool {
+ let mut claims = CLAIMS.lock().unwrap_or_else(PoisonError::into_inner);
+ if in_use(path) {
+ // Chrome's own lock guards the folder now, so a claim made for that
+ // Chrome has done its work.
+ claims.remove(path);
+ return false;
+ }
+ if claims
+ .get(path)
+ .is_some_and(|claimed| claimed.elapsed() < CLAIM_GRACE)
+ {
+ return false;
+ }
+ claims.insert(path.to_path_buf(), Instant::now());
+ true
+}
+
+/// Gives up the claim on `path`: its browser did not start, or has started
+/// and holds the folder itself.
+pub(crate) fn release(path: &Path) {
+ CLAIMS
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .remove(path);
+}
+
#[cfg(test)]
#[path = "browser_profile_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/modules/browser_profile_tests.rs b/crates/openhuman-core/src/modules/browser_profile_tests.rs
index 84cc3ed4c9..2d44da12f0 100644
--- a/crates/openhuman-core/src/modules/browser_profile_tests.rs
+++ b/crates/openhuman-core/src/modules/browser_profile_tests.rs
@@ -64,7 +64,7 @@ async fn waiting_ends_as_soon_as_the_folder_is_let_go() {
let path = folder("closing");
let lock = path.join("SingletonLock");
std::os::unix::fs::symlink(format!("{here}-{}", std::process::id()), &lock).unwrap();
- assert!(!free_within(&path, Duration::from_millis(300)).await);
+ assert!(!claim_within(&path, Duration::from_millis(300)).await);
let letting_go = {
let lock = lock.clone();
tokio::spawn(async move {
@@ -72,7 +72,52 @@ async fn waiting_ends_as_soon_as_the_folder_is_let_go() {
std::fs::remove_file(lock).unwrap();
})
};
- assert!(free_within(&path, PROFILE_WAIT).await);
+ assert!(claim_within(&path, PROFILE_WAIT).await);
letting_go.await.unwrap();
+ release(&path);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[tokio::test]
+async fn a_folder_claimed_for_a_starting_browser_is_held_until_released() {
+ let path = folder("claimed");
+ assert!(claim_within(&path, Duration::ZERO).await);
+ assert!(
+ !claim_within(&path, Duration::from_millis(50)).await,
+ "a browser still starting on it holds it"
+ );
+ release(&path);
+ assert!(claim_within(&path, Duration::ZERO).await);
+ release(&path);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[tokio::test]
+async fn of_two_browsers_starting_together_one_claims_the_folder() {
+ // Both look before either Chrome has locked the folder.
+ let path = folder("together");
+ let (first, second) = tokio::join!(
+ claim_within(&path, Duration::from_millis(50)),
+ claim_within(&path, Duration::from_millis(50)),
+ );
+ assert!(first ^ second, "first {first}, second {second}");
+ release(&path);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[cfg(not(windows))]
+#[tokio::test]
+async fn a_claim_ends_when_its_chrome_holds_the_folder() {
+ let here = sysinfo::System::host_name().unwrap_or_default();
+ let path = folder("taken-up");
+ assert!(claim_within(&path, Duration::ZERO).await);
+ // Its Chrome has started and locked the folder.
+ let lock = path.join("SingletonLock");
+ std::os::unix::fs::symlink(format!("{here}-{}", std::process::id()), &lock).unwrap();
+ assert!(!claim_within(&path, Duration::ZERO).await);
+ // That Chrome has closed: nothing of the claim is left to hold the folder.
+ std::fs::remove_file(&lock).unwrap();
+ assert!(claim_within(&path, Duration::ZERO).await);
+ release(&path);
let _ = std::fs::remove_dir_all(&path);
}
diff --git a/crates/openhuman-core/src/modules/browser_task.rs b/crates/openhuman-core/src/modules/browser_task.rs
index 80c09d3538..943be21f95 100644
--- a/crates/openhuman-core/src/modules/browser_task.rs
+++ b/crates/openhuman-core/src/modules/browser_task.rs
@@ -10,6 +10,7 @@
use std::collections::BTreeMap;
use std::future::Future;
+use std::path::PathBuf;
use std::pin::Pin;
use std::time::{Duration, Instant};
@@ -118,7 +119,7 @@ pub(crate) async fn begin<'a>(
return Err("a browser task needs at least one allowed origin".to_owned());
}
let mut request = start_request(config, task);
- free_profile(&mut request, super::browser_profile::PROFILE_WAIT).await;
+ let claimed = claim_profile(&mut request, super::browser_profile::PROFILE_WAIT).await;
let mut following = super::browser_sites::apply(config, task, &mut request).await;
tracing::debug!(
origins = task.origins.len(),
@@ -127,18 +128,28 @@ pub(crate) async fn begin<'a>(
learning = following.is_some(),
"[browser-task] starting"
);
- let view = match send(request.clone()).await {
+ let sent = match send(request.clone()).await {
Err(error) if refused_flow(&error) => match following.as_mut() {
Some(reusing) if reusing.reuses_plan() => {
// The error's text is the module's, and can quote the plan.
tracing::warn!("[browser-task] the module refused a saved plan; planning afresh");
super::browser_sites::refused(config, reusing).await;
request.flow = None;
- send(request).await?
+ send(request).await
}
- _ => return Err(error),
+ _ => Err(error),
},
- sent => sent?,
+ sent => sent,
+ };
+ let view = match sent {
+ Ok(view) => view,
+ Err(error) => {
+ // A task that did not start starts no browser on the profile.
+ if let Some(profile) = claimed {
+ super::browser_profile::release(&profile);
+ }
+ return Err(error);
+ }
};
super::browser_sites::follow(config, &view.id, following);
Ok(view)
@@ -286,21 +297,22 @@ fn refused_flow(error: &str) -> bool {
))
}
-/// Leaves `request` its persistent profile only when no other Chrome holds
-/// it within `wait`. Chrome lets one browser at a time use a profile folder,
-/// so a task waits a moment for one closing on it (the browser of the task
-/// before it, which closes as it ends), and otherwise runs in a fresh profile
-/// rather than fail to start its browser.
-async fn free_profile(request: &mut StartTaskRequest, wait: Duration) {
- let Some(profile) = request.constraints.browser_profile.clone() else {
- return;
- };
- if !super::browser_profile::free_within(std::path::Path::new(&profile), wait).await {
- tracing::warn!(
- "[browser-task] another Chrome holds the persistent profile; this task runs in a fresh profile"
- );
- request.constraints.browser_profile = None;
+/// Claims `request`'s persistent profile for the task's browser, or leaves it
+/// a fresh profile when another browser still holds the folder after `wait`;
+/// the folder it claimed. Chrome lets one browser at a time use a profile
+/// folder, so a task waits a moment for one closing on it (the browser of the
+/// task before it, which closes as it ends), and otherwise runs in a fresh
+/// profile rather than fail to start its browser.
+async fn claim_profile(request: &mut StartTaskRequest, wait: Duration) -> Option<PathBuf> {
+ let profile = PathBuf::from(request.constraints.browser_profile.as_ref()?);
+ if super::browser_profile::claim_within(&profile, wait).await {
+ return Some(profile);
}
+ tracing::warn!(
+ "[browser-task] another browser holds the persistent profile; this task runs in a fresh profile"
+ );
+ request.constraints.browser_profile = None;
+ None
}
/// A module reply as its data, or as the error the tool reports: its code,
diff --git a/crates/openhuman-core/src/modules/browser_task_tests.rs b/crates/openhuman-core/src/modules/browser_task_tests.rs
index 862c3c35e7..8a3b631ce0 100644
--- a/crates/openhuman-core/src/modules/browser_task_tests.rs
+++ b/crates/openhuman-core/src/modules/browser_task_tests.rs
@@ -190,7 +190,10 @@ async fn a_task_keeps_the_persistent_profile_only_while_no_other_chrome_holds_it
// Free: the task keeps it.
let mut request = start_request(&config, &task());
- free_profile(&mut request, Duration::from_millis(50)).await;
+ assert_eq!(
+ claim_profile(&mut request, Duration::from_millis(50)).await,
+ Some(profile.clone())
+ );
assert_eq!(
request.constraints.browser_profile.as_deref(),
config.browser.profile_path.as_deref()
@@ -206,17 +209,95 @@ async fn a_task_keeps_the_persistent_profile_only_while_no_other_chrome_holds_it
)
.unwrap();
let mut request = start_request(&config, &task());
- free_profile(&mut request, Duration::from_millis(50)).await;
+ assert_eq!(
+ claim_profile(&mut request, Duration::from_millis(50)).await,
+ None
+ );
assert!(request.constraints.browser_profile.is_none());
}
+ super::super::browser_profile::release(&profile);
let _ = std::fs::remove_dir_all(&profile);
// No persistent profile: nothing to wait for.
let mut request = start_request(&Config::default(), &task());
- free_profile(&mut request, Duration::from_millis(50)).await;
+ assert_eq!(
+ claim_profile(&mut request, Duration::from_millis(50)).await,
+ None
+ );
assert!(request.constraints.browser_profile.is_none());
}
+/// A config whose persistent profile is a fresh folder named `name`, with
+/// its workspace in `dir`.
+fn persistent_config(dir: &tempfile::TempDir, name: &str) -> (Config, PathBuf) {
+ let profile = dir.path().join(name);
+ std::fs::create_dir_all(&profile).unwrap();
+ let mut config = Config::default();
+ config.workspace_dir = dir.path().join("workspace");
+ config.browser.profile_mode = "persistent".into();
+ config.browser.profile_path = Some(profile.to_string_lossy().into_owned());
+ (config, profile)
+}
+
+#[tokio::test]
+async fn of_two_tasks_starting_together_one_runs_in_a_fresh_profile() {
+ // Neither one's Chrome has locked the folder when the other looks.
+ let dir = tempfile::tempdir().unwrap();
+ let (config, profile) = persistent_config(&dir, "together");
+ let (mut first, mut second) = (
+ start_request(&config, &task()),
+ start_request(&config, &task()),
+ );
+ let (kept_first, kept_second) = tokio::join!(
+ claim_profile(&mut first, Duration::from_millis(50)),
+ claim_profile(&mut second, Duration::from_millis(50)),
+ );
+ let profiles = [
+ first.constraints.browser_profile,
+ second.constraints.browser_profile,
+ ];
+ assert_eq!(
+ profiles.iter().filter(|kept| kept.is_some()).count(),
+ 1,
+ "{profiles:?}"
+ );
+ assert_eq!(kept_first.or(kept_second), Some(profile.clone()));
+ super::super::browser_profile::release(&profile);
+}
+
+#[tokio::test]
+async fn a_task_the_module_did_not_start_gives_its_profile_back() {
+ let dir = tempfile::tempdir().unwrap();
+ let (config, profile) = persistent_config(&dir, "refused");
+ let error = begin(&config, &task(), |_| {
+ Box::pin(async { Err::<TaskView, _>("browser task StartTask failed: bus closed".into()) })
+ })
+ .await
+ .unwrap_err();
+ assert!(error.contains("bus closed"));
+ assert!(
+ super::super::browser_profile::claim_within(&profile, Duration::ZERO).await,
+ "free for the next task at once"
+ );
+ super::super::browser_profile::release(&profile);
+
+ // A task that started keeps its claim until its Chrome holds the folder.
+ begin(&config, &task(), |request| {
+ assert!(request.constraints.browser_profile.is_some());
+ Box::pin(async {
+ Ok(serde_json::from_value::<TaskView>(json!({
+ "id": "t-claimed", "status": {"state": "running"},
+ "summary": "", "progress": 0.0, "next": []
+ }))
+ .unwrap())
+ })
+ })
+ .await
+ .unwrap();
+ assert!(!super::super::browser_profile::claim_within(&profile, Duration::ZERO).await);
+ super::super::browser_profile::release(&profile);
+}
+
#[test]
fn a_saved_flow_is_run_instead_of_planned() {
let flow: tinycomputer_bus::Flow = serde_json::from_value(serde_json::json!({
diff --git a/crates/openhuman-core/src/modules/browser_tests.rs b/crates/openhuman-core/src/modules/browser_tests.rs
index 19541b9314..a64b25afc9 100644
--- a/crates/openhuman-core/src/modules/browser_tests.rs
+++ b/crates/openhuman-core/src/modules/browser_tests.rs
@@ -201,8 +201,22 @@ async fn a_session_opens_in_a_fresh_profile_while_another_chrome_holds_it() {
user_data_dir: Some(held.clone()),
..SessionOptions::default()
};
- fresh_if_held(&mut options, std::time::Duration::from_millis(50)).await;
+ let wait = std::time::Duration::from_millis(50);
+ assert_eq!(
+ claim_profile(&mut options, wait).await,
+ Some(profile.clone())
+ );
assert_eq!(options.user_data_dir.as_deref(), Some(held.as_str()));
+
+ // A second session while the first's browser is still starting.
+ let mut second = SessionOptions {
+ user_data_dir: Some(held.clone()),
+ ..SessionOptions::default()
+ };
+ assert_eq!(claim_profile(&mut second, wait).await, None);
+ assert!(second.user_data_dir.is_none());
+ super::super::browser_profile::release(&profile);
+
#[cfg(not(windows))]
{
let here = sysinfo::System::host_name().unwrap_or_default();
@@ -211,7 +225,7 @@ async fn a_session_opens_in_a_fresh_profile_while_another_chrome_holds_it() {
profile.join("SingletonLock"),
)
.unwrap();
- fresh_if_held(&mut options, std::time::Duration::from_millis(50)).await;
+ assert_eq!(claim_profile(&mut options, wait).await, None);
assert!(options.user_data_dir.is_none());
}
let _ = std::fs::remove_dir_all(&profile);
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index c6bfec1930..20e6a95082 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -31,7 +31,8 @@
//! - [`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
-//! [`browser_profile`] tells whether a Chrome holds the persistent profile.
+//! [`browser_profile`] tells whether a Chrome holds the persistent profile
+//! and claims it for a browser about to start.
//! - [`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.