agentmux_srv/messaging/telegram/
poller.rs1use std::collections::HashMap;
11use std::sync::{Arc, Mutex};
12use std::time::{Duration, Instant};
13
14use tokio::sync::mpsc;
15
16use crate::backend::reactive::types::InjectionRequest;
17use crate::messaging::{BridgeHealth, BridgeStatus, OutboundMsg};
18
19use super::rest;
20use super::types::Update;
21use super::TelegramConfig;
22
23const RECONNECT_DELAY_SECS: u64 = 5;
24const MAX_RECONNECT_DELAY_SECS: u64 = 60;
25
26const CHAT_MIN_SPACING: Duration = Duration::from_millis(1100);
29
30pub async fn run_poll_loop(
46 config: TelegramConfig,
47 http: reqwest::Client,
48 outbound_rx: mpsc::UnboundedReceiver<OutboundMsg>,
49 health: Arc<Mutex<BridgeHealth>>,
50) {
51 let inbound_config = config.clone();
52 tokio::join!(
53 run_inbound_loop(inbound_config, health),
54 run_outbound_loop(config, http, outbound_rx),
55 );
56}
57
58async fn run_inbound_loop(config: TelegramConfig, health: Arc<Mutex<BridgeHealth>>) {
59 let poll_http = rest::build_poll_client();
65
66 let mut offset: i64 = 0;
67 let mut delay_secs = RECONNECT_DELAY_SECS;
68
69 loop {
70 match rest::get_updates(&poll_http, &config.token, offset).await {
71 Ok(updates) => {
72 delay_secs = RECONNECT_DELAY_SECS;
73 {
74 let mut h = health.lock().unwrap();
75 h.status = BridgeStatus::Connected;
76 h.error = None;
77 }
78
79 let mut max_update_id = offset - 1;
83 for raw in &updates {
84 let update_id = raw.get("update_id").and_then(|v| v.as_i64());
85 let Some(update_id) = update_id else {
86 tracing::warn!(
87 "telegram_bridge: update missing update_id, skipping (offset cannot advance past it)"
88 );
89 continue;
90 };
91 if update_id > max_update_id {
92 max_update_id = update_id;
93 }
94
95 match serde_json::from_value::<Update>(raw.clone()) {
96 Ok(update) => handle_update(&update, &config, &health),
97 Err(e) => {
98 tracing::warn!(
99 "telegram_bridge: malformed update {update_id}: {e} — skipping"
100 );
101 }
102 }
103 }
104 if max_update_id >= offset {
105 offset = max_update_id + 1;
106 }
107 }
108 Err(e) => {
109 tracing::warn!("telegram_bridge: getUpdates failed: {e}");
110 {
111 let mut h = health.lock().unwrap();
112 h.status = BridgeStatus::Error;
113 h.error = Some(e);
114 h.reconnect_count += 1;
115 }
116 tokio::time::sleep(Duration::from_secs(delay_secs)).await;
117 delay_secs = (delay_secs * 2).min(MAX_RECONNECT_DELAY_SECS);
118 }
119 }
120 }
121}
122
123async fn run_outbound_loop(
124 config: TelegramConfig,
125 http: reqwest::Client,
126 mut outbound_rx: mpsc::UnboundedReceiver<OutboundMsg>,
127) {
128 let mut chat_last_sent: HashMap<i64, Instant> = HashMap::new();
132 let mut chat_backoff_until: HashMap<i64, Instant> = HashMap::new();
133 let mut global_backoff_until: Option<Instant> = None;
134
135 while let Some(msg) = outbound_rx.recv().await {
136 handle_outbound(
137 &http,
138 &config,
139 msg,
140 &mut chat_last_sent,
141 &mut chat_backoff_until,
142 &mut global_backoff_until,
143 )
144 .await;
145 }
146}
147
148fn handle_update(update: &Update, config: &TelegramConfig, health: &Arc<Mutex<BridgeHealth>>) {
151 let Some(message) = &update.message else {
152 tracing::debug!("telegram_bridge: unhandled update kind (update_id={})", update.update_id);
155 return;
156 };
157
158 if message.from.as_ref().map(|u| u.is_bot).unwrap_or(false) {
160 return;
161 }
162
163 if !config.allowed_chat_ids.contains(&message.chat.id) {
168 tracing::debug!(
169 "telegram_bridge: dropping message from non-allowlisted chat {}",
170 message.chat.id
171 );
172 return;
173 }
174
175 {
176 let mut h = health.lock().unwrap();
177 h.last_event_at = Some(unix_secs());
178 }
179
180 let Some(target) = &config.target_agent else {
181 tracing::debug!("telegram_bridge: message from chat {} (no target agent configured)", message.chat.id);
182 return;
183 };
184
185 let username = message
186 .from
187 .as_ref()
188 .and_then(|u| u.username.as_deref())
189 .unwrap_or("unknown");
190 let text = message.text.as_deref().unwrap_or("");
191 let envelope = format!("[Telegram @{username}]: {text}");
192
193 let req = InjectionRequest {
194 target_agent: target.clone(),
195 message: envelope,
196 source_agent: Some("telegram".to_string()),
197 request_id: Some(update.update_id.to_string()),
198 priority: None,
199 jekt_tier: None,
200 delivery_tier: Some("wan".to_string()),
201 forward_hops: 0,
202 ..Default::default()
203 };
204 let result = crate::server::jekt_entry::inject_from_bridge(req, text);
205 if result.success {
206 tracing::debug!("telegram_bridge: injected msg from {username} to agent {target}");
207 } else {
208 tracing::warn!("telegram_bridge: inject to agent {target} failed: {:?}", result.error);
209 }
210}
211
212fn resolve_chat_id(channel_id: &str, default_chat_id: Option<i64>) -> Option<i64> {
215 if channel_id.is_empty() {
216 return default_chat_id;
217 }
218 channel_id.trim().parse::<i64>().ok().or(default_chat_id)
219}
220
221async fn handle_outbound(
222 http: &reqwest::Client,
223 config: &TelegramConfig,
224 msg: OutboundMsg,
225 chat_last_sent: &mut HashMap<i64, Instant>,
226 chat_backoff_until: &mut HashMap<i64, Instant>,
227 global_backoff_until: &mut Option<Instant>,
228) {
229 let Some(chat_id) = resolve_chat_id(&msg.channel_id, config.default_chat_id) else {
230 tracing::warn!(
231 "telegram_bridge: send dropped — no chat_id (empty channel_id and no messaging:telegram:default_chat configured)"
232 );
233 return;
234 };
235
236 if let Some(until) = *global_backoff_until {
237 let now = Instant::now();
238 if now < until {
239 tokio::time::sleep(until - now).await;
240 }
241 *global_backoff_until = None;
242 }
243
244 if let Some(until) = chat_backoff_until.get(&chat_id).copied() {
245 let now = Instant::now();
246 if now < until {
247 tokio::time::sleep(until - now).await;
248 }
249 chat_backoff_until.remove(&chat_id);
250 }
251
252 if let Some(last) = chat_last_sent.get(&chat_id) {
253 let elapsed = last.elapsed();
254 if elapsed < CHAT_MIN_SPACING {
255 tokio::time::sleep(CHAT_MIN_SPACING - elapsed).await;
256 }
257 }
258
259 match rest::send_or_edit(http, &config.token, chat_id, &msg.text, msg.edit_message_id).await {
260 Ok(_) => {
261 chat_last_sent.insert(chat_id, Instant::now());
262 }
263 Err(e) => {
264 tracing::warn!("telegram_bridge: send failed: {e}");
265 if let Some(retry_after) = e.retry_after {
266 let backoff = Duration::from_secs(retry_after) + jitter();
267 if e.chat_scoped {
268 chat_backoff_until.insert(chat_id, Instant::now() + backoff);
269 } else {
270 *global_backoff_until = Some(Instant::now() + backoff);
271 }
272 }
273 }
274 }
275}
276
277fn jitter() -> Duration {
280 let nanos = std::time::SystemTime::now()
281 .duration_since(std::time::UNIX_EPOCH)
282 .map(|d| d.subsec_nanos())
283 .unwrap_or(0);
284 Duration::from_millis((nanos % 300) as u64)
285}
286
287fn unix_secs() -> u64 {
288 agentmux_common::time::now_secs_u64()
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn resolve_chat_id_uses_channel_id_when_present() {
297 assert_eq!(resolve_chat_id("123456", Some(999)), Some(123456));
298 }
299
300 #[test]
301 fn resolve_chat_id_falls_back_to_default_when_empty() {
302 assert_eq!(resolve_chat_id("", Some(999)), Some(999));
303 }
304
305 #[test]
306 fn resolve_chat_id_none_when_empty_and_no_default() {
307 assert_eq!(resolve_chat_id("", None), None);
308 }
309
310 #[test]
311 fn resolve_chat_id_falls_back_to_default_on_unparseable_channel_id() {
312 assert_eq!(resolve_chat_id("not-a-number", Some(999)), Some(999));
313 }
314
315 #[test]
316 fn resolve_chat_id_trims_whitespace() {
317 assert_eq!(resolve_chat_id(" 42 ", None), Some(42));
318 }
319}