//! Sends to Telegram, one call at a time, in the order the bridge queued them. //! //! The outbox resolves where a session message goes: into the session's topic when topics //! are in use, otherwise into the main chat with the `[cwd ยท model]` tag in front. It also //! creates and renames topics, so a topic exists before the first message that needs it. use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; use tokio::sync::mpsc; use tracing::warn; use crate::api::ApiError; use crate::api::Button; use crate::api::TelegramApi; use crate::settings; use crate::text; use crate::text::Rich; use crate::topics::TopicEntry; use crate::topics::Topics; /// The command menu of private chats. pub(crate) const COMMANDS: [(&str, &str); 6] = [ ("sessioni", "Elenco delle sessioni con Apri, Stop e Stato"), ("nuova", "Avvia una nuova sessione"), ("stato", "Stato della sessione"), ("stop", "Interrompe il turno in corso"), ("impostazioni", "Notifiche, streaming e reazioni"), ("aiuto", "Come si usa il bot"), ]; /// Draft text limit (Telegram accepts 4096 characters). const DRAFT_LIMIT: usize = 4000; #[derive(Clone, Debug)] pub(crate) enum Dest { /// The main chat, or one of its topics. Chat(Option), /// A session: its topic, or the main chat with `tag` in front. Session { id: String, tag: String }, } #[derive(Clone, Debug)] pub(crate) enum Tag { None, /// A session message: replies to it go to the session. Session(String), Approval(u64), /// A plan message of a session, at this plan version. Plan(String, u64), SessionList, } pub(crate) enum Outbox { Send { chat_id: i64, dest: Dest, text: Rich, buttons: Option>>, tag: Tag, }, Edit { chat_id: i64, message_id: i64, text: Rich, buttons: Option>>, /// Sent instead when Telegram refuses the edit (for example a disabled button). fallback: Option, }, Answer { callback_id: String, text: String, }, /// Creates the topic of `session` when missing (`create`), and renames it to `name`. Topic { chat_id: i64, session: String, name: String, create: bool, }, Draft { chat_id: i64, session: String, tag: String, draft_id: i64, text: String, }, React { chat_id: i64, message_id: i64, emoji: &'static str, }, /// Reads the bot (`getMe`: username, topics) and, with `commands`, sets the menu. Setup { commands: bool }, } pub(crate) enum Feedback { Sent { tag: Tag, chat_id: i64, message_id: i64, }, /// `sendMessageDraft` is not available: stop streaming. DraftFailed, } pub(crate) struct OutboxTask { pub api: TelegramApi, pub topics: Arc>, pub codex_home: std::path::PathBuf, pub feedback: mpsc::UnboundedSender, } fn lock(topics: &Mutex) -> std::sync::MutexGuard<'_, Topics> { topics.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } fn is_bad_request(err: &ApiError) -> bool { matches!(err, ApiError::Api { code: 400, .. }) } fn mentions(err: &ApiError, words: &[&str]) -> bool { match err { ApiError::Api { description, .. } => { let description = description.to_ascii_lowercase(); words.iter().any(|word| description.contains(word)) } _ => false, } } impl OutboxTask { pub async fn run(self, mut outbox: mpsc::UnboundedReceiver) { while let Some(item) = outbox.recv().await { self.process(item).await; } } async fn with_retry(&self, mut call: F) -> Result<(), ApiError> where F: FnMut() -> Fut, Fut: std::future::Future>, { let first = call().await; let Err(err) = first else { return Ok(()); }; if is_bad_request(&err) || err.is_unauthorized() { return Err(err); } let wait = err.retry_after().unwrap_or(2).min(30); warn!("telegram: send failed, retrying in {wait}s: {err}"); tokio::time::sleep(Duration::from_secs(wait)).await; call().await } async fn process(&self, item: Outbox) { match item { Outbox::Send { chat_id, dest, text, buttons, tag, } => self.send(chat_id, dest, text, buttons, tag).await, Outbox::Edit { chat_id, message_id, text, buttons, fallback, } => { let result = self .with_retry(|| { self.api.edit_message_text( chat_id, message_id, &text.text, &text.entities, buttons.as_deref(), ) }) .await; match result { Ok(()) => {} Err(err) if mentions(&err, &["not modified"]) => {} Err(err) => { warn!("telegram: edit failed: {err}"); if let Some(fallback) = fallback && is_bad_request(&err) && let Err(err) = self .api .edit_message_text( chat_id, message_id, &fallback.text, &fallback.entities, None, ) .await { warn!("telegram: edit failed: {err}"); } } } } Outbox::Answer { callback_id, text } => { if let Err(err) = self.api.answer_callback_query(&callback_id, &text).await { warn!("telegram: answerCallbackQuery failed: {err}"); } } Outbox::Topic { chat_id, session, name, create, } => self.topic(chat_id, &session, &name, create).await, Outbox::Draft { chat_id, session, tag, draft_id, text, } => { let thread = lock(&self.topics).thread_for(chat_id, &session); let text = if thread.is_some() { text } else { format!("{tag}\n{text}") }; let text = text::truncate(&text, DRAFT_LIMIT); if let Err(err) = self .api .send_message_draft(chat_id, thread, draft_id, &text) .await { warn!("telegram: sendMessageDraft failed, streaming off: {err}"); if !matches!(err, ApiError::Network(_)) { let _ = self.feedback.send(Feedback::DraftFailed); } } } Outbox::React { chat_id, message_id, emoji, } => { if let Err(err) = self .api .set_message_reaction(chat_id, message_id, Some(emoji)) .await { warn!("telegram: setMessageReaction failed: {err}"); } } Outbox::Setup { commands } => self.setup(commands).await, } } async fn setup(&self, commands: bool) { match self.api.get_me().await { Ok(me) => { let topics = me.has_topics_enabled == Some(true); { let mut store = lock(&self.topics); store.enabled = topics; store.bot_username = me.username.clone(); } if let Some(username) = &me.username && let Err(err) = settings::save_bot_info(&self.codex_home, username, topics) { warn!("telegram: cannot save the bot info: {err}"); } } Err(err) => warn!("telegram: getMe failed, topics off: {err}"), } if commands && let Err(err) = self.api.set_my_commands(&COMMANDS).await { warn!("telegram: setMyCommands failed: {err}"); } } async fn topic(&self, chat_id: i64, session: &str, name: &str, create: bool) { // Topics exist only in private chats (positive ids). if chat_id <= 0 { return; } let (enabled, existing) = { let store = lock(&self.topics); (store.enabled, store.entry(chat_id, session).cloned()) }; if !enabled { return; } match existing { Some(entry) if entry.name != name => { match self.api.edit_forum_topic(chat_id, entry.thread, name).await { Ok(()) => lock(&self.topics).set_name(chat_id, session, name), Err(err) => warn!("telegram: editForumTopic failed: {err}"), } } Some(_) => {} None if create => match self.api.create_forum_topic(chat_id, name).await { Ok(topic) => lock(&self.topics).insert(TopicEntry { chat_id, session: session.to_string(), thread: topic.message_thread_id, name: name.to_string(), }), Err(ApiError::Network(err)) => { warn!("telegram: createForumTopic failed, retrying later: {err}"); } Err(err) => { // Topics refused: use the main chat from now on. warn!("telegram: createForumTopic failed, topics off: {err}"); lock(&self.topics).enabled = false; } }, None => {} } } async fn send( &self, chat_id: i64, dest: Dest, text: Rich, buttons: Option>>, tag: Tag, ) { let (thread, prefixed) = match &dest { Dest::Chat(thread) => (*thread, None), Dest::Session { id, tag } => { let thread = lock(&self.topics).thread_for(chat_id, id); (thread, Some((id.clone(), text.prefixed(&format!("{tag} "))))) } }; let attempt = |thread: Option, text: &Rich| { let text = text.clone(); let buttons = buttons.clone(); async move { self.api .send_message(chat_id, thread, &text.text, &text.entities, buttons.as_deref()) .await } }; let first_text = match (&thread, &prefixed) { (None, Some((_, prefixed))) => prefixed.clone(), _ => text.clone(), }; let mut result = attempt(thread, &first_text).await; if let Err(err) = &result { if thread.is_some() && let Some((session, prefixed)) = &prefixed && mentions(err, &["thread", "topic"]) { // The user deleted the topic: forget it and use the main chat. warn!("telegram: topic gone, writing to the main chat: {err}"); lock(&self.topics).remove(chat_id, session); result = attempt(None, prefixed).await; } else if !is_bad_request(err) && !err.is_unauthorized() { let wait = err.retry_after().unwrap_or(2).min(30); warn!("telegram: send failed, retrying in {wait}s: {err}"); tokio::time::sleep(Duration::from_secs(wait)).await; result = attempt(thread, &first_text).await; } } match result { Ok(message) => { let _ = self.feedback.send(Feedback::Sent { tag, chat_id, message_id: message.message_id, }); } Err(err) => warn!("telegram: send failed: {err}"), } } }