Skip to content

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

refactor(channels): replace test channel mocks with shared TestChannel

Steven Enamakel46bf8d227e1b
diff --git a/crates/openhuman-core/src/channels/host/channel_events.rs b/crates/openhuman-core/src/channels/host/channel_events.rs
index 5559545166..ded73fdbdd 100644
--- a/crates/openhuman-core/src/channels/host/channel_events.rs
+++ b/crates/openhuman-core/src/channels/host/channel_events.rs
@@ -10,8 +10,6 @@ use std::sync::{Arc, Mutex};
use tinybus::module::ModuleClient;
use tinybus::EventHandler;
use tinychannels_bus::{approvals::ReplyContext, ChannelMessage};
-#[cfg(test)]
-use tinychannels_runtime::ChannelSendExt;
/// Captures the account configuration and reply addresses used by approvals.
pub struct ChannelApprovalSurfaceSubscriber {
diff --git a/crates/openhuman-core/src/channels/host/channel_events_tests.rs b/crates/openhuman-core/src/channels/host/channel_events_tests.rs
index 2c3608637e..01ac239308 100644
--- a/crates/openhuman-core/src/channels/host/channel_events_tests.rs
+++ b/crates/openhuman-core/src/channels/host/channel_events_tests.rs
@@ -2,41 +2,22 @@
use super::*;
use std::path::Path;
-use std::sync::Mutex as StdMutex;
#[cfg(feature = "e2e-test-support")]
use tempfile::tempdir;
-use tinychannels_bus::{ChannelMessage, SendMessage};
-
-struct RecordingChannel {
- name: String,
- sent: StdMutex<Vec<SendMessage>>,
-}
-
-#[async_trait]
-impl Channel for RecordingChannel {
- fn name(&self) -> &str {
- &self.name
- }
- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
- self.sent.lock().unwrap().push(message.clone());
- Ok(())
- }
- async fn listen(&self, _tx: tokio::sync::mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
- Ok(())
- }
-}
-
-fn recording(name: &str) -> Arc<RecordingChannel> {
- Arc::new(RecordingChannel {
- name: name.into(),
- sent: StdMutex::new(Vec::new()),
- })
+use crate::channels::runtime::{ChannelHandle, TestChannel};
+
+fn recording(name: &str) -> (Arc<ChannelHandle>, Arc<TestChannel>) {
+ let channel = Arc::new(TestChannel::new(name));
+ (
+ Arc::new(ChannelHandle::Test(Arc::clone(&channel))),
+ channel,
+ )
}
-fn approval_subscriber(channels: &[Arc<RecordingChannel>]) -> ChannelApprovalSurfaceSubscriber {
- let map: HashMap<String, Arc<dyn Channel>> = channels
+fn approval_subscriber(channels: &[(&str, Arc<ChannelHandle>)]) -> ChannelApprovalSurfaceSubscriber {
+ let map: HashMap<String, Arc<ChannelHandle>> = channels
.iter()
- .map(|c| (c.name.clone(), Arc::clone(c) as Arc<dyn Channel>))
+ .map(|(name, channel)| ((*name).to_owned(), Arc::clone(channel)))
.collect();
ChannelApprovalSurfaceSubscriber::new(Arc::new(map))
}
@@ -126,8 +107,8 @@ async fn approval_prompts_reach_every_chat_channel() {
("discord", None, "discord_alice_chat-1"),
("slack", Some("1700.1"), "slack_alice_chat-1_thread:1700.1"),
] {
- let ch = recording(channel);
- let sub = approval_subscriber(&[Arc::clone(&ch)]);
+ let (handle, ch) = recording(channel);
+ let sub = approval_subscriber(&[(channel, handle)]);
assert_eq!(sub.name(), "channels::approval_surface");
assert_eq!(sub.domains(), Some(&["channel", "approval"][..]));
sub.handle(&received(channel, "chat-1", thread_ts, &ws))
@@ -145,9 +126,9 @@ async fn approval_prompts_reach_every_chat_channel() {
#[tokio::test]
async fn approvals_for_web_email_or_unrouted_requests_are_ignored() {
let ws = PathBuf::from("/tmp");
- let email = recording("email");
- let discord = recording("discord");
- let sub = approval_subscriber(&[Arc::clone(&email), Arc::clone(&discord)]);
+ let (email_handle, email) = recording("email");
+ let (discord_handle, discord) = recording("discord");
+ let sub = approval_subscriber(&[("email", email_handle), ("discord", discord_handle)]);
sub.handle(&received("email", "[email protected]", None, &ws)).await;
sub.handle(&approval(Some("[email protected]"), Some("email")))
.await;
diff --git a/crates/openhuman-core/src/channels/mod.rs b/crates/openhuman-core/src/channels/mod.rs
index 712efa9285..61892f7b53 100644
--- a/crates/openhuman-core/src/channels/mod.rs
+++ b/crates/openhuman-core/src/channels/mod.rs
@@ -11,8 +11,6 @@ pub mod contract_schema;
pub(crate) mod credentials;
pub use tinychannels_bus::SendMessage;
-#[cfg(test)]
-use tinychannels_runtime::Channel;
#[cfg(feature = "channels")]
pub mod bus;
diff --git a/crates/openhuman-core/src/channels/proactive.rs b/crates/openhuman-core/src/channels/proactive.rs
index 33d3d2f187..36bcb3d677 100644
--- a/crates/openhuman-core/src/channels/proactive.rs
+++ b/crates/openhuman-core/src/channels/proactive.rs
@@ -21,8 +21,6 @@ use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use tinybus::EventHandler;
-#[cfg(test)]
-use tinychannels_runtime::ChannelSendExt;
#[cfg(not(test))]
fn proactive_approval_gate() -> Option<Arc<crate::security::approval::ApprovalGate>> {
diff --git a/crates/openhuman-core/src/channels/proactive_tests.rs b/crates/openhuman-core/src/channels/proactive_tests.rs
index 7c02b608d7..f002473012 100644
--- a/crates/openhuman-core/src/channels/proactive_tests.rs
+++ b/crates/openhuman-core/src/channels/proactive_tests.rs
@@ -1,73 +1,15 @@
use super::*;
-use std::sync::atomic::{AtomicUsize, Ordering};
-use tinychannels_bus::ChannelMessage;
-use tokio::sync::mpsc;
-
-struct MockChannel {
- name: String,
- send_count: Arc<AtomicUsize>,
- outbound_intent_count: Arc<AtomicUsize>,
- /// Configured proactive delivery target. `Some` ⇒ the channel can
- /// receive recipient-less proactive sends; `None` ⇒ proactive routing
- /// skips it (models Telegram, which has no stored default chat).
- target: Option<String>,
-}
-
-impl MockChannel {
- /// A channel that *can* receive proactive sends (target defaults to its
- /// own name, mirroring Discord's configured `channel_id`).
- fn new(name: &str, send_count: Arc<AtomicUsize>) -> Self {
- Self {
- name: name.to_string(),
- send_count,
- outbound_intent_count: Arc::new(AtomicUsize::new(0)),
- target: Some(name.to_string()),
- }
- }
-
- /// A channel with no resolvable proactive target (e.g. Telegram).
- fn without_target(name: &str, send_count: Arc<AtomicUsize>) -> Self {
- Self {
- name: name.to_string(),
- send_count,
- outbound_intent_count: Arc::new(AtomicUsize::new(0)),
- target: None,
- }
- }
-
- fn with_recorder(
- name: &str,
- send_count: Arc<AtomicUsize>,
- outbound_intent_count: Arc<AtomicUsize>,
- ) -> Self {
- Self {
- name: name.to_string(),
- send_count,
- outbound_intent_count,
- target: Some(name.to_string()),
- }
- }
-}
-
-#[async_trait]
-impl Channel for MockChannel {
- fn name(&self) -> &str {
- &self.name
- }
- fn proactive_target(&self) -> Option<String> {
- self.target.clone()
- }
- async fn send(&self, _message: &SendMessage) -> anyhow::Result<()> {
- self.send_count.fetch_add(1, Ordering::SeqCst);
- Ok(())
- }
- async fn send_idempotent(&self, message: &SendMessage) -> anyhow::Result<()> {
- self.outbound_intent_count.fetch_add(1, Ordering::SeqCst);
- self.send(message).await
- }
- async fn listen(&self, _tx: mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
- Ok(())
- }
+use crate::channels::runtime::{ChannelHandle, TestChannel};
+use std::sync::atomic::Ordering;
+
+fn channel(name: &str, target: Option<&str>) -> (Arc<ChannelHandle>, Arc<TestChannel>) {
+ let mut channel = TestChannel::new(name);
+ channel.proactive_target = target.map(str::to_owned);
+ let channel = Arc::new(channel);
+ (
+ Arc::new(ChannelHandle::Test(Arc::clone(&channel))),
+ channel,
+ )
}
fn proactive_event() -> DomainEvent {
@@ -81,27 +23,20 @@ fn proactive_event() -> DomainEvent {
#[tokio::test]
async fn routes_to_active_external_channel() {
- let send_count = Arc::new(AtomicUsize::new(0));
- let outbound_intent_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel::with_recorder(
- "telegram",
- Arc::clone(&send_count),
- Arc::clone(&outbound_intent_count),
- ));
- let map: HashMap<String, Arc<dyn Channel>> = [("telegram".into(), ch)].into();
+ let (ch, state) = channel("telegram", Some("telegram"));
+ let map: HashMap<String, Arc<ChannelHandle>> = [("telegram".into(), ch)].into();
let sub = ProactiveMessageSubscriber::new(Arc::new(map), Some("telegram".into()));
sub.handle(&proactive_event()).await;
- assert_eq!(send_count.load(Ordering::SeqCst), 1);
- assert_eq!(outbound_intent_count.load(Ordering::SeqCst), 1);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 1);
+ assert_eq!(state.outbound_intent_count.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn web_and_external_proactive_subscribers_deliver_each_destination_once() {
- let send_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel::new("telegram", Arc::clone(&send_count)));
- let map: HashMap<String, Arc<dyn Channel>> = [("telegram".into(), ch)].into();
+ let (ch, state) = channel("telegram", Some("telegram"));
+ let map: HashMap<String, Arc<ChannelHandle>> = [("telegram".into(), ch)].into();
let external = ProactiveMessageSubscriber::new(Arc::new(map), Some("telegram".into()));
let web = crate::web_chat::proactive::WebProactiveSubscriber;
let mut web_events = crate::web_chat::subscribe_web_channel_events();
@@ -122,7 +57,7 @@ async fn web_and_external_proactive_subscribers_deliver_each_destination_once()
web_events.try_recv().is_err(),
"web event must not be duplicated"
);
- assert_eq!(send_count.load(Ordering::SeqCst), 1);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 1);
}
#[tokio::test]
@@ -131,66 +66,58 @@ async fn skips_external_when_channel_has_no_proactive_target() {
// delivery target (e.g. Telegram with no stored chat). Proactive routing
// must skip it rather than calling `send` with an empty recipient
// (#3794 review — Codex P2).
- let send_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel::without_target(
- "telegram",
- Arc::clone(&send_count),
- ));
- let map: HashMap<String, Arc<dyn Channel>> = [("telegram".into(), ch)].into();
+ let (ch, state) = channel("telegram", None);
+ let map: HashMap<String, Arc<ChannelHandle>> = [("telegram".into(), ch)].into();
let sub = ProactiveMessageSubscriber::new(Arc::new(map), Some("telegram".into()));
sub.handle(&proactive_event()).await;
- assert_eq!(send_count.load(Ordering::SeqCst), 0);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn skips_external_when_active_is_web() {
- let send_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel::new("telegram", Arc::clone(&send_count)));
- let map: HashMap<String, Arc<dyn Channel>> = [("telegram".into(), ch)].into();
+ let (ch, state) = channel("telegram", Some("telegram"));
+ let map: HashMap<String, Arc<ChannelHandle>> = [("telegram".into(), ch)].into();
let sub = ProactiveMessageSubscriber::new(Arc::new(map), Some("web".into()));
sub.handle(&proactive_event()).await;
// Active channel is "web" — external channel should NOT be called.
- assert_eq!(send_count.load(Ordering::SeqCst), 0);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn skips_external_when_active_is_none() {
- let send_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel::new("telegram", Arc::clone(&send_count)));
- let map: HashMap<String, Arc<dyn Channel>> = [("telegram".into(), ch)].into();
+ let (ch, state) = channel("telegram", Some("telegram"));
+ let map: HashMap<String, Arc<ChannelHandle>> = [("telegram".into(), ch)].into();
let sub = ProactiveMessageSubscriber::new(Arc::new(map), None);
sub.handle(&proactive_event()).await;
- assert_eq!(send_count.load(Ordering::SeqCst), 0);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn runtime_update_active_channel() {
- let send_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel::new("discord", Arc::clone(&send_count)));
- let map: HashMap<String, Arc<dyn Channel>> = [("discord".into(), ch)].into();
+ let (ch, state) = channel("discord", Some("discord"));
+ let map: HashMap<String, Arc<ChannelHandle>> = [("discord".into(), ch)].into();
let sub = ProactiveMessageSubscriber::new(Arc::new(map), None);
// Initially no active channel — external not called.
sub.handle(&proactive_event()).await;
- assert_eq!(send_count.load(Ordering::SeqCst), 0);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 0);
// Update at runtime.
sub.set_active_channel(Some("discord".into()));
sub.handle(&proactive_event()).await;
- assert_eq!(send_count.load(Ordering::SeqCst), 1);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn ignores_non_proactive_events() {
- let send_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel::new("telegram", Arc::clone(&send_count)));
- let map: HashMap<String, Arc<dyn Channel>> = [("telegram".into(), ch)].into();
+ let (ch, state) = channel("telegram", Some("telegram"));
+ let map: HashMap<String, Arc<ChannelHandle>> = [("telegram".into(), ch)].into();
let sub = ProactiveMessageSubscriber::new(Arc::new(map), Some("telegram".into()));
sub.handle(&DomainEvent::CronJobTriggered {
@@ -200,5 +127,5 @@ async fn ignores_non_proactive_events() {
})
.await;
- assert_eq!(send_count.load(Ordering::SeqCst), 0);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 0);
}
diff --git a/crates/openhuman-core/src/channels/providers/relay/channel.rs b/crates/openhuman-core/src/channels/providers/relay/channel.rs
index c3f8aec82b..d1bc7feac0 100644
--- a/crates/openhuman-core/src/channels/providers/relay/channel.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/channel.rs
@@ -10,13 +10,7 @@ use std::sync::Mutex;
use serde_json::json;
use crate::web_chat::{publish_web_channel_event, publish_web_channel_event_in, WebChannelEvent};
-#[cfg(test)]
-use async_trait::async_trait;
-#[cfg(test)]
-use tinychannels_bus::ChannelMessage;
use tinychannels_bus::SendMessage;
-#[cfg(test)]
-use tinychannels_runtime::Channel;
/// The event name a relayed reply is published under.
pub const CHANNEL_OUTBOUND_EVENT: &str = "channel_outbound";
@@ -150,24 +144,6 @@ impl RelayChannel {
}
}
-#[cfg(test)]
-#[async_trait]
-impl Channel for RelayChannel {
- fn name(&self) -> &str {
- &self.channel
- }
-
- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
- RelayChannel::send(self, message).await
- }
-
- async fn listen(&self, _tx: tokio::sync::mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
- anyhow::bail!(
- "a relayed channel has no listener: its messages arrive through channel_relay_inbound"
- )
- }
-}
-
#[cfg(test)]
#[path = "channel_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs
index 54e6e3cc53..a0002a5285 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@ -225,14 +225,8 @@ pub(crate) async fn run_relay_turn(
}
};
- #[cfg(test)]
- let mut channels_by_name: HashMap<String, Arc<dyn crate::channels::Channel>> = HashMap::new();
- #[cfg(test)]
- channels_by_name.insert(params.channel.clone(), channel.clone());
- #[cfg(not(test))]
let mut channels_by_name: HashMap<String, Arc<crate::channels::runtime::ChannelHandle>> =
HashMap::new();
- #[cfg(not(test))]
channels_by_name.insert(
params.channel.clone(),
Arc::new(crate::channels::runtime::ChannelHandle::Relay(
diff --git a/crates/openhuman-core/src/channels/routes.rs b/crates/openhuman-core/src/channels/routes.rs
index b1297943c3..e4be8ed7c3 100644
--- a/crates/openhuman-core/src/channels/routes.rs
+++ b/crates/openhuman-core/src/channels/routes.rs
@@ -9,8 +9,6 @@ use tinychannels_bus as traits;
use tinychannels_bus::module_control::{
ChannelControlRequest, ChannelControlResult, ProviderDescriptor,
};
-#[cfg(test)]
-use tinychannels_runtime::ChannelSendExt;
fn provider_descriptors() -> Vec<ProviderDescriptor> {
provider::list_providers()
diff --git a/crates/openhuman-core/src/channels/routes_remote_reset_tests.rs b/crates/openhuman-core/src/channels/routes_remote_reset_tests.rs
index b34e21ee74..6bc14cfcd3 100644
--- a/crates/openhuman-core/src/channels/routes_remote_reset_tests.rs
+++ b/crates/openhuman-core/src/channels/routes_remote_reset_tests.rs
@@ -5,26 +5,6 @@ use std::path::Path;
use std::sync::Arc;
use tinyagents_session::transcript::{SessionRef, TranscriptMessage, TranscriptMeta};
-struct ConfiguredChannel;
-
-#[async_trait::async_trait]
-impl crate::channels::Channel for ConfiguredChannel {
- fn name(&self) -> &str {
- "telegram:bot-a"
- }
-
- async fn send(&self, _message: &crate::channels::SendMessage) -> anyhow::Result<()> {
- Ok(())
- }
-
- async fn listen(
- &self,
- _tx: tokio::sync::mpsc::Sender<tinychannels_bus::ChannelMessage>,
- ) -> anyhow::Result<()> {
- Ok(())
- }
-}
-
fn transcript_meta(thread_id: &str, agent_id: &str) -> TranscriptMeta {
TranscriptMeta {
agent_name: agent_id.into(),
@@ -137,7 +117,9 @@ fn tenant_runtime(
runtime.core = Some(Arc::downgrade(&core));
runtime.channels_by_name = Arc::new(HashMap::from([(
"telegram:bot-a".into(),
- Arc::new(ConfiguredChannel) as Arc<dyn crate::channels::Channel>,
+ Arc::new(crate::channels::runtime::ChannelHandle::Test(Arc::new(
+ crate::channels::runtime::TestChannel::new("telegram:bot-a"),
+ ))),
)]));
(core, runtime)
}
diff --git a/crates/openhuman-core/src/channels/routes_tests.rs b/crates/openhuman-core/src/channels/routes_tests.rs
index 949a279542..765a49f7aa 100644
--- a/crates/openhuman-core/src/channels/routes_tests.rs
+++ b/crates/openhuman-core/src/channels/routes_tests.rs
@@ -35,26 +35,7 @@ impl Tool for DummyTool {
}
}
-#[derive(Default)]
-struct RecordingChannel {
- sent: Mutex<Vec<SendMessage>>,
-}
-
-#[async_trait]
-impl Channel for RecordingChannel {
- fn name(&self) -> &str {
- "recording"
- }
-
- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
- self.sent.lock().unwrap().push(message.clone());
- Ok(())
- }
-
- async fn listen(&self, _tx: tokio::sync::mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
- Ok(())
- }
-}
+use crate::channels::runtime::{ChannelHandle, TestChannel};
pub(super) fn runtime_context(workspace_dir: PathBuf) -> ChannelRuntimeContext {
let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
@@ -302,8 +283,8 @@ async fn load_cached_model_preview_returns_empty_when_cache_json_is_invalid() {
#[tokio::test]
async fn handle_runtime_command_unknown_provider_sends_helpful_error() {
let ctx = runtime_context(PathBuf::from("/tmp"));
- let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_state = Arc::new(TestChannel::new("recording"));
+ let channel = Arc::new(ChannelHandle::Test(Arc::clone(&channel_state)));
let msg = ChannelMessage {
reply_to_id: None,
topic_id: None,
@@ -326,7 +307,7 @@ async fn handle_runtime_command_unknown_provider_sends_helpful_error() {
.await;
assert!(handled);
- let sent = channel_impl.sent.lock().unwrap();
+ let sent = channel_state.sent.lock().unwrap();
assert_eq!(sent.len(), 1);
assert!(sent[0]
.content
@@ -338,8 +319,8 @@ async fn handle_runtime_command_unknown_provider_sends_helpful_error() {
async fn clear_history_command_uses_reset_callback_and_persists_route_override() {
let ctx = runtime_context(PathBuf::from("/tmp"));
let key = "telegram_alice_room";
- let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_state = Arc::new(TestChannel::new("recording"));
+ let channel = Arc::new(ChannelHandle::Test(Arc::clone(&channel_state)));
let msg = ChannelMessage {
reply_to_id: None,
topic_id: None,
@@ -380,7 +361,7 @@ async fn clear_history_command_uses_reset_callback_and_persists_route_override()
}
);
- let sent = channel_impl.sent.lock().unwrap();
+ let sent = channel_state.sent.lock().unwrap();
assert_eq!(sent.len(), 1);
assert!(sent[0].content.contains("Model switched to `gpt-5-mini`"));
}
@@ -394,8 +375,8 @@ async fn failed_history_reset_does_not_apply_requested_route() {
model: "reasoning-v1".into(),
};
set_route_selection(&ctx, key, before.clone());
- let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_state = Arc::new(TestChannel::new("recording"));
+ let channel = Arc::new(ChannelHandle::Test(Arc::clone(&channel_state)));
let msg = ChannelMessage {
reply_to_id: None,
topic_id: None,
@@ -423,7 +404,7 @@ async fn failed_history_reset_does_not_apply_requested_route() {
assert!(handled);
assert_eq!(get_route_selection(&ctx, key), before);
- let sent = channel_impl.sent.lock().unwrap();
+ let sent = channel_state.sent.lock().unwrap();
assert_eq!(sent.len(), 1);
assert_eq!(sent[0].content, "Something went wrong. Please try again.");
assert!(!sent[0].content.contains("durable reset failed"));
@@ -432,8 +413,8 @@ async fn failed_history_reset_does_not_apply_requested_route() {
#[tokio::test]
async fn handle_runtime_command_telegram_status_replies_without_agent() {
let ctx = runtime_context(PathBuf::from("/tmp"));
- let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_state = Arc::new(TestChannel::new("recording"));
+ let channel = Arc::new(ChannelHandle::Test(Arc::clone(&channel_state)));
let msg = ChannelMessage {
reply_to_id: None,
topic_id: None,
@@ -456,7 +437,7 @@ async fn handle_runtime_command_telegram_status_replies_without_agent() {
.await;
assert!(handled);
- let sent = channel_impl.sent.lock().unwrap();
+ let sent = channel_state.sent.lock().unwrap();
assert_eq!(sent.len(), 1);
assert!(
sent[0].content.contains("**Status**"),
@@ -490,8 +471,8 @@ async fn handle_runtime_command_without_target_channel_still_consumes_command()
#[tokio::test]
async fn handle_runtime_command_telegram_help_replies_with_remote_command_list() {
let ctx = runtime_context(PathBuf::from("/tmp"));
- let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_state = Arc::new(TestChannel::new("recording"));
+ let channel = Arc::new(ChannelHandle::Test(Arc::clone(&channel_state)));
let msg = ChannelMessage {
reply_to_id: None,
topic_id: None,
@@ -514,7 +495,7 @@ async fn handle_runtime_command_telegram_help_replies_with_remote_command_list()
.await;
assert!(handled);
- let sent = channel_impl.sent.lock().unwrap();
+ let sent = channel_state.sent.lock().unwrap();
assert_eq!(sent.len(), 1);
assert!(sent[0].content.contains("Remote control:"));
assert!(sent[0].content.contains("`/status`"));
@@ -529,8 +510,8 @@ async fn handle_runtime_command_telegram_help_replies_with_remote_command_list()
async fn handle_runtime_command_telegram_sessions_reports_empty_store() {
let tempdir = tempfile::tempdir().unwrap();
let ctx = runtime_context(tempdir.path().to_path_buf());
- let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_state = Arc::new(TestChannel::new("recording"));
+ let channel = Arc::new(ChannelHandle::Test(Arc::clone(&channel_state)));
let msg = ChannelMessage {
reply_to_id: None,
topic_id: None,
@@ -553,7 +534,7 @@ async fn handle_runtime_command_telegram_sessions_reports_empty_store() {
.await;
assert!(handled);
- let sent = channel_impl.sent.lock().unwrap();
+ let sent = channel_state.sent.lock().unwrap();
assert_eq!(sent.len(), 1);
assert!(sent[0]
.content
@@ -566,8 +547,8 @@ async fn handle_runtime_command_telegram_sessions_reports_empty_store() {
async fn handle_runtime_command_telegram_new_status_and_sessions_round_trip() {
let tempdir = tempfile::tempdir().unwrap();
let ctx = runtime_context(tempdir.path().to_path_buf());
- let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_state = Arc::new(TestChannel::new("recording"));
+ let channel = Arc::new(ChannelHandle::Test(Arc::clone(&channel_state)));
let sender_key = "telegram_alice_chat-remote";
let new_msg = ChannelMessage {
@@ -658,7 +639,7 @@ async fn handle_runtime_command_telegram_new_status_and_sessions_round_trip() {
.await
);
- let sent = channel_impl.sent.lock().unwrap();
+ let sent = channel_state.sent.lock().unwrap();
assert_eq!(sent.len(), 3);
assert!(sent[0].content.contains("Started new session"));
assert!(sent[0]
@@ -683,8 +664,8 @@ async fn handle_runtime_command_telegram_new_status_and_sessions_round_trip() {
async fn handle_runtime_command_telegram_new_reports_unavailable_storage() {
let tempdir = tempfile::tempdir().unwrap();
let ctx = runtime_context(tempdir.path().to_path_buf());
- let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_state = Arc::new(TestChannel::new("recording"));
+ let channel = Arc::new(ChannelHandle::Test(Arc::clone(&channel_state)));
let msg = ChannelMessage {
reply_to_id: None,
topic_id: None,
@@ -706,7 +687,7 @@ async fn handle_runtime_command_telegram_new_reports_unavailable_storage() {
)
.await
);
- let sent = channel_impl.sent.lock().unwrap();
+ let sent = channel_state.sent.lock().unwrap();
assert_eq!(sent.len(), 1);
assert!(
sent[0].content.contains("Created thread"),
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/helpers_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/helpers_tests.rs
index 27035b81eb..aa878202d2 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/helpers_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/helpers_tests.rs
@@ -3,46 +3,36 @@ use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use tokio::sync::{oneshot, Notify};
-struct DeferredTyping {
- started: Notify,
- release: Notify,
- stopped: std::sync::Mutex<Option<oneshot::Sender<String>>>,
-}
-#[async_trait::async_trait]
-impl crate::channels::Channel for DeferredTyping {
- fn name(&self) -> &str {
- "fixture"
- }
- async fn send(&self, _: &crate::channels::SendMessage) -> anyhow::Result<()> {
- Ok(())
- }
- async fn listen(
- &self,
- _: tokio::sync::mpsc::Sender<traits::ChannelMessage>,
- ) -> anyhow::Result<()> {
- Ok(())
- }
- async fn begin_typing_refresh(&self, _: &str, _: u64) -> anyhow::Result<Option<String>> {
- self.started.notify_one();
- self.release.notified().await;
- Ok(Some("module-handle".into()))
- }
- async fn end_typing_refresh(&self, handle: &str) -> anyhow::Result<()> {
- if let Some(sender) = self.stopped.lock().unwrap().take() {
- let _ = sender.send(handle.into());
- }
- Ok(())
- }
-}
-
#[tokio::test]
async fn canceled_waiter_closes_handle_returned_by_in_flight_typing_start() {
let (sender, receiver) = oneshot::channel();
- let channel = Arc::new(DeferredTyping {
- started: Notify::new(),
- release: Notify::new(),
- stopped: std::sync::Mutex::new(Some(sender)),
- });
+ let started = Arc::new(Notify::new());
+ let release = Arc::new(Notify::new());
+ let stopped = Arc::new(std::sync::Mutex::new(Some(sender)));
+ let mut test_channel = crate::channels::runtime::TestChannel::new("fixture");
+ test_channel.begin_typing_refresh = Some(Arc::new({
+ let started = Arc::clone(&started);
+ let release = Arc::clone(&release);
+ move |_, _| {
+ let started = Arc::clone(&started);
+ let release = Arc::clone(&release);
+ Box::pin(async move {
+ started.notify_one();
+ release.notified().await;
+ Ok(Some("module-handle".into()))
+ })
+ }
+ }));
+ test_channel.end_typing_refresh = Some(Arc::new(move |handle| {
+ let stopped = Arc::clone(&stopped);
+ Box::pin(async move {
+ if let Some(sender) = stopped.lock().unwrap().take() {
+ let _ = sender.send(handle);
+ }
+ Ok(())
+ })
+ }));
+ let channel = Arc::new(crate::channels::runtime::ChannelHandle::Test(Arc::new(test_channel)));
let cancellation = tokio_util::sync::CancellationToken::new();
let waiter = spawn_typing_task(
&DispatchCtx::unbound(),
@@ -50,10 +40,10 @@ async fn canceled_waiter_closes_handle_returned_by_in_flight_typing_start() {
"recipient".into(),
cancellation.clone(),
);
- channel.started.notified().await;
+ started.notified().await;
waiter.abort();
cancellation.cancel();
- channel.release.notify_one();
+ release.notify_one();
assert_eq!(
tokio::time::timeout(std::time::Duration::from_secs(2), receiver)
.await
@@ -63,31 +53,6 @@ async fn canceled_waiter_closes_handle_returned_by_in_flight_typing_start() {
);
}
-struct ProbeTyping(std::sync::Mutex<Option<oneshot::Sender<Option<String>>>>);
-#[async_trait::async_trait]
-impl crate::channels::Channel for ProbeTyping {
- fn name(&self) -> &str {
- "probe"
- }
- async fn send(&self, _: &crate::channels::SendMessage) -> anyhow::Result<()> {
- Ok(())
- }
- async fn listen(
- &self,
- _: tokio::sync::mpsc::Sender<traits::ChannelMessage>,
- ) -> anyhow::Result<()> {
- Ok(())
- }
- async fn begin_typing_refresh(&self, _: &str, _: u64) -> anyhow::Result<Option<String>> {
- let agent = crate::core::runtime::CoreContext::current()
- .and_then(|core| core.session_agent().map(str::to_owned));
- if let Some(sender) = self.0.lock().unwrap().take() {
- let _ = sender.send(agent);
- }
- Ok(None)
- }
-}
-
#[tokio::test]
async fn typing_task_runs_under_the_handed_context_not_the_active_one() {
use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
@@ -104,7 +69,20 @@ async fn typing_task_runs_under_the_handed_context_not_the_active_one() {
let asha = DispatchCtx::new(agent_ctx("u-asha"));
let ravi = agent_ctx("u-ravi");
let (sender, receiver) = oneshot::channel();
- let channel = Arc::new(ProbeTyping(std::sync::Mutex::new(Some(sender))));
+ let sender = Arc::new(std::sync::Mutex::new(Some(sender)));
+ let mut test_channel = crate::channels::runtime::TestChannel::new("probe");
+ test_channel.begin_typing_refresh = Some(Arc::new(move |_, _| {
+ let sender = Arc::clone(&sender);
+ Box::pin(async move {
+ let agent = crate::core::runtime::CoreContext::current()
+ .and_then(|core| core.session_agent().map(str::to_owned));
+ if let Some(sender) = sender.lock().unwrap().take() {
+ let _ = sender.send(agent);
+ }
+ Ok(None)
+ })
+ }));
+ let channel = Arc::new(crate::channels::runtime::ChannelHandle::Test(Arc::new(test_channel)));
let cancellation = tokio_util::sync::CancellationToken::new();
// The caller's own scope is Ravi's; the typing task was handed Asha's.
let (waiter_tx, waiter_rx) = oneshot::channel();
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs
index db6d31c2eb..2a721e4b97 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs
@@ -14,38 +14,20 @@ use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use tinychannels_bus as traits;
-use tinychannels_runtime::Channel;
use tinytools::{PermissionLevel, Tool, ToolResult};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
-#[derive(Default)]
-struct Telegram {
- sent: Mutex<Vec<String>>,
-}
-
-#[async_trait::async_trait]
-impl Channel for Telegram {
- fn name(&self) -> &str {
- "telegram"
- }
- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
- self.sent.lock().unwrap().push(message.content.clone());
- Ok(())
- }
- async fn listen(
- &self,
- _tx: tokio::sync::mpsc::Sender<traits::ChannelMessage>,
- ) -> anyhow::Result<()> {
- Ok(())
- }
-}
-
-fn context(channel: Arc<Telegram>, config: Config) -> Arc<ChannelRuntimeContext> {
- let channel: Arc<dyn Channel> = channel;
+fn context(
+ channel: Arc<crate::channels::runtime::TestChannel>,
+ config: Config,
+) -> Arc<ChannelRuntimeContext> {
Arc::new(ChannelRuntimeContext {
relay_thread: None,
- channels_by_name: Arc::new(HashMap::from([("telegram".to_string(), channel)])),
+ channels_by_name: Arc::new(HashMap::from([(
+ "telegram".to_string(),
+ Arc::new(crate::channels::runtime::ChannelHandle::Test(channel)),
+ )])),
module_objects: Arc::new(HashMap::new()),
turn_model_source: None,
default_provider: Arc::new("test-provider".to_string()),
@@ -117,7 +99,7 @@ async fn a_binding_no_agent_answers_is_refused_not_sent_to_the_orchestrator() {
})
.await;
let tmp = tempfile::tempdir().unwrap();
- let channel = Arc::new(Telegram::default());
+ let channel = Arc::new(crate::channels::runtime::TestChannel::new("telegram"));
let ctx = context(
Arc::clone(&channel),
config(&tmp, Some("nobody-registered")),
@@ -130,7 +112,13 @@ async fn a_binding_no_agent_answers_is_refused_not_sent_to_the_orchestrator() {
0,
"never widened to the orchestrator"
);
- let sent = channel.sent.lock().unwrap().clone();
+ let sent = channel
+ .sent
+ .lock()
+ .unwrap()
+ .iter()
+ .map(|message| message.content.clone())
+ .collect::<Vec<_>>();
assert_eq!(sent.len(), 1, "{sent:?}");
assert!(sent[0].contains("not available"), "{sent:?}");
}
@@ -151,13 +139,13 @@ async fn an_unbound_channel_still_runs_the_orchestrator() {
.agent
.channel_agents
.insert("discord".into(), "some-agent".into());
- let channel = Arc::new(Telegram::default());
+ let channel = Arc::new(crate::channels::runtime::TestChannel::new("telegram"));
process_channel_message(context(Arc::clone(&channel), config), message("hello")).await;
assert_eq!(calls.load(Ordering::SeqCst), 1);
assert_eq!(
- channel.sent.lock().unwrap().clone(),
+ channel.sent.lock().unwrap().iter().map(|message| message.content.clone()).collect::<Vec<_>>(),
vec!["orchestrator answered".to_string()]
);
}
@@ -341,7 +329,7 @@ async fn bound_channel_runs_its_host_agent() {
writes: Arc::clone(&writes),
origins: Arc::clone(&origins),
});
- let channel = Arc::new(Telegram::default());
+ let channel = Arc::new(crate::channels::runtime::TestChannel::new("telegram"));
let ctx = context(Arc::clone(&channel), config(&tmp, Some("teeny-chat")));
let outcome = {
@@ -353,7 +341,7 @@ async fn bound_channel_runs_its_host_agent() {
};
assert_eq!(
- channel.sent.lock().unwrap().clone(),
+ channel.sent.lock().unwrap().iter().map(|message| message.content.clone()).collect::<Vec<_>>(),
vec!["teeny says hi".to_string()],
"the host agent's reply goes back to the chat"
);
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/mod.rs b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/mod.rs
index f157cec3b3..efd1855b5a 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/mod.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/mod.rs
@@ -26,10 +26,6 @@ use crate::config::Config;
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
use tinychannels_bus as traits;
-#[cfg(test)]
-#[cfg(test)]
-use tinychannels_runtime::ChannelSendExt;
-
pub(crate) mod posture;
mod turn;
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
index d9032caf6b..34685ce448 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@ -11,9 +11,6 @@ use crate::core::events::DomainEvent;
use crate::util::truncate_with_ellipsis;
use std::sync::Arc;
use std::time::Instant;
-#[cfg(test)]
-#[cfg(test)]
-use tinychannels_runtime::ChannelSendExt;
use tokio_util::sync::CancellationToken;
use tokio_util::task::AbortOnDropHandle;
diff --git a/crates/openhuman-core/src/channels/runtime/mod.rs b/crates/openhuman-core/src/channels/runtime/mod.rs
index 842d2381bb..0fb97e9a9b 100644
--- a/crates/openhuman-core/src/channels/runtime/mod.rs
+++ b/crates/openhuman-core/src/channels/runtime/mod.rs
@@ -10,6 +10,8 @@ pub use startup::start_channels;
pub(crate) use startup::start_channels_with_session;
pub(crate) use startup::ChannelHandle;
#[cfg(test)]
+pub(crate) use startup::TestChannel;
+#[cfg(test)]
pub(crate) use startup::{prepare_module_runtime_for_test, ModuleRuntimeTestGuard};
// The hosted-channel relay (`channels::providers::relay`) runs one message
// through the same pipeline, with a context built from the caller's config.
diff --git a/crates/openhuman-core/src/channels/runtime/startup.rs b/crates/openhuman-core/src/channels/runtime/startup.rs
index 9b30919022..38df98224e 100644
--- a/crates/openhuman-core/src/channels/runtime/startup.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup.rs
@@ -13,24 +13,60 @@ mod turn_parts;
use anyhow::Result;
use tinybus::module::{ModuleCallError, ModuleClient};
-#[cfg(test)]
-pub(crate) type ChannelHandle = dyn tinychannels_runtime::Channel;
-
/// Host-owned handle to a configured channel instance. Production operations
/// are dispatched through the loaded TinyChannels module's bus object.
-#[cfg(not(test))]
#[derive(Clone)]
pub(crate) enum ChannelHandle {
Module(module_providers::ModuleChannel),
Relay(std::sync::Arc<crate::channels::providers::relay::RelayChannel>),
+ /// Test-only sink for narrow policy tests that do not need the linked module.
+ #[cfg(test)]
+ Test(std::sync::Arc<TestChannel>),
+}
+
+#[cfg(test)]
+pub(crate) struct TestChannel {
+ pub(crate) name: String,
+ pub(crate) proactive_target: Option<String>,
+ pub(crate) supports_reactions: bool,
+ pub(crate) sent: std::sync::Arc<std::sync::Mutex<Vec<tinychannels_bus::SendMessage>>>,
+ pub(crate) sent_messages: tokio::sync::Mutex<Vec<String>>,
+ pub(crate) send_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ pub(crate) outbound_intent_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ pub(crate) start_typing_calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ pub(crate) stop_typing_calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ pub(crate) send_error: Option<String>,
+ pub(crate) begin_typing_refresh: Option<
+ std::sync::Arc<
+ dyn Fn(
+ String,
+ u64,
+ ) -> futures::future::BoxFuture<'static, anyhow::Result<Option<String>>>
+ + Send
+ + Sync,
+ >,
+ >,
+ pub(crate) end_typing_refresh: Option<
+ std::sync::Arc<
+ dyn Fn(String) -> futures::future::BoxFuture<'static, anyhow::Result<()>>
+ + Send
+ + Sync,
+ >,
+ >,
}
-#[cfg(not(test))]
impl ChannelHandle {
+ #[cfg(test)]
+ pub(crate) fn test(channel: TestChannel) -> Self {
+ Self::Test(std::sync::Arc::new(channel))
+ }
+
pub(crate) fn name(&self) -> &str {
match self {
Self::Module(channel) => &channel.name,
Self::Relay(channel) => channel.name(),
+ #[cfg(test)]
+ Self::Test(channel) => &channel.name,
}
}
@@ -38,6 +74,8 @@ impl ChannelHandle {
match self {
Self::Module(channel) => channel.proactive_target(),
Self::Relay(_) => None,
+ #[cfg(test)]
+ Self::Test(channel) => channel.proactive_target.clone(),
}
}
@@ -45,6 +83,8 @@ impl ChannelHandle {
match self {
Self::Module(channel) => channel.capabilities(),
Self::Relay(_) => tinychannels_bus::ChannelCapabilities::unknown(),
+ #[cfg(test)]
+ Self::Test(channel) => tinychannels_bus::ChannelCapabilities::unknown(),
}
}
@@ -52,6 +92,8 @@ impl ChannelHandle {
match self {
Self::Module(channel) => channel.interaction.supports_reactions,
Self::Relay(_) => false,
+ #[cfg(test)]
+ Self::Test(channel) => channel.supports_reactions,
}
}
@@ -59,6 +101,8 @@ impl ChannelHandle {
match self {
Self::Module(channel) => channel.send_prepared(message).await,
Self::Relay(channel) => channel.send(message).await,
+ #[cfg(test)]
+ Self::Test(channel) => channel.send(message).await,
}
}
@@ -66,7 +110,17 @@ impl ChannelHandle {
&self,
message: &tinychannels_bus::SendMessage,
) -> anyhow::Result<()> {
- self.send(message).await
+ match self {
+ Self::Module(channel) => channel.send_prepared(message).await,
+ Self::Relay(channel) => channel.send(message).await,
+ #[cfg(test)]
+ Self::Test(channel) => {
+ channel
+ .outbound_intent_count
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ channel.send(message).await
+ }
+ }
}
pub(crate) async fn start_typing(&self, recipient: &str) -> anyhow::Result<()> {
@@ -79,6 +133,12 @@ impl ChannelHandle {
.await
}
Self::Relay(_) => Ok(()),
+ #[cfg(test)]
+ Self::Test(channel) => {
+ let _ = recipient;
+ channel.start_typing_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(())
+ }
}
}
@@ -92,6 +152,12 @@ impl ChannelHandle {
.await
}
Self::Relay(_) => Ok(()),
+ #[cfg(test)]
+ Self::Test(channel) => {
+ let _ = recipient;
+ channel.stop_typing_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(())
+ }
}
}
@@ -103,6 +169,11 @@ impl ChannelHandle {
match self {
Self::Module(channel) => channel.begin_typing_refresh(recipient, interval_secs).await,
Self::Relay(_) => Ok(None),
+ #[cfg(test)]
+ Self::Test(channel) => match &channel.begin_typing_refresh {
+ Some(begin) => begin(recipient.to_owned(), interval_secs).await,
+ None => Ok(None),
+ },
}
}
@@ -110,10 +181,59 @@ impl ChannelHandle {
match self {
Self::Module(channel) => channel.end_typing_refresh(handle).await,
Self::Relay(_) => Ok(()),
+ #[cfg(test)]
+ Self::Test(channel) => match &channel.end_typing_refresh {
+ Some(end) => end(handle.to_owned()).await,
+ None => Ok(()),
+ },
}
}
}
+#[cfg(test)]
+impl TestChannel {
+ pub(crate) fn new(name: impl Into<String>) -> Self {
+ Self {
+ name: name.into(),
+ proactive_target: None,
+ supports_reactions: false,
+ sent: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
+ sent_messages: tokio::sync::Mutex::new(Vec::new()),
+ send_count: Default::default(),
+ outbound_intent_count: Default::default(),
+ start_typing_calls: Default::default(),
+ stop_typing_calls: Default::default(),
+ send_error: None,
+ begin_typing_refresh: None,
+ end_typing_refresh: None,
+ }
+ }
+
+ pub(crate) fn name(&self) -> &str {
+ &self.name
+ }
+
+ async fn send(&self, message: &tinychannels_bus::SendMessage) -> anyhow::Result<()> {
+ self.send_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if let Some(error) = &self.send_error {
+ anyhow::bail!(error.clone());
+ }
+ self.sent.lock().expect("test send lock").push(message.clone());
+ self.sent_messages
+ .lock()
+ .await
+ .push(format!("{}:{}", message.recipient, message.content));
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+impl Default for TestChannel {
+ fn default() -> Self {
+ Self::new("test-channel")
+ }
+}
+
/// Ask the owning module to prepare effective execution limits for this host
/// runtime. A malformed response fails closed and reports only the module ID.
pub(crate) async fn prepare_runtime_limits(
diff --git a/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs b/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs
index 8d0feb4add..de4fd60c9b 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs
@@ -11,8 +11,7 @@ use tinychannels_bus::channel::{
use tinychannels_bus::module_progressive::{
ChannelOutputEvent, ProgressiveTransportRequest, ProgressiveTransportResult,
};
-use tinychannels_bus::{ChannelBackendRequest, ChannelBackendResult, SendMessage};
-use tinychannels_runtime::Channel;
+use tinychannels_bus::{ChannelBackendRequest, ChannelBackendResult};
#[derive(Default)]
struct RecordingOutputObserver {
@@ -56,17 +55,7 @@ impl RecordingChannel {
}
}
-#[async_trait::async_trait]
-#[allow(deprecated)]
-impl Channel for RecordingChannel {
- fn name(&self) -> &str {
- &self.name
- }
-
- async fn send(&self, _message: &SendMessage) -> anyhow::Result<()> {
- anyhow::bail!("progressive native send must use the typed adapter")
- }
-
+impl RecordingChannel {
async fn send_typed_with_receipt(
&self,
message: &ChannelOutboundMessage,
@@ -88,12 +77,6 @@ impl Channel for RecordingChannel {
})
}
- async fn listen(
- &self,
- _tx: tokio::sync::mpsc::Sender<tinychannels_bus::ChannelMessage>,
- ) -> anyhow::Result<()> {
- Ok(())
- }
}
#[async_trait::async_trait]
@@ -145,7 +128,7 @@ impl ProgressiveChannelTransport for RecordingChannel {
}
fn callback_for_channels(
- channels: HashMap<String, Arc<dyn Channel>>,
+ channels: HashMap<String, Arc<super::ChannelHandle>>,
progressive_channels: HashMap<String, Arc<dyn ProgressiveChannelTransport>>,
output_observer: Option<Arc<dyn ProgressiveOutputObserver>>,
) -> (ChannelHostCallbacks, Arc<ChannelRuntimeContext>) {
@@ -201,14 +184,14 @@ fn callback_for_channels(
async fn native_progressive_transport_dispatches_typed_content_through_configured_channel() {
let other_account = Arc::new(RecordingChannel::new("telegram:bot-a"));
let selected_account = Arc::new(RecordingChannel::new("telegram:bot-b"));
- let channels: HashMap<String, Arc<dyn Channel>> = HashMap::from([
+ let channels: HashMap<String, Arc<super::ChannelHandle>> = HashMap::from([
(
other_account.name().to_owned(),
- other_account.clone() as Arc<dyn Channel>,
+ Arc::new(super::ChannelHandle::test(super::TestChannel::new(other_account.name()))),
),
(
selected_account.name().to_owned(),
- selected_account.clone() as Arc<dyn Channel>,
+ Arc::new(super::ChannelHandle::test(super::TestChannel::new(selected_account.name()))),
),
]);
let progressive_channels: HashMap<String, Arc<dyn ProgressiveChannelTransport>> =
@@ -318,14 +301,14 @@ async fn native_progressive_transport_dispatches_typed_content_through_configure
async fn native_progressive_transport_rejects_unconfigured_account_without_provider_fallback() {
let first_account = Arc::new(RecordingChannel::new("telegram:bot-a"));
let second_account = Arc::new(RecordingChannel::new("telegram:bot-b"));
- let channels: HashMap<String, Arc<dyn Channel>> = HashMap::from([
+ let channels: HashMap<String, Arc<super::ChannelHandle>> = HashMap::from([
(
"telegram:bot-a".into(),
- first_account.clone() as Arc<dyn Channel>,
+ Arc::new(super::ChannelHandle::test(super::TestChannel::new(first_account.name()))),
),
(
"telegram:bot-b".into(),
- second_account.clone() as Arc<dyn Channel>,
+ Arc::new(super::ChannelHandle::test(super::TestChannel::new(second_account.name()))),
),
]);
let progressive_channels: HashMap<String, Arc<dyn ProgressiveChannelTransport>> =
@@ -381,7 +364,7 @@ async fn native_progressive_output_event_is_acknowledged_by_optional_host_observ
let observer = Arc::new(RecordingOutputObserver::default());
let adapter = Arc::new(RecordingChannel::new("telegram:bot-b"));
let (callback, _context) = callback_for_channels(
- HashMap::from([("telegram:bot-b".into(), adapter.clone() as Arc<dyn Channel>)]),
+ HashMap::from([("telegram:bot-b".into(), Arc::new(super::ChannelHandle::test(super::TestChannel::new("telegram:bot-b"))))]),
HashMap::from([(
"telegram:bot-b".into(),
adapter.clone() as Arc<dyn ProgressiveChannelTransport>,
@@ -457,7 +440,7 @@ fn output_event_request(
async fn native_progressive_output_event_validates_scope_without_observer() {
let adapter = Arc::new(RecordingChannel::new("telegram:bot-b"));
let (callback, _context) = callback_for_channels(
- HashMap::from([("telegram:bot-b".into(), adapter.clone() as Arc<dyn Channel>)]),
+ HashMap::from([("telegram:bot-b".into(), Arc::new(super::ChannelHandle::test(super::TestChannel::new("telegram:bot-b"))))]),
HashMap::from([(
"telegram:bot-b".into(),
adapter.clone() as Arc<dyn ProgressiveChannelTransport>,
@@ -495,7 +478,7 @@ async fn native_progressive_output_event_validates_scope_before_observer() {
let observer = Arc::new(RecordingOutputObserver::default());
let adapter = Arc::new(RecordingChannel::new("telegram:bot-b"));
let (callback, _) = callback_for_channels(
- HashMap::from([("telegram:bot-b".into(), adapter.clone() as Arc<dyn Channel>)]),
+ HashMap::from([("telegram:bot-b".into(), Arc::new(super::ChannelHandle::test(super::TestChannel::new("telegram:bot-b"))))]),
HashMap::from([(
"telegram:bot-b".into(),
adapter as Arc<dyn ProgressiveChannelTransport>,
@@ -520,7 +503,7 @@ async fn native_progressive_callbacks_stop_after_channel_session_cancellation()
let observer = Arc::new(RecordingOutputObserver::default());
let adapter = Arc::new(RecordingChannel::new("telegram:bot-b"));
let (callback, _context) = callback_for_channels(
- HashMap::from([("telegram:bot-b".into(), adapter.clone() as Arc<dyn Channel>)]),
+ HashMap::from([("telegram:bot-b".into(), Arc::new(super::ChannelHandle::test(super::TestChannel::new("telegram:bot-b"))))]),
HashMap::from([(
"telegram:bot-b".into(),
adapter as Arc<dyn ProgressiveChannelTransport>,
@@ -544,7 +527,7 @@ async fn native_progressive_callbacks_stop_after_channel_session_cancellation()
async fn native_progressive_callbacks_fail_closed_after_transport_owner_drops() {
let adapter = Arc::new(RecordingChannel::new("telegram:bot-b"));
let (callback, context) = callback_for_channels(
- HashMap::from([("telegram:bot-b".into(), adapter.clone() as Arc<dyn Channel>)]),
+ HashMap::from([("telegram:bot-b".into(), Arc::new(super::ChannelHandle::test(super::TestChannel::new("telegram:bot-b"))))]),
HashMap::from([(
"telegram:bot-b".into(),
adapter.clone() as Arc<dyn ProgressiveChannelTransport>,
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 352ecfde89..a29900f661 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
@@ -6,8 +6,6 @@ use crate::channels::runtime::dispatch::RuntimeChannelMessage;
use crate::config::Config;
use crate::modules::channel_runtime::ChannelRuntimeLease;
use anyhow::{Context, Result};
-#[cfg(test)]
-use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock, Weak};
use tinybus::module::{ModuleCallError, ModuleClient, ModuleObjectClient};
@@ -15,13 +13,8 @@ use tinychannels_bus::module_runtime::{
ChannelIngressKind, ChannelMessagePreparation, ConfiguredChannelInfo,
};
use tinychannels_bus::module_supervision::ChannelSupervisionPolicy;
-#[cfg(test)]
-use tinychannels_bus::ChannelMessage;
use tinychannels_bus::SendMessage;
use tinychannels_bus::{ChannelInteraction, ChannelInteractionResult};
-#[cfg(test)]
-use tinychannels_runtime::Channel;
-use tokio::sync::mpsc;
/// Channel objects sharing one captured config, callback object and module lease.
pub(super) struct ModuleChannelRuntime {
@@ -31,9 +24,6 @@ pub(super) struct ModuleChannelRuntime {
proxy: tinychannels_bus::HttpProxyPolicy,
infos: Vec<ConfiguredChannelInfo>,
relay: Option<tinychannels_bus::module_relay::RelayReservation>,
- #[cfg(test)]
- channels: Arc<HashMap<String, Arc<dyn Channel>>>,
- #[cfg(not(test))]
channels: Arc<HashMap<String, Arc<super::ChannelHandle>>>,
closed: bool,
}
@@ -144,9 +134,6 @@ impl ModuleChannelRuntime {
.any(|identity| identity.platform == channel)
})
};
- #[cfg(test)]
- let mut channels: HashMap<String, Arc<dyn Channel>> = HashMap::new();
- #[cfg(not(test))]
let mut channels: HashMap<String, Arc<super::ChannelHandle>> = HashMap::new();
let mut progressive = HashMap::new();
for info in &infos {
@@ -158,9 +145,6 @@ impl ModuleChannelRuntime {
relay_fronted: relay_fronts(&info.name),
};
let channel = Arc::new(channel);
- #[cfg(test)]
- channels.insert(info.name.clone(), channel.clone() as Arc<dyn Channel>);
- #[cfg(not(test))]
channels.insert(
info.name.clone(),
Arc::new(super::ChannelHandle::Module((*channel).clone())),
@@ -185,12 +169,6 @@ impl ModuleChannelRuntime {
})
}
- #[cfg(test)]
- pub(super) fn channels(&self) -> Arc<HashMap<String, Arc<dyn Channel>>> {
- Arc::clone(&self.channels)
- }
-
- #[cfg(not(test))]
pub(super) fn channels(&self) -> Arc<HashMap<String, Arc<super::ChannelHandle>>> {
Arc::clone(&self.channels)
}
@@ -450,65 +428,6 @@ impl ModuleChannel {
}
}
-#[cfg(test)]
-#[async_trait]
-impl Channel for ModuleChannel {
- fn name(&self) -> &str {
- ModuleChannel::name(self)
- }
-
- fn proactive_target(&self) -> Option<String> {
- ModuleChannel::proactive_target(self)
- }
-
- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
- ModuleChannel::send(self, message).await
- }
-
- async fn listen(&self, _tx: mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
- anyhow::bail!("TinyChannels module owns provider listeners")
- }
-
- async fn send_typed_with_receipt(
- &self,
- message: &tinychannels_bus::channel::ChannelOutboundMessage,
- ) -> anyhow::Result<tinychannels_bus::channel::ChannelSendOutcome> {
- ModuleChannel::send_typed_with_receipt(self, message).await
- }
-
- async fn health_check(&self) -> bool {
- ModuleChannel::health_check(self).await
- }
-
- async fn start_typing(&self, recipient: &str) -> anyhow::Result<()> {
- ModuleChannel::start_typing(self, recipient).await
- }
-
- async fn stop_typing(&self, recipient: &str) -> anyhow::Result<()> {
- ModuleChannel::stop_typing(self, recipient).await
- }
-
- async fn begin_typing_refresh(
- &self,
- recipient: &str,
- interval_secs: u64,
- ) -> anyhow::Result<Option<String>> {
- ModuleChannel::begin_typing_refresh(self, recipient, interval_secs).await
- }
-
- async fn end_typing_refresh(&self, handle: &str) -> anyhow::Result<()> {
- ModuleChannel::end_typing_refresh(self, handle).await
- }
-
- fn capabilities(&self) -> tinychannels_bus::ChannelCapabilities {
- ModuleChannel::capabilities(self)
- }
-
- fn supports_reactions(&self) -> bool {
- ModuleChannel::supports_reactions(self)
- }
-}
-
impl ModuleChannel {
pub(super) async fn send_progressive_typed(
&self,
diff --git a/crates/openhuman-core/src/channels/runtime/test_support.rs b/crates/openhuman-core/src/channels/runtime/test_support.rs
index 480a689034..dc4ae7560b 100644
--- a/crates/openhuman-core/src/channels/runtime/test_support.rs
+++ b/crates/openhuman-core/src/channels/runtime/test_support.rs
@@ -20,8 +20,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tinyagents_harness::progress::AgentProgress;
-use tinychannels_bus::{ChannelMessage, SendMessage};
-use tinychannels_runtime::Channel;
+use tinychannels_bus::ChannelMessage;
use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};
use tinytools::{Tool, ToolResult};
use wiremock::matchers::{method, path};
@@ -224,54 +223,6 @@ pub(crate) async fn linked_telegram_runtime() -> LinkedTelegramRuntime {
}
}
-#[derive(Default)]
-struct HarnessState {
- sends: tokio::sync::Mutex<Vec<ObservedSend>>,
- start_typing_calls: AtomicUsize,
- stop_typing_calls: AtomicUsize,
-}
-
-struct HarnessChannel {
- name: String,
- supports_reactions: bool,
- state: Arc<HarnessState>,
-}
-
-#[async_trait]
-impl Channel for HarnessChannel {
- fn name(&self) -> &str {
- &self.name
- }
-
- async fn send(&self, message: &SendMessage) -> Result<()> {
- self.state.sends.lock().await.push(ObservedSend {
- kind: "send",
- recipient: message.recipient.clone(),
- content: message.content.clone(),
- thread_ts: message.thread_ts.clone(),
- });
- Ok(())
- }
-
- async fn listen(&self, _tx: tokio::sync::mpsc::Sender<ChannelMessage>) -> Result<()> {
- Ok(())
- }
-
- async fn start_typing(&self, _recipient: &str) -> Result<()> {
- self.state.start_typing_calls.fetch_add(1, Ordering::SeqCst);
- Ok(())
- }
-
- async fn stop_typing(&self, _recipient: &str) -> Result<()> {
- self.state.stop_typing_calls.fetch_add(1, Ordering::SeqCst);
- Ok(())
- }
-
- fn supports_reactions(&self) -> bool {
- self.supports_reactions
- }
-}
-
struct HarnessModel;
#[async_trait]
@@ -412,24 +363,14 @@ pub async fn run_dispatch_harness(options: DispatchHarnessOptions) -> DispatchHa
}
});
- let state = Arc::new(HarnessState::default());
- let channel_impl = Arc::new(HarnessChannel {
- name: options.channel_name.clone(),
- supports_reactions: options.supports_reactions,
- state: Arc::clone(&state),
- });
- #[cfg(test)]
- let channel: Arc<dyn Channel> = channel_impl;
- #[cfg(test)]
- let mut channels_by_name = HashMap::new();
- #[cfg(test)]
- channels_by_name.insert(options.channel_name.clone(), channel);
- #[cfg(not(test))]
+ let state = Arc::new(crate::channels::runtime::TestChannel::new(
+ options.channel_name.clone(),
+ ));
+ state.supports_reactions = options.supports_reactions;
let mut channels_by_name = HashMap::new();
- #[cfg(not(test))]
channels_by_name.insert(
options.channel_name.clone(),
- Arc::new(crate::channels::runtime::ChannelHandle::Test(channel_impl)),
+ Arc::new(crate::channels::runtime::ChannelHandle::Test(Arc::clone(&state))),
);
let model: Arc<dyn ChatModel<()>> = Arc::new(HarnessModel);
@@ -511,7 +452,18 @@ pub async fn run_dispatch_harness(options: DispatchHarnessOptions) -> DispatchHa
}
};
- let sends = state.sends.lock().await.clone();
+ let sends = state
+ .sent
+ .lock()
+ .expect("test sends lock")
+ .iter()
+ .map(|message| ObservedSend {
+ kind: "send",
+ recipient: message.recipient.clone(),
+ content: message.content.clone(),
+ thread_ts: message.thread_ts.clone(),
+ })
+ .collect();
let handler_history_roles = handler_roles.lock().expect("roles lock").clone();
let handler_history_text = handler_text.lock().expect("text lock").clone();
let handler_provider_name = handler_provider.lock().expect("provider lock").clone();
diff --git a/crates/openhuman-core/src/channels/tests/common.rs b/crates/openhuman-core/src/channels/tests/common.rs
index b1f1e290a6..048faa4fd2 100644
--- a/crates/openhuman-core/src/channels/tests/common.rs
+++ b/crates/openhuman-core/src/channels/tests/common.rs
@@ -1,10 +1,8 @@
-use crate::channels::SendMessage;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tempfile::TempDir;
-use tinychannels_bus as traits;
-use tinychannels_runtime::Channel;
+use crate::channels::runtime::TestChannel;
use tinyinference_llm::message::{AssistantMessage, Message};
use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
use tinyinference_llm::tool::ToolCall;
@@ -91,79 +89,7 @@ impl ChatModel<()> for DummyModel {
}
}
-#[derive(Default)]
-pub(super) struct RecordingChannel {
- pub(super) sent_messages: tokio::sync::Mutex<Vec<String>>,
- pub(super) start_typing_calls: AtomicUsize,
- pub(super) stop_typing_calls: AtomicUsize,
-}
-
-#[derive(Default)]
-pub(super) struct TelegramRecordingChannel {
- pub(super) sent_messages: tokio::sync::Mutex<Vec<String>>,
-}
-
-#[async_trait::async_trait]
-impl Channel for TelegramRecordingChannel {
- fn name(&self) -> &str {
- "telegram"
- }
-
- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
- self.sent_messages
- .lock()
- .await
- .push(format!("{}:{}", message.recipient, message.content));
- Ok(())
- }
-
- async fn listen(
- &self,
- _tx: tokio::sync::mpsc::Sender<traits::ChannelMessage>,
- ) -> anyhow::Result<()> {
- Ok(())
- }
-
- async fn start_typing(&self, _recipient: &str) -> anyhow::Result<()> {
- Ok(())
- }
-
- async fn stop_typing(&self, _recipient: &str) -> anyhow::Result<()> {
- Ok(())
- }
-}
-
-#[async_trait::async_trait]
-impl Channel for RecordingChannel {
- fn name(&self) -> &str {
- "test-channel"
- }
-
- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
- self.sent_messages
- .lock()
- .await
- .push(format!("{}:{}", message.recipient, message.content));
- Ok(())
- }
-
- async fn listen(
- &self,
- _tx: tokio::sync::mpsc::Sender<traits::ChannelMessage>,
- ) -> anyhow::Result<()> {
- Ok(())
- }
-
- async fn start_typing(&self, _recipient: &str) -> anyhow::Result<()> {
- self.start_typing_calls.fetch_add(1, Ordering::SeqCst);
- Ok(())
- }
-
- async fn stop_typing(&self, _recipient: &str) -> anyhow::Result<()> {
- self.stop_typing_calls.fetch_add(1, Ordering::SeqCst);
- Ok(())
- }
-}
+pub(super) type RecordingChannel = TestChannel;
pub(super) struct SlowModel {
pub(super) delay: Duration,
@@ -345,26 +271,3 @@ impl Tool for MockPriceTool {
}
}
-pub(super) struct AlwaysFailChannel {
- pub(super) name: &'static str,
- pub(super) calls: Arc<AtomicUsize>,
-}
-
-#[async_trait::async_trait]
-impl Channel for AlwaysFailChannel {
- fn name(&self) -> &str {
- self.name
- }
-
- async fn send(&self, _message: &SendMessage) -> anyhow::Result<()> {
- Ok(())
- }
-
- async fn listen(
- &self,
- _tx: tokio::sync::mpsc::Sender<traits::ChannelMessage>,
- ) -> anyhow::Result<()> {
- self.calls.fetch_add(1, Ordering::SeqCst);
- anyhow::bail!("listen boom")
- }
-}
diff --git a/crates/openhuman-core/src/channels/tests/mod.rs b/crates/openhuman-core/src/channels/tests/mod.rs
index 67380b4147..fadd5ca672 100644
--- a/crates/openhuman-core/src/channels/tests/mod.rs
+++ b/crates/openhuman-core/src/channels/tests/mod.rs
@@ -6,9 +6,8 @@
//!
//! `common.rs` holds the shared fixtures the files below build on: fake
//! models per scenario (`DummyModel`, `SlowModel`, `ToolCallingModel`,
-//! `IterativeToolModel`, `HistoryCaptureModel`, `ModelCaptureModel`), fake
-//! `Channel` implementations that record sends or always fail
-//! (`RecordingChannel`, `TelegramRecordingChannel`, `AlwaysFailChannel`), a
+//! `IterativeToolModel`, `HistoryCaptureModel`, `ModelCaptureModel`), a
+//! concrete test channel handle that records sends and typing calls,
//! `MockPriceTool`, `make_workspace` for identity-file
//! fixtures, and a re-export of `agent::bus::use_real_agent_handler`.
//!
diff --git a/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs b/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs
index 7a3b55b319..a716545afc 100644
--- a/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs
+++ b/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs
@@ -14,7 +14,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tinychannels_bus as traits;
-use tinychannels_runtime::Channel;
+use crate::channels::runtime::ChannelHandle;
use tokio::sync::Barrier;
#[tokio::test]
@@ -113,7 +113,7 @@ async fn message_dispatch_processes_messages_in_parallel() {
let build_runtime = || {
let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel = Arc::new(ChannelHandle::Test(channel_impl.clone()));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
@@ -302,7 +302,7 @@ async fn dispatch_routes_through_agent_run_turn_bus_handler() {
.await;
let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel = Arc::new(ChannelHandle::Test(channel_impl.clone()));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
@@ -428,7 +428,7 @@ fn unrelated_processed_event(n: usize) -> DomainEvent {
async fn resolved_route_ctx() -> Arc<ChannelRuntimeContext> {
let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl;
+ let channel = Arc::new(ChannelHandle::Test(channel_impl));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
@@ -555,7 +555,7 @@ async fn process_channel_message_hardens_multimodal_files_against_smuggled_marke
.await;
let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel = Arc::new(ChannelHandle::Test(channel_impl.clone()));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
@@ -651,7 +651,7 @@ async fn process_channel_message_hardens_against_relative_path_markers() {
.await;
let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel = Arc::new(ChannelHandle::Test(channel_impl.clone()));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
diff --git a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs
index 79febb5c83..6577ee7428 100644
--- a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs
+++ b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs
@@ -5,21 +5,22 @@ use super::super::context::{
use super::super::runtime::process_channel_message;
use super::common::{
IterativeToolModel, MockPriceTool, ModelCaptureModel, RecordingChannel,
- TelegramRecordingChannel, ToolCallingModel,
+ ToolCallingModel,
};
+use crate::channels::runtime::TestChannel;
use crate::inference::provider;
use std::collections::HashMap;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};
use tinychannels_bus as traits;
-use tinychannels_runtime::Channel;
+use crate::channels::runtime::ChannelHandle;
use tinyinference_llm::model::ChatModel;
#[tokio::test]
async fn process_channel_message_executes_native_tool_calls() {
let _bus_guard = super::common::use_real_agent_handler().await;
let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel = Arc::new(ChannelHandle::Test(channel_impl.clone()));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
@@ -78,8 +79,8 @@ async fn process_channel_message_executes_native_tool_calls() {
#[tokio::test]
async fn process_channel_message_handles_models_command_without_llm_call() {
let _bus_guard = super::common::use_real_agent_handler().await;
- let channel_impl = Arc::new(TelegramRecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_impl = Arc::new(TestChannel::new("telegram"));
+ let channel = Arc::new(ChannelHandle::Test(channel_impl.clone()));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
@@ -162,8 +163,8 @@ async fn process_channel_message_handles_models_command_without_llm_call() {
#[tokio::test]
async fn process_channel_message_uses_route_override_provider_and_model() {
let _bus_guard = super::common::use_real_agent_handler().await;
- let channel_impl = Arc::new(TelegramRecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel_impl = Arc::new(TestChannel::new("telegram"));
+ let channel = Arc::new(ChannelHandle::Test(channel_impl.clone()));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
@@ -250,7 +251,7 @@ async fn process_channel_message_uses_route_override_provider_and_model() {
async fn process_channel_message_respects_configured_max_tool_iterations_above_default() {
let _bus_guard = super::common::use_real_agent_handler().await;
let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel = Arc::new(ChannelHandle::Test(channel_impl.clone()));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
@@ -312,7 +313,7 @@ async fn process_channel_message_respects_configured_max_tool_iterations_above_d
async fn process_channel_message_reports_configured_max_tool_iterations_limit() {
let _bus_guard = super::common::use_real_agent_handler().await;
let channel_impl = Arc::new(RecordingChannel::default());
- let channel: Arc<dyn Channel> = channel_impl.clone();
+ let channel = Arc::new(ChannelHandle::Test(channel_impl.clone()));
let mut channels_by_name = HashMap::new();
channels_by_name.insert(channel.name().to_string(), channel);
diff --git a/crates/openhuman-core/src/cron/bus_tests.rs b/crates/openhuman-core/src/cron/bus_tests.rs
index 643cda71d1..0aa9eac9f1 100644
--- a/crates/openhuman-core/src/cron/bus_tests.rs
+++ b/crates/openhuman-core/src/cron/bus_tests.rs
@@ -1,31 +1,6 @@
use super::*;
-use std::sync::atomic::{AtomicUsize, Ordering};
-use tinychannels_bus::ChannelMessage;
-use tokio::sync::mpsc;
-
-/// Minimal mock channel that tracks send() calls.
-struct MockChannel {
- name: String,
- send_count: Arc<AtomicUsize>,
- fail: bool,
-}
-
-#[async_trait]
-impl Channel for MockChannel {
- fn name(&self) -> &str {
- &self.name
- }
- async fn send(&self, _message: &SendMessage) -> anyhow::Result<()> {
- self.send_count.fetch_add(1, Ordering::SeqCst);
- if self.fail {
- anyhow::bail!("mock send failure");
- }
- Ok(())
- }
- async fn listen(&self, _tx: mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
- Ok(())
- }
-}
+use crate::channels::runtime::{ChannelHandle, TestChannel};
+use std::sync::atomic::Ordering;
fn delivery_event(channel: &str) -> DomainEvent {
DomainEvent::CronDeliveryRequested {
@@ -36,22 +11,24 @@ fn delivery_event(channel: &str) -> DomainEvent {
}
}
-fn make_subscriber(channels: Vec<Arc<dyn Channel>>) -> CronDeliverySubscriber {
- let map: HashMap<String, Arc<dyn Channel>> = channels
+fn test_channel(name: &str, fail: bool) -> (Arc<ChannelHandle>, Arc<TestChannel>) {
+ let mut state = TestChannel::new(name);
+ state.send_error = fail.then(|| "mock send failure".to_owned());
+ let state = Arc::new(state);
+ (Arc::new(ChannelHandle::Test(Arc::clone(&state))), state)
+}
+
+fn make_subscriber(channels: Vec<Arc<ChannelHandle>>) -> CronDeliverySubscriber {
+ let map: HashMap<String, Arc<ChannelHandle>> = channels
.into_iter()
- .map(|c| (c.name().to_string(), c))
+ .map(|channel| (channel.name().to_string(), channel))
.collect();
CronDeliverySubscriber::new(Arc::new(map))
}
#[tokio::test]
async fn ignores_non_delivery_events() {
- let send_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel {
- name: "telegram".into(),
- send_count: Arc::clone(&send_count),
- fail: false,
- });
+ let (ch, state) = test_channel("telegram", false);
let sub = make_subscriber(vec![ch]);
sub.handle(&DomainEvent::CronJobTriggered {
@@ -61,22 +38,17 @@ async fn ignores_non_delivery_events() {
})
.await;
- assert_eq!(send_count.load(Ordering::SeqCst), 0);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn dispatches_to_matching_channel() {
- let send_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel {
- name: "telegram".into(),
- send_count: Arc::clone(&send_count),
- fail: false,
- });
+ let (ch, state) = test_channel("telegram", false);
let sub = make_subscriber(vec![ch]);
sub.handle(&delivery_event("Telegram")).await;
- assert_eq!(send_count.load(Ordering::SeqCst), 1);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 1);
}
#[tokio::test]
@@ -88,15 +60,10 @@ async fn missing_channel_does_not_panic() {
#[tokio::test]
async fn send_failure_does_not_panic() {
- let send_count = Arc::new(AtomicUsize::new(0));
- let ch: Arc<dyn Channel> = Arc::new(MockChannel {
- name: "slack".into(),
- send_count: Arc::clone(&send_count),
- fail: true,
- });
+ let (ch, state) = test_channel("slack", true);
let sub = make_subscriber(vec![ch]);
// Should log a warning but not panic.
sub.handle(&delivery_event("slack")).await;
- assert_eq!(send_count.load(Ordering::SeqCst), 1);
+ assert_eq!(state.send_count.load(Ordering::SeqCst), 1);
}