Skip to content

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

fix(computer): retry failed report fetches and keep traced reports private

Shanuc9fccdac819c
diff --git a/crates/openhuman-core/src/modules/browser_task_report.rs b/crates/openhuman-core/src/modules/browser_task_report.rs
index 1bc9e3fdda..bc1b9d0818 100644
--- a/crates/openhuman-core/src/modules/browser_task_report.rs
+++ b/crates/openhuman-core/src/modules/browser_task_report.rs
@@ -4,17 +4,22 @@
//! `<workspace>/state/computer/tasks/`.
//!
//! A report holds page text (step notes, records and, when traced, every Jev
-//! exchange), so it is written only to the workspace and never logged: the
-//! log gets counts, the failed step's position and kind, and the module's own
-//! one-line reason.
+//! exchange), so it is written only to the workspace, readable by its owner
+//! alone, and never logged: the log gets counts, the failed step's position
+//! and kind, and the module's own one-line reason.
use std::collections::VecDeque;
-use std::path::PathBuf;
-use std::sync::{Mutex, OnceLock};
+use std::future::Future;
+#[cfg(unix)]
+use std::os::unix::fs::PermissionsExt;
+use std::path::{Path, PathBuf};
+use std::pin::Pin;
+use std::sync::{Mutex, MutexGuard, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
-use tinycomputer_bus::agent::{RescueOutcome, TaskReport, TaskStatus, TaskView};
+use tinycomputer_bus::agent::{RescueOutcome, TaskId, TaskReport, TaskStatus, TaskView};
use tinycomputer_bus::flow::StepOutcome;
+use tokio::io::AsyncWriteExt;
use crate::config::Config;
@@ -28,17 +33,42 @@ const REMEMBERED: usize = 64;
/// The most characters of a failure reason written to the log.
const REASON_CHARS: usize = 240;
+/// A pending `TaskReport` call.
+type ReportFetch<'a> = Pin<Box<dyn Future<Output = Result<TaskReport, String>> + Send + 'a>>;
+
/// Records `view` once per task and state: a log summary when it stopped
/// short, and the full report on disk when tracing is on and it settled.
-/// Never fails the caller; a report that cannot be fetched is only logged.
+/// Never fails the caller; a report that cannot be fetched is only logged,
+/// and the next settle of the same state tries again.
pub(crate) async fn record(config: &Config, view: &TaskView) {
let traced = super::computer_config::tracing_enabled(config);
- if !worth_recording(&view.status, traced) || !first_time(view) {
+ record_with(config, view, traced, |id, trace| {
+ Box::pin(super::browser_task::report_with(config, id, trace))
+ })
+ .await;
+}
+
+/// [`record`] with tracing on or off as `traced` says, and the module's
+/// `TaskReport` call passed in as `fetch`.
+async fn record_with<'a>(
+ config: &'a Config,
+ view: &TaskView,
+ traced: bool,
+ fetch: impl FnOnce(TaskId, bool) -> ReportFetch<'a>,
+) {
+ if !worth_recording(&view.status, traced) {
+ return;
+ }
+ let key = record_key(view);
+ let claimed = recorded().claim(&key);
+ if !claimed {
return;
}
- let report = match super::browser_task::report_with(config, view.id.clone(), traced).await {
+ let report = match fetch(view.id.clone(), traced).await {
Ok(report) => report,
Err(error) => {
+ // Give the claim back, so the next settle of this state tries again.
+ recorded().release(&key);
tracing::warn!(task = %view.id, %error, "[browser-task] report unavailable");
return;
}
@@ -72,33 +102,66 @@ fn stopped_short(status: &TaskStatus) -> bool {
)
}
+/// Whether a stop in `status` is recorded: always when it stopped short, and
+/// any settled stop when `traced`.
fn worth_recording(status: &TaskStatus, traced: bool) -> bool {
stopped_short(status) || (traced && !matches!(status, TaskStatus::Running))
}
-/// Whether this task has not been recorded in this state yet.
-fn first_time(view: &TaskView) -> bool {
- static SEEN: OnceLock<Mutex<VecDeque<String>>> = OnceLock::new();
- let key = format!(
+/// What a task's stop is remembered by: the task, its state and its progress.
+fn record_key(view: &TaskView) -> String {
+ format!(
"{}|{}|{:.3}",
view.id,
status_name(&view.status),
view.progress
- );
- let mut seen = SEEN
- .get_or_init(Mutex::default)
+ )
+}
+
+/// The stops this process has recorded, or is recording.
+fn recorded() -> MutexGuard<'static, Recorded> {
+ static RECORDED: OnceLock<Mutex<Recorded>> = OnceLock::new();
+ RECORDED
+ .get_or_init(|| Mutex::new(Recorded::new(REMEMBERED)))
.lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- if seen.contains(&key) {
- return false;
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// Stops claimed for recording, oldest first, at most `cap` of them.
+#[derive(Debug)]
+struct Recorded {
+ keys: VecDeque<String>,
+ cap: usize,
+}
+
+impl Recorded {
+ /// Remembers at most `cap` stops.
+ fn new(cap: usize) -> Self {
+ Self {
+ keys: VecDeque::new(),
+ cap,
+ }
}
- if seen.len() == REMEMBERED {
- seen.pop_front();
+
+ /// Claims `key`; false when it is already recorded or being recorded.
+ fn claim(&mut self, key: &str) -> bool {
+ if self.keys.iter().any(|seen| seen == key) {
+ return false;
+ }
+ if self.keys.len() == self.cap {
+ self.keys.pop_front();
+ }
+ self.keys.push_back(key.to_owned());
+ true
+ }
+
+ /// Gives a claim back, so the stop can be recorded later.
+ fn release(&mut self, key: &str) {
+ self.keys.retain(|seen| seen != key);
}
- seen.push_back(key);
- true
}
+/// The state's wire name, for the log and the record key.
fn status_name(status: &TaskStatus) -> &'static str {
match status {
TaskStatus::Running => "running",
@@ -138,6 +201,7 @@ struct Summary {
}
impl Summary {
+ /// The counts in `report`, and the failed step when `status` names one.
fn of(status: &TaskStatus, report: &TaskReport) -> Self {
let failed_step = match status {
TaskStatus::Failed { step, .. } => *step,
@@ -204,32 +268,48 @@ fn report_path(config: &Config, id: &str, millis: u128) -> PathBuf {
.join(format!("{millis}-{id}.json"))
}
+/// Writes `report` under the workspace's trace directory, and logs where;
+/// a failure is logged, never raised.
async fn write(config: &Config, report: &TaskReport) {
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_millis());
let path = report_path(config, &report.view.id.0, millis);
- let bytes = match serde_json::to_vec_pretty(report) {
- Ok(bytes) => bytes,
- Err(error) => {
- tracing::warn!(%error, "[browser-task] report not serializable");
- return;
- }
- };
- if let Some(dir) = path.parent() {
- if let Err(error) = tokio::fs::create_dir_all(dir).await {
- tracing::warn!(%error, "[browser-task] report directory unavailable");
- return;
- }
- }
- match tokio::fs::write(&path, &bytes).await {
- Ok(()) => tracing::info!(
+ match write_private(&path, report).await {
+ Ok(bytes) => tracing::info!(
task = %report.view.id,
path = %path.display(),
- bytes = bytes.len(),
+ bytes,
exchanges = report.trace.len(),
"[browser-task] report written"
),
- Err(error) => tracing::warn!(%error, "[browser-task] report not written"),
+ Err(error) => tracing::warn!(
+ task = %report.view.id,
+ %error,
+ "[browser-task] report not written"
+ ),
+ }
+}
+
+/// Writes `report` to `path` as JSON, in a directory and a file only their
+/// owner can read, also when either already existed: a report holds page
+/// text. Returns how many bytes were written.
+async fn write_private(path: &Path, report: &TaskReport) -> std::io::Result<usize> {
+ let bytes = serde_json::to_vec_pretty(report).map_err(std::io::Error::other)?;
+ if let Some(dir) = path.parent() {
+ tokio::fs::create_dir_all(dir).await?;
+ #[cfg(unix)]
+ tokio::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).await?;
}
+ let mut options = tokio::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ options.mode(0o600);
+ let mut file = options.open(path).await?;
+ #[cfg(unix)]
+ file.set_permissions(std::fs::Permissions::from_mode(0o600))
+ .await?;
+ file.write_all(&bytes).await?;
+ file.flush().await?;
+ Ok(bytes.len())
}
diff --git a/crates/openhuman-core/src/modules/browser_task_report_tests.rs b/crates/openhuman-core/src/modules/browser_task_report_tests.rs
index 423c79bd2c..09bcf325dd 100644
--- a/crates/openhuman-core/src/modules/browser_task_report_tests.rs
+++ b/crates/openhuman-core/src/modules/browser_task_report_tests.rs
@@ -1,9 +1,74 @@
//! A stopped task is summarised without page content, recorded once per
-//! state, and its full report is written inside the workspace.
+//! state (and again when its report could not be fetched), and its full
+//! report is written inside the workspace, readable by its owner alone.
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
use super::*;
use serde_json::{json, Value};
+/// Log lines written on this thread while the guard from [`capture_logs`]
+/// lives.
+#[derive(Clone, Default)]
+struct Capture(Arc<std::sync::Mutex<Vec<u8>>>);
+
+impl Capture {
+ /// Everything logged so far.
+ fn text(&self) -> String {
+ String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
+ }
+}
+
+impl std::io::Write for Capture {
+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture {
+ type Writer = Self;
+
+ fn make_writer(&'a self) -> Self::Writer {
+ self.clone()
+ }
+}
+
+/// Captures this thread's log lines, at every level, until the guard drops.
+fn capture_logs() -> (Capture, tracing::subscriber::DefaultGuard) {
+ let capture = Capture::default();
+ let subscriber = tracing_subscriber::fmt()
+ .with_writer(capture.clone())
+ .with_ansi(false)
+ .with_max_level(tracing::Level::TRACE)
+ .finish();
+ (capture, tracing::subscriber::set_default(subscriber))
+}
+
+/// A config whose workspace is inside `dir`.
+fn workspace_config(dir: &tempfile::TempDir) -> Config {
+ let mut config = Config::default();
+ config.workspace_dir = dir.path().join("workspace");
+ config
+}
+
+/// A `fetch` for [`record_with`] that counts its calls and answers `reply`.
+fn fetch_counted<'a>(
+ calls: &'a AtomicUsize,
+ reply: Result<TaskReport, String>,
+) -> impl FnOnce(TaskId, bool) -> ReportFetch<'a> {
+ move |_, _| {
+ calls.fetch_add(1, Ordering::SeqCst);
+ Box::pin(async move { reply })
+ }
+}
+
+/// A view of task `id` in `status`.
fn view(id: &str, status: Value, progress: f32) -> TaskView {
serde_json::from_value(json!({
"id": id,
@@ -15,6 +80,7 @@ fn view(id: &str, status: Value, progress: f32) -> TaskView {
.unwrap()
}
+/// A failed status at step 2, with the module's one-line reason.
fn failed() -> Value {
json!({
"state": "failed",
@@ -25,6 +91,7 @@ fn failed() -> Value {
})
}
+/// A report of three steps, the last one failed, with one rescue.
fn report(view: &TaskView) -> TaskReport {
serde_json::from_value(json!({
"view": view,
@@ -93,15 +160,203 @@ fn only_a_task_that_stopped_short_or_a_traced_settled_one_is_recorded() {
}
#[test]
-fn the_same_stop_is_recorded_once() {
- let first = view("t-dedupe", failed(), 0.33);
- assert!(first_time(&first));
+fn the_same_stop_is_claimed_once_and_can_be_given_back() {
+ let mut recorded = Recorded::new(8);
+ let first = record_key(&view("t-dedupe", failed(), 0.33));
+ assert!(recorded.claim(&first));
assert!(
- !first_time(&first),
+ !recorded.claim(&first),
"followed again, it is not recorded twice"
);
- let later = view("t-dedupe", failed(), 0.66);
- assert!(first_time(&later), "a later stop of the same task is new");
+ let later = record_key(&view("t-dedupe", failed(), 0.66));
+ assert!(
+ recorded.claim(&later),
+ "a later stop of the same task is new"
+ );
+ recorded.release(&first);
+ assert!(
+ recorded.claim(&first),
+ "a released stop can be claimed again"
+ );
+}
+
+#[test]
+fn the_oldest_remembered_stop_is_forgotten_first() {
+ let mut recorded = Recorded::new(2);
+ assert!(recorded.claim("a"));
+ assert!(recorded.claim("b"));
+ assert!(recorded.claim("c"));
+ assert!(recorded.claim("a"), "the oldest was forgotten to make room");
+ assert!(!recorded.claim("c"));
+}
+
+#[test]
+fn every_state_has_its_own_name() {
+ let names = [
+ (json!({"state": "running"}), "running"),
+ (json!({"state": "needs_input", "fields": []}), "needs_input"),
+ (
+ json!({"state": "needs_approval", "action": "send it", "target": "Send"}),
+ "needs_approval",
+ ),
+ (
+ json!({"state": "checkpoint", "reason": "payment", "location": "pay page",
+ "summary": "", "continuable": false}),
+ "checkpoint",
+ ),
+ (
+ json!({"state": "needs_human", "reason": "log in"}),
+ "needs_human",
+ ),
+ (json!({"state": "needs_plan", "guide": "…"}), "needs_plan"),
+ (
+ json!({"state": "done", "answer": "found", "records": {}}),
+ "done",
+ ),
+ (failed(), "failed"),
+ (json!({"state": "cancelled"}), "cancelled"),
+ ];
+ for (status, name) in names {
+ let status: TaskStatus = serde_json::from_value(status).unwrap();
+ assert_eq!(status_name(&status), name);
+ }
+}
+
+#[test]
+fn a_task_that_needs_a_person_names_no_failed_step() {
+ let view = view(
+ "t-human-summary",
+ json!({"state": "needs_human", "reason": "log in"}),
+ 0.5,
+ );
+ let summary = Summary::of(&view.status, &report(&view));
+ assert_eq!(summary.failed_step, None);
+ assert_eq!(summary.failed_kind, Some("do"));
+}
+
+#[tokio::test]
+async fn a_stopped_task_is_logged_once_with_counts_and_no_step_text() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = workspace_config(&dir);
+ let view = view("t-rec-once", failed(), 0.33);
+ let (logs, _guard) = capture_logs();
+ let calls = AtomicUsize::new(0);
+
+ record_with(
+ &config,
+ &view,
+ false,
+ fetch_counted(&calls, Ok(report(&view))),
+ )
+ .await;
+ record_with(
+ &config,
+ &view,
+ false,
+ fetch_counted(&calls, Ok(report(&view))),
+ )
+ .await;
+
+ assert_eq!(calls.load(Ordering::SeqCst), 1, "fetched once per stop");
+ let text = logs.text();
+ assert_eq!(text.matches("task stopped short").count(), 1, "{text}");
+ assert!(text.contains("jev_calls=35"), "{text}");
+ assert!(text.contains("changed nothing on screen"), "{text}");
+ for page_text in ["type Asha", "search for trains", "open the site"] {
+ assert!(!text.contains(page_text), "step text leaked: {text}");
+ }
+ assert!(
+ !super::super::computer_config::trace_dir(&config).exists(),
+ "an untraced stop writes no report"
+ );
+}
+
+#[tokio::test]
+async fn a_report_that_could_not_be_fetched_is_fetched_on_the_next_settle() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = workspace_config(&dir);
+ let view = view("t-rec-retry", failed(), 0.33);
+ let (logs, _guard) = capture_logs();
+ let calls = AtomicUsize::new(0);
+
+ record_with(
+ &config,
+ &view,
+ false,
+ fetch_counted(&calls, Err("module unavailable".to_owned())),
+ )
+ .await;
+ assert!(
+ logs.text().contains("report unavailable"),
+ "{}",
+ logs.text()
+ );
+ assert!(!logs.text().contains("task stopped short"));
+
+ record_with(
+ &config,
+ &view,
+ false,
+ fetch_counted(&calls, Ok(report(&view))),
+ )
+ .await;
+ assert_eq!(
+ calls.load(Ordering::SeqCst),
+ 2,
+ "the failed fetch was retried"
+ );
+ assert!(
+ logs.text().contains("task stopped short"),
+ "{}",
+ logs.text()
+ );
+}
+
+#[tokio::test]
+async fn a_traced_task_that_settled_writes_its_traced_report() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = workspace_config(&dir);
+ let view = view(
+ "t-rec-traced",
+ json!({"state": "done", "answer": "found", "records": {}}),
+ 1.0,
+ );
+ let asked_for_trace = Arc::new(std::sync::Mutex::new(None));
+ let asked = Arc::clone(&asked_for_trace);
+ let reply = report(&view);
+
+ record_with(&config, &view, true, move |id, trace| {
+ *asked.lock().unwrap() = Some((id, trace));
+ Box::pin(async move { Ok(reply) })
+ })
+ .await;
+
+ assert_eq!(
+ *asked_for_trace.lock().unwrap(),
+ Some((TaskId("t-rec-traced".to_owned()), true))
+ );
+ let tasks = super::super::computer_config::trace_dir(&config).join("tasks");
+ assert_eq!(std::fs::read_dir(&tasks).unwrap().count(), 1);
+}
+
+#[tokio::test]
+async fn an_untraced_task_that_finished_is_not_fetched() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = workspace_config(&dir);
+ let view = view(
+ "t-rec-done",
+ json!({"state": "done", "answer": "found", "records": {}}),
+ 1.0,
+ );
+ let calls = AtomicUsize::new(0);
+ record_with(
+ &config,
+ &view,
+ false,
+ fetch_counted(&calls, Ok(report(&view))),
+ )
+ .await;
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
}
#[test]
@@ -165,3 +420,53 @@ async fn a_traced_report_is_written_whole_into_the_workspace() {
let back: TaskReport = serde_json::from_slice(&std::fs::read(&written[0]).unwrap()).unwrap();
assert_eq!(back, report);
}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn a_report_and_its_directory_are_readable_by_their_owner_alone() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let config = workspace_config(&dir);
+ let tasks = super::super::computer_config::trace_dir(&config).join("tasks");
+ // A directory left open by an earlier run is narrowed too.
+ std::fs::create_dir_all(&tasks).unwrap();
+ std::fs::set_permissions(&tasks, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let view = view("t-private", failed(), 0.33);
+ write(&config, &report(&view)).await;
+
+ let mode =
+ |path: &std::path::Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode(&tasks), 0o700);
+ let file = std::fs::read_dir(&tasks)
+ .unwrap()
+ .next()
+ .unwrap()
+ .unwrap()
+ .path();
+ assert_eq!(mode(&file), 0o600);
+
+ // Overwriting a file that was readable by others narrows it as well.
+ std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
+ write_private(&file, &report(&view)).await.unwrap();
+ assert_eq!(mode(&file), 0o600);
+}
+
+#[tokio::test]
+async fn a_report_that_cannot_be_written_is_only_logged() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = workspace_config(&dir);
+ // `state` is a file, so the report's directory cannot be made.
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ std::fs::write(config.workspace_dir.join("state"), b"not a directory").unwrap();
+ let (logs, _guard) = capture_logs();
+
+ let view = view("t-unwritable", failed(), 0.33);
+ write(&config, &report(&view)).await;
+
+ assert!(
+ logs.text().contains("report not written"),
+ "{}",
+ logs.text()
+ );
+}
diff --git a/crates/openhuman-core/src/modules/browser_task_tests.rs b/crates/openhuman-core/src/modules/browser_task_tests.rs
index f18842f3d1..c662c34136 100644
--- a/crates/openhuman-core/src/modules/browser_task_tests.rs
+++ b/crates/openhuman-core/src/modules/browser_task_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use serde_json::json;
use tinycomputer_bus::agent::AgentError;
fn task() -> BrowserTask {
@@ -88,3 +89,21 @@ fn a_saved_flow_is_run_instead_of_planned() {
assert_eq!(request.flow, Some(flow));
assert_eq!(request.task.as_deref(), Some("Find the opening hours"));
}
+
+#[tokio::test]
+async fn a_task_that_already_stopped_settles_without_calling_the_module() {
+ // Not running, so no `AwaitTask`; finished and untraced, so no report is
+ // fetched either.
+ let mut config = Config::default();
+ config.computer.trace = false;
+ let view: TaskView = serde_json::from_value(json!({
+ "id": "t-settled",
+ "status": {"state": "done", "answer": "found", "records": {}},
+ "summary": "found it",
+ "progress": 1.0,
+ "next": []
+ }))
+ .unwrap();
+ let settled = settle(&config, view.clone()).await.unwrap();
+ assert_eq!(settled, view);
+}
diff --git a/crates/openhuman-core/src/modules/computer_config.rs b/crates/openhuman-core/src/modules/computer_config.rs
index 5064a569c2..3b6eb40095 100644
--- a/crates/openhuman-core/src/modules/computer_config.rs
+++ b/crates/openhuman-core/src/modules/computer_config.rs
@@ -11,7 +11,9 @@
//! - `browser` — the Chrome executable the user picked, if any.
//! - `trace_path` — where desktop commands are traced, when tracing is on.
-use std::path::PathBuf;
+#[cfg(unix)]
+use std::os::unix::fs::PermissionsExt;
+use std::path::{Path, PathBuf};
use serde_json::{json, Map, Value};
@@ -68,6 +70,9 @@ fn jev(config: &Config, hosted: Option<&str>) -> Option<Value> {
/// module's defaults.
pub const HOSTED_REASONING_MODEL: &str = "agentic-v1";
+/// The `planner` configuration: the hosted route with the session's bearer
+/// when signed in, else the user's OpenRouter key; the user's chosen models,
+/// with [`HOSTED_REASONING_MODEL`] for any unchosen role on the hosted route.
fn planner(config: &Config, hosted: Option<&str>) -> Option<Value> {
let mut planner = match hosted {
Some(api_key) => json!({
@@ -105,6 +110,7 @@ pub fn tracing_enabled(config: &Config) -> bool {
tracing_enabled_with(config, std::env::var(TRACE_ENV).ok().as_deref())
}
+/// [`tracing_enabled`] with the environment switch's value passed in.
fn tracing_enabled_with(config: &Config, env: Option<&str>) -> bool {
config.computer.trace
|| matches!(
@@ -119,6 +125,15 @@ pub fn trace_dir(config: &Config) -> PathBuf {
config.workspace_dir.join("state").join("computer")
}
+/// Creates `dir` for traces, readable by its owner alone, also when it
+/// already existed: a trace holds what the screen showed.
+fn create_trace_dir(dir: &Path) -> std::io::Result<()> {
+ std::fs::create_dir_all(dir)?;
+ #[cfg(unix)]
+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
+ Ok(())
+}
+
/// Build the module configuration for `config`.
#[must_use]
pub fn module_config(config: &Config) -> Value {
@@ -136,7 +151,7 @@ pub fn module_config(config: &Config) -> Value {
let traced = tracing_enabled(config);
if traced {
let dir = trace_dir(config);
- if let Err(error) = std::fs::create_dir_all(&dir) {
+ if let Err(error) = create_trace_dir(&dir) {
tracing::warn!(%error, "[computer] trace directory unavailable");
}
out.insert(
diff --git a/crates/openhuman-core/src/modules/computer_config_tests.rs b/crates/openhuman-core/src/modules/computer_config_tests.rs
index 78db732eb1..70a8e8223a 100644
--- a/crates/openhuman-core/src/modules/computer_config_tests.rs
+++ b/crates/openhuman-core/src/modules/computer_config_tests.rs
@@ -134,3 +134,35 @@ fn chrome_path_is_the_module_browser_executable() {
json!({"executable": "/Applications/Chrome.app"})
);
}
+
+#[test]
+fn a_trace_directory_that_cannot_be_made_still_leaves_the_module_configured() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.computer.trace = true;
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ // `state` is a file, so the trace directory cannot be made.
+ std::fs::write(config.workspace_dir.join("state"), b"not a directory").unwrap();
+ let value = module_config(&config);
+ assert!(value["trace_path"].is_string());
+ assert!(!trace_dir(&config).is_dir());
+}
+
+#[cfg(unix)]
+#[test]
+fn the_trace_directory_is_readable_by_its_owner_alone() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.computer.trace = true;
+ // A directory left open by an earlier run is narrowed too.
+ std::fs::create_dir_all(trace_dir(&config)).unwrap();
+ std::fs::set_permissions(trace_dir(&config), std::fs::Permissions::from_mode(0o755)).unwrap();
+ let _ = module_config(&config);
+ let mode = std::fs::metadata(trace_dir(&config))
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777;
+ assert_eq!(mode, 0o700);
+}