Telegram: un topic per sessione, streaming, pulsanti e impostazioni

- Menu comandi (setMyCommands, chat private): /sessioni /nuova /stato /stop
  /impostazioni /aiuto; /usa rimosso.
- Un topic per sessione (createForumTopic in chat privata), nome
  "<cartella> · <modello>", rinominato al cambio di modello e "(chiusa)" alla
  chiusura; mappa salvata in AKODE_HOME/telegram-topics.json. Senza topic:
  prefisso [cartella · modello] e scelta della sessione con pulsanti.
- /sessioni con Apri (link al topic), Stato e Stop; il messaggio si aggiorna
  modificandolo.
- Streaming con sendMessageDraft (can_stop, al massimo 1/s, stop = interrompe
  il turno), messaggio finale con piede "ctx · t/s · durata".
- Approvazioni con pulsanti colorati, poi un pulsante disattivato con l'esito.
- Piano come elenco modificato; reazioni ricevuto/fatto configurabili.
- /impostazioni con interruttori Sì/No salvati in [telegram]
  (streaming, reactions nuovi).
- Messaggi modificati: un comando modificato riparte, il testo no.
- Pulsanti con token opachi lato server; allowlist anche sui pulsanti.
- Nessuna emoji nei testi in uscita (test dedicato).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-12 11:12:01 +01:00
parent 466ed04fba
commit 2b8d77593d
17 changed files with 2643 additions and 449 deletions

View File

@@ -263,6 +263,10 @@ pub struct TelegramConfigToml {
pub allowed_chat_ids: Option<Vec<i64>>, pub allowed_chat_ids: Option<Vec<i64>>,
/// Which events are sent to Telegram. Every level defaults to `true`. /// Which events are sent to Telegram. Every level defaults to `true`.
pub notify: Option<TelegramNotifyToml>, pub notify: Option<TelegramNotifyToml>,
/// Live output of running turns (message drafts) and the plan. Defaults to `true`.
pub streaming: Option<bool>,
/// Reactions on the user's messages (received, done). Defaults to `true`.
pub reactions: Option<bool>,
} }
/// `[telegram.notify]`: which events reach Telegram. /// `[telegram.notify]`: which events reach Telegram.

View File

@@ -4759,6 +4759,14 @@
} }
], ],
"description": "Which events are sent to Telegram. Every level defaults to `true`." "description": "Which events are sent to Telegram. Every level defaults to `true`."
},
"reactions": {
"description": "Reactions on the user's messages (received, done). Defaults to `true`.",
"type": "boolean"
},
"streaming": {
"description": "Live output of running turns (message drafts) and the plan. Defaults to `true`.",
"type": "boolean"
} }
}, },
"type": "object" "type": "object"

View File

@@ -63,6 +63,9 @@ pub struct User {
pub username: Option<String>, pub username: Option<String>,
#[serde(default)] #[serde(default)]
pub first_name: String, pub first_name: String,
/// Topics in private chats are enabled for the bot (`getMe` only).
#[serde(default)]
pub has_topics_enabled: Option<bool>,
} }
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
@@ -75,27 +78,61 @@ pub struct Message {
pub message_id: i64, pub message_id: i64,
pub chat: Chat, pub chat: Chat,
#[serde(default)] #[serde(default)]
pub message_thread_id: Option<i64>,
#[serde(default)]
pub is_topic_message: Option<bool>,
#[serde(default)]
pub text: Option<String>, pub text: Option<String>,
#[serde(default)] #[serde(default)]
pub reply_to_message: Option<Box<Message>>, pub reply_to_message: Option<Box<Message>>,
} }
impl Message {
/// The topic the message belongs to, if any.
pub fn topic(&self) -> Option<i64> {
self.message_thread_id
.filter(|_| self.is_topic_message.unwrap_or(true))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct CallbackQuery { pub struct CallbackQuery {
pub id: String, pub id: String,
#[serde(default)] #[serde(default)]
pub from: Option<User>,
#[serde(default)]
pub message: Option<Message>, pub message: Option<Message>,
#[serde(default)] #[serde(default)]
pub data: Option<String>, pub data: Option<String>,
} }
/// The user pressed the stop button of a streamed draft.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct MessageGenerationStopped {
pub chat: Chat,
#[serde(default)]
pub message_thread_id: Option<i64>,
pub draft_id: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ForumTopic {
pub message_thread_id: i64,
#[serde(default)]
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Update { pub struct Update {
pub update_id: i64, pub update_id: i64,
#[serde(default)] #[serde(default)]
pub message: Option<Message>, pub message: Option<Message>,
#[serde(default)] #[serde(default)]
pub edited_message: Option<Message>,
#[serde(default)]
pub callback_query: Option<CallbackQuery>, pub callback_query: Option<CallbackQuery>,
#[serde(default)]
pub stopped_message_generation: Option<MessageGenerationStopped>,
} }
impl Update { impl Update {
@@ -103,6 +140,7 @@ impl Update {
pub fn chat_id(&self) -> Option<i64> { pub fn chat_id(&self) -> Option<i64> {
self.message self.message
.as_ref() .as_ref()
.or(self.edited_message.as_ref())
.map(|message| message.chat.id) .map(|message| message.chat.id)
.or_else(|| { .or_else(|| {
self.callback_query self.callback_query
@@ -110,14 +148,78 @@ impl Update {
.and_then(|query| query.message.as_ref()) .and_then(|query| query.message.as_ref())
.map(|message| message.chat.id) .map(|message| message.chat.id)
}) })
.or_else(|| {
self.stopped_message_generation
.as_ref()
.map(|stopped| stopped.chat.id)
})
} }
} }
/// `DisabledButton`: currently an empty object.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DisabledButton {}
/// One inline keyboard button. /// One inline keyboard button.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Button { pub struct Button {
pub text: String, pub text: String,
pub callback_data: String, #[serde(skip_serializing_if = "Option::is_none")]
pub callback_data: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// `success` (green), `danger` (red) or `primary` (blue).
#[serde(skip_serializing_if = "Option::is_none")]
pub style: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled: Option<DisabledButton>,
}
impl Button {
pub fn callback(text: impl Into<String>, data: impl Into<String>) -> Self {
Self {
text: text.into(),
callback_data: Some(data.into()),
url: None,
style: None,
disabled: None,
}
}
pub fn link(text: impl Into<String>, url: impl Into<String>) -> Self {
Self {
text: text.into(),
callback_data: None,
url: Some(url.into()),
style: None,
disabled: None,
}
}
/// A button that does nothing, used to show an outcome in place of choices.
pub fn disabled(text: impl Into<String>) -> Self {
Self {
text: text.into(),
callback_data: None,
url: None,
style: None,
disabled: Some(DisabledButton {}),
}
}
pub fn styled(mut self, style: &'static str) -> Self {
self.style = Some(style);
self
}
}
/// A message entity; offsets and lengths are in UTF-16 code units.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Entity {
#[serde(rename = "type")]
pub kind: &'static str,
pub offset: usize,
pub length: usize,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -204,7 +306,12 @@ impl TelegramApi {
) -> Result<Vec<Update>, ApiError> { ) -> Result<Vec<Update>, ApiError> {
let mut body = json!({ let mut body = json!({
"timeout": timeout_secs, "timeout": timeout_secs,
"allowed_updates": ["message", "callback_query"], "allowed_updates": [
"message",
"edited_message",
"callback_query",
"stopped_message_generation",
],
}); });
if let Some(offset) = offset { if let Some(offset) = offset {
body["offset"] = json!(offset); body["offset"] = json!(offset);
@@ -217,17 +324,26 @@ impl TelegramApi {
.await .await
} }
async fn call_unit(&self, method: &str, body: Value) -> Result<(), ApiError> {
self.call::<Value>(method, body, REQUEST_TIMEOUT)
.await
.map(|_| ())
}
pub async fn send_message( pub async fn send_message(
&self, &self,
chat_id: i64, chat_id: i64,
thread: Option<i64>,
text: &str, text: &str,
reply_to: Option<i64>, entities: &[Entity],
buttons: Option<&[Vec<Button>]>, buttons: Option<&[Vec<Button>]>,
) -> Result<Message, ApiError> { ) -> Result<Message, ApiError> {
let mut body = json!({ "chat_id": chat_id, "text": text }); let mut body = json!({ "chat_id": chat_id, "text": text });
if let Some(reply_to) = reply_to { if let Some(thread) = thread {
body["reply_parameters"] = body["message_thread_id"] = json!(thread);
json!({ "message_id": reply_to, "allow_sending_without_reply": true }); }
if !entities.is_empty() {
body["entities"] = json!(entities);
} }
if let Some(buttons) = buttons { if let Some(buttons) = buttons {
body["reply_markup"] = json!({ "inline_keyboard": buttons }); body["reply_markup"] = json!({ "inline_keyboard": buttons });
@@ -235,23 +351,88 @@ impl TelegramApi {
self.call("sendMessage", body, REQUEST_TIMEOUT).await self.call("sendMessage", body, REQUEST_TIMEOUT).await
} }
/// Replaces a message's text; the inline keyboard is removed. /// Replaces a message's text; without `buttons` the inline keyboard is removed.
pub async fn edit_message_text( pub async fn edit_message_text(
&self, &self,
chat_id: i64, chat_id: i64,
message_id: i64, message_id: i64,
text: &str, text: &str,
entities: &[Entity],
buttons: Option<&[Vec<Button>]>,
) -> Result<(), ApiError> { ) -> Result<(), ApiError> {
let body = json!({ "chat_id": chat_id, "message_id": message_id, "text": text }); let mut body = json!({ "chat_id": chat_id, "message_id": message_id, "text": text });
self.call::<Value>("editMessageText", body, REQUEST_TIMEOUT) if !entities.is_empty() {
.await body["entities"] = json!(entities);
.map(|_| ()) }
if let Some(buttons) = buttons {
body["reply_markup"] = json!({ "inline_keyboard": buttons });
}
self.call_unit("editMessageText", body).await
} }
/// Answers a button press with a short notice shown only to the user who pressed it.
pub async fn answer_callback_query(&self, id: &str, text: &str) -> Result<(), ApiError> { pub async fn answer_callback_query(&self, id: &str, text: &str) -> Result<(), ApiError> {
let body = json!({ "callback_query_id": id, "text": text }); let body = json!({ "callback_query_id": id, "text": text });
self.call::<Value>("answerCallbackQuery", body, REQUEST_TIMEOUT) self.call_unit("answerCallbackQuery", body).await
.await }
.map(|_| ())
/// Sets the command menu of private chats.
pub async fn set_my_commands(&self, commands: &[(&str, &str)]) -> Result<(), ApiError> {
let commands: Vec<Value> = commands
.iter()
.map(|(command, description)| json!({ "command": command, "description": description }))
.collect();
let body = json!({ "commands": commands, "scope": { "type": "all_private_chats" } });
self.call_unit("setMyCommands", body).await
}
pub async fn create_forum_topic(&self, chat_id: i64, name: &str) -> Result<ForumTopic, ApiError> {
let body = json!({ "chat_id": chat_id, "name": name });
self.call("createForumTopic", body, REQUEST_TIMEOUT).await
}
pub async fn edit_forum_topic(
&self,
chat_id: i64,
thread: i64,
name: &str,
) -> Result<(), ApiError> {
let body = json!({ "chat_id": chat_id, "message_thread_id": thread, "name": name });
self.call_unit("editForumTopic", body).await
}
/// Streams a partial message (a temporary preview, replaced by the next message).
pub async fn send_message_draft(
&self,
chat_id: i64,
thread: Option<i64>,
draft_id: i64,
text: &str,
) -> Result<(), ApiError> {
let mut body = json!({
"chat_id": chat_id,
"draft_id": draft_id,
"text": text,
"can_stop": true,
});
if let Some(thread) = thread {
body["message_thread_id"] = json!(thread);
}
self.call_unit("sendMessageDraft", body).await
}
/// Sets one standard reaction on a message, or clears it with `None`.
pub async fn set_message_reaction(
&self,
chat_id: i64,
message_id: i64,
emoji: Option<&str>,
) -> Result<(), ApiError> {
let reaction: Vec<Value> = emoji
.map(|emoji| json!({ "type": "emoji", "emoji": emoji }))
.into_iter()
.collect();
let body = json!({ "chat_id": chat_id, "message_id": message_id, "reaction": reaction });
self.call_unit("setMessageReaction", body).await
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -16,9 +16,11 @@
pub mod api; pub mod api;
pub mod bridge; pub mod bridge;
pub mod lock; pub mod lock;
mod outbox;
pub mod pairing; pub mod pairing;
pub mod settings; pub mod settings;
pub mod text; pub mod text;
pub mod topics;
/// Key store id of the bot token. /// Key store id of the bot token.
pub const TOKEN_ID: &str = "telegram-bot"; pub const TOKEN_ID: &str = "telegram-bot";

View File

@@ -0,0 +1,379 @@
//! 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<i64>),
/// 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<Vec<Vec<Button>>>,
tag: Tag,
},
Edit {
chat_id: i64,
message_id: i64,
text: Rich,
buttons: Option<Vec<Vec<Button>>>,
/// Sent instead when Telegram refuses the edit (for example a disabled button).
fallback: Option<Rich>,
},
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<Mutex<Topics>>,
pub codex_home: std::path::PathBuf,
pub feedback: mpsc::UnboundedSender<Feedback>,
}
fn lock(topics: &Mutex<Topics>) -> 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<Outbox>) {
while let Some(item) = outbox.recv().await {
self.process(item).await;
}
}
async fn with_retry<F, Fut>(&self, mut call: F) -> Result<(), ApiError>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<(), ApiError>>,
{
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<Vec<Vec<Button>>>,
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<i64>, 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}"),
}
}
}

View File

@@ -24,7 +24,7 @@ pub const PAIRING_TTL: Duration = Duration::from_secs(10 * 60);
const MAX_WRONG_ATTEMPTS: u32 = 5; const MAX_WRONG_ATTEMPTS: u32 = 5;
/// Reply sent to a chat that has just been paired. /// Reply sent to a chat that has just been paired.
pub const PAIRED_REPLY: &str = "✅ Chat abbinata ad aKode. Scrivi /sessioni per vedere le sessioni."; pub const PAIRED_REPLY: &str = "Chat abbinata ad aKode. Scrivi /sessioni per vedere le sessioni.";
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
struct Pending { struct Pending {
@@ -132,7 +132,7 @@ pub async fn poll_once(
{ {
paired = Some(message.chat.id); paired = Some(message.chat.id);
let _ = api let _ = api
.send_message(message.chat.id, PAIRED_REPLY, None, None) .send_message(message.chat.id, None, PAIRED_REPLY, &[], None)
.await; .await;
} }
} }

View File

@@ -33,11 +33,15 @@ impl Default for NotifySettings {
} }
} }
#[derive(Debug, Clone, PartialEq, Eq, Default)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct TelegramSettings { pub struct TelegramSettings {
pub enabled: bool, pub enabled: bool,
pub allowed_chat_ids: Vec<i64>, pub allowed_chat_ids: Vec<i64>,
pub notify: NotifySettings, pub notify: NotifySettings,
/// Live drafts of running turns and the plan.
pub streaming: bool,
/// Reactions on the user's messages.
pub reactions: bool,
pub key_store: AuthCredentialsStoreMode, pub key_store: AuthCredentialsStoreMode,
/// Configured model display names (`[model_providers.*.models."id"] display_name`). /// Configured model display names (`[model_providers.*.models."id"] display_name`).
pub display_names: HashMap<String, String>, pub display_names: HashMap<String, String>,
@@ -92,6 +96,8 @@ impl TelegramSettings {
errors: notify.errors.unwrap_or(defaults.errors), errors: notify.errors.unwrap_or(defaults.errors),
loops: notify.loops.unwrap_or(defaults.loops), loops: notify.loops.unwrap_or(defaults.loops),
}, },
streaming: telegram.streaming.unwrap_or(true),
reactions: telegram.reactions.unwrap_or(true),
key_store: config key_store: config
.provider_api_key_store .provider_api_key_store
.unwrap_or(AuthCredentialsStoreMode::Auto), .unwrap_or(AuthCredentialsStoreMode::Auto),
@@ -114,6 +120,81 @@ impl TelegramSettings {
} }
} }
impl Default for TelegramSettings {
fn default() -> Self {
Self::parse("")
}
}
/// A yes/no option that `/impostazioni` toggles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Toggle {
Approvals,
TurnEnd,
Errors,
Loops,
Streaming,
Reactions,
}
impl Toggle {
pub const ALL: [Toggle; 6] = [
Toggle::Approvals,
Toggle::TurnEnd,
Toggle::Errors,
Toggle::Loops,
Toggle::Streaming,
Toggle::Reactions,
];
pub fn label(self) -> &'static str {
match self {
Toggle::Approvals => "Approvazioni",
Toggle::TurnEnd => "Fine turno",
Toggle::Errors => "Errori",
Toggle::Loops => "Loop",
Toggle::Streaming => "Streaming e piano",
Toggle::Reactions => "Reazioni",
}
}
/// Key path under `[telegram]`.
fn path(self) -> (Option<&'static str>, &'static str) {
match self {
Toggle::Approvals => (Some("notify"), "approvals"),
Toggle::TurnEnd => (Some("notify"), "turn_end"),
Toggle::Errors => (Some("notify"), "errors"),
Toggle::Loops => (Some("notify"), "loops"),
Toggle::Streaming => (None, "streaming"),
Toggle::Reactions => (None, "reactions"),
}
}
pub fn get(self, settings: &TelegramSettings) -> bool {
match self {
Toggle::Approvals => settings.notify.approvals,
Toggle::TurnEnd => settings.notify.turn_end,
Toggle::Errors => settings.notify.errors,
Toggle::Loops => settings.notify.loops,
Toggle::Streaming => settings.streaming,
Toggle::Reactions => settings.reactions,
}
}
}
/// Writes one toggle to `[telegram]` (or `[telegram.notify]`).
pub fn set_toggle(codex_home: &Path, toggle: Toggle, value: bool) -> io::Result<()> {
edit_config(codex_home, |table| match toggle.path() {
(None, key) => table[key] = toml_edit::value(value),
(Some(section), key) => {
if !table.get(section).is_some_and(toml_edit::Item::is_table_like) {
table[section] = toml_edit::Item::Table(toml_edit::Table::new());
}
table[section][key] = toml_edit::value(value);
}
})
}
fn edit_config( fn edit_config(
codex_home: &Path, codex_home: &Path,
edit: impl FnOnce(&mut toml_edit::Table), edit: impl FnOnce(&mut toml_edit::Table),
@@ -204,10 +285,28 @@ pub fn save_bot_name(codex_home: &Path, username: &str) -> io::Result<()> {
std::fs::write(codex_home.join(BOT_FILE), text) std::fs::write(codex_home.join(BOT_FILE), text)
} }
pub fn load_bot_name(codex_home: &Path) -> Option<String> { fn load_bot_file(codex_home: &Path) -> Option<serde_json::Value> {
let text = std::fs::read_to_string(codex_home.join(BOT_FILE)).ok()?; let text = std::fs::read_to_string(codex_home.join(BOT_FILE)).ok()?;
let value: serde_json::Value = serde_json::from_str(&text).ok()?; serde_json::from_str(&text).ok()
value["username"].as_str().map(ToString::to_string) }
pub fn load_bot_name(codex_home: &Path) -> Option<String> {
load_bot_file(codex_home)?["username"]
.as_str()
.map(ToString::to_string)
}
/// Remembers the bot's username and whether topics in private chats are enabled, as
/// seen by the running bridge.
pub fn save_bot_info(codex_home: &Path, username: &str, topics: bool) -> io::Result<()> {
std::fs::create_dir_all(codex_home)?;
let text = serde_json::json!({ "username": username, "topics": topics }).to_string();
std::fs::write(codex_home.join(BOT_FILE), text)
}
/// Whether the bot had topics enabled when the bridge last checked.
pub fn load_bot_topics(codex_home: &Path) -> Option<bool> {
load_bot_file(codex_home)?["topics"].as_bool()
} }
pub fn forget_bot_name(codex_home: &Path) { pub fn forget_bot_name(codex_home: &Path) {
@@ -240,4 +339,18 @@ mod tests {
assert!(settings.enabled); assert!(settings.enabled);
assert_eq!(settings.allowed_chat_ids, vec![42]); assert_eq!(settings.allowed_chat_ids, vec![42]);
} }
#[test]
fn toggles_persist() {
let home = tempfile::tempdir().unwrap();
std::fs::write(home.path().join(CONFIG_FILE), "[telegram]\nenabled = true\n").unwrap();
let settings = TelegramSettings::load(home.path());
assert!(Toggle::ALL.iter().all(|toggle| toggle.get(&settings)));
set_toggle(home.path(), Toggle::Approvals, false).unwrap();
set_toggle(home.path(), Toggle::Streaming, false).unwrap();
let settings = TelegramSettings::load(home.path());
assert!(!settings.notify.approvals);
assert!(!settings.streaming);
assert!(settings.notify.turn_end && settings.reactions && settings.enabled);
}
} }

View File

@@ -2,6 +2,8 @@
use std::path::Path; use std::path::Path;
use crate::api::Entity;
/// Telegram accepts up to 4096 characters per message; keep a margin for the tag. /// Telegram accepts up to 4096 characters per message; keep a margin for the tag.
pub const MESSAGE_LIMIT: usize = 4000; pub const MESSAGE_LIMIT: usize = 4000;
@@ -13,18 +15,118 @@ const BASELINE_TOKENS: i64 = 12_000;
/// `[<cwd basename> · <model>]`. /// `[<cwd basename> · <model>]`.
pub fn session_tag(cwd: &Path, model: &str) -> String { pub fn session_tag(cwd: &Path, model: &str) -> String {
let dir = cwd format!("[{}]", topic_name(cwd, model))
.file_name() }
/// Longest session tag or topic name kept.
const NAME_LIMIT: usize = 64;
fn dir_name(cwd: &Path) -> &str {
cwd.file_name()
.and_then(|name| name.to_str()) .and_then(|name| name.to_str())
.filter(|name| !name.is_empty()) .filter(|name| !name.is_empty())
.unwrap_or("/"); .unwrap_or("/")
if model.is_empty() { }
format!("[{dir}]")
/// Topic name of a session: `<cwd basename> · <model>`.
pub fn topic_name(cwd: &Path, model: &str) -> String {
let dir = dir_name(cwd);
let name = if model.is_empty() {
dir.to_string()
} else { } else {
format!("[{dir} · {model}]") format!("{dir} · {model}")
};
truncate(&name, NAME_LIMIT)
}
/// Topic name of a closed session.
pub fn closed_topic_name(name: &str) -> String {
format!("{} (chiusa)", truncate(name, NAME_LIMIT))
}
/// `1m 28s`, `42s`, `1h 05m`.
pub fn format_duration(ms: i64) -> String {
let secs = (ms.max(0) + 500) / 1000;
match secs {
0..60 => format!("{secs}s"),
60..3600 => format!("{}m {:02}s", secs / 60, secs % 60),
_ => format!("{}h {:02}m", secs / 3600, (secs % 3600) / 60),
} }
} }
/// Text with formatting entities, built piece by piece.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Rich {
pub text: String,
pub entities: Vec<Entity>,
}
impl Rich {
pub fn plain(text: impl Into<String>) -> Self {
Self {
text: text.into(),
entities: Vec::new(),
}
}
pub fn push(&mut self, text: &str) -> &mut Self {
self.text.push_str(text);
self
}
/// Appends `text` covered by an entity of type `kind` (`pre`, `italic`,
/// `expandable_blockquote`, ...).
pub fn push_styled(&mut self, kind: &'static str, text: &str) -> &mut Self {
let offset = utf16_len(&self.text);
let length = utf16_len(text);
self.text.push_str(text);
if length > 0 {
self.entities.push(Entity {
kind,
offset,
length,
});
}
self
}
/// `prefix` in front, entities shifted accordingly.
pub fn prefixed(&self, prefix: &str) -> Self {
let shift = utf16_len(prefix);
Self {
text: format!("{prefix}{}", self.text),
entities: self
.entities
.iter()
.map(|entity| Entity {
offset: entity.offset + shift,
..entity.clone()
})
.collect(),
}
}
}
pub fn utf16_len(text: &str) -> usize {
text.encode_utf16().count()
}
/// Whether `text` contains a pictographic emoji or an emoji presentation selector.
pub fn contains_emoji(text: &str) -> bool {
text.chars().any(|c| {
matches!(u32::from(c),
0x1F000..=0x1FAFF
| 0x2600..=0x27BF
| 0x2300..=0x23FF
| 0x2B00..=0x2BFF
| 0x2190..=0x21FF
| 0x3030 | 0x303D | 0x3297 | 0x3299
| 0xFE0F
| 0x20E3
| 0xE0020..=0xE007F)
})
}
/// `model` without directory and extension when it looks like a model file path. /// `model` without directory and extension when it looks like a model file path.
pub fn short_model_name(model: &str) -> String { pub fn short_model_name(model: &str) -> String {
const EXTENSIONS: [&str; 6] = ["gguf", "ggml", "bin", "safetensors", "onnx", "mlx"]; const EXTENSIONS: [&str; 6] = ["gguf", "ggml", "bin", "safetensors", "onnx", "mlx"];
@@ -159,5 +261,26 @@ mod tests {
assert_eq!(context_used_percent(62_000, 112_000), Some(50)); assert_eq!(context_used_percent(62_000, 112_000), Some(50));
assert_eq!(truncate("abcdef", 4), "abc…"); assert_eq!(truncate("abcdef", 4), "abc…");
assert_eq!(diff_counts("--- a\n+++ b\n+x\n-y\n+z\n ctx"), (2, 1)); assert_eq!(diff_counts("--- a\n+++ b\n+x\n-y\n+z\n ctx"), (2, 1));
assert_eq!(topic_name(Path::new("/a/progetto"), "Qwen"), "progetto · Qwen");
assert_eq!(closed_topic_name("progetto · Qwen"), "progetto · Qwen (chiusa)");
assert_eq!(format_duration(88_000), "1m 28s");
assert_eq!(format_duration(4_000), "4s");
}
#[test]
fn rich_text_offsets_are_utf16() {
let mut rich = Rich::default();
rich.push("è ").push_styled("pre", "ls");
let shifted = rich.prefixed("[x] ");
assert_eq!(shifted.text, "[x] è ls");
assert_eq!(shifted.entities[0].offset, 6);
assert_eq!(shifted.entities[0].length, 2);
}
#[test]
fn emoji_detection() {
assert!(contains_emoji("ok \u{2705}"));
assert!(contains_emoji("\u{1F510} chiave"));
assert!(!contains_emoji("Approvato · ctx 23% — +3 \u{2212}1 … «Sì»"));
} }
} }

View File

@@ -0,0 +1,165 @@
//! One Telegram topic per aKode session, in each allowed private chat.
//!
//! The map from (chat, session) to topic is kept in `AKODE_HOME/telegram-topics.json`, so
//! a restarted bridge writes into the topics it created before instead of making new ones.
//! The file also remembers the recent working directories offered by `/nuova`.
use std::path::Path;
use std::path::PathBuf;
use serde::Deserialize;
use serde::Serialize;
pub const TOPICS_FILE: &str = "telegram-topics.json";
const MAX_TOPICS: usize = 500;
const MAX_RECENT_CWDS: usize = 8;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TopicEntry {
pub chat_id: i64,
pub session: String,
pub thread: i64,
pub name: String,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct StoreFile {
#[serde(default)]
topics: Vec<TopicEntry>,
#[serde(default)]
recent_cwds: Vec<String>,
}
/// Topic map plus what the bridge learned from `getMe`.
#[derive(Debug)]
pub struct Topics {
path: PathBuf,
file: StoreFile,
/// Topics can be used (`has_topics_enabled` and no API refusal).
pub enabled: bool,
/// The bot's username, for topic links.
pub bot_username: Option<String>,
}
impl Topics {
pub fn load(codex_home: &Path) -> Self {
let path = codex_home.join(TOPICS_FILE);
let file = std::fs::read_to_string(&path)
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or_default();
Self {
path,
file,
enabled: false,
bot_username: None,
}
}
fn save(&self) {
let Ok(text) = serde_json::to_string_pretty(&self.file) else {
return;
};
let tmp = self.path.with_extension("json.tmp");
if let Err(err) = std::fs::write(&tmp, text).and_then(|()| std::fs::rename(&tmp, &self.path))
{
tracing::warn!("telegram: cannot save the topic map: {err}");
}
}
pub fn entry(&self, chat_id: i64, session: &str) -> Option<&TopicEntry> {
self.file
.topics
.iter()
.find(|entry| entry.chat_id == chat_id && entry.session == session)
}
/// The topic of `session` in `chat_id`, when topics are in use.
pub fn thread_for(&self, chat_id: i64, session: &str) -> Option<i64> {
if !self.enabled {
return None;
}
self.entry(chat_id, session).map(|entry| entry.thread)
}
/// The session a topic belongs to (also for closed sessions).
pub fn session_for(&self, chat_id: i64, thread: i64) -> Option<&str> {
self.file
.topics
.iter()
.find(|entry| entry.chat_id == chat_id && entry.thread == thread)
.map(|entry| entry.session.as_str())
}
pub fn insert(&mut self, entry: TopicEntry) {
self.file
.topics
.retain(|old| !(old.chat_id == entry.chat_id && old.session == entry.session));
self.file.topics.push(entry);
let extra = self.file.topics.len().saturating_sub(MAX_TOPICS);
self.file.topics.drain(..extra);
self.save();
}
pub fn set_name(&mut self, chat_id: i64, session: &str, name: &str) {
if let Some(entry) = self
.file
.topics
.iter_mut()
.find(|entry| entry.chat_id == chat_id && entry.session == session)
{
entry.name = name.to_string();
self.save();
}
}
/// Forgets a topic the user deleted.
pub fn remove(&mut self, chat_id: i64, session: &str) {
self.file
.topics
.retain(|entry| !(entry.chat_id == chat_id && entry.session == session));
self.save();
}
pub fn remember_cwd(&mut self, cwd: &str) {
if self.file.recent_cwds.first().map(String::as_str) == Some(cwd) {
return;
}
self.file.recent_cwds.retain(|old| old != cwd);
self.file.recent_cwds.insert(0, cwd.to_string());
self.file.recent_cwds.truncate(MAX_RECENT_CWDS);
self.save();
}
pub fn recent_cwds(&self) -> &[String] {
&self.file.recent_cwds
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn map_survives_a_reload() {
let home = tempfile::tempdir().unwrap();
let mut topics = Topics::load(home.path());
topics.insert(TopicEntry {
chat_id: 1,
session: "t1".to_string(),
thread: 77,
name: "alfa · Qwen".to_string(),
});
topics.remember_cwd("/a");
topics.remember_cwd("/b");
topics.remember_cwd("/a");
let mut topics = Topics::load(home.path());
assert_eq!(topics.thread_for(1, "t1"), None, "unused until getMe says so");
topics.enabled = true;
assert_eq!(topics.thread_for(1, "t1"), Some(77));
assert_eq!(topics.session_for(1, 77), Some("t1"));
assert_eq!(topics.recent_cwds(), ["/a".to_string(), "/b".to_string()]);
}
}

View File

@@ -21,6 +21,8 @@ use akode_telegram::bridge::BridgeOptions;
use akode_telegram::bridge::run_supervisor; use akode_telegram::bridge::run_supervisor;
use akode_telegram::pairing; use akode_telegram::pairing;
use akode_telegram::settings; use akode_telegram::settings;
use akode_telegram::text::contains_emoji;
use akode_telegram::topics;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use serde_json::Value; use serde_json::Value;
use serde_json::json; use serde_json::json;
@@ -65,7 +67,7 @@ impl Respond for Sender {
} }
struct Harness { struct Harness {
home: tempfile::TempDir, home: Arc<tempfile::TempDir>,
telegram: MockServer, telegram: MockServer,
feed: Arc<Mutex<VecDeque<Value>>>, feed: Arc<Mutex<VecDeque<Value>>>,
next_update: AtomicI64, next_update: AtomicI64,
@@ -85,7 +87,20 @@ fn write_config(home: &Path, enabled: bool) {
.unwrap(); .unwrap();
} }
async fn mock_telegram() -> (MockServer, Arc<Mutex<VecDeque<Value>>>) { struct Topics(Arc<AtomicI64>);
impl Respond for Topics {
fn respond(&self, request: &Request) -> ResponseTemplate {
let body: Value = serde_json::from_slice(&request.body).unwrap_or_default();
let id = self.0.fetch_add(1, Ordering::SeqCst);
ResponseTemplate::new(200).set_body_json(json!({
"ok": true,
"result": {"message_thread_id": id, "name": body["name"], "icon_color": 7322096}
}))
}
}
async fn mock_telegram(topics: bool) -> (MockServer, Arc<Mutex<VecDeque<Value>>>) {
let telegram = MockServer::start().await; let telegram = MockServer::start().await;
let feed = Arc::new(Mutex::new(VecDeque::new())); let feed = Arc::new(Mutex::new(VecDeque::new()));
Mock::given(method("POST")) Mock::given(method("POST"))
@@ -99,7 +114,21 @@ async fn mock_telegram() -> (MockServer, Arc<Mutex<VecDeque<Value>>>) {
.mount(&telegram) .mount(&telegram)
.await; .await;
Mock::given(method("POST")) Mock::given(method("POST"))
.and(path_regex(".*/(editMessageText|answerCallbackQuery|getMe)$")) .and(path_regex(".*/getMe$"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": {
"id": 1, "is_bot": true, "first_name": "aKode", "username": "akode_bot",
"has_topics_enabled": topics}})))
.mount(&telegram)
.await;
Mock::given(method("POST"))
.and(path_regex(".*/createForumTopic$"))
.respond_with(Topics(Arc::new(AtomicI64::new(500))))
.mount(&telegram)
.await;
Mock::given(method("POST"))
.and(path_regex(
".*/(editMessageText|answerCallbackQuery|setMyCommands|editForumTopic|sendMessageDraft|setMessageReaction)$",
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": true}))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": true})))
.mount(&telegram) .mount(&telegram)
.await; .await;
@@ -112,15 +141,23 @@ fn options(home: &Path, telegram: &MockServer) -> BridgeOptions {
api_base: telegram.uri(), api_base: telegram.uri(),
settings_poll: Duration::from_millis(100), settings_poll: Duration::from_millis(100),
long_poll_secs: 0, long_poll_secs: 0,
draft_interval: Duration::from_millis(600),
} }
} }
impl Harness { impl Harness {
async fn start() -> Self { async fn start() -> Self {
let home = tempfile::tempdir().unwrap(); Self::start_with(Arc::new(tempfile::tempdir().unwrap()), false).await
}
async fn with_topics() -> Self {
Self::start_with(Arc::new(tempfile::tempdir().unwrap()), true).await
}
async fn start_with(home: Arc<tempfile::TempDir>, topics: bool) -> Self {
write_config(home.path(), true); write_config(home.path(), true);
settings::save_token(home.path(), AuthCredentialsStoreMode::File, TOKEN).unwrap(); settings::save_token(home.path(), AuthCredentialsStoreMode::File, TOKEN).unwrap();
let (telegram, feed) = mock_telegram().await; let (telegram, feed) = mock_telegram(topics).await;
let (to_bridge, from_server) = mpsc::unbounded_channel(); let (to_bridge, from_server) = mpsc::unbounded_channel();
let (to_server, from_bridge) = mpsc::unbounded_channel(); let (to_server, from_bridge) = mpsc::unbounded_channel();
let connection = Arc::new(Mutex::new(Some(BridgeConnection { let connection = Arc::new(Mutex::new(Some(BridgeConnection {
@@ -224,6 +261,25 @@ impl Harness {
.collect() .collect()
} }
/// Every outgoing body except reactions (which are emoji by nature).
async fn outgoing_texts(&self) -> Vec<String> {
self.telegram
.received_requests()
.await
.unwrap_or_default()
.into_iter()
.filter(|request| {
let path = request.url.path();
!path.ends_with("/setMessageReaction") && !path.ends_with("/getUpdates")
})
.map(|request| String::from_utf8_lossy(&request.body).to_string())
.map(|body| {
// Decode JSON escapes so `\uXXXX` sequences are checked too.
serde_json::from_str::<Value>(&body).map_or(body, |value| value_text(&value))
})
.collect()
}
async fn wait_for_calls(&self, api_method: &str, count: usize) -> Vec<Value> { async fn wait_for_calls(&self, api_method: &str, count: usize) -> Vec<Value> {
for _ in 0..100 { for _ in 0..100 {
let calls = self.calls(api_method).await; let calls = self.calls(api_method).await;
@@ -278,8 +334,58 @@ fn text_message(chat: i64, text: &str, reply_to: Option<i64>) -> Value {
} }
fn callback(chat: i64, data: &str) -> Value { fn callback(chat: i64, data: &str) -> Value {
json!({"callback_query": {"id": "cb", "data": data, callback_on(chat, data, 1000)
"message": {"message_id": 1000, "chat": {"id": chat}}}}) }
fn callback_on(chat: i64, data: &str, message_id: i64) -> Value {
json!({"callback_query": {"id": "cb", "data": data, "from": {"id": chat, "first_name": "A"},
"message": {"message_id": message_id, "chat": {"id": chat}}}})
}
fn topic_message(chat: i64, thread: i64, text: &str) -> Value {
json!({"message": {"message_id": 7, "chat": {"id": chat}, "message_thread_id": thread,
"is_topic_message": true, "text": text}})
}
/// All strings inside a JSON value, joined.
fn value_text(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
Value::Array(items) => items.iter().map(value_text).collect::<Vec<_>>().join("\n"),
Value::Object(map) => map
.iter()
.map(|(key, value)| format!("{key}={}", value_text(value)))
.collect::<Vec<_>>()
.join("\n"),
other => other.to_string(),
}
}
/// The callback data of the button labelled `label` in a sent or edited message.
fn button(call: &Value, label: &str) -> String {
call["reply_markup"]["inline_keyboard"]
.as_array()
.into_iter()
.flatten()
.flat_map(|row| row.as_array().cloned().unwrap_or_default())
.find(|button| button["text"] == label)
.and_then(|button| button["callback_data"].as_str().map(ToString::to_string))
.unwrap_or_else(|| panic!("no button {label:?} in {call}"))
}
fn labels(call: &Value) -> Vec<Vec<String>> {
call["reply_markup"]["inline_keyboard"]
.as_array()
.into_iter()
.flatten()
.map(|row| {
row.as_array()
.into_iter()
.flatten()
.map(|button| button["text"].as_str().unwrap_or_default().to_string())
.collect()
})
.collect()
} }
fn command_approval(thread: &str) -> Value { fn command_approval(thread: &str) -> Value {
@@ -287,16 +393,43 @@ fn command_approval(thread: &str) -> Value {
"command": "rm -rf build", "cwd": "/tmp/alfa"}) "command": "rm -rf build", "cwd": "/tmp/alfa"})
} }
fn is_response(message: &JSONRPCMessage) -> bool {
matches!(message, JSONRPCMessage::Response(_))
}
async fn next_response(h: &mut Harness) -> JSONRPCResponse {
loop {
if let JSONRPCMessage::Response(response) = h.next_from_bridge().await {
return response;
}
}
}
fn complete_turn(h: &Harness, thread: &str, turn: &str, answer: &str) {
h.notify(
"item/completed",
json!({"threadId": thread, "turnId": turn, "completedAtMs": 0, "item": {
"type": "agentMessage", "id": format!("m-{turn}"), "text": answer}}),
);
h.notify("turn/completed", json!({"threadId": thread, "turn": turn_json(turn, "completed")}));
}
#[tokio::test] #[tokio::test]
async fn ignores_chats_outside_the_allowlist() { async fn ignores_chats_outside_the_allowlist() {
let mut h = Harness::start().await; let mut h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa"); h.start_thread("t1", "/tmp/alfa");
h.server_request("item/commandExecution/requestApproval", command_approval("t1")); h.server_request("item/commandExecution/requestApproval", command_approval("t1"));
h.wait_for_calls("sendMessage", 1).await; let sends = h.wait_for_calls("sendMessage", 1).await;
let approve = button(&sends[0], "Approva");
assert!(approve.starts_with('k') && approve.len() == 17, "opaque token: {approve}");
h.push_update(text_message(999, "rm -rf /", None)); h.push_update(text_message(999, "rm -rf /", None));
h.push_update(text_message(999, "/sessioni", None)); h.push_update(text_message(999, "/sessioni", None));
h.push_update(callback(999, "a:1:y")); // A valid token pressed in an unknown chat, and by another user in the allowed chat.
h.push_update(callback(999, &approve));
let mut foreign = callback(CHAT, &approve);
foreign["callback_query"]["from"]["id"] = json!(555);
h.push_update(foreign);
let seen = h.settle().await; let seen = h.settle().await;
assert!( assert!(
seen.iter().all(|m| !matches!(m, JSONRPCMessage::Response(_) | JSONRPCMessage::Request(_))), seen.iter().all(|m| !matches!(m, JSONRPCMessage::Response(_) | JSONRPCMessage::Request(_))),
@@ -306,6 +439,13 @@ async fn ignores_chats_outside_the_allowlist() {
assert!(sends.iter().all(|send| send["chat_id"] == json!(CHAT))); assert!(sends.iter().all(|send| send["chat_id"] == json!(CHAT)));
assert!(h.calls("answerCallbackQuery").await.is_empty()); assert!(h.calls("answerCallbackQuery").await.is_empty());
// A forged raw command is not a token.
h.push_update(callback(CHAT, "a:1:y"));
let seen = h.settle().await;
assert!(seen.iter().all(|m| !is_response(m)));
let answers = h.wait_for_calls("answerCallbackQuery", 1).await;
assert_eq!(answers[0]["text"], "Pulsante scaduto: ripeti il comando.");
// The allowed chat is served. // The allowed chat is served.
h.push_update(text_message(CHAT, "ciao", None)); h.push_update(text_message(CHAT, "ciao", None));
let start = h.expect_request("turn/start").await; let start = h.expect_request("turn/start").await;
@@ -335,26 +475,33 @@ async fn approval_answered_on_telegram_wins() {
let id = h.server_request("item/commandExecution/requestApproval", command_approval("t1")); let id = h.server_request("item/commandExecution/requestApproval", command_approval("t1"));
let sends = h.wait_for_calls("sendMessage", 1).await; let sends = h.wait_for_calls("sendMessage", 1).await;
let text = sends[0]["text"].as_str().unwrap(); let text = sends[0]["text"].as_str().unwrap();
assert!(text.starts_with("[alfa · Qwen 3.6] 🔐"), "{text}"); assert!(text.starts_with("[alfa · Qwen 3.6] Approvazione richiesta: comando"), "{text}");
assert!(text.contains("rm -rf build")); assert!(text.contains("rm -rf build"));
assert_eq!(sends[0]["reply_markup"]["inline_keyboard"][0].as_array().unwrap().len(), 3); assert!(sends[0]["entities"].as_array().unwrap().iter().any(|e| e["type"] == "pre"));
assert_eq!(
labels(&sends[0]),
vec![vec!["Approva", "Approva sempre"], vec!["Rifiuta"]]
);
let keyboard = &sends[0]["reply_markup"]["inline_keyboard"];
assert_eq!(keyboard[0][0]["style"], "success");
assert_eq!(keyboard[1][0]["style"], "danger");
h.push_update(callback(CHAT, "a:1:y")); h.push_update(callback(CHAT, &button(&sends[0], "Approva")));
let response = loop { let response = next_response(&mut h).await;
if let JSONRPCMessage::Response(response) = h.next_from_bridge().await {
break response;
}
};
assert_eq!(response.id, id); assert_eq!(response.id, id);
assert_eq!(response.result, json!({"decision": "accept"})); assert_eq!(response.result, json!({"decision": "accept"}));
let edits = h.wait_for_calls("editMessageText", 1).await; let edits = h.wait_for_calls("editMessageText", 1).await;
assert!(edits[0]["text"].as_str().unwrap().ends_with("✅ approvato da Telegram")); assert_eq!(edits[0]["message_id"], 1000);
assert_eq!(labels(&edits[0]), vec![vec!["Approvato da Telegram"]]);
assert_eq!(edits[0]["reply_markup"]["inline_keyboard"][0][0]["disabled"], json!({}));
let answers = h.wait_for_calls("answerCallbackQuery", 1).await;
assert_eq!(answers[0]["text"], "Approvato da Telegram");
// The server tells everyone it is resolved; the Mac side cannot answer any more. // The server tells everyone it is resolved; nobody can answer any more.
h.notify("serverRequest/resolved", json!({"threadId": "t1", "requestId": id})); h.notify("serverRequest/resolved", json!({"threadId": "t1", "requestId": id}));
h.push_update(callback(CHAT, "a:1:n")); h.push_update(callback(CHAT, &button(&sends[0], "Rifiuta")));
let seen = h.settle().await; let seen = h.settle().await;
assert!(seen.iter().all(|m| !matches!(m, JSONRPCMessage::Response(_)))); assert!(seen.iter().all(|m| !is_response(m)));
assert_eq!(h.calls("editMessageText").await.len(), 1); assert_eq!(h.calls("editMessageText").await.len(), 1);
let answers = h.wait_for_calls("answerCallbackQuery", 2).await; let answers = h.wait_for_calls("answerCallbackQuery", 2).await;
assert_eq!(answers[1]["text"], "Già risolta."); assert_eq!(answers[1]["text"], "Già risolta.");
@@ -365,7 +512,7 @@ async fn approval_answered_on_the_mac_wins() {
let mut h = Harness::start().await; let mut h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa"); h.start_thread("t1", "/tmp/alfa");
let id = h.server_request("item/commandExecution/requestApproval", command_approval("t1")); let id = h.server_request("item/commandExecution/requestApproval", command_approval("t1"));
h.wait_for_calls("sendMessage", 1).await; let sends = h.wait_for_calls("sendMessage", 1).await;
h.notify("serverRequest/resolved", json!({"threadId": "t1", "requestId": id})); h.notify("serverRequest/resolved", json!({"threadId": "t1", "requestId": id}));
h.notify( h.notify(
@@ -376,55 +523,293 @@ async fn approval_answered_on_the_mac_wins() {
"commandActions": [], "aggregatedOutput": null, "exitCode": null, "durationMs": null}}), "commandActions": [], "aggregatedOutput": null, "exitCode": null, "durationMs": null}}),
); );
let edits = h.wait_for_calls("editMessageText", 2).await; let edits = h.wait_for_calls("editMessageText", 2).await;
assert!(edits[0]["text"].as_str().unwrap().ends_with("☑️ risposto dal Mac")); assert_eq!(labels(&edits[0]), vec![vec!["Risposto dal Mac"]]);
assert!(edits[1]["text"].as_str().unwrap().ends_with("✅ approvato dal Mac")); assert_eq!(labels(&edits[1]), vec![vec!["Approvato dal Mac"]]);
h.push_update(callback(CHAT, "a:1:y")); h.push_update(callback(CHAT, &button(&sends[0], "Approva")));
let seen = h.settle().await; let seen = h.settle().await;
assert!( assert!(
seen.iter().all(|m| !matches!(m, JSONRPCMessage::Response(_))), seen.iter().all(|m| !is_response(m)),
"Telegram answered a resolved request: {seen:?}" "Telegram answered a resolved request: {seen:?}"
); );
} }
#[tokio::test] #[tokio::test]
async fn replies_go_to_the_session_they_answer() { async fn topics_are_created_mapped_and_reused_after_a_restart() {
let mut h = Harness::start().await; let home;
{
let h = Harness::with_topics().await;
home = Arc::clone(&h.home);
h.start_thread("t1", "/tmp/alfa");
let topics = h.wait_for_calls("createForumTopic", 1).await;
assert_eq!(topics[0]["chat_id"], json!(CHAT));
assert_eq!(topics[0]["name"], "alfa · Qwen 3.6");
let commands = h.wait_for_calls("setMyCommands", 1).await;
let names: Vec<&str> = commands[0]["commands"]
.as_array()
.unwrap()
.iter()
.map(|c| c["command"].as_str().unwrap())
.collect();
assert_eq!(names, ["sessioni", "nuova", "stato", "stop", "impostazioni", "aiuto"]);
assert_eq!(commands[0]["scope"]["type"], "all_private_chats");
complete_turn(&h, "t1", "turn-1", "Fatto.");
let sends = h.wait_for_calls("sendMessage", 1).await;
assert_eq!(sends[0]["message_thread_id"], 500);
assert!(sends[0]["text"].as_str().unwrap().starts_with("Fatto."), "no tag inside a topic");
let saved = std::fs::read_to_string(home.path().join(topics::TOPICS_FILE)).unwrap();
assert!(saved.contains("\"thread\": 500"), "{saved}");
h.notify("thread/closed", json!({"threadId": "t1"}));
let renames = h.wait_for_calls("editForumTopic", 1).await;
assert_eq!(renames[0]["message_thread_id"], 500);
assert_eq!(renames[0]["name"], "alfa · Qwen 3.6 (chiusa)");
h.shutdown.cancel();
tokio::time::sleep(Duration::from_millis(300)).await;
}
// A new bridge on the same home writes into the same topic and reopens its name.
let h = Harness::start_with(home, true).await;
h.start_thread("t1", "/tmp/alfa");
let renames = h.wait_for_calls("editForumTopic", 1).await;
assert_eq!(renames[0]["name"], "alfa · Qwen 3.6");
complete_turn(&h, "t1", "turn-2", "Ancora.");
let sends = h.wait_for_calls("sendMessage", 1).await;
assert_eq!(sends[0]["message_thread_id"], 500);
assert!(h.calls("createForumTopic").await.is_empty());
}
#[tokio::test]
async fn topic_messages_go_to_their_session() {
let mut h = Harness::with_topics().await;
h.start_thread("t1", "/tmp/alfa"); h.start_thread("t1", "/tmp/alfa");
h.start_thread("t2", "/tmp/beta"); h.start_thread("t2", "/tmp/beta");
h.notify("turn/started", json!({"threadId": "t2", "turn": turn_json("turn-2", "inProgress")})); h.wait_for_calls("createForumTopic", 2).await;
h.notify( // Let the outbox store both topics.
"item/completed", h.settle().await;
json!({"threadId": "t2", "turnId": "turn-2", "completedAtMs": 0, "item": {
"type": "agentMessage", "id": "m1", "text": "Fatto: test verdi."}}),
);
h.notify("turn/completed", json!({"threadId": "t2", "turn": turn_json("turn-2", "completed")}));
let sends = h.wait_for_calls("sendMessage", 1).await;
let text = sends[0]["text"].as_str().unwrap();
assert!(text.starts_with("[beta · Qwen 3.6] ✅ Turno finito"), "{text}");
assert!(text.ends_with("Fatto: test verdi."));
// Message ids start at 1000 in the mock. h.push_update(topic_message(CHAT, 501, "continua"));
h.push_update(text_message(CHAT, "continua", Some(1000)));
let start = h.expect_request("turn/start").await; let start = h.expect_request("turn/start").await;
let params = start.params.unwrap(); let params = start.params.unwrap();
assert_eq!(params["threadId"], "t2"); assert_eq!(params["threadId"], "t2");
assert_eq!(params["input"][0]["text"], "continua"); assert_eq!(params["input"][0]["text"], "continua");
// Without a reply and with two sessions the bridge asks which one. // Commands in a topic act on its session and answer in the topic.
h.push_update(topic_message(CHAT, 500, "/stato"));
let sends = h.wait_for_calls("sendMessage", 1).await;
assert_eq!(sends[0]["message_thread_id"], 500);
assert!(sends[0]["text"].as_str().unwrap().starts_with("alfa · Qwen 3.6 · libera"));
// The session list links each topic and refreshes in place.
h.push_update(text_message(CHAT, "/sessioni", None));
let sends = h.wait_for_calls("sendMessage", 2).await;
let list = &sends[1];
assert_eq!(
labels(list),
vec![
vec!["1 · Apri", "1 · Stato", "1 · Stop"],
vec!["2 · Apri", "2 · Stato", "2 · Stop"],
vec!["Aggiorna", "Nuova sessione"],
]
);
assert_eq!(list["reply_markup"]["inline_keyboard"][1][0]["url"], "https://t.me/akode_bot/501");
let list_id = 1001;
h.push_update(callback_on(CHAT, &button(list, "2 · Stato"), list_id));
let answers = h.wait_for_calls("answerCallbackQuery", 1).await;
assert!(answers[0]["text"].as_str().unwrap().starts_with("beta · Qwen 3.6"));
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-9", "inProgress")}));
let edits = h.wait_for_calls("editMessageText", 1).await;
assert_eq!(edits[0]["message_id"], list_id);
assert!(edits[0]["text"].as_str().unwrap().contains("al lavoro"));
assert_eq!(h.calls("sendMessage").await.len(), 2, "refresh edits, never sends");
h.push_update(callback_on(CHAT, &button(list, "1 · Stop"), list_id));
let interrupt = h.expect_request("turn/interrupt").await;
assert_eq!(interrupt.params.unwrap()["turnId"], "turn-9");
}
#[tokio::test]
async fn without_topics_messages_are_tagged_and_buttons_pick_the_session() {
let mut h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa");
h.start_thread("t2", "/tmp/beta");
h.notify("turn/started", json!({"threadId": "t2", "turn": turn_json("turn-2", "inProgress")}));
complete_turn(&h, "t2", "turn-2", "Fatto: test verdi.");
let sends = h.wait_for_calls("sendMessage", 1).await;
let text = sends[0]["text"].as_str().unwrap();
assert!(text.starts_with("[beta · Qwen 3.6] Fatto: test verdi."), "{text}");
assert!(text.ends_with("2s"), "footer: {text}");
assert!(sends[0]["entities"].as_array().unwrap().iter().any(|e| e["type"] == "italic"));
assert!(sends[0].get("message_thread_id").is_none());
assert!(h.calls("createForumTopic").await.is_empty());
// A reply goes to the session it answers; the message gets the received reaction.
h.push_update(text_message(CHAT, "continua", Some(1000)));
let start = h.expect_request("turn/start").await;
assert_eq!(start.params.clone().unwrap()["threadId"], "t2");
h.respond(start.id, json!({"turn": turn_json("turn-3", "inProgress")}));
let reactions = h.wait_for_calls("setMessageReaction", 1).await;
assert_eq!(reactions[0]["message_id"], 1);
assert_eq!(reactions[0]["reaction"][0]["type"], "emoji");
// Without a reply and with two sessions the bridge asks with buttons.
h.push_update(text_message(CHAT, "e adesso?", None)); h.push_update(text_message(CHAT, "e adesso?", None));
let sends = h.wait_for_calls("sendMessage", 2).await;
assert_eq!(labels(&sends[1]), vec![vec!["alfa · Qwen 3.6"], vec!["beta · Qwen 3.6"]]);
h.push_update(callback(CHAT, &button(&sends[1], "alfa · Qwen 3.6")));
let start = h.expect_request("turn/start").await;
let params = start.params.unwrap();
assert_eq!(params["threadId"], "t1");
assert_eq!(params["input"][0]["text"], "e adesso?");
// The choice is used once.
h.push_update(callback(CHAT, &button(&sends[1], "beta · Qwen 3.6")));
let seen = h.settle().await; let seen = h.settle().await;
assert!(seen.iter().all(|m| !matches!(m, JSONRPCMessage::Request(_)))); assert!(seen.iter().all(|m| !matches!(m, JSONRPCMessage::Request(_))));
// `/usa 1` picks the first session; a busy session is steered. // `/aiuto` explains how to enable topics.
h.push_update(text_message(CHAT, "/usa 1", None)); h.push_update(text_message(CHAT, "/aiuto", None));
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-9", "inProgress")})); let sends = h.wait_for_calls("sendMessage", 3).await;
assert!(sends[2]["text"].as_str().unwrap().contains("Threaded Mode"));
}
#[tokio::test]
async fn settings_toggles_persist_to_config() {
let mut h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa");
h.push_update(text_message(CHAT, "/impostazioni", None));
let sends = h.wait_for_calls("sendMessage", 1).await;
assert_eq!(
labels(&sends[0]),
vec![
vec!["Approvazioni: Sì"],
vec!["Fine turno: Sì"],
vec!["Errori: Sì"],
vec!["Loop: Sì"],
vec!["Streaming e piano: Sì"],
vec!["Reazioni: Sì"],
]
);
h.push_update(callback(CHAT, &button(&sends[0], "Approvazioni: Sì")));
let edits = h.wait_for_calls("editMessageText", 1).await;
assert_eq!(labels(&edits[0])[0], vec!["Approvazioni: No"]);
let answers = h.wait_for_calls("answerCallbackQuery", 1).await;
assert_eq!(answers[0]["text"], "Approvazioni: No");
let saved = settings::TelegramSettings::load(h.home.path());
assert!(!saved.notify.approvals);
assert!(saved.enabled && saved.streaming);
// Approvals are no longer sent.
h.server_request("item/commandExecution/requestApproval", command_approval("t1"));
h.settle().await; h.settle().await;
h.push_update(text_message(CHAT, "aggiungi i test", None)); assert_eq!(h.calls("sendMessage").await.len(), 1);
h.push_update(callback(CHAT, &button(&edits[0], "Approvazioni: No")));
h.wait_for_calls("editMessageText", 2).await;
assert!(settings::TelegramSettings::load(h.home.path()).notify.approvals);
}
#[tokio::test]
async fn edited_commands_run_again_and_edited_text_is_ignored() {
let mut h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa");
h.push_update(json!({"edited_message": {"message_id": 3, "chat": {"id": CHAT}, "text": "ciao"}}));
let seen = h.settle().await;
assert!(seen.iter().all(|m| !matches!(m, JSONRPCMessage::Request(_))));
assert!(h.calls("sendMessage").await.is_empty());
h.push_update(json!({"edited_message": {"message_id": 3, "chat": {"id": CHAT}, "text": "/aiuto"}}));
let sends = h.wait_for_calls("sendMessage", 1).await;
assert!(sends[0]["text"].as_str().unwrap().starts_with("aKode su Telegram"));
}
#[tokio::test]
async fn drafts_are_throttled_and_stop_interrupts() {
let mut h = Harness::with_topics().await;
h.start_thread("t1", "/tmp/alfa");
h.wait_for_calls("createForumTopic", 1).await;
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-1", "inProgress")}));
for word in ["Sto ", "leggendo ", "i ", "file ", "del ", "progetto."] {
h.notify(
"item/agentMessage/delta",
json!({"threadId": "t1", "turnId": "turn-1", "itemId": "m1", "delta": word}),
);
}
tokio::time::sleep(Duration::from_millis(300)).await;
let drafts = h.calls("sendMessageDraft").await;
assert_eq!(drafts.len(), 1, "one draft inside the interval: {drafts:?}");
assert_eq!(drafts[0]["text"], "Sto ");
assert_eq!(drafts[0]["message_thread_id"], 500);
assert_eq!(drafts[0]["can_stop"], true);
let drafts = h.wait_for_calls("sendMessageDraft", 2).await;
assert_eq!(drafts[1]["text"], "Sto leggendo i file del progetto.");
assert_eq!(drafts[1]["draft_id"], drafts[0]["draft_id"]);
tokio::time::sleep(Duration::from_millis(800)).await;
assert_eq!(h.calls("sendMessageDraft").await.len(), 2, "nothing new, no draft");
let draft_id = drafts[0]["draft_id"].clone();
h.push_update(json!({"stopped_message_generation": {
"chat": {"id": CHAT}, "message_thread_id": 500, "draft_id": draft_id}}));
let interrupt = h.expect_request("turn/interrupt").await;
assert_eq!(interrupt.params.unwrap()["threadId"], "t1");
h.notify("turn/completed", json!({"threadId": "t1", "turn": turn_json("turn-1", "interrupted")}));
let sends = h.wait_for_calls("sendMessage", 1).await;
assert!(sends[0]["text"].as_str().unwrap().starts_with("Turno interrotto."));
}
#[tokio::test]
async fn no_emoji_in_any_outgoing_text() {
let mut h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa");
for command in ["/aiuto", "/sessioni", "/impostazioni", "/nuova", "/stato", "/stop", "/boh"] {
h.push_update(text_message(CHAT, command, None));
}
let id = h.server_request("item/commandExecution/requestApproval", command_approval("t1"));
h.server_request(
"item/fileChange/requestApproval",
json!({"threadId": "t1", "turnId": "turn-1", "itemId": "item-2", "startedAtMs": 0,
"reason": "nuovo modulo"}),
);
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-1", "inProgress")}));
h.notify(
"turn/plan/updated",
json!({"threadId": "t1", "turnId": "turn-1", "explanation": null, "plan": [
{"step": "Leggere", "status": "completed"},
{"step": "Scrivere", "status": "inProgress"},
{"step": "Provare", "status": "pending"}]}),
);
h.notify(
"error",
json!({"threadId": "t1", "turnId": "turn-1", "willRetry": false,
"error": {"message": "Il modello ripete lo stesso comando", "codexErrorInfo": null}}),
);
h.notify(
"error",
json!({"threadId": "t1", "turnId": "turn-1", "willRetry": false,
"error": {"message": "HTTP 429", "codexErrorInfo": null}}),
);
let sends = h.wait_for_calls("sendMessage", 10).await;
let approval = sends
.iter()
.find(|send| send["text"].as_str().unwrap_or_default().contains("rm -rf build"))
.expect("approval sent")
.clone();
h.push_update(callback(CHAT, &button(&approval, "Rifiuta")));
let response = next_response(&mut h).await;
assert_eq!(response.id, id);
h.push_update(text_message(CHAT, "ciao", None));
let steer = h.expect_request("turn/steer").await; let steer = h.expect_request("turn/steer").await;
let params = steer.params.unwrap(); h.respond(steer.id, json!({"turnId": "turn-1"}));
assert_eq!(params["threadId"], "t1"); complete_turn(&h, "t1", "turn-1", "Fatto.");
assert_eq!(params["expectedTurnId"], "turn-9"); h.notify("thread/closed", json!({"threadId": "t1"}));
h.push_update(text_message(CHAT, "/sessioni", None));
h.settle().await;
let texts = h.outgoing_texts().await;
assert!(texts.len() > 15, "{texts:?}");
for text in texts {
assert!(!contains_emoji(&text), "emoji in an outgoing payload: {text}");
}
} }
#[tokio::test] #[tokio::test]
@@ -461,7 +846,7 @@ async fn nothing_is_polled_while_disabled() {
let home = tempfile::tempdir().unwrap(); let home = tempfile::tempdir().unwrap();
write_config(home.path(), false); write_config(home.path(), false);
settings::save_token(home.path(), AuthCredentialsStoreMode::File, TOKEN).unwrap(); settings::save_token(home.path(), AuthCredentialsStoreMode::File, TOKEN).unwrap();
let (telegram, _feed) = mock_telegram().await; let (telegram, _feed) = mock_telegram(false).await;
let connects = Arc::new(AtomicUsize::new(0)); let connects = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&connects); let counter = Arc::clone(&connects);
let shutdown = CancellationToken::new(); let shutdown = CancellationToken::new();

View File

@@ -1,5 +1,6 @@
--- ---
source: tui/src/telegram_panel_tests.rs source: tui/src/telegram_panel_tests.rs
assertion_line: 47
expression: "render(&panel, width, 16)" expression: "render(&panel, width, 16)"
--- ---
Telegram esc chiudi Telegram esc chiudi
@@ -8,13 +9,13 @@ expression: "render(&panel, width, 16)"
Stato attivo · connesso Stato attivo · connesso
Chat 123456789 Chat 123456789
Notifiche approvazioni · fine turno · errori · loop Notifiche approvazioni · fine turno · errori · loop
Opzioni streaming sì · reazioni sì
Topic non attivi: @BotFather › il bot › Bot Settings › Threaded Mode
› Cambia il token del bot › Cambia il token del bot
Abbina una chat Abbina una chat
Disattiva Disattiva
Rimuovi il token Rimuovi il token
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
↑↓ scegli · invio conferma · esc chiudi ↑↓ scegli · invio conferma · esc chiudi

View File

@@ -1,6 +1,6 @@
--- ---
source: tui/src/telegram_panel_tests.rs source: tui/src/telegram_panel_tests.rs
assertion_line: 46 assertion_line: 47
expression: "render(&panel, width, 16)" expression: "render(&panel, width, 16)"
--- ---
Telegram esc chiudi Telegram esc chiudi
@@ -9,13 +9,13 @@ expression: "render(&panel, width, 16)"
Stato attivo · connesso Stato attivo · connesso
Chat 123456789 Chat 123456789
Notifiche approvazioni · fine turno · errori · loop Notifiche approvazioni · fine turno · errori · loop
Opzioni streaming sì · reazioni sì
Topic non attivi: @BotFather › il bot › Bot Settings › Threaded Mode
› Cambia il token del bot › Cambia il token del bot
Abbina una chat Abbina una chat
Disattiva Disattiva
Rimuovi il token Rimuovi il token
──────────────────────────────────────────────────────────────────────────── ────────────────────────────────────────────────────────────────────────────
↑↓ scegli · invio conferma · esc chiudi ↑↓ scegli · invio conferma · esc chiudi

View File

@@ -1,5 +1,6 @@
--- ---
source: tui/src/telegram_panel_tests.rs source: tui/src/telegram_panel_tests.rs
assertion_line: 55
expression: "render(&panel, width, 16)" expression: "render(&panel, width, 16)"
--- ---
Telegram esc chiudi Telegram esc chiudi
@@ -8,13 +9,13 @@ expression: "render(&panel, width, 16)"
Stato disattivato Stato disattivato
Chat nessuna abbinata Chat nessuna abbinata
Notifiche approvazioni · fine turno · errori · loop Notifiche approvazioni · fine turno · errori · loop
Opzioni streaming sì · reazioni sì
Topic da verificare (si vede col bot attivo)
› Imposta il token del bot › Imposta il token del bot
Abbina una chat Abbina una chat
Attiva Attiva
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
↑↓ scegli · invio conferma · esc chiudi ↑↓ scegli · invio conferma · esc chiudi

View File

@@ -1,6 +1,6 @@
--- ---
source: tui/src/telegram_panel_tests.rs source: tui/src/telegram_panel_tests.rs
assertion_line: 54 assertion_line: 55
expression: "render(&panel, width, 16)" expression: "render(&panel, width, 16)"
--- ---
Telegram esc chiudi Telegram esc chiudi
@@ -9,13 +9,13 @@ expression: "render(&panel, width, 16)"
Stato disattivato Stato disattivato
Chat nessuna abbinata Chat nessuna abbinata
Notifiche approvazioni · fine turno · errori · loop Notifiche approvazioni · fine turno · errori · loop
Opzioni streaming sì · reazioni sì
Topic da verificare (si vede col bot attivo)
› Imposta il token del bot › Imposta il token del bot
Abbina una chat Abbina una chat
Attiva Attiva
──────────────────────────────────────────────────────────────────────────── ────────────────────────────────────────────────────────────────────────────
↑↓ scegli · invio conferma · esc chiudi ↑↓ scegli · invio conferma · esc chiudi

View File

@@ -72,6 +72,8 @@ pub(crate) struct TelegramStatus {
pub(crate) has_token: bool, pub(crate) has_token: bool,
pub(crate) bot_name: Option<String>, pub(crate) bot_name: Option<String>,
pub(crate) connected: bool, pub(crate) connected: bool,
/// Topics in private chats, as the bridge last saw them (`None`: not checked yet).
pub(crate) topics: Option<bool>,
} }
impl TelegramStatus { impl TelegramStatus {
@@ -82,6 +84,7 @@ impl TelegramStatus {
let connected = settings.enabled && has_token && PollLock::try_acquire(codex_home).is_none(); let connected = settings.enabled && has_token && PollLock::try_acquire(codex_home).is_none();
Self { Self {
bot_name: settings::load_bot_name(codex_home), bot_name: settings::load_bot_name(codex_home),
topics: settings::load_bot_topics(codex_home),
settings, settings,
has_token, has_token,
connected, connected,
@@ -412,6 +415,25 @@ impl TelegramPanel {
Span::from(levels.join(" · ")) Span::from(levels.join(" · "))
}, },
)); ));
lines.push(field(
"Opzioni",
Span::from(format!(
"streaming {} · reazioni {}",
if status.settings.streaming { "sì" } else { "no" },
if status.settings.reactions { "sì" } else { "no" },
)),
));
lines.push(field(
"Topic",
match status.topics {
Some(true) => Span::from("uno per sessione"),
Some(false) => Span::styled(
"non attivi: @BotFather › il bot › Bot Settings › Threaded Mode",
status_style(StatusTone::Attention),
),
None => "da verificare (si vede col bot attivo)".dim(),
},
));
lines.push(Line::from("")); lines.push(Line::from(""));
for (index, (_, label)) in self.actions().into_iter().enumerate() { for (index, (_, label)) in self.actions().into_iter().enumerate() {
let line = if index == self.selected { let line = if index == self.selected {

View File

@@ -11,6 +11,7 @@ fn status() -> TelegramStatus {
has_token: true, has_token: true,
bot_name: Some("akode_bot".to_string()), bot_name: Some("akode_bot".to_string()),
connected: true, connected: true,
topics: Some(false),
} }
} }