Skip to content

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

feat(modules): add storage grant tests for tiny channels

Steven Enamakel07d49c59172c
diff --git a/crates/openhuman-core/src/channels/runtime/startup/delivery_import_tests.rs b/crates/openhuman-core/src/channels/runtime/startup/delivery_import_tests.rs
new file mode 100644
index 0000000000..50279db41a
--- /dev/null
+++ b/crates/openhuman-core/src/channels/runtime/startup/delivery_import_tests.rs
@@ -0,0 +1,170 @@
+use super::*;
+use tinychannels_bus::{ChannelOutboundIntent, DeliveryDurability, OutboundPayload};
+use tinystoragedrivers::{MemoryStorage, Scope, StorageBackend};
+
+fn entry(id: &str, at: u64) -> DeliveryQueueEntry {
+ DeliveryQueueEntry::new(
+ id,
+ ChannelOutboundIntent {
+ idempotency_key: id.to_owned(),
+ channel_id: "telegram".into(),
+ conversation_id: "chat-1".into(),
+ reply_to_id: None,
+ thread_id: None,
+ durability: DeliveryDurability::Required,
+ payload: OutboundPayload::Text {
+ text: "hello".into(),
+ },
+ },
+ at,
+ )
+}
+
+fn docs() -> Arc<dyn DocumentStore> {
+ let backend = MemoryStorage::new();
+ let scoped = backend
+ .for_scope(&Scope::new("module:tinychannels@test").unwrap())
+ .unwrap();
+ Arc::clone(scoped.documents())
+}
+
+fn write_legacy(workspace: &Path, body: &Value) {
+ let path = workspace.join(LEGACY_FILE);
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(path, serde_json::to_vec(body).unwrap()).unwrap();
+}
+
+fn legacy_state() -> Value {
+ let fresh = DeliveryTerminalResult {
+ id: "done".into(),
+ intent_fingerprint: "fp".into(),
+ completed_at_unix_ms: now_unix_ms(),
+ ..serde_json::from_value(json!({
+ "id": "done", "intentFingerprint": "fp", "completedAtUnixMs": 0,
+ "messageId": null
+ }))
+ .unwrap()
+ };
+ let stale = DeliveryTerminalResult {
+ id: "old".into(),
+ completed_at_unix_ms: 1,
+ ..fresh.clone()
+ };
+ json!({
+ "pending": {"p1": entry("p1", 2), "p2": entry("p2", 1)},
+ "failed": {"f1": entry("f1", 3)},
+ "results": {"done": fresh, "old": stale},
+ })
+}
+
+#[tokio::test]
+async fn legacy_queue_lands_in_the_module_collections_and_the_file_is_untouched() {
+ let dir = tempfile::tempdir().unwrap();
+ write_legacy(dir.path(), &legacy_state());
+ let before = std::fs::read(dir.path().join(LEGACY_FILE)).unwrap();
+ let docs = docs();
+
+ let outcome = import_into(&docs, dir.path()).await.unwrap();
+
+ // Expired results are not carried over.
+ assert_eq!(
+ outcome,
+ Outcome::Imported {
+ found: 4,
+ written: 4
+ }
+ );
+ assert!(docs.get(PENDING, "p1").await.unwrap().is_some());
+ assert!(docs.get(PENDING, "p2").await.unwrap().is_some());
+ assert!(docs.get(FAILED, "f1").await.unwrap().is_some());
+ let result = docs.get(RESULTS, "done").await.unwrap().unwrap().doc;
+ assert!(result["expiresAtUnixMs"].as_u64().unwrap() > now_unix_ms());
+ assert_eq!(result["result"]["id"], "done");
+ assert!(docs.get(RESULTS, "old").await.unwrap().is_none());
+ assert_eq!(std::fs::read(dir.path().join(LEGACY_FILE)).unwrap(), before);
+}
+
+#[tokio::test]
+async fn the_import_runs_once_so_a_finished_delivery_is_not_resurrected() {
+ let dir = tempfile::tempdir().unwrap();
+ write_legacy(dir.path(), &legacy_state());
+ let docs = docs();
+ import_into(&docs, dir.path()).await.unwrap();
+
+ docs.delete(PENDING, "p1", Precondition::None).await.unwrap();
+ assert_eq!(
+ import_into(&docs, dir.path()).await.unwrap(),
+ Outcome::AlreadyDone
+ );
+ assert!(docs.get(PENDING, "p1").await.unwrap().is_none());
+}
+
+#[tokio::test]
+async fn an_existing_module_record_is_never_overwritten() {
+ let dir = tempfile::tempdir().unwrap();
+ write_legacy(dir.path(), &legacy_state());
+ let docs = docs();
+ let newer = serde_json::to_value(entry("p1", 99)).unwrap();
+ docs.put(PENDING, "p1", newer.clone(), Precondition::Absent)
+ .await
+ .unwrap();
+
+ let outcome = import_into(&docs, dir.path()).await.unwrap();
+
+ assert_eq!(
+ outcome,
+ Outcome::Imported {
+ found: 4,
+ written: 3
+ }
+ );
+ assert_eq!(docs.get(PENDING, "p1").await.unwrap().unwrap().doc, newer);
+}
+
+#[tokio::test]
+async fn a_missing_file_imports_nothing_and_writes_no_marker() {
+ let dir = tempfile::tempdir().unwrap();
+ let docs = docs();
+ assert_eq!(
+ import_into(&docs, dir.path()).await.unwrap(),
+ Outcome::NoSource
+ );
+ write_legacy(dir.path(), &legacy_state());
+ assert!(matches!(
+ import_into(&docs, dir.path()).await.unwrap(),
+ Outcome::Imported { .. }
+ ));
+}
+
+#[tokio::test]
+async fn a_corrupt_file_fails_without_a_marker_and_is_retried_once_repaired() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join(LEGACY_FILE);
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, b"{ not json").unwrap();
+ let docs = docs();
+ assert!(import_into(&docs, dir.path()).await.is_err());
+
+ write_legacy(dir.path(), &legacy_state());
+ assert!(matches!(
+ import_into(&docs, dir.path()).await.unwrap(),
+ Outcome::Imported { written: 4, .. }
+ ));
+}
+
+#[tokio::test]
+async fn records_whose_key_does_not_match_their_id_are_skipped() {
+ let dir = tempfile::tempdir().unwrap();
+ write_legacy(
+ dir.path(),
+ &json!({"pending": {"wrong-key": entry("p1", 1)}}),
+ );
+ let docs = docs();
+ assert_eq!(
+ import_into(&docs, dir.path()).await.unwrap(),
+ Outcome::Imported {
+ found: 0,
+ written: 0
+ }
+ );
+}
diff --git a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
index 44f0583b7d..4b2a6cf564 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
@@ -46,6 +46,15 @@ impl ModuleChannelRuntime {
dispatch: mpsc::Sender<RuntimeChannelMessage>,
) -> Result<Self> {
let client = ModuleClient::new((*config).clone());
+ // Queued deliveries from before the storage contract move into the
+ // module's storage before it starts and reads its queue. Best effort:
+ // a failure is retried at the next start, never fatal to channels.
+ match super::delivery_import::import_legacy_delivery(&config.workspace_dir).await {
+ Ok(outcome) => tracing::debug!("[channels] legacy delivery import: {outcome:?}"),
+ Err(error) => {
+ tracing::warn!("[channels] legacy delivery import failed, will retry: {error:#}");
+ }
+ }
let callback = ChannelHostCallbacks::new(Arc::clone(&config), context, dispatch);
let lease = ChannelRuntimeLease::open(client.clone(), callback)
.await
diff --git a/crates/openhuman-core/src/modules/storage_grant_tinychannels_tests.rs b/crates/openhuman-core/src/modules/storage_grant_tinychannels_tests.rs
new file mode 100644
index 0000000000..ae489f5bb0
--- /dev/null
+++ b/crates/openhuman-core/src/modules/storage_grant_tinychannels_tests.rs
@@ -0,0 +1,86 @@
+use super::*;
+use crate::modules::storage_grants::{authorize, declared, Denied, Object, Plan};
+use serde_json::json;
+
+fn allowed(object: Object, selector: &str, request: serde_json::Value) -> bool {
+ matches!(
+ authorize(&grant(), object, selector, &request),
+ Ok(Plan::Forward { .. })
+ )
+}
+
+#[test]
+fn the_grant_is_declared_for_tinychannels_and_validates() {
+ let declared = declared(MODULE_ID).expect("tinychannels declares storage");
+ assert_eq!(declared, grant());
+ declared.validate().expect("a valid grant");
+ assert!(declared.writable);
+ assert!(declared.stream_prefixes.is_empty());
+ assert!(declared.blob_prefixes.is_empty());
+ assert!(declared.secret_prefixes.is_empty());
+}
+
+#[test]
+fn the_declared_module_id_is_a_registry_module() {
+ assert!(crate::modules::registry::ALL
+ .iter()
+ .any(|record| record.id == MODULE_ID));
+}
+
+#[test]
+fn delivery_remote_and_whatsapp_collections_are_all_granted() {
+ let names: Vec<String> = grant().collections.iter().map(|s| s.name.clone()).collect();
+ assert_eq!(names.len(), 14);
+ for name in &names {
+ assert!(
+ allowed(
+ Object::Documents,
+ "Put",
+ json!({"collection": name, "id": "x"})
+ ),
+ "{name}"
+ );
+ }
+ for expected in [
+ "channels_delivery_pending",
+ "channels_delivery_failed",
+ "channels_delivery_results",
+ "channel_remote_bindings",
+ "whatsapp_session",
+ "whatsapp_prekey",
+ ] {
+ assert!(names.iter().any(|n| n == expected), "{expected}");
+ }
+}
+
+#[test]
+fn other_collections_and_the_host_import_marker_are_refused() {
+ for other in ["approvals", "mcp_servers", "channels_host_import", "_secrets"] {
+ assert_eq!(
+ authorize(
+ &grant(),
+ Object::Documents,
+ "Get",
+ &json!({"collection": other, "id": "x"})
+ ),
+ Err(Denied::Target),
+ "{other}"
+ );
+ }
+}
+
+#[test]
+fn streams_blobs_and_secrets_are_not_granted() {
+ assert_eq!(
+ authorize(&grant(), Object::Streams, "Append", &json!({"stream": "s"})),
+ Err(Denied::Object)
+ );
+ assert_eq!(
+ authorize(&grant(), Object::Blobs, "Get", &json!({"key": "k"})),
+ Err(Denied::Object)
+ );
+ assert_eq!(
+ authorize(&grant(), Object::Secrets, "Get", &json!({"name": "n"})),
+ Err(Denied::Object)
+ );
+}
diff --git a/crates/openhuman-core/src/modules/storage_grants_tests.rs b/crates/openhuman-core/src/modules/storage_grants_tests.rs
index 4f8fbd223f..189f25e6f0 100644
--- a/crates/openhuman-core/src/modules/storage_grants_tests.rs
+++ b/crates/openhuman-core/src/modules/storage_grants_tests.rs
@@ -333,7 +333,7 @@ fn only_modules_with_a_declared_grant_have_storage() {
for record in crate::modules::registry::ALL {
assert_eq!(
declared(record.id).is_some(),
- record.id == "tinymcp",
+ matches!(record.id, "tinymcp" | "tinychannels"),
"{}",
record.id
);