Skip to content

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

test(relay): add unit tests for ops, schemas, and store

Steven Enamakel9b7ff404ffdc
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs b/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs
new file mode 100644
index 0000000000..692be110a6
--- /dev/null
+++ b/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs
@@ -0,0 +1,152 @@
+use super::*;
+use crate::agent::bus::{mock_agent_run_turn, AgentTurnRequest, AgentTurnResponse};
+use crate::agent::turn_origin::AgentTurnOrigin;
+use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
+use std::sync::Mutex;
+
+fn config(tmp: &tempfile::TempDir) -> Config {
+ let workspace = tmp.path().join("workspace");
+ std::fs::create_dir_all(&workspace).unwrap();
+ let mut config = Config {
+ workspace_dir: workspace.clone(),
+ action_dir: workspace,
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+ config.local_ai.runtime_enabled = false;
+ config.runtime_python.enabled = false;
+ config.memory.conversations.enabled = false;
+ config.agent.session_dual_write = false;
+ config.agent.session_shadow_reads = false;
+ config
+}
+
+fn params(message_id: &str, text: &str) -> RelayInboundParams {
+ serde_json::from_value(json!({
+ "channel": "telegram",
+ "chat_id": "-100",
+ "sender_id": "42",
+ "sender_name": "Ada",
+ "message_id": message_id,
+ "text": text,
+ "client_id": "gw-ops-test",
+ }))
+ .expect("params")
+}
+
+/// What the stubbed `agent.run_turn` saw.
+#[derive(Default)]
+struct Seen {
+ histories: Vec<Vec<(String, String)>>,
+ origins: Vec<AgentTurnOrigin>,
+}
+
+#[tokio::test]
+async fn a_relayed_turn_runs_as_an_external_channel_and_keeps_its_thread() {
+ let seen = Arc::new(Mutex::new(Seen::default()));
+ let stub_seen = Arc::clone(&seen);
+ let _bus = mock_agent_run_turn(move |req: AgentTurnRequest| {
+ let mut seen = stub_seen.lock().unwrap();
+ seen.histories.push(
+ req.history
+ .iter()
+ .map(|m| (m.role.clone(), m.content.clone()))
+ .collect(),
+ );
+ seen.origins.push(req.origin.clone());
+ let n = seen.histories.len();
+ async move { Ok(AgentTurnResponse::new(format!("answer {n}"))) }
+ })
+ .await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config(&tmp);
+ let workspace = config.workspace_dir.clone();
+ let mut events = crate::web_chat::subscribe_web_channel_events();
+
+ for (id, text) in [("m1", "first question"), ("m2", "second question")] {
+ let p = params(id, text);
+ let thread = p.thread_id();
+ assert_eq!(
+ store::record_inbound(&workspace, &p, &thread).await,
+ Ok(Recorded::New)
+ );
+ let replies = run_relay_turn(config.clone(), p, thread, format!("req-{id}")).await;
+ assert_eq!(replies.len(), 1, "{replies:?}");
+ }
+
+ let seen = seen.lock().unwrap();
+ assert_eq!(seen.histories.len(), 2, "one agent turn per message");
+ for origin in &seen.origins {
+ match origin {
+ AgentTurnOrigin::ExternalChannel {
+ channel, sender, ..
+ } => {
+ assert_eq!(channel, "telegram");
+ assert_eq!(sender.as_deref(), Some("42"));
+ }
+ other => panic!("relayed turns run as an external channel, got {other:?}"),
+ }
+ }
+ // The second turn is seeded from the thread: the first exchange, then
+ // the new message.
+ let second = &seen.histories[1];
+ let contents: Vec<&str> = second.iter().map(|(_, c)| c.as_str()).collect();
+ assert!(
+ contents.iter().any(|c| c.contains("first question")),
+ "{contents:?}"
+ );
+ assert!(contents.contains(&"answer 1"), "{contents:?}");
+ assert!(
+ contents.last().is_some_and(|c| c.contains("second question")),
+ "{contents:?}"
+ );
+
+ let thread = params("m1", "x").thread_id();
+ let messages = crate::threads::store::get_messages(workspace.clone(), &thread).unwrap();
+ let ids: Vec<&str> = messages.iter().map(|m| m.id.as_str()).collect();
+ assert_eq!(
+ ids,
+ vec!["user:m1", "assistant:m1", "user:m2", "assistant:m2"]
+ );
+ assert_eq!(messages[1].content, "answer 1");
+
+ let mut outbound = Vec::new();
+ while let Ok(event) = events.try_recv() {
+ if event.client_id == "gw-ops-test" {
+ outbound.push(event);
+ }
+ }
+ assert_eq!(outbound.len(), 2, "one channel_outbound per reply");
+ assert!(outbound.iter().all(|e| e.event == CHANNEL_OUTBOUND_EVENT));
+ assert!(outbound.iter().all(|e| e.thread_id == thread));
+ assert_eq!(outbound[0].request_id, "req-m1");
+ assert_eq!(outbound[0].full_response.as_deref(), Some("answer 1"));
+ assert_eq!(outbound[0].structured.as_ref().unwrap()["chat_id"], "-100");
+}
+
+#[tokio::test]
+async fn invalid_or_repeated_messages_start_no_turn() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config(&tmp);
+ let workspace = config.workspace_dir.clone();
+ let ctx = CoreContext::for_test(DomainSet::full(), Some(workspace.clone())).derive_with(
+ ContextOverlay::new(config, DomainSet::full(), Default::default()),
+ );
+
+ CoreContext::scope(ctx, async {
+ let mut bad = params("m1", "hello");
+ bad.chat_id = "a/b".into();
+ let err = channel_relay_inbound(bad).await.expect_err("invalid");
+ assert!(err.contains("chat_id"), "{err}");
+
+ let p = params("m1", "hello");
+ let thread = p.thread_id();
+ store::record_inbound(&workspace, &p, &thread).await.unwrap();
+ let outcome = channel_relay_inbound(p).await.expect("duplicate is not an error");
+ let value = outcome.into_cli_compatible_json().unwrap();
+ let text = value.to_string();
+ assert!(text.contains("\"duplicate\":true"), "{text}");
+ assert!(text.contains(&thread), "{text}");
+ })
+ .await;
+}
diff --git a/crates/openhuman-core/src/channels/providers/relay/schemas_tests.rs b/crates/openhuman-core/src/channels/providers/relay/schemas_tests.rs
new file mode 100644
index 0000000000..52436db182
--- /dev/null
+++ b/crates/openhuman-core/src/channels/providers/relay/schemas_tests.rs
@@ -0,0 +1,38 @@
+use super::*;
+
+#[test]
+fn the_controller_is_channel_relay_inbound() {
+ let controllers = all_relay_registered_controllers();
+ assert_eq!(controllers.len(), 1);
+ assert_eq!(
+ controllers[0].rpc_method_name(),
+ "openhuman.channel_relay_inbound"
+ );
+ let schema = &all_relay_controller_schemas()[0];
+ let required: Vec<&str> = schema
+ .inputs
+ .iter()
+ .filter(|f| f.required)
+ .map(|f| f.name)
+ .collect();
+ assert_eq!(
+ required,
+ vec!["channel", "chat_id", "sender_id", "message_id", "text"]
+ );
+ assert_eq!(schemas("nope").function, "unknown");
+}
+
+#[test]
+fn the_controller_is_registered() {
+ assert!(crate::core::all::all_registered_controllers()
+ .iter()
+ .any(|c| c.rpc_method_name() == "openhuman.channel_relay_inbound"));
+}
+
+#[tokio::test]
+async fn malformed_params_are_refused_before_any_work() {
+ let mut params = Map::new();
+ params.insert("channel".into(), Value::String("telegram".into()));
+ let err = handle_relay_inbound(params).await.expect_err("missing fields");
+ assert!(err.contains("invalid params"), "{err}");
+}
diff --git a/crates/openhuman-core/src/channels/providers/relay/store_tests.rs b/crates/openhuman-core/src/channels/providers/relay/store_tests.rs
new file mode 100644
index 0000000000..391f573113
--- /dev/null
+++ b/crates/openhuman-core/src/channels/providers/relay/store_tests.rs
@@ -0,0 +1,69 @@
+use super::*;
+use serde_json::json;
+
+fn params(message_id: &str, text: &str) -> RelayInboundParams {
+ serde_json::from_value(json!({
+ "channel": "telegram",
+ "chat_id": "-100",
+ "sender_id": "42",
+ "message_id": message_id,
+ "text": text,
+ }))
+ .expect("params")
+}
+
+#[tokio::test]
+async fn an_inbound_message_is_recorded_once() {
+ let tmp = tempfile::tempdir().unwrap();
+ let p = params("m1", "hello");
+ let thread = p.thread_id();
+ assert_eq!(record_inbound(tmp.path(), &p, &thread).await, Ok(Recorded::New));
+ assert_eq!(
+ record_inbound(tmp.path(), &p, &thread).await,
+ Ok(Recorded::Duplicate),
+ "a gateway retry is not recorded twice"
+ );
+
+ let threads = crate::threads::store::list_threads(tmp.path().to_path_buf()).unwrap();
+ assert_eq!(threads.len(), 1);
+ assert_eq!(threads[0].id, thread);
+ assert_eq!(threads[0].title, "telegram · 42 · -100");
+ let messages = crate::threads::store::get_messages(tmp.path().to_path_buf(), &thread).unwrap();
+ assert_eq!(messages.len(), 1);
+ assert_eq!(messages[0].id, "user:m1");
+ assert_eq!(messages[0].sender, "user");
+ assert_eq!(messages[0].extra_metadata["channel"], "telegram");
+}
+
+#[tokio::test]
+async fn replies_are_recorded_and_seed_the_next_turn() {
+ let tmp = tempfile::tempdir().unwrap();
+ let first = params("m1", "hello");
+ let thread = first.thread_id();
+ record_inbound(tmp.path(), &first, &thread).await.unwrap();
+ record_reply(tmp.path(), &first, &thread, &[])
+ .await
+ .expect("nothing sent, nothing recorded");
+ record_reply(tmp.path(), &first, &thread, &["hi".into(), "there".into()])
+ .await
+ .unwrap();
+ let second = params("m2", "again");
+ record_inbound(tmp.path(), &second, &thread).await.unwrap();
+
+ let prior = prior_turns(tmp.path(), &thread, "m2", 10).await.unwrap();
+ let rows: Vec<(String, String)> = prior
+ .iter()
+ .map(|m| (m.role.clone(), m.content.clone()))
+ .collect();
+ assert_eq!(
+ rows,
+ vec![
+ ("user".to_string(), "hello".to_string()),
+ ("assistant".to_string(), "hi\n\nthere".to_string()),
+ ],
+ "earlier turns only, not the message being answered"
+ );
+ let limited = prior_turns(tmp.path(), &thread, "m2", 1).await.unwrap();
+ assert_eq!(limited.len(), 1);
+ assert_eq!(limited[0].content, "hi\n\nthere", "the most recent rows");
+}