Skip to content

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

test(cron): add unit tests for origin, channel bridge, and job builder

Steven Enamakelec7b6033519a
diff --git a/crates/openhuman-core/src/cron/channel_bridge_tests.rs b/crates/openhuman-core/src/cron/channel_bridge_tests.rs
new file mode 100644
index 0000000000..8a91e7af62
--- /dev/null
+++ b/crates/openhuman-core/src/cron/channel_bridge_tests.rs
@@ -0,0 +1,67 @@
+use super::*;
+use async_trait::async_trait;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use tinychannels_bus::ChannelMessage;
+use tokio::sync::mpsc;
+
+struct MockChannel {
+ sends: Arc<AtomicUsize>,
+ last_target: Arc<Mutex<String>>,
+}
+
+#[async_trait]
+impl Channel for MockChannel {
+ fn name(&self) -> &str {
+ "telegram"
+ }
+ async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
+ self.sends.fetch_add(1, Ordering::SeqCst);
+ *self.last_target.lock().unwrap() = message.recipient.clone();
+ Ok(())
+ }
+ async fn listen(&self, _tx: mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+// One test: the bridge is process-global, so keep its steps sequential.
+#[tokio::test]
+async fn bridge_reads_appends_trims_and_sends() {
+ let histories: ChannelHistories = Arc::new(Mutex::new(HashMap::new()));
+ histories.lock().unwrap().insert(
+ "k".into(),
+ vec![
+ TranscriptMessage::user("remind me"),
+ TranscriptMessage::assistant("ok"),
+ ],
+ );
+ let sends = Arc::new(AtomicUsize::new(0));
+ let last_target = Arc::new(Mutex::new(String::new()));
+ let ch: Arc<dyn Channel> = Arc::new(MockChannel {
+ sends: Arc::clone(&sends),
+ last_target: Arc::clone(&last_target),
+ });
+ let channels = Arc::new(HashMap::from([("telegram".to_string(), ch)]));
+ register_channel_bridge(Arc::clone(&histories), channels, 3);
+
+ assert_eq!(
+ history_messages("k"),
+ vec![
+ ("user".to_string(), "remind me".to_string()),
+ ("assistant".to_string(), "ok".to_string())
+ ]
+ );
+ assert!(history_messages("missing").is_empty());
+
+ assert!(append_assistant_message("k", "drink water"));
+ assert!(append_assistant_message("k", "again"));
+ let got = history_messages("k");
+ assert_eq!(got.len(), 3, "trimmed to the registered maximum");
+ assert_eq!(got.last().unwrap().1, "again");
+ assert_eq!(got[0].1, "ok");
+
+ send_to_channel("Telegram", "42", None, "hi").await.unwrap();
+ assert_eq!(sends.load(Ordering::SeqCst), 1);
+ assert_eq!(*last_target.lock().unwrap(), "42");
+ assert!(send_to_channel("slack", "42", None, "hi").await.is_err());
+}
diff --git a/crates/openhuman-core/src/cron/job_builder_tests.rs b/crates/openhuman-core/src/cron/job_builder_tests.rs
new file mode 100644
index 0000000000..bd7728d2d8
--- /dev/null
+++ b/crates/openhuman-core/src/cron/job_builder_tests.rs
@@ -0,0 +1,127 @@
+use super::*;
+use crate::cron::list_jobs;
+use tempfile::TempDir;
+
+fn config(tmp: &TempDir) -> Config {
+ let config = Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ config
+}
+
+fn input() -> AgentJobInput {
+ AgentJobInput {
+ name: Some("water".into()),
+ schedule: Schedule::Every { every_ms: 300_000 },
+ prompt: "drink water".into(),
+ session_target: None,
+ model: None,
+ delivery: None,
+ delete_after_run: false,
+ }
+}
+
+fn web() -> JobOrigin {
+ JobOrigin::Web {
+ thread_id: "t-1".into(),
+ agent_id: None,
+ }
+}
+
+fn channel() -> JobOrigin {
+ JobOrigin::Channel {
+ channel: "telegram".into(),
+ reply_target: "42".into(),
+ history_key: "telegram_alice_42".into(),
+ sender: Some("alice".into()),
+ thread_id: None,
+ }
+}
+
+#[test]
+fn origin_defaults_to_current_target_and_origin_delivery() {
+ let tmp = TempDir::new().unwrap();
+ let cfg = config(&tmp);
+ let job = create_agent_job(&cfg, input(), Some(web())).unwrap();
+ assert_eq!(job.session_target, SessionTarget::Current);
+ assert_eq!(job.delivery.mode, "origin");
+ assert_eq!(job.origin, Some(web()));
+ // And it round-trips through the store.
+ assert_eq!(list_jobs(&cfg).unwrap()[0].origin, Some(web()));
+}
+
+#[test]
+fn no_origin_keeps_isolated_and_proactive() {
+ let tmp = TempDir::new().unwrap();
+ let job = create_agent_job(&config(&tmp), input(), None).unwrap();
+ assert_eq!(job.session_target, SessionTarget::Isolated);
+ assert_eq!(job.delivery.mode, "proactive");
+ assert_eq!(job.origin, None);
+}
+
+#[test]
+fn explicit_delivery_and_target_win_and_drop_the_unused_origin() {
+ let tmp = TempDir::new().unwrap();
+ let mut i = input();
+ i.session_target = Some(SessionTarget::Isolated);
+ i.delivery = Some(DeliveryConfig {
+ mode: "none".into(),
+ channel: None,
+ to: None,
+ best_effort: true,
+ });
+ let job = create_agent_job(&config(&tmp), i, Some(web())).unwrap();
+ assert_eq!(job.session_target, SessionTarget::Isolated);
+ assert_eq!(job.delivery.mode, "none");
+ assert_eq!(job.origin, None, "nothing uses the origin, so it is not kept");
+}
+
+#[test]
+fn origin_delivery_or_current_target_without_an_origin_is_an_error() {
+ let tmp = TempDir::new().unwrap();
+ let cfg = config(&tmp);
+ let mut i = input();
+ i.delivery = Some(default_delivery(Some(&web())));
+ assert!(create_agent_job(&cfg, i, None)
+ .unwrap_err()
+ .contains("origin"));
+ let mut i = input();
+ i.session_target = Some(SessionTarget::Current);
+ assert!(create_agent_job(&cfg, i, None)
+ .unwrap_err()
+ .contains("current"));
+}
+
+fn announce(channel_name: &str, to: &str) -> DeliveryConfig {
+ DeliveryConfig {
+ mode: "announce".into(),
+ channel: Some(channel_name.into()),
+ to: Some(to.into()),
+ best_effort: true,
+ }
+}
+
+#[test]
+fn announce_to_origin_reply_target_skips_allowed_users() {
+ let tmp = TempDir::new().unwrap();
+ let mut cfg = config(&tmp);
+ cfg.channels_config.telegram = Some(crate::config::TelegramConfig {
+ bot_token: "t".into(),
+ chat_id: None,
+ allowed_users: vec!["alice".into()],
+ stream_mode: Default::default(),
+ draft_update_interval_ms: 1000,
+ silent_streaming: true,
+ mention_only: false,
+ });
+ // Chat id 42 is not in allowed_users (a username), but it is the asker.
+ assert!(validate_delivery(&cfg, &announce("telegram", "42"), Some(&channel())).is_ok());
+ // Without the origin, or for another target, the allowlist still applies.
+ assert!(validate_delivery(&cfg, &announce("telegram", "42"), None).is_err());
+ assert!(validate_delivery(&cfg, &announce("telegram", "99"), Some(&channel())).is_err());
+ assert!(validate_delivery(&cfg, &announce("discord", "42"), Some(&channel())).is_err());
+}
diff --git a/crates/openhuman-core/src/cron/origin_tests.rs b/crates/openhuman-core/src/cron/origin_tests.rs
index 53d24db7d0..965ea40473 100644
--- a/crates/openhuman-core/src/cron/origin_tests.rs
+++ b/crates/openhuman-core/src/cron/origin_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::cron::Schedule;
use crate::agent::turn_origin::{with_origin, TrustedAutomationSource};
use serde_json::json;
@@ -75,9 +76,27 @@ async fn current_job_origin_reads_the_scoped_turn() {
}
fn job_with_origin(origin: Option<JobOrigin>) -> CronJob {
- let mut job = crate::cron::job_builder_test_job();
- job.origin = origin;
- job
+ CronJob {
+ id: "job-1".into(),
+ expression: "* * * * *".into(),
+ schedule: Schedule::Every { every_ms: 300_000 },
+ command: String::new(),
+ prompt: Some("p".into()),
+ name: None,
+ job_type: crate::cron::JobType::Agent,
+ session_target: crate::cron::SessionTarget::Current,
+ model: None,
+ agent_id: None,
+ enabled: true,
+ delivery: crate::cron::DeliveryConfig::default(),
+ delete_after_run: false,
+ created_at: chrono::Utc::now(),
+ next_run: chrono::Utc::now(),
+ last_run: None,
+ last_status: None,
+ last_output: None,
+ origin,
+ }
}
#[test]
diff --git a/crates/openhuman-core/src/cron/scheduler/origin_context_tests.rs b/crates/openhuman-core/src/cron/scheduler/origin_context_tests.rs
new file mode 100644
index 0000000000..53d62f3f84
--- /dev/null
+++ b/crates/openhuman-core/src/cron/scheduler/origin_context_tests.rs
@@ -0,0 +1,47 @@
+use super::*;
+
+fn m(role: &str, text: &str) -> (String, String) {
+ (role.to_string(), text.to_string())
+}
+
+#[test]
+fn tail_keeps_the_newest_messages_in_order() {
+ let msgs: Vec<_> = (0..15)
+ .map(|i| m(if i % 2 == 0 { "user" } else { "assistant" }, &format!("msg{i}")))
+ .collect();
+ let tail = bounded_tail(&msgs, 10, 1400);
+ let lines: Vec<_> = tail.lines().collect();
+ assert_eq!(lines.len(), 10);
+ assert_eq!(lines[0], "assistant: msg5");
+ assert_eq!(lines[9], "user: msg14");
+}
+
+#[test]
+fn tail_is_bounded_by_characters_and_keeps_the_newest() {
+ let long = "x".repeat(1000);
+ let msgs = vec![m("user", "old one"), m("user", &long), m("assistant", &long)];
+ let tail = bounded_tail(&msgs, 10, 1400);
+ assert!(tail.chars().count() <= 1400 + 1, "len {}", tail.chars().count());
+ assert!(tail.ends_with(&"x".repeat(100)));
+ assert!(tail.lines().last().unwrap().starts_with("assistant: "));
+ assert!(!tail.contains("old one"));
+}
+
+#[test]
+fn tail_skips_empty_and_non_chat_roles() {
+ let msgs = vec![m("system", "secret"), m("user", " "), m("user", "hi")];
+ assert_eq!(bounded_tail(&msgs, 10, 1400), "user: hi");
+ assert_eq!(bounded_tail(&[], 10, 1400), "");
+}
+
+#[test]
+fn current_prompt_has_preamble_context_and_task() {
+ let p = compose_current_prompt("j1", "water", "drink water", "user: hi");
+ assert!(p.starts_with("[cron:j1 water] "));
+ assert!(p.contains(UNATTENDED_PREAMBLE));
+ assert!(p.contains("NO_REPLY"));
+ assert!(p.contains("user: hi"));
+ assert!(p.ends_with("Scheduled task: drink water"));
+ let bare = compose_current_prompt("j1", "water", "drink water", "");
+ assert!(!bare.contains("Recent conversation"));
+}