Skip to content

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

chore(telegram): remove legacy approval surface, bus subscriber, and remote control modules

Steven Enamakel703507fcdace
diff --git a/crates/openhuman-core/src/channels/providers/telegram/approval_surface.rs b/crates/openhuman-core/src/channels/providers/telegram/approval_surface.rs
deleted file mode 100644
index 4d57d5bfd2..0000000000
--- a/crates/openhuman-core/src/channels/providers/telegram/approval_surface.rs
+++ /dev/null
@@ -1,227 +0,0 @@
-//! Bridge `ApprovalRequested` domain events to Telegram chat messages.
-//!
-//! Background — sub-issue 2 of #3098: prior to this subscriber, channel
-//! turns initiated from Telegram (Discord, Slack, iMessage, …) carried
-//! no [`ApprovalChatContext`], so the [`ApprovalGate`]'s "no chat
-//! context → allow straight through" branch (`approval/gate.rs:225-231`)
-//! silently bypassed every `Prompt`-class tool call. A user on
-//! `level=supervised` got the same unprompted behavior as `level=full`
-//! over Telegram, which voids the entire supervised approval model.
-//!
-//! This subscriber, paired with the [`APPROVAL_CHAT_CONTEXT`] scope set
-//! in `channels/runtime/dispatch.rs` for Telegram turns, makes the
-//! approval gate actually fire over Telegram:
-//!
-//! 1. The dispatch loop scopes the agent turn in an [`ApprovalChatContext`]
-//! whose `thread_id` is the conversation history key and `client_id`
-//! is `"telegram"`.
-//! 2. When a tool call gets parked, the gate publishes
-//! [`DomainEvent::ApprovalRequested`] with those identifiers.
-//! 3. This subscriber sees the event, looks up the original
-//! `(reply_target, thread_ts)` by `thread_id` (populated from the
-//! parallel [`DomainEvent::ChannelMessageReceived`] stream), and sends
-//! a Telegram message asking the user to reply `yes`/`no`.
-//! 4. The user replies in Telegram; the dispatch loop intercepts the
-//! reply, parses it via [`parse_approval_reply`], and routes it to
-//! [`ApprovalGate::decide`] — resuming the parked tool call.
-//!
-//! Discord, Slack, iMessage, and Mattermost are still in the silent
-//! bypass state (no per-channel surface subscriber, no
-//! `ApprovalChatContext` scoping). Each will get its own follow-up PR.
-//!
-//! [`APPROVAL_CHAT_CONTEXT`]: crate::security::approval::APPROVAL_CHAT_CONTEXT
-//! [`ApprovalChatContext`]: crate::security::approval::ApprovalChatContext
-//! [`ApprovalGate`]: crate::security::approval::ApprovalGate
-//! [`ApprovalGate::decide`]: crate::security::approval::ApprovalGate::decide
-//! [`parse_approval_reply`]: crate::security::approval::parse_approval_reply
-
-use crate::channels::traits::{ChannelSendExt, SendMessage};
-use crate::channels::Channel;
-use crate::core::events::DomainEvent;
-use async_trait::async_trait;
-use std::collections::HashMap;
-use std::sync::{Arc, Mutex};
-use tinybus::EventHandler;
-
-const LOG_PREFIX: &str = "[telegram-approval]";
-use tinychannels::providers::telegram::format_approval_prompt;
-pub use tinychannels::providers::telegram::TELEGRAM_APPROVAL_CLIENT_ID;
-
-/// Reply context captured from a Telegram inbound message so a later
-/// `ApprovalRequested` event can be sent back to the right Telegram chat
-/// (and reply thread, when one is in use).
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub(crate) struct ReplyContext {
- pub(crate) reply_target: String,
- pub(crate) thread_ts: Option<String>,
-}
-
-/// Same shape as `channels::context::conversation_history_key` but
-/// reconstructable from individual `ChannelMessageReceived` event fields
-/// (the helper takes a `&ChannelMessage`). Keep in sync with that
-/// helper's Telegram branch — Telegram drops `thread_ts` from the key so
-/// reply threads stay glued to the same history.
-fn telegram_history_key(sender: &str, reply_target: &str) -> String {
- format!("telegram_{sender}_{reply_target}")
-}
-
-/// Subscriber that turns `ApprovalRequested` events for Telegram-originated
-/// turns into Telegram messages. Holds a small in-memory map keyed by the
-/// conversation history key so the inbound message context (reply_target,
-/// thread_ts) is available when an approval surfaces later in the same
-/// turn.
-pub struct TelegramApprovalSurfaceSubscriber {
- channels_by_name: Arc<HashMap<String, Arc<dyn Channel>>>,
- reply_index: Arc<Mutex<HashMap<String, ReplyContext>>>,
-}
-
-impl TelegramApprovalSurfaceSubscriber {
- pub fn new(channels_by_name: Arc<HashMap<String, Arc<dyn Channel>>>) -> Self {
- Self {
- channels_by_name,
- reply_index: Arc::new(Mutex::new(HashMap::new())),
- }
- }
-
- /// For tests: snapshot a reply context by history key. Returns `None`
- /// if the subscriber hasn't seen a Telegram message on that thread.
- #[cfg(test)]
- pub(crate) fn reply_context(&self, history_key: &str) -> Option<ReplyContext> {
- self.reply_index
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .get(history_key)
- .cloned()
- }
-
- /// For tests: directly seed a reply context, simulating an inbound
- /// `ChannelMessageReceived` for a Telegram message. Lets tests cover
- /// the `ApprovalRequested` branch without spinning up the runtime
- /// dispatch loop.
- #[cfg(test)]
- pub(crate) fn record_reply_context_for_test(&self, history_key: &str, ctx: ReplyContext) {
- self.reply_index
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .insert(history_key.to_string(), ctx);
- }
-
- fn record_reply_context(&self, sender: &str, reply_target: &str, thread_ts: Option<&str>) {
- let key = telegram_history_key(sender, reply_target);
- let ctx = ReplyContext {
- reply_target: reply_target.to_string(),
- thread_ts: thread_ts.map(str::to_string),
- };
- self.reply_index
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .insert(key, ctx);
- }
-
- async fn send_approval_prompt(
- &self,
- request_id: &str,
- tool_name: &str,
- action_summary: &str,
- thread_id: &str,
- ) {
- let reply_ctx = match self
- .reply_index
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .get(thread_id)
- .cloned()
- {
- Some(ctx) => ctx,
- None => {
- tracing::warn!(
- "{LOG_PREFIX} no reply context recorded for thread_id={thread_id} \
- (approval request_id={request_id} tool={tool_name}); cannot surface \
- prompt — the parked turn will TTL-deny"
- );
- return;
- }
- };
-
- let channel = match self.channels_by_name.get(TELEGRAM_APPROVAL_CLIENT_ID) {
- Some(c) => Arc::clone(c),
- None => {
- tracing::warn!(
- "{LOG_PREFIX} telegram channel not registered in runtime; \
- dropping approval prompt for request_id={request_id}"
- );
- return;
- }
- };
-
- let body = format_approval_prompt(tool_name, action_summary);
- let send = SendMessage::new(body, &reply_ctx.reply_target).in_thread(reply_ctx.thread_ts);
-
- tracing::info!(
- "{LOG_PREFIX} surfacing approval prompt request_id={request_id} tool={tool_name} \
- thread_id={thread_id} reply_target={}",
- reply_ctx.reply_target
- );
-
- if let Err(err) = channel.send_with_outbound_intent(&send).await {
- tracing::warn!(
- "{LOG_PREFIX} failed to send approval prompt request_id={request_id} \
- tool={tool_name}: {err}"
- );
- }
- }
-}
-
-#[async_trait]
-impl EventHandler<DomainEvent> for TelegramApprovalSurfaceSubscriber {
- fn name(&self) -> &str {
- "telegram::approval_surface"
- }
-
- fn domains(&self) -> Option<&[&str]> {
- Some(&["channel", "approval"])
- }
-
- async fn handle(&self, event: &DomainEvent) {
- match event {
- DomainEvent::ChannelMessageReceived {
- channel,
- sender,
- reply_target,
- thread_ts,
- ..
- } if channel == TELEGRAM_APPROVAL_CLIENT_ID => {
- self.record_reply_context(sender, reply_target, thread_ts.as_deref());
- }
- DomainEvent::ApprovalRequested {
- request_id,
- tool_name,
- action_summary,
- thread_id,
- client_id,
- ..
- } => {
- let Some(client) = client_id.as_deref() else {
- return;
- };
- if client != TELEGRAM_APPROVAL_CLIENT_ID {
- return;
- }
- let Some(thread_id) = thread_id.as_deref() else {
- tracing::warn!(
- "{LOG_PREFIX} approval request_id={request_id} tool={tool_name} \
- has client_id=telegram but no thread_id — cannot route"
- );
- return;
- };
- self.send_approval_prompt(request_id, tool_name, action_summary, thread_id)
- .await;
- }
- _ => {}
- }
- }
-}
-
-#[cfg(test)]
-#[path = "approval_surface_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/channels/providers/telegram/approval_surface_tests.rs b/crates/openhuman-core/src/channels/providers/telegram/approval_surface_tests.rs
deleted file mode 100644
index dd414e624d..0000000000
--- a/crates/openhuman-core/src/channels/providers/telegram/approval_surface_tests.rs
+++ /dev/null
@@ -1,230 +0,0 @@
-//! Tests for the Telegram approval-surface subscriber.
-
-use super::*;
-use crate::channels::traits::{ChannelMessage, SendMessage};
-use crate::channels::Channel;
-use async_trait::async_trait;
-use std::collections::HashMap;
-use std::path::PathBuf;
-use std::sync::Mutex as StdMutex;
-use tinybus::EventHandler;
-
-/// Mock channel that records every outbound `send()` call. Used in place
-/// of the real `TelegramChannel` so tests can assert what the subscriber
-/// would have sent without needing the Telegram Bot API or a network.
-struct RecordingChannel {
- name: String,
- sent: StdMutex<Vec<SendMessage>>,
-}
-
-impl RecordingChannel {
- fn new(name: &str) -> Self {
- Self {
- name: name.to_string(),
- sent: StdMutex::new(Vec::new()),
- }
- }
-
- fn drain(&self) -> Vec<SendMessage> {
- std::mem::take(&mut *self.sent.lock().unwrap())
- }
-}
-
-#[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 subscriber_with_channel(channel: Arc<RecordingChannel>) -> TelegramApprovalSurfaceSubscriber {
- let mut map: HashMap<String, Arc<dyn Channel>> = HashMap::new();
- map.insert("telegram".to_string(), channel);
- TelegramApprovalSurfaceSubscriber::new(Arc::new(map))
-}
-
-fn approval_event(thread_id: Option<&str>, client_id: Option<&str>) -> DomainEvent {
- DomainEvent::ApprovalRequested {
- request_id: "req-1".to_string(),
- tool_name: "file_write".to_string(),
- action_summary: "Write notes/today.md (1.2 KiB)".to_string(),
- args_redacted: serde_json::json!({"path": "notes/today.md"}),
- thread_id: thread_id.map(str::to_string),
- client_id: client_id.map(str::to_string),
- tool_call_id: None,
- expires_at: None,
- }
-}
-
-fn inbound_event(sender: &str, reply_target: &str, thread_ts: Option<&str>) -> DomainEvent {
- DomainEvent::ChannelMessageReceived {
- channel: "telegram".to_string(),
- message_id: "m-1".to_string(),
- sender: sender.to_string(),
- reply_target: reply_target.to_string(),
- content: "hi".to_string(),
- thread_ts: thread_ts.map(str::to_string),
- inbound_envelope: None,
- workspace_dir: PathBuf::from("/tmp"),
- }
-}
-
-#[tokio::test]
-async fn channel_message_received_records_reply_context() {
- let channel = Arc::new(RecordingChannel::new("telegram"));
- let sub = subscriber_with_channel(Arc::clone(&channel));
-
- sub.handle(&inbound_event("alice", "chat-42", None)).await;
-
- let ctx = sub
- .reply_context("telegram_alice_chat-42")
- .expect("reply context should be recorded for the inbound message");
- assert_eq!(ctx.reply_target, "chat-42");
- assert_eq!(ctx.thread_ts, None);
-}
-
-#[tokio::test]
-async fn channel_message_received_ignores_non_telegram_channels() {
- let channel = Arc::new(RecordingChannel::new("telegram"));
- let sub = subscriber_with_channel(Arc::clone(&channel));
-
- let discord_event = DomainEvent::ChannelMessageReceived {
- channel: "discord".to_string(),
- message_id: "d-1".to_string(),
- sender: "bob".to_string(),
- reply_target: "channel-9".to_string(),
- content: "hi".to_string(),
- thread_ts: None,
- inbound_envelope: None,
- workspace_dir: PathBuf::from("/tmp"),
- };
- sub.handle(&discord_event).await;
-
- assert!(
- sub.reply_context("discord_bob_channel-9").is_none(),
- "subscriber must scope to telegram and not pollute its index with other channels"
- );
-}
-
-#[tokio::test]
-async fn approval_request_sends_telegram_message_with_recorded_context() {
- let channel = Arc::new(RecordingChannel::new("telegram"));
- let sub = subscriber_with_channel(Arc::clone(&channel));
- sub.record_reply_context_for_test(
- "telegram_alice_chat-42",
- ReplyContext {
- reply_target: "chat-42".to_string(),
- thread_ts: Some("987654321".to_string()),
- },
- );
-
- sub.handle(&approval_event(
- Some("telegram_alice_chat-42"),
- Some("telegram"),
- ))
- .await;
-
- let sent = channel.drain();
- assert_eq!(sent.len(), 1, "exactly one message should have been sent");
- let msg = &sent[0];
- assert_eq!(msg.recipient, "chat-42");
- assert_eq!(msg.thread_ts.as_deref(), Some("987654321"));
- assert!(
- msg.content.contains("Approval needed"),
- "prompt body should advertise itself as an approval ask, got: {}",
- msg.content
- );
- assert!(
- msg.content.contains("file_write"),
- "prompt body should include the tool name"
- );
- assert!(
- msg.content.contains("yes") && msg.content.contains("no"),
- "prompt body must tell the user how to reply, got: {}",
- msg.content
- );
-}
-
-#[tokio::test]
-async fn approval_request_without_recorded_context_does_not_send_anything() {
- let channel = Arc::new(RecordingChannel::new("telegram"));
- let sub = subscriber_with_channel(Arc::clone(&channel));
-
- // No record_reply_context_for_test call — subscriber has never seen
- // an inbound message for this thread.
- sub.handle(&approval_event(
- Some("telegram_alice_chat-42"),
- Some("telegram"),
- ))
- .await;
-
- assert!(
- channel.drain().is_empty(),
- "subscriber must not invent a reply target when no inbound context was recorded"
- );
-}
-
-#[tokio::test]
-async fn approval_request_for_non_telegram_client_is_ignored() {
- let channel = Arc::new(RecordingChannel::new("telegram"));
- let sub = subscriber_with_channel(Arc::clone(&channel));
- // Seed a context so we'd otherwise be able to send.
- sub.record_reply_context_for_test(
- "telegram_alice_chat-42",
- ReplyContext {
- reply_target: "chat-42".to_string(),
- thread_ts: None,
- },
- );
-
- // Web-channel approval — must not be handled here.
- sub.handle(&approval_event(Some("thread-web-1"), Some("web")))
- .await;
-
- assert!(
- channel.drain().is_empty(),
- "subscriber must scope by client_id; web/discord/etc. approvals are handled by their own surfaces"
- );
-}
-
-#[tokio::test]
-async fn approval_request_without_client_id_is_ignored() {
- let channel = Arc::new(RecordingChannel::new("telegram"));
- let sub = subscriber_with_channel(Arc::clone(&channel));
- sub.record_reply_context_for_test(
- "telegram_alice_chat-42",
- ReplyContext {
- reply_target: "chat-42".to_string(),
- thread_ts: None,
- },
- );
-
- sub.handle(&approval_event(Some("telegram_alice_chat-42"), None))
- .await;
-
- assert!(
- channel.drain().is_empty(),
- "background / triage approvals (no client_id) must not be routed to Telegram"
- );
-}
-
-#[test]
-fn telegram_history_key_matches_format_in_dispatch_helper() {
- // Locking the key shape so the dispatch loop's
- // `conversation_history_key` and this module's `telegram_history_key`
- // stay byte-identical for Telegram — they MUST agree, or the
- // subscriber's lookup will miss every parked approval.
- assert_eq!(
- telegram_history_key("alice", "chat-42"),
- "telegram_alice_chat-42"
- );
-}
diff --git a/crates/openhuman-core/src/channels/providers/telegram/bus.rs b/crates/openhuman-core/src/channels/providers/telegram/bus.rs
deleted file mode 100644
index d42210978a..0000000000
--- a/crates/openhuman-core/src/channels/providers/telegram/bus.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-//! Event-bus subscriber for Telegram remote-control lifecycle signals.
-
-use crate::channels::providers::telegram::session_store::with_store;
-use crate::core::events::DomainEvent;
-use async_trait::async_trait;
-use std::path::PathBuf;
-use tinybus::EventHandler;
-
-const LOG_PREFIX: &str = "[telegram-remote]";
-
-/// Tracks Telegram turn lifecycle via channel domain events and exposes busy
-/// state for `/status`.
-pub struct TelegramRemoteSubscriber {
- workspace_dir: PathBuf,
-}
-
-impl TelegramRemoteSubscriber {
- pub fn new(workspace_dir: PathBuf) -> Self {
- Self { workspace_dir }
- }
-
- async fn set_busy(&self, reply_target: &str, busy: bool) {
- let workspace_dir = self.workspace_dir.clone();
- let reply_target_owned = reply_target.to_string();
- let join_result = tokio::task::spawn_blocking(move || {
- with_store(&workspace_dir, |store| {
- store.set_busy(&reply_target_owned, busy);
- Ok(())
- })
- })
- .await;
-
- match join_result {
- Ok(Ok(())) => {}
- Ok(Err(error)) => tracing::warn!(
- "{LOG_PREFIX} failed to persist busy={busy} reply_target={reply_target}: {error}"
- ),
- Err(error) => tracing::warn!(
- "{LOG_PREFIX} join error persisting busy={busy} reply_target={reply_target}: {error}"
- ),
- }
- }
-}
-
-#[async_trait]
-impl EventHandler<DomainEvent> for TelegramRemoteSubscriber {
- fn name(&self) -> &str {
- "telegram::remote_control"
- }
-
- fn domains(&self) -> Option<&[&str]> {
- Some(&["channel"])
- }
-
- async fn handle(&self, event: &DomainEvent) {
- match event {
- DomainEvent::ChannelMessageReceived {
- channel,
- reply_target,
- workspace_dir,
- ..
- } if channel == "telegram" => {
- if *workspace_dir != self.workspace_dir {
- tracing::debug!(
- "{LOG_PREFIX} dropping stale-workspace ChannelMessageReceived \
- event_ws={} self_ws={}",
- workspace_dir.display(),
- self.workspace_dir.display()
- );
- return;
- }
- tracing::debug!("{LOG_PREFIX} turn started reply_target={reply_target}");
- self.set_busy(reply_target, true).await;
- }
- DomainEvent::ChannelMessageProcessed {
- channel,
- reply_target,
- success,
- elapsed_ms,
- workspace_dir,
- ..
- } if channel == "telegram" => {
- if *workspace_dir != self.workspace_dir {
- tracing::debug!(
- "{LOG_PREFIX} dropping stale-workspace ChannelMessageProcessed \
- event_ws={} self_ws={}",
- workspace_dir.display(),
- self.workspace_dir.display()
- );
- return;
- }
- tracing::debug!(
- "{LOG_PREFIX} turn finished reply_target={reply_target} success={success} elapsed_ms={elapsed_ms}"
- );
- self.set_busy(reply_target, false).await;
- }
- _ => {}
- }
- }
-}
diff --git a/crates/openhuman-core/src/channels/providers/telegram/bus_tests.rs b/crates/openhuman-core/src/channels/providers/telegram/bus_tests.rs
deleted file mode 100644
index e2802b3923..0000000000
--- a/crates/openhuman-core/src/channels/providers/telegram/bus_tests.rs
+++ /dev/null
@@ -1,219 +0,0 @@
-use super::bus::TelegramRemoteSubscriber;
-use crate::core::events::DomainEvent;
-use tempfile::tempdir;
-use tinybus::EventHandler;
-
-#[tokio::test]
-async fn subscriber_marks_busy_on_received_and_clears_on_processed() {
- let dir = tempdir().expect("tempdir");
- let subscriber = TelegramRemoteSubscriber::new(dir.path().to_path_buf());
- assert_eq!(subscriber.name(), "telegram::remote_control");
- assert_eq!(subscriber.domains(), Some(&["channel"][..]));
-
- subscriber
- .handle(&DomainEvent::ChannelMessageReceived {
- channel: "telegram".into(),
- message_id: "m1".into(),
- sender: "alice".into(),
- reply_target: "chat-99".into(),
- content: "hi".into(),
- thread_ts: Some("1".into()),
- inbound_envelope: None,
- workspace_dir: dir.path().to_path_buf(),
- })
- .await;
-
- let busy = super::session_store::with_store(dir.path(), |store| Ok(store.is_busy("chat-99")))
- .expect("store");
- assert!(busy);
-
- subscriber
- .handle(&DomainEvent::ChannelMessageProcessed {
- channel: "telegram".into(),
- message_id: "m1".into(),
- sender: "alice".into(),
- reply_target: "chat-99".into(),
- content: "hi".into(),
- thread_ts: Some("1".into()),
- response: "ok".into(),
- provider: "test-provider".into(),
- model: "test-model".into(),
- elapsed_ms: 10,
- success: true,
- workspace_dir: dir.path().to_path_buf(),
- })
- .await;
-
- let busy = super::session_store::with_store(dir.path(), |store| Ok(store.is_busy("chat-99")))
- .expect("store");
- assert!(!busy);
-}
-
-#[tokio::test]
-async fn subscriber_ignores_non_telegram_channel_events() {
- let dir = tempdir().expect("tempdir");
- let subscriber = TelegramRemoteSubscriber::new(dir.path().to_path_buf());
-
- subscriber
- .handle(&DomainEvent::ChannelMessageReceived {
- channel: "discord".into(),
- message_id: "m1".into(),
- sender: "alice".into(),
- reply_target: "chat-99".into(),
- content: "hi".into(),
- thread_ts: None,
- inbound_envelope: None,
- workspace_dir: dir.path().to_path_buf(),
- })
- .await;
-
- let busy = super::session_store::with_store(dir.path(), |store| Ok(store.is_busy("chat-99")))
- .expect("store");
- assert!(!busy);
-}
-
-// ── Workspace-identity guard tests ───────────────────────────────────────────
-
-/// Positive control: matching workspace sets busy state as expected.
-#[tokio::test]
-async fn telegram_received_matching_workspace_sets_busy() {
- let dir = tempdir().expect("tempdir");
- let subscriber = TelegramRemoteSubscriber::new(dir.path().to_path_buf());
-
- subscriber
- .handle(&DomainEvent::ChannelMessageReceived {
- channel: "telegram".into(),
- message_id: "m1".into(),
- sender: "alice".into(),
- reply_target: "chat-10".into(),
- content: "hi".into(),
- thread_ts: None,
- inbound_envelope: None,
- workspace_dir: dir.path().to_path_buf(),
- })
- .await;
-
- let busy = super::session_store::with_store(dir.path(), |store| Ok(store.is_busy("chat-10")))
- .expect("store");
- assert!(busy, "matching workspace should mark busy");
-}
-
-/// Stale workspace on `ChannelMessageReceived` — busy must NOT be set.
-#[tokio::test]
-async fn telegram_received_stale_workspace_does_not_set_busy() {
- let dir = tempdir().expect("tempdir");
- let stale = tempdir().expect("stale tempdir");
- let subscriber = TelegramRemoteSubscriber::new(dir.path().to_path_buf());
-
- subscriber
- .handle(&DomainEvent::ChannelMessageReceived {
- channel: "telegram".into(),
- message_id: "m1".into(),
- sender: "alice".into(),
- reply_target: "chat-20".into(),
- content: "hi".into(),
- thread_ts: None,
- inbound_envelope: None,
- workspace_dir: stale.path().to_path_buf(),
- })
- .await;
-
- let busy = super::session_store::with_store(dir.path(), |store| Ok(store.is_busy("chat-20")))
- .expect("store");
- assert!(!busy, "stale workspace should not set busy");
-}
-
-/// Matching workspace on `ChannelMessageProcessed` clears busy state correctly.
-#[tokio::test]
-async fn telegram_processed_matching_workspace_clears_busy() {
- let dir = tempdir().expect("tempdir");
- let subscriber = TelegramRemoteSubscriber::new(dir.path().to_path_buf());
-
- // First mark as busy via a matching received event.
- subscriber
- .handle(&DomainEvent::ChannelMessageReceived {
- channel: "telegram".into(),
- message_id: "m1".into(),
- sender: "alice".into(),
- reply_target: "chat-30".into(),
- content: "hi".into(),
- thread_ts: None,
- inbound_envelope: None,
- workspace_dir: dir.path().to_path_buf(),
- })
- .await;
-
- let busy = super::session_store::with_store(dir.path(), |store| Ok(store.is_busy("chat-30")))
- .expect("store");
- assert!(busy, "should be busy after received");
-
- // Now clear with a matching processed event.
- subscriber
- .handle(&DomainEvent::ChannelMessageProcessed {
- channel: "telegram".into(),
- message_id: "m1".into(),
- sender: "alice".into(),
- reply_target: "chat-30".into(),
- content: "hi".into(),
- thread_ts: None,
- response: "done".into(),
- provider: "test-provider".into(),
- model: "test-model".into(),
- elapsed_ms: 50,
- success: true,
- workspace_dir: dir.path().to_path_buf(),
- })
- .await;
-
- let busy = super::session_store::with_store(dir.path(), |store| Ok(store.is_busy("chat-30")))
- .expect("store");
- assert!(!busy, "matching processed should clear busy");
-}
-
-/// Stale workspace on `ChannelMessageProcessed` — busy must NOT be cleared.
-#[tokio::test]
-async fn telegram_processed_stale_workspace_does_not_clear_busy() {
- let dir = tempdir().expect("tempdir");
- let stale = tempdir().expect("stale tempdir");
- let subscriber = TelegramRemoteSubscriber::new(dir.path().to_path_buf());
-
- // Mark as busy via a matching received event.
- subscriber
- .handle(&DomainEvent::ChannelMessageReceived {
- channel: "telegram".into(),
- message_id: "m1".into(),
- sender: "alice".into(),
- reply_target: "chat-40".into(),
- content: "hi".into(),
- thread_ts: None,
- inbound_envelope: None,
- workspace_dir: dir.path().to_path_buf(),
- })
- .await;
-
- let busy = super::session_store::with_store(dir.path(), |store| Ok(store.is_busy("chat-40")))
- .expect("store");
- assert!(busy, "should be busy after matching received");
-
- // Attempt to clear with a stale-workspace processed event — must be ignored.
- subscriber
- .handle(&DomainEvent::ChannelMessageProcessed {
- channel: "telegram".into(),
- message_id: "m1".into(),
- sender: "alice".into(),
- reply_target: "chat-40".into(),
- content: "hi".into(),
- thread_ts: None,
- response: "done".into(),
- provider: "test-provider".into(),
- model: "test-model".into(),
- elapsed_ms: 50,
- success: true,
- workspace_dir: stale.path().to_path_buf(),
- })
- .await;
-
- let busy = super::session_store::with_store(dir.path(), |store| Ok(store.is_busy("chat-40")))
- .expect("store");
- assert!(busy, "stale processed must not clear busy state");
-}
diff --git a/crates/openhuman-core/src/channels/providers/telegram/mod.rs b/crates/openhuman-core/src/channels/providers/telegram/mod.rs
deleted file mode 100644
index 5ee1dc59c4..0000000000
--- a/crates/openhuman-core/src/channels/providers/telegram/mod.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-//! Telegram channel — host-side glue.
-//!
-//! The transport (Bot API driver, session store, pairing) now lives in
-//! `tinychannels::providers::telegram`; re-export it here so existing paths
-//! keep resolving. What stays are the host-coupled pieces that depend on the
-//! OpenHuman event bus, runtime context, and cross-channel calls:
-//! - [`remote_control`] — `/status /sessions /new` command handling (uses the
-//! agent runtime context + web session invalidation).
-//! - [`bus`] — the `TelegramRemoteSubscriber` busy-state event handler.
-//! - [`approval_surface`] — the `TelegramApprovalSurfaceSubscriber`.
-
-mod approval_surface;
-mod bus;
-pub mod remote_control;
-
-// Transport moved to tinychannels.
-pub use tinychannels::providers::telegram::{session_store, TelegramChannel};
-
-pub use approval_surface::{TelegramApprovalSurfaceSubscriber, TELEGRAM_APPROVAL_CLIENT_ID};
-pub use bus::TelegramRemoteSubscriber;
-pub use remote_control::TelegramRemoteCommand;
-
-#[cfg(any(test, debug_assertions))]
-#[path = "mod_test_support_tests.rs"]
-pub mod test_support;
-
-#[cfg(test)]
-#[path = "bus_tests.rs"]
-mod bus_tests;
diff --git a/crates/openhuman-core/src/channels/providers/telegram/mod_test_support_tests.rs b/crates/openhuman-core/src/channels/providers/telegram/mod_test_support_tests.rs
deleted file mode 100644
index 031a7365b9..0000000000
--- a/crates/openhuman-core/src/channels/providers/telegram/mod_test_support_tests.rs
+++ /dev/null
@@ -1,4 +0,0 @@
-//! Debug-build seams for raw integration coverage of Telegram send helpers.
-//! Delegates to the tinychannels transport crate where the logic now lives.
-
-pub use tinychannels::providers::telegram::test_support::parse_reaction_marker_for_test;
diff --git a/crates/openhuman-core/src/channels/providers/telegram/remote_control.rs b/crates/openhuman-core/src/channels/providers/telegram/remote_control.rs
deleted file mode 100644
index 76478377fa..0000000000
--- a/crates/openhuman-core/src/channels/providers/telegram/remote_control.rs
+++ /dev/null
@@ -1,218 +0,0 @@
-//! Telegram remote-control slash commands (phase 1: `/status`, `/sessions`, `/new`).
-
-use super::session_store::{with_store, with_store_read, TelegramChatBinding};
-use crate::channels::context::{
- clear_sender_history, conversation_history_key, ChannelRouteSelection, ChannelRuntimeContext,
-};
-use crate::channels::traits::ChannelMessage;
-use crate::memory::conversations::{self as conversations, CreateConversationThread};
-pub use tinychannels::providers::telegram::parse_telegram_remote_command;
-pub use tinychannels::providers::telegram::TelegramRemoteCommand;
-use tinychannels::providers::telegram::{
- build_new_session_response as render_new_session_response, build_remote_help_response,
- build_status_response as render_status_response, format_session_line, SESSIONS_LIST_LIMIT,
-};
-
-const LOG_PREFIX: &str = "[telegram-remote]";
-
-pub(crate) async fn build_remote_command_response(
- ctx: &ChannelRuntimeContext,
- msg: &ChannelMessage,
- command: TelegramRemoteCommand,
-) -> String {
- tracing::debug!(
- "{LOG_PREFIX} command={command:?} reply_target={} sender={}",
- msg.reply_target,
- msg.sender
- );
- match command {
- TelegramRemoteCommand::Status => build_status_response(ctx, msg).await,
- TelegramRemoteCommand::Sessions => build_sessions_response(ctx, msg).await,
- TelegramRemoteCommand::New => build_new_session_response(ctx, msg).await,
- TelegramRemoteCommand::Help => build_remote_help_response(),
- }
-}
-
-fn route_for_sender(ctx: &ChannelRuntimeContext, sender_key: &str) -> ChannelRouteSelection {
- ctx.route_overrides
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .get(sender_key)
- .cloned()
- .unwrap_or_else(|| ChannelRouteSelection {
- provider: ctx.default_provider.as_str().to_string(),
- model: ctx.model.as_str().to_string(),
- })
-}
-
-async fn build_status_response(ctx: &ChannelRuntimeContext, msg: &ChannelMessage) -> String {
- let sender_key = conversation_history_key(msg);
- let route = route_for_sender(ctx, &sender_key);
- let history_len = ctx
- .conversation_histories
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .get(&sender_key)
- .map(|h| h.len())
- .unwrap_or(0);
-
- let workspace = ctx.workspace_dir.clone();
- let reply_target = msg.reply_target.clone();
- // Use with_store_read (no disk write) and spawn_blocking to keep the async
- // executor thread unblocked during mutex acquisition + file I/O.
- let (binding, busy) = tokio::task::spawn_blocking(move || {
- with_store_read(&workspace, |store| {
- Ok((
- store.binding(&reply_target).cloned(),
- store.is_busy(&reply_target),
- ))
- })
- })
- .await
- .unwrap_or_else(|join_err| {
- tracing::warn!("{LOG_PREFIX} status: join error reading session store: {join_err}");
- Ok((None, false))
- })
- .unwrap_or_else(|store_err| {
- tracing::warn!("{LOG_PREFIX} status: session store error: {store_err}");
- (None, false)
- });
-
- let thread_line = match binding {
- Some(TelegramChatBinding {
- ref thread_id,
- ref title,
- ..
- }) => {
- // Use the stored title (captured at /new time) — O(1), no disk read.
- let display_title = title
- .as_deref()
- .filter(|t| !t.trim().is_empty())
- .unwrap_or(thread_id);
- format!("Thread: `{display_title}` (`{thread_id}`)")
- }
- None => "Thread: _(none — send `/new` to bind a thread)_".to_string(),
- };
-
- render_status_response(
- &thread_line,
- &route.provider,
- &route.model,
- history_len,
- busy,
- )
-}
-
-async fn build_sessions_response(ctx: &ChannelRuntimeContext, msg: &ChannelMessage) -> String {
- let workspace = ctx.workspace_dir.clone();
- let reply_target = msg.reply_target.clone();
- // Read-only lookup — use with_store_read (no save) wrapped in spawn_blocking.
- let active_thread_id = tokio::task::spawn_blocking(move || {
- with_store_read(&workspace, |store| {
- Ok(store.binding(&reply_target).map(|b| b.thread_id.clone()))
- })
- })
- .await
- .ok()
- .and_then(|res| res.ok())
- .flatten();
- let workspace = ctx.workspace_dir.as_path();
-
- let threads = match conversations::list_threads(workspace.to_path_buf()) {
- Ok(list) => list,
- Err(error) => {
- tracing::warn!("{LOG_PREFIX} sessions: list_threads failed: {error}");
- return format!("Could not list sessions: {error}");
- }
- };
-
- if threads.is_empty() {
- return "No conversation threads yet. Send `/new` to create one.".to_string();
- }
-
- let mut sorted = threads;
- sorted.sort_by(|a, b| b.last_message_at.cmp(&a.last_message_at));
-
- let mut lines = vec![
- "**Recent sessions**".to_string(),
- format!("Showing up to {SESSIONS_LIST_LIMIT} threads:"),
- String::new(),
- ];
-
- for thread in sorted.into_iter().take(SESSIONS_LIST_LIMIT) {
- lines.push(format_session_line(
- &thread.title,
- &thread.id,
- thread.message_count,
- active_thread_id.as_deref() == Some(thread.id.as_str()),
- ));
- }
-
- lines.join("\n")
-}
-
-async fn build_new_session_response(ctx: &ChannelRuntimeContext, msg: &ChannelMessage) -> String {
- let workspace = ctx.workspace_dir.as_path();
- let sender_key = conversation_history_key(msg);
- let thread_id = format!("thread-{}", uuid::Uuid::new_v4());
- let now = chrono::Utc::now();
- let title = format!(
- "Telegram {} {}",
- now.format("%b %-d"),
- now.format("%-I:%M %p")
- );
- let created_at = now.to_rfc3339();
-
- if let Err(error) = conversations::ensure_thread(
- workspace.to_path_buf(),
- CreateConversationThread {
- id: thread_id.clone(),
- title: title.clone(),
- created_at,
- parent_thread_id: None,
- labels: Some(vec!["telegram".to_string(), "remote".to_string()]),
- personality_id: None,
- },
- ) {
- tracing::warn!("{LOG_PREFIX} new: ensure_thread failed: {error}");
- return format!("Failed to create session: {error}");
- }
-
- clear_sender_history(ctx, &sender_key);
-
- let workspace_dir = ctx.workspace_dir.clone();
- let reply_target_owned = msg.reply_target.clone();
- let thread_id_owned = thread_id.clone();
- let sender_key_owned = sender_key.clone();
- let title_owned = title.clone();
- // Write-back path — use with_store (saves) wrapped in spawn_blocking.
- let bind_result = tokio::task::spawn_blocking(move || {
- with_store(&workspace_dir, |store| {
- store.set_binding(
- &reply_target_owned,
- thread_id_owned,
- sender_key_owned,
- Some(title_owned),
- );
- Ok(())
- })
- })
- .await
- .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {e}")));
-
- if let Err(error) = bind_result {
- tracing::warn!("{LOG_PREFIX} new: persist binding failed: {error}");
- return format!(
- "Created thread `{thread_id}` but failed to persist Telegram binding: {error}"
- );
- }
-
- crate::web_chat::invalidate_thread_sessions(&thread_id).await;
-
- tracing::info!(
- "{LOG_PREFIX} new session thread_id={thread_id} reply_target={} sender_key={sender_key}",
- msg.reply_target
- );
-
- render_new_session_response(&title, &thread_id)
-}