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
test(tinymemes): cover index round-trips and callback registration
Steven Enamakel08bd669171ed
diff --git a/Cargo.lock b/Cargo.lockindex 4ca804f3a9..5423b724f8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4619,7 +4619,7 @@ dependencies = ["tinysearch-bus","tinyskills","tinystoragedrivers",- "tinystoragedrivers-bus 0.7.0",+ "tinystoragedrivers-bus","tinystoragedrivers-client","tinytools","tinytools-agent",@@ -8085,8 +8085,6 @@ version = "0.2.0"dependencies = ["serde","serde_json",- "tinybus",- "tinystoragedrivers-bus 0.5.0",][[package]]@@ -8189,16 +8187,6 @@ dependencies = ["tinystoragedrivers-sqlite",]-[[package]]-name = "tinystoragedrivers-bus"-version = "0.5.0"-source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=7c5596f37e5d5440fbfa3a049a3ca98571885584#7c5596f37e5d5440fbfa3a049a3ca98571885584"-dependencies = [- "serde",- "serde_json",- "tinybus",-]-[[package]]name = "tinystoragedrivers-bus"version = "0.7.0"@@ -8215,7 +8203,7 @@ dependencies = ["async-trait","serde","serde_json",- "tinystoragedrivers-bus 0.7.0",+ "tinystoragedrivers-bus","tinystoragedrivers-core","tinystoragedrivers-secrets","tokio",diff --git a/crates/openhuman-core/src/tinymemes/callbacks_tests.rs b/crates/openhuman-core/src/tinymemes/callbacks_tests.rsindex a26e91816f..5323651141 100644--- a/crates/openhuman-core/src/tinymemes/callbacks_tests.rs+++ b/crates/openhuman-core/src/tinymemes/callbacks_tests.rs@@ -14,7 +14,7 @@ fn decode<T: DeserializeOwned>(value: Value) -> HostResult<T> {}#[tokio::test]-async fn an_index_saved_through_the_host_loads_back() {+async fn an_index_saved_through_the_host_loads_back_per_kind() {let dir = tempfile::tempdir().unwrap();let session = Session::new(&config_in(dir.path()));@@ -27,39 +27,30 @@ async fn an_index_saved_through_the_host_loads_back() {.unwrap();assert_eq!(decode::<Option<String>>(missing), Ok(None));- let saved = dispatch(- &session,- host_methods::SAVE_INDEX,- json!([{ "kind": "slang", "json": "{\"terms\":1}" }]),- )- .await- .unwrap();- assert_eq!(decode::<()>(saved), Ok(()));-- let loaded = dispatch(- &session,- host_methods::LOAD_INDEX,- json!([{ "kind": "slang" }]),- )- .await- .unwrap();- assert_eq!(- decode::<Option<String>>(loaded),- Ok(Some("{\"terms\":1}".into()))- );- // The other index is a different document.- let memes = dispatch(- &session,- host_methods::LOAD_INDEX,- json!([{ "kind": "memes" }]),- )- .await- .unwrap();- assert_eq!(decode::<Option<String>>(memes), Ok(None));- assert!(dir- .path()- .join("workspace/tinymemes/slang-index.json")- .is_file());+ for (kind, body) in [+ ("slang", "{\"terms\":1}"),+ ("memes", "{\"memes\":2}"),+ ("remixed", "[\"m1\"]"),+ ] {+ let saved = dispatch(+ &session,+ host_methods::SAVE_INDEX,+ json!([{ "kind": kind, "json": body }]),+ )+ .await+ .unwrap();+ assert_eq!(decode::<()>(saved), Ok(()));+ }+ for (kind, body) in [+ ("slang", "{\"terms\":1}"),+ ("memes", "{\"memes\":2}"),+ ("remixed", "[\"m1\"]"),+ ] {+ let loaded = dispatch(&session, host_methods::LOAD_INDEX, json!([{ "kind": kind }]))+ .await+ .unwrap();+ assert_eq!(decode::<Option<String>>(loaded), Ok(Some(body.into())));+ }}#[tokio::test]@@ -113,15 +104,47 @@ async fn deliver_is_acknowledged_and_unknown_members_are_refused() {.is_err());}-#[tokio::test]-async fn callbacks_answer_only_while_a_remix_runs() {+#[test]+fn registrations_are_independent_and_forgotten_on_drop() {let dir = tempfile::tempdir().unwrap();let config = config_in(dir.path());- assert!(active().is_none());- let seen = run_with(&config, async { active().is_some() }).await;- assert!(seen);- assert!(- active().is_none(),- "the session is cleared when the remix ends"+ let a = register(&config);+ let b = register(&config);+ assert_ne!(a.correlation(), b.correlation());+ assert!(session(a.correlation()).is_some() && session(b.correlation()).is_some());+ let a_id = a.correlation().to_owned();+ drop(a);+ assert!(session(&a_id).is_none(), "a failed call leaves nothing behind");+ assert!(session(b.correlation()).is_some());+ assert!(session("").is_none() && session("unknown").is_none());+}++#[test]+fn a_kept_registration_lives_until_the_module_reports_the_end() {+ let dir = tempfile::tempdir().unwrap();+ let registration = register(&config_in(dir.path()));+ let id = registration.correlation().to_owned();+ registration.keep_for_background();+ assert!(session(&id).is_some(), "background research may still call back");+ end(&id);+ assert!(session(&id).is_none());+ end(&id);+}++#[test]+fn the_correlation_id_is_read_from_the_first_argument_only() {+ assert_eq!(+ correlation_of(&json!([{ "correlation": "c1", "kind": "slang" }])),+ Some("c1"));+ for bad in [+ json!([{ "correlation": "" }]),+ json!([{ "correlation": 7 }]),+ json!([{}]),+ json!([]),+ json!({ "correlation": "c1" }),+ json!("c1"),+ ] {+ assert_eq!(correlation_of(&bad), None, "{bad}");+ }}diff --git a/crates/openhuman-core/src/tinymemes/service.rs b/crates/openhuman-core/src/tinymemes/service.rsindex 5f24e8cef4..918819286e 100644--- a/crates/openhuman-core/src/tinymemes/service.rs+++ b/crates/openhuman-core/src/tinymemes/service.rs@@ -127,3 +127,7 @@ pub(crate) async fn remix(Err(error) => Err(format!("tinymemes remix call failed: {error}")),}}++#[cfg(test)]+#[path = "service_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/tinymemes/service_tests.rs b/crates/openhuman-core/src/tinymemes/service_tests.rsnew file mode 100644index 0000000000..6ba3b1844f--- /dev/null+++ b/crates/openhuman-core/src/tinymemes/service_tests.rs@@ -0,0 +1,208 @@+use super::*;+use serde_json::{json, Value};+use tinybus::{broker::Broker, transport::memory::MemoryBus};+use tinymemes_bus::{HostFailure, HostResult};++fn config_in(dir: &std::path::Path) -> Config {+ let mut config = Config::default();+ config.config_path = dir.join("config.toml");+ config.workspace_dir = dir.join("workspace");+ config.secrets.encrypt = false;+ config+}++/// A host connection serving the callbacks, the peer that owns the module's+/// bus name, and a peer that does not.+struct Bus {+ host: Connection,+ module: Connection,+ intruder: Connection,+}++async fn bus() -> Bus {+ let bus = MemoryBus::new();+ Broker::new().spawn(bus.clone());+ let connect = || async { Connection::connect(bus.connect().await.unwrap()).await.unwrap() };+ let (host, module, intruder) = (connect().await, connect().await, connect().await);+ install(&host).await.unwrap();+ module.request_name(STATE_INTERFACE).await.unwrap();+ Bus {+ host,+ module,+ intruder,+ }+}++impl Bus {+ async fn call(&self, from: &Connection, member: &str, payload: Value) -> tinybus::Result<Value> {+ let host = self.host.unique_name().unwrap();+ from.proxy(host.as_str(), HOST_PATH, HOST_INTERFACE)+ .unwrap()+ .call(member, (payload,))+ .await+ }+}++fn decode<T: serde::de::DeserializeOwned>(value: Value) -> HostResult<T> {+ serde_json::from_value(value).unwrap()+}++#[tokio::test]+async fn only_the_module_may_call_back_and_only_for_a_live_remix() {+ let dir = tempfile::tempdir().unwrap();+ let bus = bus().await;+ let registration = callbacks::register(&config_in(dir.path()));+ let correlation = registration.correlation().to_owned();+ let deliver = json!({ "correlation": correlation, "reply": "hi", "remixed": true });++ // The module, for its own live remix.+ let ok = bus+ .call(&bus.module, host_methods::DELIVER, deliver.clone())+ .await+ .unwrap();+ assert_eq!(decode::<()>(ok), Ok(()));++ // A peer that does not own the module's bus name, with a valid id.+ let refused = bus+ .call(&bus.intruder, host_methods::DELIVER, deliver)+ .await;+ assert!(refused.is_err(), "a stranger must not reach the callbacks");++ // The module, with an id nobody registered, or none at all.+ for payload in [+ json!({ "correlation": "not-a-live-remix", "reply": "hi", "remixed": true }),+ json!({ "reply": "hi", "remixed": true }),+ json!({ "correlation": "", "reply": "hi", "remixed": true }),+ ] {+ let refused = bus.call(&bus.module, host_methods::DELIVER, payload).await;+ assert!(refused.is_err(), "no live remix, no answer");+ }+}++#[tokio::test]+async fn a_direct_call_without_the_brokers_context_is_unauthenticated() {+ let bus = bus().await;+ let service = HostService {+ connection: bus.host.clone(),+ };+ let error = tinybus::Interface::call(+ &service,+ &MemberName::new(host_methods::DELIVER).unwrap(),+ json!([{}]),+ )+ .await+ .unwrap_err();+ assert!(error.to_string().contains("unauthenticated"), "{error}");+}++#[tokio::test]+async fn remixes_for_different_workspaces_are_served_at_once_each_for_its_own() {+ let (dir_a, dir_b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());+ let bus = bus().await;+ let a = callbacks::register(&config_in(dir_a.path()));+ let b = callbacks::register(&config_in(dir_b.path()));+ assert_ne!(a.correlation(), b.correlation());++ // Both are live together: neither waits for the other.+ let save = |registration: &callbacks::Registration, json: &str| {+ let payload = json!({ "correlation": registration.correlation(), "kind": "slang", "json": json });+ bus.call(&bus.module, host_methods::SAVE_INDEX, payload)+ };+ let (saved_a, saved_b) = tokio::join!(save(&a, "{\"a\":1}"), save(&b, "{\"b\":1}"));+ assert_eq!(decode::<()>(saved_a.unwrap()), Ok(()));+ assert_eq!(decode::<()>(saved_b.unwrap()), Ok(()));++ let load = |registration: &callbacks::Registration| {+ let payload = json!({ "correlation": registration.correlation(), "kind": "slang" });+ bus.call(&bus.module, host_methods::LOAD_INDEX, payload)+ };+ assert_eq!(+ decode::<Option<String>>(load(&a).await.unwrap()),+ Ok(Some("{\"a\":1}".into()))+ );+ assert_eq!(+ decode::<Option<String>>(load(&b).await.unwrap()),+ Ok(Some("{\"b\":1}".into()))+ );+}++#[tokio::test]+async fn end_retires_the_remix_and_is_harmless_when_repeated_or_unknown() {+ let dir = tempfile::tempdir().unwrap();+ let bus = bus().await;+ let registration = callbacks::register(&config_in(dir.path()));+ let correlation = registration.correlation().to_owned();+ registration.keep_for_background();++ let ended = bus+ .call(+ &bus.module,+ host_methods::END,+ json!({ "correlation": correlation }),+ )+ .await+ .unwrap();+ assert_eq!(decode::<()>(ended), Ok(()));+ let after = bus+ .call(+ &bus.module,+ host_methods::EVALUATE,+ json!({ "correlation": correlation, "body": {} }),+ )+ .await;+ assert!(after.is_err(), "an ended remix answers nothing");++ for correlation in [correlation.as_str(), "never-registered"] {+ let again = bus+ .call(+ &bus.module,+ host_methods::END,+ json!({ "correlation": correlation }),+ )+ .await+ .unwrap();+ assert_eq!(decode::<()>(again), Ok(()));+ }+ // A stranger cannot end somebody else's remix.+ let dir2 = tempfile::tempdir().unwrap();+ let live = callbacks::register(&config_in(dir2.path()));+ let refused = bus+ .call(+ &bus.intruder,+ host_methods::END,+ json!({ "correlation": live.correlation() }),+ )+ .await;+ assert!(refused.is_err());+ assert!(callbacks::session(live.correlation()).is_some());+}++#[tokio::test]+async fn an_unavailable_capability_is_reported_not_faked() {+ let dir = tempfile::tempdir().unwrap();+ let bus = bus().await;+ let registration = callbacks::register(&config_in(dir.path()));+ let reply = bus+ .call(+ &bus.module,+ host_methods::EVALUATE,+ json!({ "correlation": registration.correlation(), "body": { "questions": {} } }),+ )+ .await+ .unwrap();+ assert_eq!(+ decode::<tinymemes_bus::EvaluateEnvelope>(reply),+ Err(HostFailure::Unsupported)+ );+}++#[tokio::test]+async fn component_off_refuses_before_registering_anything() {+ let mut config = Config::default();+ config.components.memes = false;+ let before = callbacks::live_count();+ let request: RemixRequest =+ serde_json::from_str(r#"{"conversation":[],"reply":"hi"}"#).unwrap();+ assert!(remix(&config, request).await.is_err());+ assert_eq!(callbacks::live_count(), before);+}