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
chore(channels): remove legacy supervision and integration tests
Steven Enamakelab18459c343b
diff --git a/crates/openhuman-core/src/channels/host/host_tests.rs b/crates/openhuman-core/src/channels/host/host_tests.rsindex 788613a0ec..b06daab423 100644--- a/crates/openhuman-core/src/channels/host/host_tests.rs+++ b/crates/openhuman-core/src/channels/host/host_tests.rs@@ -297,7 +297,7 @@ async fn event_sink_routes_channel_reactions_to_domain_bus() {.await.is_ok());assert!(sink- .publish(+ .publish_host("channel","reaction_sent",serde_json::json!({diff --git a/crates/openhuman-core/src/channels/runtime/mod.rs b/crates/openhuman-core/src/channels/runtime/mod.rsindex 25bc6501ca..d0d6e7cfe0 100644--- a/crates/openhuman-core/src/channels/runtime/mod.rs+++ b/crates/openhuman-core/src/channels/runtime/mod.rs@@ -3,8 +3,6 @@pub(crate) mod dispatch;pub(crate) mod session;mod startup;-#[cfg(test)]-mod supervision;pub(crate) use startup::hydrate_channel_credentials;pub(crate) use startup::prepare_runtime_limits;@@ -24,5 +22,3 @@ pub mod test_support;// Re-exported for `channels::tests` only; omit in normal lib builds to avoid unused-import warnings.#[cfg(test)]pub(crate) use dispatch::run_message_dispatch_loop;-#[cfg(test)]-pub(crate) use supervision::spawn_supervised_listener;diff --git a/crates/openhuman-core/src/channels/runtime/supervision.rs b/crates/openhuman-core/src/channels/runtime/supervision.rsdeleted file mode 100644index 53b33638b6..0000000000--- a/crates/openhuman-core/src/channels/runtime/supervision.rs+++ /dev/null@@ -1,93 +0,0 @@-//! OpenHuman observer adapter for TinyChannels listener supervision.--use super::super::Channel;-use crate::core::bus::BUS;-use crate::core::events::DomainEvent;-use std::sync::Arc;-use tinychannels::runtime::ListenerObserver;-use tinychannels_bus as traits;--/// Publishes reusable listener lifecycle facts onto OpenHuman's domain bus.-struct OpenHumanListenerObserver;--impl ListenerObserver for OpenHumanListenerObserver {- fn connected(&self, channel: &str) {- BUS.publish(DomainEvent::ChannelConnected {- channel: channel.to_string(),- });- }-- fn disconnected(&self, channel: &str, reason: &str, failed: bool) {- if failed {- let message = format!("Channel {channel} error: {reason}; restarting");- crate::core::observability::report_error_or_expected(- &message,- "channels",- "supervised_listener",- &[("channel", channel)],- );- } else {- tracing::warn!("Channel {channel} exited unexpectedly; restarting");- }- BUS.publish(DomainEvent::ChannelDisconnected {- channel: channel.to_string(),- reason: reason.to_string(),- });- }-- fn restarted(&self, channel: &str) {- BUS.publish(DomainEvent::HealthRestarted {- component: format!("channel:{channel}"),- });- }-}--// Adapt host-owned test doubles to the legacy provider supervisor. Production-// receives supervision facts from the compiled module instead.-struct LegacyListenerFixture(Arc<dyn Channel>);--#[async_trait::async_trait]-impl tinychannels::Channel for LegacyListenerFixture {- fn name(&self) -> &str {- self.0.name()- }-- async fn send(&self, message: &traits::SendMessage) -> anyhow::Result<()> {- self.0.send(message).await- }-- async fn listen(- &self,- tx: tokio::sync::mpsc::Sender<traits::ChannelMessage>,- ) -> anyhow::Result<()> {- self.0.listen(tx).await- }-- async fn health_check(&self) -> bool {- self.0.health_check().await- }-}--/// Start a legacy listener fixture with OpenHuman observability attached.-pub(crate) fn spawn_supervised_listener(- channel: Arc<dyn Channel>,- tx: tokio::sync::mpsc::Sender<traits::ChannelMessage>,- initial_backoff_secs: u64,- max_backoff_secs: u64,-) -> tokio::task::JoinHandle<()> {- crate::platform::health::bus::register_health_subscriber();- tinychannels::runtime::spawn_supervised_listener(- Arc::new(LegacyListenerFixture(channel)),- tx,- initial_backoff_secs,- max_backoff_secs,- Arc::new(OpenHumanListenerObserver),- )-}--#[cfg(test)]-pub(crate) use tinychannels::runtime::{jitter_millis, MAX_JITTER_MS};--#[cfg(test)]-#[path = "supervision_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/channels/runtime/supervision_tests.rs b/crates/openhuman-core/src/channels/runtime/supervision_tests.rsdeleted file mode 100644index 37facf80f2..0000000000--- a/crates/openhuman-core/src/channels/runtime/supervision_tests.rs+++ /dev/null@@ -1,133 +0,0 @@-use super::super::super::Channel;-use super::{jitter_millis, spawn_supervised_listener, MAX_JITTER_MS};-use std::sync::{Arc, Mutex};-use tinychannels_bus as traits;-use tokio::time::Instant;--#[test]-fn supervision_discord_gateway_reqwest_failure_classifies_as_expected() {- let raw = "error sending request for url (https://discord.com/api/v10/gateway/bot)";- let wrapped = format!("Channel discord error: {raw}; restarting");- let kind = crate::core::observability::expected_error_kind(&wrapped);- assert_eq!(- kind,- Some(crate::core::observability::ExpectedErrorKind::ChannelSupervisorRestart),- "supervision wrapper must classify as ChannelSupervisorRestart \- (precedence over NetworkUnreachable) so Sentry stays quiet for \- TAURI-RUST-15/-BB (got {kind:?} for message {wrapped:?})"- );-}--#[test]-fn jitter_millis_is_bounded_by_backoff_and_max() {- // Sub-second backoff windows scale with the backoff; large ones clamp.- for _ in 0..256 {- assert!(- jitter_millis(1) < 1_000,- "1s backoff jitters within [0,1000)"- );- assert!(- jitter_millis(60) < MAX_JITTER_MS,- "large backoff jitter must clamp to MAX_JITTER_MS"- );- }- // Degenerate window: no room to sample, must not panic on `0..0`.- assert_eq!(jitter_millis(0), 0, "zero backoff yields zero jitter");-}--/// Fake channel whose `listen()` returns `Ok(())` immediately — mirroring-/// Discord's op7/op9/Close paths, which all return `Ok(())` (see the-/// tinychannels `DiscordChannel::listen` gateway loop). It records the-/// virtual-clock instant of every `listen` entry and, once it has been-/// restarted `stop_after` times, drops the receiver it holds so the-/// supervisor's `tx.is_closed()` guard breaks the loop deterministically.-struct ReconnectOkChannel {- entries: Arc<Mutex<Vec<Instant>>>,- stop_after: usize,- // Held solely to keep `tx.is_closed()` false until we choose to stop;- // dropped in-place on the final `listen` to break the supervisor loop.- rx: Mutex<Option<tokio::sync::mpsc::Receiver<traits::ChannelMessage>>>,-}--#[async_trait::async_trait]-impl Channel for ReconnectOkChannel {- fn name(&self) -> &str {- "reconnect-ok"- }-- async fn send(&self, _message: &super::super::super::SendMessage) -> anyhow::Result<()> {- Ok(())- }-- async fn listen(- &self,- _tx: tokio::sync::mpsc::Sender<traits::ChannelMessage>,- ) -> anyhow::Result<()> {- let count = {- let mut entries = self.entries.lock().expect("entries lock");- entries.push(Instant::now());- entries.len()- };- if count >= self.stop_after {- // Drop the receiver so the next `tx.is_closed()` check breaks- // the supervisor loop instead of spinning forever.- self.rx.lock().expect("rx lock").take();- }- Ok(())- }-}--/// Regression for #5350: a reconnect-style `Ok(())` exit (Discord op7/op9/-/// Close) must ESCALATE the restart backoff, not reset it to the initial-/// value every iteration. Before the fix the `Ok(())` arm reset-/// `backoff = initial_backoff_secs`, so a reconnect storm looped at a flat-/// ~2s forever; the gaps between successive `listen` entries would all be-/// ~1s here. With the fix the base backoff doubles (1 → 2 → 4 …) exactly-/// like the `Err` path, so the whole-second gaps are 1, 2, 4.-///-/// Runs under a paused clock, so the supervisor's `sleep(backoff)` calls-/// auto-advance virtual time and the test completes without real waits.-#[tokio::test(start_paused = true)]-async fn reconnect_ok_exit_escalates_backoff_instead_of_resetting() {- // A live bus is needed for the ChannelConnected/HealthRestarted publishes- // the supervisor emits each iteration (matches tests/health.rs setup).- crate::core::bus::init().await.expect("bus init");-- let entries = Arc::new(Mutex::new(Vec::new()));- // Stop after the 4th restart so we observe three inter-restart gaps- // (backoff steps 1, 2, 4) before the loop breaks.- let (tx, rx) = tokio::sync::mpsc::channel::<traits::ChannelMessage>(1);- let channel: Arc<dyn Channel> = Arc::new(ReconnectOkChannel {- entries: Arc::clone(&entries),- stop_after: 4,- rx: Mutex::new(Some(rx)),- });-- // initial=1, max=8 so the 1 → 2 → 4 escalation is fully visible before- // the cap would bite.- let handle = spawn_supervised_listener(channel, tx, 1, 8);- handle.await.expect("supervised listener task");-- let entries = entries.lock().expect("entries lock");- assert_eq!(- entries.len(),- 4,- "listener should have been restarted exactly stop_after times, got {}",- entries.len()- );-- // Whole-second gaps between successive restarts. Jitter is strictly- // < 1s (bounded by MAX_JITTER_MS), so the seconds floor isolates the- // base backoff exactly: escalating 1, 2, 4 — never the flat 1, 1, 1- // the pre-fix reset produced.- let gap_secs: Vec<u64> = entries- .windows(2)- .map(|w| w[1].duration_since(w[0]).as_secs())- .collect();- assert_eq!(- gap_secs,- vec![1, 2, 4],- "reconnect-style Ok(()) exits must escalate backoff (1,2,4), not reset it \- to the flat initial delay (which would show 1,1,1); got {gap_secs:?}"- );-}diff --git a/crates/openhuman-core/src/channels/tests/discord_integration.rs b/crates/openhuman-core/src/channels/tests/discord_integration.rsdeleted file mode 100644index d3cb5844a7..0000000000--- a/crates/openhuman-core/src/channels/tests/discord_integration.rs+++ /dev/null@@ -1,320 +0,0 @@-//! Integration tests proving the channels module is fully encapsulated for-//! the Discord dispatch path.-//!-//! "Fully encapsulated" here means: the runtime dispatch pipeline can be-//! exercised end-to-end for `channel = "discord"` with every cross-module-//! boundary (agent runtime, LLM provider) substituted with a stub/noop. These-//! tests do NOT spin up a real Discord gateway or a real LLM provider — they-//! only exercise the channels module-//! itself.-//!-//! Coverage:-//! 1. End-to-end dispatch for a Discord inbound message via the real-//! `agent.run_turn` bus handler (full pipeline smoke test).-//! 2. Discord channels report `supports_reactions() == false`, so dispatch-//! must NOT emit a `[REACTION:<emoji>]` acknowledgment even when the-//! inbound carries a `thread_ts`.-//! 3. Discord follows standard non-Telegram semantics: different-//! `thread_ts` values produce independent conversation histories at the-//! dispatch level (not just at the key function level).-//! 4. The dispatch path for Discord routes through the `agent.run_turn`-//! bus handler — proved by overriding it with a stub and asserting the-//! stub is invoked. This is the encapsulation money shot: if dispatch-//! ever reverts to calling `run_tool_call_loop` directly, this test-//! starts failing.--use super::super::context::{- conversation_history_key, ChannelRuntimeContext, CHANNEL_MESSAGE_TIMEOUT_SECS,-};-use super::super::runtime::process_channel_message;-use super::super::{Channel, SendMessage};-use super::common::HistoryCaptureModel;-use std::collections::HashMap;-use std::sync::atomic::{AtomicUsize, Ordering};-use std::sync::{Arc, Mutex};-use tinychannels_bus as traits;-use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};--// ── Test helpers ────────────────────────────────────────────────────────────--/// A full-recording Discord channel that captures every send, start_typing,-/// and stop_typing call. Reports `name() == "discord"` and leaves-/// `supports_reactions()` at its trait default of `false` — mirroring the-/// real `DiscordChannel`. No HTTP is involved.-#[derive(Default)]-struct DiscordRecordingChannel {- sent: tokio::sync::Mutex<Vec<SendMessage>>,- start_typing_calls: AtomicUsize,- stop_typing_calls: AtomicUsize,-}--#[async_trait::async_trait]-impl Channel for DiscordRecordingChannel {- fn name(&self) -> &str {- "discord"- }-- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {- self.sent.lock().await.push(message.clone());- 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(())- }-- // Intentionally left at the default `supports_reactions() -> false` so we- // can prove dispatch honors that capability for Discord.-}--/// Model that immediately returns a fixed response string — the channels-/// module never needs to know or care that it's not a real LLM.-struct FixedResponseModel {- response: &'static str,-}--#[async_trait::async_trait]-impl ChatModel<()> for FixedResponseModel {- async fn invoke(- &self,- _state: &(),- _request: ModelRequest,- ) -> tinyinference_llm::Result<ModelResponse> {- Ok(ModelResponse::assistant(self.response))- }-}--fn make_discord_ctx(- channel: Arc<dyn Channel>,- model: Arc<dyn ChatModel<()>>,-) -> Arc<ChannelRuntimeContext> {- let mut channels = HashMap::new();- channels.insert(channel.name().to_string(), channel);-- Arc::new(ChannelRuntimeContext {- relay_thread: None,- channels_by_name: Arc::new(channels),- module_objects: Arc::new(HashMap::new()),- turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),- default_provider: Arc::new("test-provider".to_string()),- tools_registry: Arc::new(vec![]),- system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),- model: Arc::new("test-model".to_string()),- temperature: 0.0,- max_tool_iterations: 1,- turn_model_source_cache: Arc::new(Mutex::new(HashMap::new())),- route_overrides: Arc::new(Mutex::new(HashMap::new())),- api_url: None,- inference_url: None,- reliability: Arc::new(crate::config::ReliabilityConfig::default()),- provider_runtime_options: crate::inference::provider::ProviderRuntimeOptions::default(),- workspace_dir: Arc::new(std::env::temp_dir()),- message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,- multimodal: crate::config::MultimodalConfig::default(),- multimodal_files: crate::config::MultimodalFileConfig::default(),- config: None,- core: None,- })-}--// ── 1. Full-pipeline smoke test ─────────────────────────────────────────────--/// A Discord inbound message must flow through the full runtime dispatch-/// pipeline — history update, `agent.run_turn` bus call,-/// channel send — without requiring any external services. The response text-/// from the stubbed provider must reach the channel's `send()` with the-/// recipient matching `reply_target`.-#[tokio::test]-async fn discord_inbound_dispatches_through_full_pipeline() {- let _bus_guard = super::common::use_real_agent_handler().await;- let recorder = Arc::new(DiscordRecordingChannel::default());- let channel: Arc<dyn Channel> = recorder.clone();- let provider: Arc<dyn ChatModel<()>> = Arc::new(FixedResponseModel {- response: "hi from discord",- });- let ctx = make_discord_ctx(channel, provider);-- process_channel_message(- ctx,- traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "discord_msg_1".to_string(),- sender: "user-123".to_string(),- reply_target: "channel-456".to_string(),- content: "what's up?".to_string(),- channel: "discord".to_string(),- timestamp: 1,- thread_ts: None,- sender_name: None,- },- )- .await;-- let sent = recorder.sent.lock().await;- assert_eq!(- sent.len(),- 1,- "expected exactly one send for discord dispatch"- );- assert_eq!(- sent[0].recipient, "channel-456",- "recipient must match reply_target"- );- assert!(- sent[0].content.contains("hi from discord"),- "dispatch must forward the stubbed provider response verbatim, got {:?}",- sent[0].content- );- assert!(- sent[0].thread_ts.is_none(),- "absent inbound thread_ts must not be fabricated on discord send"- );-}--// ── 2. Reaction capability flag is respected ───────────────────────────────--/// Dispatch must NOT emit an acknowledgment `[REACTION:<emoji>]` for Discord-/// even when the inbound message has `thread_ts` set, because Discord-/// channels report `supports_reactions() == false`. This proves the-/// dispatcher respects channel capability flags and keeps Discord free of-/// Telegram-specific behaviors.-#[tokio::test]-async fn discord_threaded_message_does_not_emit_reaction_ack() {- let _bus_guard = super::common::use_real_agent_handler().await;- let recorder = Arc::new(DiscordRecordingChannel::default());- let channel: Arc<dyn Channel> = recorder.clone();- let provider: Arc<dyn ChatModel<()>> = Arc::new(FixedResponseModel { response: "roger" });- let ctx = make_discord_ctx(channel, provider);-- process_channel_message(- ctx,- traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "discord_msg_2".to_string(),- sender: "user-123".to_string(),- reply_target: "channel-456".to_string(),- content: "in-thread message".to_string(),- channel: "discord".to_string(),- timestamp: 1,- thread_ts: Some("thread-42".to_string()),- sender_name: None,- },- )- .await;-- let sent = recorder.sent.lock().await;- // Only the real reply should be sent — no acknowledgment reaction.- assert_eq!(- sent.len(),- 1,- "Discord must not receive an ack reaction alongside the reply"- );- assert!(- !sent[0].content.starts_with("[REACTION:"),- "discord send must not contain a reaction marker, got {:?}",- sent[0].content- );- assert!(- sent[0].content.contains("roger"),- "expected the normal reply content, got {:?}",- sent[0].content- );-}--// ── 3. thread_ts splits history at the dispatch level ─────────────────────--/// Discord follows the standard non-Telegram history rules: two messages-/// with different `thread_ts` values must produce two independent-/// conversation histories. The second call's history must NOT contain the-/// first message's user content — proving the thread split is honored by-/// the actual dispatch pipeline, not just by `conversation_history_key` in-/// isolation.-#[tokio::test]-async fn discord_thread_ts_splits_conversation_history_end_to_end() {- let _bus_guard = super::common::use_real_agent_handler().await;- let recorder = Arc::new(DiscordRecordingChannel::default());- let channel: Arc<dyn Channel> = recorder.clone();- let provider_impl = Arc::new(HistoryCaptureModel::default());- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();- let ctx = make_discord_ctx(channel, provider);-- let first = traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "discord_msg_a".to_string(),- sender: "user-123".to_string(),- reply_target: "channel-456".to_string(),- content: "first thread message".to_string(),- channel: "discord".to_string(),- timestamp: 1,- thread_ts: Some("thread-A".to_string()),- sender_name: None,- };-- let second = traits::ChannelMessage {- id: "discord_msg_b".to_string(),- thread_ts: Some("thread-B".to_string()),- content: "second thread message".to_string(),- ..first.clone()- };-- // Sanity: the key function itself must split these. Without this, the- // end-to-end expectations below would be ambiguous — is the split- // happening because of the key or because of some dispatch quirk?- assert_ne!(- conversation_history_key(&first),- conversation_history_key(&second),- "discord: different thread_ts must produce different history keys"- );-- process_channel_message(ctx.clone(), first).await;- process_channel_message(ctx, second).await;-- let calls = provider_impl- .calls- .lock()- .unwrap_or_else(|e| e.into_inner());- assert_eq!(- calls.len(),- 2,- "expected two provider calls, one per thread"- );-- // Second call's history must be fresh — only system + its own user- // message — because it's in a brand new thread.- let second_history = &calls[1];- assert_eq!(- second_history.len(),- 2,- "thread-B history should only contain system + its own user message, got {:?}",- second_history- );- assert_eq!(second_history[0].0, "system");- assert_eq!(second_history[1].0, "user");- assert!(- second_history[1].1.contains("second thread message"),- "second slot must contain the thread-B user message, got {:?}",- second_history[1].1- );- assert!(- !second_history- .iter()- .any(|(_, content)| content.contains("first thread message")),- "thread-B history MUST NOT leak content from thread-A"- );-}diff --git a/crates/openhuman-core/src/channels/tests/health.rs b/crates/openhuman-core/src/channels/tests/health.rsdeleted file mode 100644index 17e0230fe7..0000000000--- a/crates/openhuman-core/src/channels/tests/health.rs+++ /dev/null@@ -1,58 +0,0 @@-use super::super::runtime::spawn_supervised_listener;-use super::super::Channel;-use super::common::AlwaysFailChannel;-use std::sync::atomic::{AtomicUsize, Ordering};-use std::sync::Arc;-use std::time::Duration;-use tinychannels_bus as traits;--#[tokio::test]-async fn supervised_listener_marks_error_and_restarts_on_failures() {- let calls = Arc::new(AtomicUsize::new(0));- let name = Box::leak(format!("test-supervised-fail-{}", uuid::Uuid::new_v4()).into_boxed_str());- let channel: Arc<dyn Channel> = Arc::new(AlwaysFailChannel {- name,- calls: Arc::clone(&calls),- });- let component_name = format!("channel:{name}");-- let (tx, rx) = tokio::sync::mpsc::channel::<traits::ChannelMessage>(1);- // The global health subscriber may have been registered by another test- // runtime; keep a fresh subscriber alive for this test's runtime too.- crate::core::bus::init().await.expect("bus init");- let _health_handle = crate::core::bus::BUS- .subscribe(Arc::new(crate::platform::health::bus::HealthSubscriber))- .expect("event bus should be initialized for channel health test");- tokio::task::yield_now().await;- let handle = spawn_supervised_listener(channel, tx, 1, 1);-- let component = wait_for_component_error(&component_name).await;- drop(rx);- handle.abort();- let _ = handle.await;-- assert_eq!(component["status"], "error");- assert!(component["restart_count"].as_u64().unwrap_or(0) >= 1);- assert!(component["last_error"]- .as_str()- .unwrap_or("")- .contains("listen boom"));- assert!(calls.load(Ordering::SeqCst) >= 1);-}--async fn wait_for_component_error(component_name: &str) -> serde_json::Value {- let deadline = tokio::time::Instant::now() + Duration::from_secs(2);- loop {- let snapshot = crate::platform::health::snapshot_json();- let component = snapshot["components"][component_name].clone();- if component["status"] == "error" && component["restart_count"].as_u64().unwrap_or(0) >= 1 {- return component;- }-- if tokio::time::Instant::now() >= deadline {- panic!("timed out waiting for {component_name} to enter error state; last={component}");- }-- tokio::time::sleep(Duration::from_millis(10)).await;- }-}diff --git a/crates/openhuman-core/src/channels/tests/mod.rs b/crates/openhuman-core/src/channels/tests/mod.rsindex d94eab8192..67380b4147 100644--- a/crates/openhuman-core/src/channels/tests/mod.rs+++ b/crates/openhuman-core/src/channels/tests/mod.rs@@ -12,10 +12,6 @@//! `MockPriceTool`, `make_workspace` for identity-file//! fixtures, and a re-export of `agent::bus::use_real_agent_handler`.//!-//! * `discord_integration.rs` — end-to-end dispatch through the Discord-//! channel with every cross-module boundary (agent runtime, provider) substituted, proving the domain stays encapsulated.-//! * `health.rs` — `spawn_supervised_listener` marking a component errored and restarting-//! when a listener keeps failing.//! * `identity.rs` — `build_system_prompt` inlining workspace identity//! markdown into the Project Context section.//! * `prompt.rs` — system-prompt section assembly and bootstrap truncation.@@ -26,14 +22,9 @@//! * `runtime_tool_calls.rs` — native tool-call execution, the `/models`//! command short-circuit, route overrides, and `max_tool_iterations`//! through `process_channel_message`.-//! * `telegram_integration.rs` — Telegram reactions, reply/thread roundtrip,-//! and typing-indicator lifecycle against a recording channel.mod common;-mod discord_integration;-mod health;mod identity;mod prompt;mod runtime_dispatch;mod runtime_tool_calls;-mod telegram_integration;diff --git a/crates/openhuman-core/src/channels/tests/telegram_integration.rs b/crates/openhuman-core/src/channels/tests/telegram_integration.rsdeleted file mode 100644index db91b7696d..0000000000--- a/crates/openhuman-core/src/channels/tests/telegram_integration.rs+++ /dev/null@@ -1,479 +0,0 @@-//! Integration tests for Telegram channel features:-//! reactions (both directions), reply/thread roundtrip, and typing indicator lifecycle.-//!-//! These tests exercise the full dispatch pipeline using a `FullRecordingChannel` that-//! captures every `SendMessage` — including `thread_ts` — so assertions can be made-//! about exactly what the channel receives, without needing a real Telegram HTTP server.--use super::super::context::{- conversation_history_key, ChannelRuntimeContext, CHANNEL_MESSAGE_TIMEOUT_SECS,-};-use super::super::runtime::process_channel_message;-use super::super::{Channel, SendMessage};-use super::common::SlowModel;-use std::collections::HashMap;-use std::sync::atomic::{AtomicUsize, Ordering};-use std::sync::{Arc, Mutex};-use std::time::Duration;-use tinychannels_bus as traits;-use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};--// ── Test helpers ────────────────────────────────────────────────────────────--/// A channel that records every `SendMessage` it receives in full, including `thread_ts`.-#[derive(Default)]-struct FullRecordingChannel {- sent: tokio::sync::Mutex<Vec<SendMessage>>,- start_typing_calls: AtomicUsize,- stop_typing_calls: AtomicUsize,-}--#[async_trait::async_trait]-impl Channel for FullRecordingChannel {- fn name(&self) -> &str {- "test-channel"- }-- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {- self.sent.lock().await.push(message.clone());- 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(())- }-}--/// Model that immediately returns a fixed response string.-struct FixedResponseModel {- response: &'static str,-}--#[async_trait::async_trait]-impl ChatModel<()> for FixedResponseModel {- async fn invoke(- &self,- _state: &(),- _request: ModelRequest,- ) -> tinyinference_llm::Result<ModelResponse> {- Ok(ModelResponse::assistant(self.response))- }-}--fn make_test_context(- channel: Arc<dyn Channel>,- model: Arc<dyn ChatModel<()>>,-) -> Arc<ChannelRuntimeContext> {- let mut channels = HashMap::new();- channels.insert(channel.name().to_string(), channel);-- Arc::new(ChannelRuntimeContext {- relay_thread: None,- channels_by_name: Arc::new(channels),- module_objects: Arc::new(HashMap::new()),- turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),- default_provider: Arc::new("test-provider".to_string()),- tools_registry: Arc::new(vec![]),- system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),- model: Arc::new("test-model".to_string()),- temperature: 0.0,- max_tool_iterations: 1,- turn_model_source_cache: Arc::new(Mutex::new(HashMap::new())),- route_overrides: Arc::new(Mutex::new(HashMap::new())),- api_url: None,- inference_url: None,- reliability: Arc::new(crate::config::ReliabilityConfig::default()),- provider_runtime_options: crate::inference::provider::ProviderRuntimeOptions::default(),- workspace_dir: Arc::new(std::env::temp_dir()),- message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,- multimodal: crate::config::MultimodalConfig::default(),- multimodal_files: crate::config::MultimodalFileConfig::default(),- config: None,- core: None,- })-}--// ── Reply / thread roundtrip ─────────────────────────────────────────────────--/// Regression: thread_ts set on the inbound ChannelMessage must be forwarded-/// unchanged to channel.send() so Telegram can visibly attach the reply.-#[tokio::test]-async fn inbound_thread_ts_is_forwarded_to_channel_send() {- let _bus_guard = super::common::use_real_agent_handler().await;- let recorder = Arc::new(FullRecordingChannel::default());- let channel: Arc<dyn Channel> = recorder.clone();- let provider: Arc<dyn ChatModel<()>> = Arc::new(FixedResponseModel { response: "pong" });- let ctx = make_test_context(channel, provider);-- process_channel_message(- ctx,- traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "tg_100_99".to_string(),- sender: "alice".to_string(),- reply_target: "100".to_string(),- content: "ping".to_string(),- channel: "test-channel".to_string(),- timestamp: 1,- thread_ts: Some("99".to_string()),- sender_name: None,- },- )- .await;-- let sent = recorder.sent.lock().await;- assert_eq!(sent.len(), 1, "expected exactly one send");- assert_eq!(- sent[0].thread_ts.as_deref(),- Some("99"),- "thread_ts must be forwarded unchanged to channel.send for reply targeting"- );- assert_eq!(- sent[0].recipient, "100",- "recipient must match reply_target"- );-}--/// Regression: when there is no thread context (thread_ts = None), the channel-/// send must also receive thread_ts = None — no phantom thread attachment.-#[tokio::test]-async fn no_thread_ts_on_inbound_message_results_in_none_on_send() {- let _bus_guard = super::common::use_real_agent_handler().await;- let recorder = Arc::new(FullRecordingChannel::default());- let channel: Arc<dyn Channel> = recorder.clone();- let provider: Arc<dyn ChatModel<()>> = Arc::new(FixedResponseModel { response: "ok" });- let ctx = make_test_context(channel, provider);-- process_channel_message(- ctx,- traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "tg_100_55".to_string(),- sender: "alice".to_string(),- reply_target: "100".to_string(),- content: "hello".to_string(),- channel: "test-channel".to_string(),- timestamp: 1,- thread_ts: None,- sender_name: None,- },- )- .await;-- let sent = recorder.sent.lock().await;- assert_eq!(sent.len(), 1, "expected exactly one send");- assert!(- sent[0].thread_ts.is_none(),- "absent thread_ts must not be fabricated on send"- );-}--// ── Outbound reaction via dispatch ──────────────────────────────────────────--/// Regression: when the LLM emits a reaction marker (`[REACTION:👍]`), the-/// dispatch layer must pass it to channel.send() with the correct thread_ts so-/// TelegramChannel can call setMessageReaction against the right message id.-#[tokio::test]-async fn reaction_marker_in_llm_response_is_passed_to_channel_send() {- let _bus_guard = super::common::use_real_agent_handler().await;- let recorder = Arc::new(FullRecordingChannel::default());- let channel: Arc<dyn Channel> = recorder.clone();- let provider: Arc<dyn ChatModel<()>> = Arc::new(FixedResponseModel {- response: "[REACTION:👍]",- });- let ctx = make_test_context(channel, provider);-- process_channel_message(- ctx,- traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "tg_100_42".to_string(),- sender: "alice".to_string(),- reply_target: "100".to_string(),- content: "great job".to_string(),- channel: "test-channel".to_string(),- timestamp: 1,- thread_ts: Some("42".to_string()), // message_id the reaction targets- sender_name: None,- },- )- .await;-- let sent = recorder.sent.lock().await;- assert_eq!(- sent.len(),- 1,- "expected exactly one send for a reaction marker"- );- assert_eq!(- sent[0].content, "[REACTION:👍]",- "reaction marker must be delivered verbatim to channel.send"- );- assert_eq!(- sent[0].thread_ts.as_deref(),- Some("42"),- "thread_ts carrying the target message_id must be forwarded with the reaction"- );-}--// ── Typing indicator lifecycle ───────────────────────────────────────────────--/// Regression: start_typing must be called at least once and stop_typing must be-/// called exactly once after the LLM finishes — regardless of response time.-///-/// Uses a 20ms provider delay so the first interval tick (which fires immediately-/// in tokio) has time to call start_typing before the cancellation arrives.-#[tokio::test]-async fn typing_indicator_starts_and_stops_once_per_message() {- let _bus_guard = super::common::use_real_agent_handler().await;- let recorder = Arc::new(FullRecordingChannel::default());- let channel: Arc<dyn Channel> = recorder.clone();- // Must be non-zero: the first typing interval fires at t=0 but the- // cancellation only arrives after the provider returns. A tiny delay- // ensures the tick wins the race reliably.- let provider: Arc<dyn ChatModel<()>> = Arc::new(SlowModel {- delay: Duration::from_millis(20),- });- let ctx = make_test_context(channel, provider);-- process_channel_message(- ctx,- traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "typing-test".to_string(),- sender: "alice".to_string(),- reply_target: "chat-123".to_string(),- content: "hello".to_string(),- channel: "test-channel".to_string(),- timestamp: 1,- thread_ts: None,- sender_name: None,- },- )- .await;-- let starts = recorder.start_typing_calls.load(Ordering::SeqCst);- let stops = recorder.stop_typing_calls.load(Ordering::SeqCst);-- assert!(starts >= 1, "start_typing must fire at least once");- assert_eq!(- stops, 1,- "stop_typing must fire exactly once after completion"- );-}--// ── Context key logic for Telegram ──────────────────────────────────────────--/// Regression: Telegram uses thread_ts for transport targeting, NOT for-/// splitting conversation history. Messages in the same chat from the same-/// sender must share one history key regardless of their thread_ts value.-#[test]-fn telegram_channel_history_key_ignores_thread_ts() {- let base_msg = traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "tg_100_1".to_string(),- sender: "alice".to_string(),- reply_target: "100".to_string(),- content: "hello".to_string(),- channel: "telegram".to_string(),- timestamp: 1,- thread_ts: None,- sender_name: None,- };-- let msg_with_thread = traits::ChannelMessage {- id: "tg_100_2".to_string(),- thread_ts: Some("42".to_string()),- ..base_msg.clone()- };-- let msg_with_different_thread = traits::ChannelMessage {- id: "tg_100_3".to_string(),- thread_ts: Some("99".to_string()),- ..base_msg.clone()- };-- let key_base = conversation_history_key(&base_msg);- let key_thread = conversation_history_key(&msg_with_thread);- let key_other_thread = conversation_history_key(&msg_with_different_thread);-- assert_eq!(- key_base, key_thread,- "telegram: no-thread and threaded messages must share one history key"- );- assert_eq!(- key_thread, key_other_thread,- "telegram: different thread_ts values must still share one history key"- );-}--// ── Full Telegram-shaped dispatch (supports_reactions = true) ──────────────--/// A recording channel that mirrors the real `TelegramChannel` contract:-/// reports `name() == "telegram"` and `supports_reactions() == true`. Used-/// to prove the dispatch pipeline emits the automatic `[REACTION:...]`-/// acknowledgment for threaded Telegram messages — a path the default-/// `FullRecordingChannel` above cannot exercise because it reports-/// `supports_reactions() == false`.-#[derive(Default)]-struct TelegramReactingChannel {- sent: tokio::sync::Mutex<Vec<SendMessage>>,-}--#[async_trait::async_trait]-impl Channel for TelegramReactingChannel {- fn name(&self) -> &str {- "telegram"- }-- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {- self.sent.lock().await.push(message.clone());- Ok(())- }-- async fn listen(- &self,- _tx: tokio::sync::mpsc::Sender<traits::ChannelMessage>,- ) -> anyhow::Result<()> {- Ok(())- }-- fn supports_reactions(&self) -> bool {- true- }-}--/// When a threaded Telegram inbound arrives AND the channel reports-/// `supports_reactions() == true`, dispatch must emit an automatic-/// acknowledgment reaction (a `[REACTION:<emoji>]` send targeting the-/// original message_id via `thread_ts`) BEFORE the real reply. The reply-/// itself should still carry the same `thread_ts` so Telegram attaches it-/// to the original message.-///-/// This is the Telegram-specific dispatch path that Discord explicitly-/// excludes (see `discord_integration.rs`). Together the two tests prove-/// the `supports_reactions()` capability flag is honored in both-/// directions.-#[tokio::test]-async fn telegram_threaded_inbound_emits_ack_reaction_then_reply() {- let _bus_guard = super::common::use_real_agent_handler().await;- let recorder = Arc::new(TelegramReactingChannel::default());- let channel: Arc<dyn Channel> = recorder.clone();- let provider: Arc<dyn ChatModel<()>> = Arc::new(FixedResponseModel { response: "pong" });- let ctx = make_test_context(channel, provider);-- process_channel_message(- ctx,- traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "tg_200_77".to_string(),- sender: "alice".to_string(),- reply_target: "200".to_string(),- content: "ping".to_string(),- channel: "telegram".to_string(),- timestamp: 1,- thread_ts: Some("77".to_string()),- sender_name: None,- },- )- .await;-- let sent = recorder.sent.lock().await;- assert!(- sent.len() >= 2,- "expected at least two sends (ack reaction + reply), got {}",- sent.len()- );-- // Exactly one of the sends must be the automatic reaction ack — its- // content must start with `[REACTION:` and its thread_ts must match the- // inbound message_id so Telegram attaches the reaction correctly.- let reaction_sends: Vec<_> = sent- .iter()- .filter(|m| m.content.starts_with("[REACTION:"))- .collect();- assert_eq!(- reaction_sends.len(),- 1,- "expected exactly one automatic [REACTION:...] ack send, got {:?}",- sent.iter().map(|m| &m.content).collect::<Vec<_>>()- );- assert_eq!(- reaction_sends[0].thread_ts.as_deref(),- Some("77"),- "ack reaction must carry thread_ts = inbound message_id for targeting"- );-- // Exactly one real reply send must also be present, carrying the same- // thread_ts so Telegram threads the reply to the original message.- let reply_sends: Vec<_> = sent- .iter()- .filter(|m| !m.content.starts_with("[REACTION:"))- .collect();- assert_eq!(- reply_sends.len(),- 1,- "expected exactly one real reply send alongside the ack"- );- assert!(- reply_sends[0].content.contains("pong"),- "reply send must contain the provider response, got {:?}",- reply_sends[0].content- );- assert_eq!(- reply_sends[0].thread_ts.as_deref(),- Some("77"),- "reply send must carry the same thread_ts as the inbound"- );-}--/// Regression: for non-Telegram channels, thread_ts DOES split history keys-/// so each thread maintains independent conversation context.-#[test]-fn non_telegram_channel_history_key_includes_thread_ts() {- let base_msg = traits::ChannelMessage {- reply_to_id: None,- topic_id: None,- id: "slack_C01_1".to_string(),- sender: "alice".to_string(),- reply_target: "C01".to_string(),- content: "hello".to_string(),- channel: "slack".to_string(),- timestamp: 1,- thread_ts: None,- sender_name: None,- };-- let msg_in_thread = traits::ChannelMessage {- id: "slack_C01_2".to_string(),- thread_ts: Some("1234567890.000001".to_string()),- ..base_msg.clone()- };-- let key_base = conversation_history_key(&base_msg);- let key_thread = conversation_history_key(&msg_in_thread);-- assert_ne!(- key_base, key_thread,- "slack: threaded messages must get a distinct history key from top-level"- );-}