The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(channels): delegate channel health checks to tinychannels
Steven Enamakelc5b2c0636ae5
diff --git a/crates/openhuman-core/src/channels/commands.rs b/crates/openhuman-core/src/channels/commands.rsindex 3ce70eb852..0017301c42 100644--- a/crates/openhuman-core/src/channels/commands.rs+++ b/crates/openhuman-core/src/channels/commands.rs@@ -1,240 +1,43 @@-//! Channel command handling and health checks.+//! `doctor channels`: health checks for every configured real-time channel.+//!+//! Channels are built by `tinychannels::build_channels` from the same hydrated+//! config the runtime uses, and checked by `tinychannels::runtime`; this module+//! only prints the report.-use super::dingtalk::DingTalkChannel;-use super::discord::DiscordChannel;-use super::email_channel::EmailChannel;-use super::imessage::IMessageChannel;-use super::irc;-use super::irc::IrcChannel;-use super::lark::LarkChannel;-use super::linq::LinqChannel;-use super::qq::QQChannel;-use super::signal::SignalChannel;-use super::slack::SlackChannel;-use super::telegram::TelegramChannel;-use super::whatsapp::WhatsAppChannel;-#[cfg(feature = "whatsapp-web")]-use super::whatsapp_web::WhatsAppWebChannel;-use super::yuanbao::YuanbaoChannel;-use super::Channel;+use super::runtime::{hydrate_channel_credentials, RuntimeProxyClients};use crate::config::Config;use anyhow::Result;use std::sync::Arc;use std::time::Duration;+use tinychannels::runtime::{check_channels_health, ChannelHealthState};-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(crate) enum ChannelHealthState {- Healthy,- Unhealthy,- Timeout,+/// Per-channel health-check budget.+const HEALTH_CHECK_TIMEOUT: Duration = Duration::from_secs(10);++/// Display label for a channel id (`telegram` → `Telegram`).+fn channel_label(channel: &str) -> String {+ tinychannels::controllers::find_channel_definition(channel)+ .map(|definition| definition.display_name.to_string())+ .unwrap_or_else(|| channel.to_string())}-pub(crate) fn classify_health_result(- result: &std::result::Result<bool, tokio::time::error::Elapsed>,-) -> ChannelHealthState {- match result {- Ok(true) => ChannelHealthState::Healthy,- Ok(false) => ChannelHealthState::Unhealthy,- Err(_) => ChannelHealthState::Timeout,+/// One report line for a channel's health state.+fn report_line(label: &str, state: ChannelHealthState) -> String {+ match state {+ ChannelHealthState::Healthy => format!(" ✅ {label:<9} healthy"),+ ChannelHealthState::Unhealthy => format!(" ❌ {label:<9} unhealthy (auth/config/network)"),+ ChannelHealthState::Timeout => format!(" ⏱️ {label:<9} timed out (>10s)"),}}/// Run health checks for configured channels.pub async fn doctor_channels(config: Config) -> Result<()> {- let mut channels: Vec<(&'static str, Arc<dyn Channel>)> = Vec::new();-- if let Some(ref tg) = config.channels_config.telegram {- channels.push((- "Telegram",- Arc::new(- TelegramChannel::new(- tg.bot_token.clone(),- tg.allowed_users.clone(),- tg.mention_only,- )- .with_streaming(- tg.stream_mode,- tg.draft_update_interval_ms,- tg.silent_streaming,- ),- ),- ));- }-- if let Some(ref dc) = config.channels_config.discord {- channels.push((- "Discord",- Arc::new(DiscordChannel::with_http_client(- dc.bot_token.clone(),- dc.guild_id.clone(),- dc.channel_id.clone(),- dc.allowed_users.clone(),- dc.listen_to_bots,- dc.mention_only,- crate::config::build_runtime_proxy_client("channel.discord"),- )),- ));- }-- if let Some(ref sl) = config.channels_config.slack {- channels.push((- "Slack",- Arc::new(SlackChannel::with_http_client(- sl.bot_token.clone(),- sl.channel_id.clone(),- sl.allowed_users.clone(),- crate::config::build_runtime_proxy_client("channel.slack"),- )),- ));- }-- if let Some(ref im) = config.channels_config.imessage {- channels.push((- "iMessage",- Arc::new(IMessageChannel::new(im.allowed_contacts.clone())),- ));- }-- if config.channels_config.matrix.is_some() {- tracing::warn!(- "Matrix channel is configured but Matrix support was removed from this build; skipping Matrix health check."- );- }-- if let Some(ref sig) = config.channels_config.signal {- channels.push((- "Signal",- Arc::new(SignalChannel::with_http_client(- sig.http_url.clone(),- sig.account.clone(),- sig.group_id.clone(),- sig.allowed_from.clone(),- sig.ignore_attachments,- sig.ignore_stories,- crate::config::apply_runtime_proxy_to_builder(- reqwest::Client::builder().connect_timeout(std::time::Duration::from_secs(10)),- "channel.signal",- )- .build()- .expect("Signal HTTP client should build"),- )),- ));- }-- if let Some(ref wa) = config.channels_config.whatsapp {- // Runtime negotiation: detect backend type from config- match wa.backend_type() {- "cloud" => {- // Cloud API mode: requires phone_number_id, access_token, verify_token- if wa.is_cloud_config() {- channels.push((- "WhatsApp",- Arc::new(WhatsAppChannel::with_http_client(- wa.access_token.clone().unwrap_or_default(),- wa.phone_number_id.clone().unwrap_or_default(),- wa.verify_token.clone().unwrap_or_default(),- wa.allowed_numbers.clone(),- crate::config::build_runtime_proxy_client("channel.whatsapp"),- )),- ));- } else {- tracing::warn!("WhatsApp Cloud API configured but missing required fields (phone_number_id, access_token, verify_token)");- }- }- "web" => {- // Web mode: requires session_path- #[cfg(feature = "whatsapp-web")]- if wa.is_web_config() {- channels.push((- "WhatsApp",- Arc::new(WhatsAppWebChannel::new(- wa.session_path.clone().unwrap_or_default(),- wa.pair_phone.clone(),- wa.pair_code.clone(),- wa.allowed_numbers.clone(),- )),- ));- } else {- tracing::warn!("WhatsApp Web configured but session_path not set");- }- #[cfg(not(feature = "whatsapp-web"))]- {- tracing::warn!("WhatsApp Web backend requires 'whatsapp-web' feature. Enable with: cargo build --features whatsapp-web");- }- }- _ => {- tracing::warn!("WhatsApp config invalid: neither phone_number_id (Cloud API) nor session_path (Web) is set");- }- }- }-- if let Some(ref lq) = config.channels_config.linq {- channels.push((- "Linq",- Arc::new(LinqChannel::new(- lq.api_token.clone(),- lq.from_phone.clone(),- lq.allowed_senders.clone(),- )),- ));- }-- if let Some(ref email_cfg) = config.channels_config.email {- channels.push(("Email", Arc::new(EmailChannel::new(email_cfg.clone()))));- }-- if let Some(ref irc) = config.channels_config.irc {- channels.push((- "IRC",- Arc::new(IrcChannel::new(irc::IrcChannelConfig {- server: irc.server.clone(),- port: irc.port,- nickname: irc.nickname.clone(),- username: irc.username.clone(),- channels: irc.channels.clone(),- allowed_users: irc.allowed_users.clone(),- server_password: irc.server_password.clone(),- nickserv_password: irc.nickserv_password.clone(),- sasl_password: irc.sasl_password.clone(),- verify_tls: irc.verify_tls.unwrap_or(true),- })),- ));- }-- if let Some(ref lk) = config.channels_config.lark {- channels.push(("Lark", Arc::new(LarkChannel::from_config(lk))));- }-- if let Some(ref dt) = config.channels_config.dingtalk {- channels.push((- "DingTalk",- Arc::new(DingTalkChannel::with_http_client(- dt.client_id.clone(),- dt.client_secret.clone(),- dt.allowed_users.clone(),- crate::config::build_runtime_proxy_client("channel.dingtalk"),- )),- ));- }-- if let Some(ref qq) = config.channels_config.qq {- channels.push((- "QQ",- Arc::new(QQChannel::with_http_client(- qq.app_id.clone(),- qq.app_secret.clone(),- qq.allowed_users.clone(),- crate::config::build_runtime_proxy_client("channel.qq"),- )),- ));- }-- if let Some(ref yb) = config.channels_config.yuanbao {- match YuanbaoChannel::new(yb.clone()) {- Ok(ch) => channels.push(("Yuanbao", Arc::new(ch))),- Err(e) => tracing::warn!("Yuanbao config invalid, skipping: {}", e),- }- }+ let host: Arc<dyn tinychannels::ChannelHost> = Arc::new(tinychannels::NoopHost);+ let channels = tinychannels::build_channels(+ &hydrate_channel_credentials(&config),+ &host,+ &RuntimeProxyClients,+ );if channels.is_empty() {println!("No real-time channels configured. Configure channels in the web UI.");@@ -244,28 +47,14 @@ pub async fn doctor_channels(config: Config) -> Result<()> {println!("🩺 OpenHuman Channel Doctor");println!();- let mut healthy = 0_u32;- let mut unhealthy = 0_u32;- let mut timeout = 0_u32;-- for (name, channel) in channels {- let result = tokio::time::timeout(Duration::from_secs(10), channel.health_check()).await;- let state = classify_health_result(&result);-+ let (mut healthy, mut unhealthy, mut timeout) = (0_u32, 0_u32, 0_u32);+ for (name, state) in check_channels_health(&channels, HEALTH_CHECK_TIMEOUT).await {match state {- ChannelHealthState::Healthy => {- healthy += 1;- println!(" ✅ {name:<9} healthy");- }- ChannelHealthState::Unhealthy => {- unhealthy += 1;- println!(" ❌ {name:<9} unhealthy (auth/config/network)");- }- ChannelHealthState::Timeout => {- timeout += 1;- println!(" ⏱️ {name:<9} timed out (>10s)");- }+ ChannelHealthState::Healthy => healthy += 1,+ ChannelHealthState::Unhealthy => unhealthy += 1,+ ChannelHealthState::Timeout => timeout += 1,}+ println!("{}", report_line(&channel_label(&name), state));}if config.channels_config.webhook.is_some() {diff --git a/crates/openhuman-core/src/channels/commands_tests.rs b/crates/openhuman-core/src/channels/commands_tests.rsindex 417837d1f1..cac0bb3b7b 100644--- a/crates/openhuman-core/src/channels/commands_tests.rs+++ b/crates/openhuman-core/src/channels/commands_tests.rs@@ -1,123 +1,22 @@use super::*;#[test]-fn classify_health_result_maps_all_outcomes() {+fn report_lines_cover_every_state() {assert_eq!(- classify_health_result(&Ok(true)),- ChannelHealthState::Healthy- );- assert_eq!(- classify_health_result(&Ok(false)),- ChannelHealthState::Unhealthy+ report_line("Telegram", ChannelHealthState::Healthy),+ " ✅ Telegram healthy");+ assert!(report_line("Slack", ChannelHealthState::Unhealthy).contains("unhealthy"));+ assert!(report_line("Slack", ChannelHealthState::Timeout).contains("timed out"));}-#[tokio::test]-async fn classify_health_result_maps_timeout() {- let elapsed = tokio::time::timeout(- std::time::Duration::from_millis(1),- std::future::pending::<()>(),- )- .await- .unwrap_err();- assert_eq!(- classify_health_result(&Err(elapsed)),- ChannelHealthState::Timeout- );-}--#[tokio::test]-async fn doctor_channels_returns_ok_when_no_channels_are_configured() {- let mut config = Config::default();- config.channels_config = crate::config::ChannelsConfig::default();- doctor_channels(config).await.unwrap();-}--#[tokio::test]-async fn doctor_channels_runs_with_telegram_config() {- use crate::config::{StreamMode, TelegramConfig};- let mut config = Config::default();- config.channels_config = crate::config::ChannelsConfig::default();- config.channels_config.telegram = Some(TelegramConfig {- bot_token: "fake:token".into(),- chat_id: None,- allowed_users: vec!["user1".into()],- stream_mode: StreamMode::default(),- draft_update_interval_ms: 2000,- silent_streaming: true,- mention_only: false,- });- let _ = doctor_channels(config).await;-}--#[tokio::test]-async fn doctor_channels_runs_with_discord_config() {- use crate::config::DiscordConfig;- let mut config = Config::default();- config.channels_config = crate::config::ChannelsConfig::default();- config.channels_config.discord = Some(DiscordConfig {- bot_token: "fake".into(),- guild_id: Some("123".into()),- channel_id: Some("456".into()),- allowed_users: vec![],- listen_to_bots: false,- mention_only: true,- });- let _ = doctor_channels(config).await;-}--#[tokio::test]-async fn doctor_channels_runs_with_slack_config() {- use crate::config::SlackConfig;- let mut config = Config::default();- config.channels_config = crate::config::ChannelsConfig::default();- config.channels_config.slack = Some(SlackConfig {- bot_token: "fake".into(),- app_token: None,- channel_id: Some("C123".into()),- allowed_users: vec![],- });- let _ = doctor_channels(config).await;-}--#[tokio::test]-async fn doctor_channels_runs_with_imessage_config() {- use crate::config::IMessageConfig;- let mut config = Config::default();- config.channels_config = crate::config::ChannelsConfig::default();- config.channels_config.imessage = Some(IMessageConfig {- allowed_contacts: vec!["[email protected]".into()],- });- let _ = doctor_channels(config).await;+#[test]+fn channel_labels_use_definition_display_names() {+ assert_eq!(channel_label("telegram"), "Telegram");+ assert_eq!(channel_label("not-a-channel"), "not-a-channel");}#[tokio::test]-async fn doctor_channels_runs_with_multiple_channels() {- use crate::config::{DiscordConfig, SlackConfig, StreamMode, TelegramConfig};- let mut config = Config::default();- config.channels_config = crate::config::ChannelsConfig::default();- config.channels_config.telegram = Some(TelegramConfig {- bot_token: "fake".into(),- chat_id: None,- allowed_users: vec![],- stream_mode: StreamMode::default(),- draft_update_interval_ms: 2000,- silent_streaming: true,- mention_only: false,- });- config.channels_config.discord = Some(DiscordConfig {- bot_token: "fake".into(),- guild_id: Some("123".into()),- channel_id: Some("456".into()),- allowed_users: vec![],- listen_to_bots: false,- mention_only: false,- });- config.channels_config.slack = Some(SlackConfig {- bot_token: "fake".into(),- app_token: None,- channel_id: Some("C123".into()),- allowed_users: vec![],- });- let _ = doctor_channels(config).await;+async fn doctor_with_no_channels_is_ok() {+ doctor_channels(Config::default()).await.unwrap();}diff --git a/crates/openhuman-core/src/channels/runtime/mod.rs b/crates/openhuman-core/src/channels/runtime/mod.rsindex 565b78c7ac..ace3eece5b 100644--- a/crates/openhuman-core/src/channels/runtime/mod.rs+++ b/crates/openhuman-core/src/channels/runtime/mod.rs@@ -5,6 +5,7 @@ pub(crate) mod session;mod startup;mod supervision;+pub(crate) use startup::{hydrate_channel_credentials, RuntimeProxyClients};pub use startup::start_channels;pub(crate) use startup::start_channels_with_session;diff --git a/crates/openhuman-core/src/channels/runtime/startup.rs b/crates/openhuman-core/src/channels/runtime/startup.rsindex ccca4671ba..b7fa05bffd 100644--- a/crates/openhuman-core/src/channels/runtime/startup.rs+++ b/crates/openhuman-core/src/channels/runtime/startup.rs@@ -6,6 +6,7 @@ mod prompt;mod relay;mod start_channels;+pub(crate) use credentials::{hydrate_channel_credentials, RuntimeProxyClients};pub use start_channels::start_channels;pub(crate) use start_channels::start_channels_with_session;diff --git a/crates/openhuman-core/src/channels/runtime/startup/credentials.rs b/crates/openhuman-core/src/channels/runtime/startup/credentials.rsindex dcc074a8ec..c042564ca5 100644--- a/crates/openhuman-core/src/channels/runtime/startup/credentials.rs+++ b/crates/openhuman-core/src/channels/runtime/startup/credentials.rs@@ -97,7 +97,7 @@ pub(super) fn resolve_email_password(/// backend and timeouts are the embedding host's business. This is where/// OpenHuman's runtime proxy settings get applied, per channel, using the same/// `channel.<name>` identifiers the config UI shows.-pub(super) struct RuntimeProxyClients;+pub(crate) struct RuntimeProxyClients;impl tinychannels::HttpClientFactory for RuntimeProxyClients {fn client_for(&self, channel: &str) -> reqwest::Client {@@ -124,7 +124,7 @@ impl tinychannels::HttpClientFactory for RuntimeProxyClients {/// keyring, an environment variable or the config, and only this host knows/// which. It therefore expects an already-hydrated config, and this is where/// that happens — on a clone, so the persisted config is never mutated.-pub(super) fn hydrate_channel_credentials(config: &Config) -> tinychannels::ChannelsConfig {+pub(crate) fn hydrate_channel_credentials(config: &Config) -> tinychannels::ChannelsConfig {let mut hydrated = config.channels_config.clone();if let Some(email_cfg) = hydrated.email.take() {hydrated.email = Some(resolve_email_password(email_cfg, config));