Skip to content

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

feat(channels): add backend controller for channel messaging

Steven Enamakel240c0c10cfdb
diff --git a/crates/openhuman-core/src/channels/controllers/backend.rs b/crates/openhuman-core/src/channels/controllers/backend.rs
index 62b77a0bd7..e883cadf82 100644
--- a/crates/openhuman-core/src/channels/controllers/backend.rs
+++ b/crates/openhuman-core/src/channels/controllers/backend.rs
@@ -126,86 +126,6 @@ fn into_anyhow<T>(result: Result<Outcome<T>, String>) -> anyhow::Result<T> {
.map_err(anyhow::Error::msg)
}
-fn parse_or_raw<T>(value: Value) -> T
-where
- T: Default + serde::de::DeserializeOwned,
- T: RawFallback,
-{
- serde_json::from_value::<T>(value.clone())
- .map(|parsed| parsed.with_raw_if_absent(value.clone()))
- .unwrap_or_else(|_| T::with_raw(value))
-}
-
-trait RawFallback {
- fn with_raw(value: Value) -> Self;
- fn with_raw_if_absent(self, value: Value) -> Self;
-}
-
-impl RawFallback for ChannelSendMessageResult {
- fn with_raw(value: Value) -> Self {
- Self {
- raw: Some(value),
- ..Default::default()
- }
- }
-
- fn with_raw_if_absent(mut self, value: Value) -> Self {
- if self.raw.is_none() {
- self.raw = Some(value);
- }
- self
- }
-}
-
-impl RawFallback for ChannelReactionResult {
- fn with_raw(value: Value) -> Self {
- Self {
- success: true,
- raw: Some(value),
- ..Default::default()
- }
- }
-
- fn with_raw_if_absent(mut self, value: Value) -> Self {
- if self.raw.is_none() {
- self.raw = Some(value);
- }
- self
- }
-}
-
-impl RawFallback for ChannelThreadResult {
- fn with_raw(value: Value) -> Self {
- Self {
- raw: Some(value),
- ..Default::default()
- }
- }
-
- fn with_raw_if_absent(mut self, value: Value) -> Self {
- if self.raw.is_none() {
- self.raw = Some(value);
- }
- self
- }
-}
-
-impl RawFallback for ChannelThreadListResult {
- fn with_raw(value: Value) -> Self {
- Self {
- raw: Some(value),
- ..Default::default()
- }
- }
-
- fn with_raw_if_absent(mut self, value: Value) -> Self {
- if self.raw.is_none() {
- self.raw = Some(value);
- }
- self
- }
-}
-
#[cfg(test)]
fn send_message_payload(message: SendMessage) -> Value {
json!({
@@ -269,15 +189,49 @@ impl OpenHumanChannelBackend {
into_anyhow(ops::channel_status(&config, channel).await)
}
+ /// Runs `request` through the registered channel callback
+ /// (`channels::callback_slot`), which serves the managed-channel requests
+ /// (reactions, threads). With none registered the call answers the
+ /// `BACKEND_UNAVAILABLE:` sentinel.
+ async fn via_callback(
+ &self,
+ channels_config: &ChannelsConfig,
+ channel: &str,
+ request: tinychannels_bus::ChannelBackendRequest,
+ ) -> anyhow::Result<tinychannels_bus::ChannelBackendResult> {
+ let Some(callback) = crate::channels::callback_slot::current() else {
+ tracing::debug!(channel, "[channels][backend] no channel callback registered");
+ anyhow::bail!(
+ "{} no channel transport registered",
+ crate::core::observability::BACKEND_UNAVAILABLE_PREFIX
+ );
+ };
+ callback(
+ crate::channels::callback_slot::ChannelCallbackCtx {
+ config: self.config_with_channels(channels_config),
+ channel: Some(channel.to_string()),
+ session: tokio_util::sync::CancellationToken::new(),
+ },
+ request,
+ )
+ .await
+ }
+
pub(crate) async fn send_reaction(
&self,
channels_config: &ChannelsConfig,
channel: &str,
reaction: Value,
) -> anyhow::Result<ChannelReactionResult> {
- let config = self.config_with_channels(channels_config);
- let value = into_anyhow(ops::channel_send_reaction(&config, channel, reaction).await)?;
- Ok(parse_or_raw(value))
+ use tinychannels_bus::{ChannelBackendRequest as Request, ChannelBackendResult as Result};
+ let request = Request::SendReaction {
+ channel: channel.to_string(),
+ reaction,
+ };
+ match self.via_callback(channels_config, channel, request).await? {
+ Result::SendReaction(result) => Ok(result),
+ _ => anyhow::bail!("channel callback answered a different request"),
+ }
}
pub(crate) async fn create_thread(
@@ -286,9 +240,15 @@ impl OpenHumanChannelBackend {
channel: &str,
title: &str,
) -> anyhow::Result<ChannelThreadResult> {
- let config = self.config_with_channels(channels_config);
- let value = into_anyhow(ops::channel_create_thread(&config, channel, title).await)?;
- Ok(parse_or_raw(value))
+ use tinychannels_bus::{ChannelBackendRequest as Request, ChannelBackendResult as Result};
+ let request = Request::CreateThread {
+ channel: channel.to_string(),
+ title: title.to_string(),
+ };
+ match self.via_callback(channels_config, channel, request).await? {
+ Result::Thread(result) => Ok(result),
+ _ => anyhow::bail!("channel callback answered a different request"),
+ }
}
pub(crate) async fn update_thread(
@@ -298,10 +258,16 @@ impl OpenHumanChannelBackend {
thread_id: &str,
action: &str,
) -> anyhow::Result<ChannelThreadResult> {
- let config = self.config_with_channels(channels_config);
- let value =
- into_anyhow(ops::channel_update_thread(&config, channel, thread_id, action).await)?;
- Ok(parse_or_raw(value))
+ use tinychannels_bus::{ChannelBackendRequest as Request, ChannelBackendResult as Result};
+ let request = Request::UpdateThread {
+ channel: channel.to_string(),
+ thread_id: thread_id.to_string(),
+ action: action.to_string(),
+ };
+ match self.via_callback(channels_config, channel, request).await? {
+ Result::Thread(result) => Ok(result),
+ _ => anyhow::bail!("channel callback answered a different request"),
+ }
}
pub(crate) async fn list_threads(
@@ -310,9 +276,15 @@ impl OpenHumanChannelBackend {
channel: &str,
active: Option<bool>,
) -> anyhow::Result<ChannelThreadListResult> {
- let config = self.config_with_channels(channels_config);
- let value = into_anyhow(ops::channel_list_threads(&config, channel, active).await)?;
- Ok(parse_or_raw(value))
+ use tinychannels_bus::{ChannelBackendRequest as Request, ChannelBackendResult as Result};
+ let request = Request::ListThreads {
+ channel: channel.to_string(),
+ active,
+ };
+ match self.via_callback(channels_config, channel, request).await? {
+ Result::Threads(result) => Ok(result),
+ _ => anyhow::bail!("channel callback answered a different request"),
+ }
}
}
diff --git a/crates/openhuman-core/src/channels/controllers/backend_tests.rs b/crates/openhuman-core/src/channels/controllers/backend_tests.rs
index 72e351de5f..bf5e846090 100644
--- a/crates/openhuman-core/src/channels/controllers/backend_tests.rs
+++ b/crates/openhuman-core/src/channels/controllers/backend_tests.rs
@@ -1,5 +1,4 @@
use super::*;
-use tinychannels_bus::controllers::ChannelThreadListResult;
#[test]
fn send_message_payload_preserves_thread_and_subject() {
@@ -12,14 +11,6 @@ fn send_message_payload_preserves_thread_and_subject() {
assert_eq!(payload["thread_ts"], "thread-1");
}
-#[test]
-fn parse_or_raw_keeps_backend_payload_when_shape_is_unknown() {
- let payload = json!({"unexpected": true});
- let result: ChannelThreadListResult = parse_or_raw(payload.clone());
- assert_eq!(result.threads.len(), 0);
- assert_eq!(result.raw, Some(payload));
-}
-
#[test]
fn disconnect_result_projects_restart_flag() {
let payload =
diff --git a/crates/openhuman-core/src/channels/controllers/ops/messaging.rs b/crates/openhuman-core/src/channels/controllers/ops/messaging.rs
deleted file mode 100644
index 1b2316d0ba..0000000000
--- a/crates/openhuman-core/src/channels/controllers/ops/messaging.rs
+++ /dev/null
@@ -1,137 +0,0 @@
-//! Channel messaging, reactions, and thread management.
-
-use serde_json::Value;
-
-use crate::backend::BackendClient;
-use crate::config::Config;
-use crate::core::Outcome;
-use crate::security::credentials::session_support::resolve_backend_credential;
-
-/// Send a reaction to a message in a channel via the backend API.
-pub async fn channel_send_reaction(
- config: &Config,
- channel: &str,
- reaction: Value,
-) -> Result<Outcome<Value>, String> {
- let api_url = crate::backend::require_base_url(&config.api_url)?;
- let jwt = resolve_backend_credential(config)?;
-
- log::debug!(
- "[channels] sending reaction to channel '{}' via {}",
- channel,
- api_url
- );
-
- let client = BackendClient::new(&api_url).map_err(|e| e.to_string())?;
- let result = client
- .send_channel_reaction(channel, &jwt, reaction)
- .await
- .map_err(|e| {
- format!(
- "failed to send channel reaction: {}",
- crate::backend::flatten_authed_error(e)
- )
- })?;
-
- log::debug!("[channels] send_reaction response: {:?}", result);
-
- Ok(Outcome::new(result, vec![]))
-}
-
-/// Create a thread in a channel via the backend API.
-pub async fn channel_create_thread(
- config: &Config,
- channel: &str,
- title: &str,
-) -> Result<Outcome<Value>, String> {
- let api_url = crate::backend::require_base_url(&config.api_url)?;
- let jwt = resolve_backend_credential(config)?;
-
- log::debug!(
- "[channels] creating thread in channel '{}' title='{}' via {}",
- channel,
- title,
- api_url
- );
-
- let client = BackendClient::new(&api_url).map_err(|e| e.to_string())?;
- let result = client
- .create_channel_thread(channel, &jwt, title)
- .await
- .map_err(|e| {
- format!(
- "failed to create channel thread: {}",
- crate::backend::flatten_authed_error(e)
- )
- })?;
-
- log::debug!("[channels] create_thread response: {:?}", result);
-
- Ok(Outcome::new(result, vec![]))
-}
-
-/// Close or reopen a thread in a channel via the backend API.
-pub async fn channel_update_thread(
- config: &Config,
- channel: &str,
- thread_id: &str,
- action: &str,
-) -> Result<Outcome<Value>, String> {
- let api_url = crate::backend::require_base_url(&config.api_url)?;
- let jwt = resolve_backend_credential(config)?;
-
- log::debug!(
- "[channels] updating thread '{}' in channel '{}' action='{}' via {}",
- thread_id,
- channel,
- action,
- api_url
- );
-
- let client = BackendClient::new(&api_url).map_err(|e| e.to_string())?;
- let result = client
- .update_channel_thread(channel, &jwt, thread_id, action)
- .await
- .map_err(|e| {
- format!(
- "failed to update channel thread: {}",
- crate::backend::flatten_authed_error(e)
- )
- })?;
-
- log::debug!("[channels] update_thread response: {:?}", result);
-
- Ok(Outcome::new(result, vec![]))
-}
-
-/// List threads in a channel via the backend API.
-pub async fn channel_list_threads(
- config: &Config,
- channel: &str,
- active: Option<bool>,
-) -> Result<Outcome<Value>, String> {
- let api_url = crate::backend::require_base_url(&config.api_url)?;
- let jwt = resolve_backend_credential(config)?;
-
- log::debug!(
- "[channels] listing threads in channel '{}' active={:?} via {}",
- channel,
- active,
- api_url
- );
-
- let client = BackendClient::new(&api_url).map_err(|e| e.to_string())?;
- let result = client
- .list_channel_threads(channel, &jwt, active)
- .await
- .map_err(|e| {
- format!(
- "failed to list channel threads: {}",
- crate::backend::flatten_authed_error(e)
- )
- })?;
-
- log::debug!("[channels] list_threads response: {:?}", result);
-
- Ok(Outcome::new(result, vec![]))
-}
diff --git a/crates/openhuman-core/src/channels/controllers/ops/mod.rs b/crates/openhuman-core/src/channels/controllers/ops/mod.rs
index 0cc30f713c..56d5d3d257 100644
--- a/crates/openhuman-core/src/channels/controllers/ops/mod.rs
+++ b/crates/openhuman-core/src/channels/controllers/ops/mod.rs
@@ -2,7 +2,6 @@
mod connect;
mod discord;
-mod messaging;
// Re-export types needed by tests.
#[cfg(test)]
@@ -16,9 +15,6 @@ pub use connect::{
get_default_channel, set_default_channel, test_channel,
};
pub use discord::{discord_check_permissions, discord_list_channels, discord_list_guilds};
-pub use messaging::{
- channel_create_thread, channel_list_threads, channel_send_reaction, channel_update_thread,
-};
#[cfg(test)]
#[path = "../ops_tests.rs"]