WIP Telegram: modulo akode-telegram (API e impostazioni), in pausa

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-12 08:21:25 +01:00
parent 9636b74c7d
commit 28bddb1b0c
41 changed files with 4216 additions and 4 deletions

View File

@@ -0,0 +1,37 @@
[package]
name = "akode-telegram"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
name = "akode_telegram"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
akode-app-server-protocol = { workspace = true }
akode-config = { workspace = true }
akode-login = { workspace = true }
akode-model-provider-info = { workspace = true }
akode-utils-rustls-provider = { workspace = true }
rand = { workspace = true }
reqwest = { workspace = true, features = ["json", "rustls-tls", "rustls-tls-native-roots"] }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] }
tokio-util = { workspace = true }
toml = { workspace = true }
toml_edit = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true, features = ["v4"] }
[dev-dependencies]
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,257 @@
//! Minimal Telegram Bot API client. Errors never carry the request URL, which contains
//! the bot token.
use std::fmt;
use std::time::Duration;
use serde::Deserialize;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use serde_json::json;
use crate::TELEGRAM_API_BASE;
#[derive(Clone)]
pub struct TelegramApi {
client: reqwest::Client,
base: String,
token: String,
}
impl fmt::Debug for TelegramApi {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TelegramApi")
.field("base", &self.base)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ApiError {
#[error("Telegram non raggiungibile: {0}")]
Network(String),
#[error("Telegram ha risposto {code}: {description}")]
Api {
code: i64,
description: String,
retry_after: Option<u64>,
},
#[error("risposta di Telegram non valida: {0}")]
Decode(String),
}
impl ApiError {
/// Seconds Telegram asked to wait (429), if any.
pub fn retry_after(&self) -> Option<u64> {
match self {
Self::Api { retry_after, .. } => *retry_after,
_ => None,
}
}
/// The token was refused (revoked or mistyped).
pub fn is_unauthorized(&self) -> bool {
matches!(self, Self::Api { code: 401 | 404, .. })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct User {
pub id: i64,
#[serde(default)]
pub username: Option<String>,
#[serde(default)]
pub first_name: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Chat {
pub id: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Message {
pub message_id: i64,
pub chat: Chat,
#[serde(default)]
pub text: Option<String>,
#[serde(default)]
pub reply_to_message: Option<Box<Message>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct CallbackQuery {
pub id: String,
#[serde(default)]
pub message: Option<Message>,
#[serde(default)]
pub data: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Update {
pub update_id: i64,
#[serde(default)]
pub message: Option<Message>,
#[serde(default)]
pub callback_query: Option<CallbackQuery>,
}
impl Update {
/// Chat the update comes from.
pub fn chat_id(&self) -> Option<i64> {
self.message
.as_ref()
.map(|message| message.chat.id)
.or_else(|| {
self.callback_query
.as_ref()
.and_then(|query| query.message.as_ref())
.map(|message| message.chat.id)
})
}
}
/// One inline keyboard button.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Button {
pub text: String,
pub callback_data: String,
}
#[derive(Deserialize)]
struct Envelope<T> {
ok: bool,
#[serde(default = "Option::default")]
result: Option<T>,
#[serde(default)]
error_code: Option<i64>,
#[serde(default)]
description: Option<String>,
#[serde(default)]
parameters: Option<ResponseParameters>,
}
#[derive(Deserialize)]
struct ResponseParameters {
#[serde(default)]
retry_after: Option<u64>,
}
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
impl TelegramApi {
pub fn new(token: &str) -> Self {
Self::with_base_url(TELEGRAM_API_BASE, token)
}
/// Client for another base URL; only tests use it (a mock server).
pub fn with_base_url(base: &str, token: &str) -> Self {
akode_utils_rustls_provider::ensure_rustls_crypto_provider();
let client = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(15))
.build()
.unwrap_or_default();
Self {
client,
base: base.trim_end_matches('/').to_string(),
token: token.trim().to_string(),
}
}
async fn call<T: DeserializeOwned>(
&self,
method: &str,
body: Value,
timeout: Duration,
) -> Result<T, ApiError> {
let url = format!("{}/bot{}/{method}", self.base, self.token);
let response = self
.client
.post(url)
.timeout(timeout)
.json(&body)
.send()
.await
.map_err(|err| ApiError::Network(err.without_url().to_string()))?;
let envelope: Envelope<T> = response
.json()
.await
.map_err(|err| ApiError::Decode(err.without_url().to_string()))?;
if envelope.ok {
envelope
.result
.ok_or_else(|| ApiError::Decode("risultato mancante".to_string()))
} else {
Err(ApiError::Api {
code: envelope.error_code.unwrap_or_default(),
description: envelope.description.unwrap_or_default(),
retry_after: envelope.parameters.and_then(|p| p.retry_after),
})
}
}
pub async fn get_me(&self) -> Result<User, ApiError> {
self.call("getMe", json!({}), REQUEST_TIMEOUT).await
}
/// Long poll: waits up to `timeout_secs` for new updates after `offset`.
pub async fn get_updates(
&self,
offset: Option<i64>,
timeout_secs: u64,
) -> Result<Vec<Update>, ApiError> {
let mut body = json!({
"timeout": timeout_secs,
"allowed_updates": ["message", "callback_query"],
});
if let Some(offset) = offset {
body["offset"] = json!(offset);
}
self.call(
"getUpdates",
body,
Duration::from_secs(timeout_secs) + REQUEST_TIMEOUT,
)
.await
}
pub async fn send_message(
&self,
chat_id: i64,
text: &str,
reply_to: Option<i64>,
buttons: Option<&[Vec<Button>]>,
) -> Result<Message, ApiError> {
let mut body = json!({ "chat_id": chat_id, "text": text });
if let Some(reply_to) = reply_to {
body["reply_parameters"] =
json!({ "message_id": reply_to, "allow_sending_without_reply": true });
}
if let Some(buttons) = buttons {
body["reply_markup"] = json!({ "inline_keyboard": buttons });
}
self.call("sendMessage", body, REQUEST_TIMEOUT).await
}
/// Replaces a message's text; the inline keyboard is removed.
pub async fn edit_message_text(
&self,
chat_id: i64,
message_id: i64,
text: &str,
) -> Result<(), ApiError> {
let body = json!({ "chat_id": chat_id, "message_id": message_id, "text": text });
self.call::<Value>("editMessageText", body, REQUEST_TIMEOUT)
.await
.map(|_| ())
}
pub async fn answer_callback_query(&self, id: &str, text: &str) -> Result<(), ApiError> {
let body = json!({ "callback_query_id": id, "text": text });
self.call::<Value>("answerCallbackQuery", body, REQUEST_TIMEOUT)
.await
.map(|_| ())
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,30 @@
//! Telegram control of running aKode sessions.
//!
//! The bridge runs inside the app-server that hosts the sessions: the shared daemon, or a
//! `--no-daemon` process. Telegram allows one `getUpdates` poller per bot token, so every
//! process takes [`lock::PollLock`] in `AKODE_HOME` first and only the holder polls; the
//! others retry later and take over when the holder exits.
//!
//! The bridge is an ordinary app-server client (an internal connection): it subscribes to
//! the loaded threads, answers approvals through the same JSON-RPC responses the TUI sends
//! (the first answer wins, the other side receives `serverRequest/resolved`) and starts or
//! steers turns with `turn/start`, `turn/steer`, `thread/queue/add` and `turn/interrupt`.
//!
//! Only `https://api.telegram.org` is contacted, only while `[telegram] enabled = true`,
//! and only chats in `allowed_chat_ids` are served. The bot token stays in the key store.
pub mod api;
pub mod bridge;
pub mod lock;
pub mod pairing;
pub mod settings;
pub mod text;
/// Key store id of the bot token.
pub const TOKEN_ID: &str = "telegram-bot";
/// The only host the bridge contacts.
pub const TELEGRAM_API_BASE: &str = "https://api.telegram.org";
/// App-server client name of the bridge connection.
pub const CLIENT_NAME: &str = "akode-telegram";

View File

@@ -0,0 +1,46 @@
//! One Telegram poller per `AKODE_HOME`.
//!
//! Telegram rejects a second `getUpdates` poller for the same bot (409), so the shared
//! daemon, every `--no-daemon` session and the `/telegram` pairing screen take this lock
//! before polling. Whoever fails skips polling and retries later; the lock is released
//! when its holder stops polling or exits (the OS drops it with the process).
use std::fs::File;
use std::fs::OpenOptions;
use std::path::Path;
pub const LOCK_FILE: &str = "telegram.lock";
#[derive(Debug)]
pub struct PollLock {
_file: File,
}
impl PollLock {
/// Takes the lock without waiting; `None` when another poller holds it.
pub fn try_acquire(codex_home: &Path) -> Option<Self> {
std::fs::create_dir_all(codex_home).ok()?;
let file = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(codex_home.join(LOCK_FILE))
.ok()?;
file.try_lock().ok()?;
Some(Self { _file: file })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_one_holder_at_a_time() {
let home = tempfile::tempdir().unwrap();
let first = PollLock::try_acquire(home.path()).expect("first holder");
assert!(PollLock::try_acquire(home.path()).is_none());
drop(first);
assert!(PollLock::try_acquire(home.path()).is_some());
}
}

View File

@@ -0,0 +1,175 @@
//! Pairing a chat: `/telegram` shows a 6-digit code, the user sends it to the bot, and the
//! sending chat joins `allowed_chat_ids`.
//!
//! The pending code lives in `AKODE_HOME/telegram-pairing.json` so that whichever process
//! polls (the pairing screen itself, or a running bridge) can accept it. A code expires
//! after ten minutes or after five wrong 6-digit attempts from unknown chats.
use std::io;
use std::path::Path;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use rand::Rng;
use serde::Deserialize;
use serde::Serialize;
use crate::api::ApiError;
use crate::api::TelegramApi;
use crate::settings;
pub const PAIRING_FILE: &str = "telegram-pairing.json";
pub const PAIRING_TTL: Duration = Duration::from_secs(10 * 60);
const MAX_WRONG_ATTEMPTS: u32 = 5;
/// 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.";
#[derive(Debug, Serialize, Deserialize)]
struct Pending {
code: String,
expires_at: u64,
#[serde(default)]
wrong_attempts: u32,
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.as_secs())
.unwrap_or_default()
}
fn write_pending(codex_home: &Path, pending: &Pending) -> io::Result<()> {
std::fs::create_dir_all(codex_home)?;
let path = codex_home.join(PAIRING_FILE);
let text = serde_json::to_string(pending).map_err(io::Error::other)?;
std::fs::write(&path, text)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
fn read_pending(codex_home: &Path) -> Option<Pending> {
let text = std::fs::read_to_string(codex_home.join(PAIRING_FILE)).ok()?;
let pending: Pending = serde_json::from_str(&text).ok()?;
(pending.expires_at > now() && pending.wrong_attempts < MAX_WRONG_ATTEMPTS).then_some(pending)
}
/// Starts a pairing and returns the code to show.
pub fn start(codex_home: &Path) -> io::Result<String> {
let code = format!("{:06}", rand::rng().random_range(0..1_000_000u32));
write_pending(
codex_home,
&Pending {
code: code.clone(),
expires_at: now() + PAIRING_TTL.as_secs(),
wrong_attempts: 0,
},
)?;
Ok(code)
}
pub fn cancel(codex_home: &Path) {
let _ = std::fs::remove_file(codex_home.join(PAIRING_FILE));
}
/// The code still waiting to be sent, if any.
pub fn pending_code(codex_home: &Path) -> Option<String> {
read_pending(codex_home).map(|pending| pending.code)
}
/// Pairs `chat_id` when `text` is the pending code. A wrong 6-digit attempt counts toward
/// invalidating the code; any other text is ignored.
pub fn try_pair(codex_home: &Path, chat_id: i64, text: &str) -> io::Result<bool> {
let Some(mut pending) = read_pending(codex_home) else {
return Ok(false);
};
let text = text.trim();
if text == pending.code {
settings::add_allowed_chat(codex_home, chat_id)?;
cancel(codex_home);
return Ok(true);
}
if text.len() == 6 && text.chars().all(|c| c.is_ascii_digit()) {
pending.wrong_attempts += 1;
if pending.wrong_attempts >= MAX_WRONG_ATTEMPTS {
cancel(codex_home);
} else {
write_pending(codex_home, &pending)?;
}
}
Ok(false)
}
/// One short poll for the pairing screen, used only while no bridge holds the poll lock.
/// Returns the paired chat, if the code arrived.
pub async fn poll_once(
api: &TelegramApi,
codex_home: &Path,
offset: &mut Option<i64>,
timeout_secs: u64,
) -> Result<Option<i64>, ApiError> {
let updates = api.get_updates(*offset, timeout_secs).await?;
let mut paired = None;
for update in updates {
*offset = Some(update.update_id + 1);
let Some(message) = update.message else {
continue;
};
let Some(text) = message.text.as_deref() else {
continue;
};
if paired.is_none()
&& try_pair(codex_home, message.chat.id, text).unwrap_or_else(|err| {
tracing::warn!("telegram: cannot save the paired chat: {err}");
false
})
{
paired = Some(message.chat.id);
let _ = api
.send_message(message.chat.id, PAIRED_REPLY, None, None)
.await;
}
}
if offset.is_some() {
// Acknowledge what was read so the bridge does not see it again.
let _ = api.get_updates(*offset, 0).await;
}
Ok(paired)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn code_pairs_once_and_wrong_attempts_expire_it() {
let home = tempfile::tempdir().unwrap();
let code = start(home.path()).unwrap();
assert_eq!(code.len(), 6);
assert!(!try_pair(home.path(), 7, "hello").unwrap());
assert!(try_pair(home.path(), 7, &format!(" {code} ")).unwrap());
assert_eq!(pending_code(home.path()), None);
assert!(!try_pair(home.path(), 8, &code).unwrap());
assert_eq!(
settings::TelegramSettings::load(home.path()).allowed_chat_ids,
vec![7]
);
let code = start(home.path()).unwrap();
let wrong = if code == "000000" { "111111" } else { "000000" };
for _ in 0..MAX_WRONG_ATTEMPTS {
assert!(!try_pair(home.path(), 9, wrong).unwrap());
}
assert!(!try_pair(home.path(), 9, &code).unwrap());
assert_eq!(
settings::TelegramSettings::load(home.path()).allowed_chat_ids,
vec![7]
);
}
}

View File

@@ -0,0 +1,243 @@
//! `[telegram]` settings read from `AKODE_HOME/config.toml`, and the bot token in the key
//! store. The token is never written to the config file or to logs.
use std::collections::HashMap;
use std::io;
use std::path::Path;
use akode_config::types::AuthCredentialsStoreMode;
use akode_config::types::TelegramConfigToml;
use akode_model_provider_info::ProviderApiKeyStore;
use serde::Deserialize;
use crate::TOKEN_ID;
const CONFIG_FILE: &str = "config.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NotifySettings {
pub approvals: bool,
pub turn_end: bool,
pub errors: bool,
pub loops: bool,
}
impl Default for NotifySettings {
fn default() -> Self {
Self {
approvals: true,
turn_end: true,
errors: true,
loops: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TelegramSettings {
pub enabled: bool,
pub allowed_chat_ids: Vec<i64>,
pub notify: NotifySettings,
pub key_store: AuthCredentialsStoreMode,
/// Configured model display names (`[model_providers.*.models."id"] display_name`).
pub display_names: HashMap<String, String>,
}
#[derive(Deserialize, Default)]
struct ModelSettingsToml {
display_name: Option<String>,
}
#[derive(Deserialize, Default)]
struct ProviderToml {
#[serde(default)]
models: HashMap<String, ModelSettingsToml>,
}
#[derive(Deserialize, Default)]
struct PartialConfig {
telegram: Option<TelegramConfigToml>,
provider_api_key_store: Option<AuthCredentialsStoreMode>,
#[serde(default)]
model_providers: HashMap<String, ProviderToml>,
}
impl TelegramSettings {
/// Settings from the user config; a missing or unreadable file means disabled.
pub fn load(codex_home: &Path) -> Self {
let text = std::fs::read_to_string(codex_home.join(CONFIG_FILE)).unwrap_or_default();
Self::parse(&text)
}
pub fn parse(text: &str) -> Self {
let config: PartialConfig = toml::from_str(text).unwrap_or_default();
let telegram = config.telegram.unwrap_or_default();
let notify = telegram.notify.unwrap_or_default();
let defaults = NotifySettings::default();
let display_names = config
.model_providers
.into_values()
.flat_map(|provider| provider.models.into_iter())
.filter_map(|(model, settings)| {
let name = settings.display_name?.trim().to_string();
(!name.is_empty()).then_some((model, name))
})
.collect();
Self {
enabled: telegram.enabled.unwrap_or(false),
allowed_chat_ids: telegram.allowed_chat_ids.unwrap_or_default(),
notify: NotifySettings {
approvals: notify.approvals.unwrap_or(defaults.approvals),
turn_end: notify.turn_end.unwrap_or(defaults.turn_end),
errors: notify.errors.unwrap_or(defaults.errors),
loops: notify.loops.unwrap_or(defaults.loops),
},
key_store: config
.provider_api_key_store
.unwrap_or(AuthCredentialsStoreMode::Auto),
display_names,
}
}
/// Whether `chat_id` may use the bot. This is the only gate for incoming updates.
pub fn is_allowed(&self, chat_id: i64) -> bool {
self.allowed_chat_ids.contains(&chat_id)
}
/// Name shown for `model`: the configured display name, else the file stem of a
/// path-like id, else the id itself.
pub fn model_display_name(&self, model: &str) -> String {
if let Some(name) = self.display_names.get(model) {
return name.clone();
}
crate::text::short_model_name(model)
}
}
fn edit_config(
codex_home: &Path,
edit: impl FnOnce(&mut toml_edit::Table),
) -> io::Result<()> {
let path = codex_home.join(CONFIG_FILE);
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(err) if err.kind() == io::ErrorKind::NotFound => String::new(),
Err(err) => return Err(err),
};
let mut doc: toml_edit::DocumentMut = text
.parse()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, format!("{err}")))?;
let entry = doc
.entry("telegram")
.or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()));
let Some(table) = entry.as_table_mut() else {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"[telegram] in config.toml non è una tabella",
));
};
edit(table);
std::fs::create_dir_all(codex_home)?;
let tmp = codex_home.join(format!(".{CONFIG_FILE}.telegram.tmp"));
std::fs::write(&tmp, doc.to_string())?;
std::fs::rename(&tmp, &path)
}
/// Sets `[telegram] enabled`.
pub fn set_enabled(codex_home: &Path, enabled: bool) -> io::Result<()> {
edit_config(codex_home, |table| {
table["enabled"] = toml_edit::value(enabled);
})
}
/// Adds `chat_id` to `[telegram] allowed_chat_ids` (once).
pub fn add_allowed_chat(codex_home: &Path, chat_id: i64) -> io::Result<()> {
edit_config(codex_home, |table| {
let mut ids = table
.get("allowed_chat_ids")
.and_then(|item| item.as_array())
.cloned()
.unwrap_or_default();
if !ids.iter().any(|value| value.as_integer() == Some(chat_id)) {
ids.push(chat_id);
}
table["allowed_chat_ids"] = toml_edit::value(ids);
})
}
fn store(codex_home: &Path, mode: AuthCredentialsStoreMode) -> std::sync::Arc<dyn ProviderApiKeyStore> {
akode_login::configured_provider_api_key_store(codex_home, mode)
}
/// The bot token, if one is stored.
pub fn load_token(codex_home: &Path, mode: AuthCredentialsStoreMode) -> Option<String> {
match store(codex_home, mode).load(TOKEN_ID) {
Ok(token) => token.filter(|token| !token.trim().is_empty()),
Err(err) => {
tracing::warn!("telegram: cannot read the bot token from the key store: {err}");
None
}
}
}
pub fn save_token(
codex_home: &Path,
mode: AuthCredentialsStoreMode,
token: &str,
) -> Result<(), String> {
store(codex_home, mode)
.save(TOKEN_ID, token.trim())
.map(|_| ())
}
pub fn delete_token(codex_home: &Path, mode: AuthCredentialsStoreMode) -> Result<(), String> {
store(codex_home, mode).delete(TOKEN_ID).map(|_| ())
}
const BOT_FILE: &str = "telegram-bot.json";
/// Remembers the verified bot's username, so `/telegram` can show it without calling
/// Telegram.
pub fn save_bot_name(codex_home: &Path, username: &str) -> io::Result<()> {
std::fs::create_dir_all(codex_home)?;
let text = serde_json::json!({ "username": username }).to_string();
std::fs::write(codex_home.join(BOT_FILE), text)
}
pub fn load_bot_name(codex_home: &Path) -> Option<String> {
let text = std::fs::read_to_string(codex_home.join(BOT_FILE)).ok()?;
let value: serde_json::Value = serde_json::from_str(&text).ok()?;
value["username"].as_str().map(ToString::to_string)
}
pub fn forget_bot_name(codex_home: &Path) {
let _ = std::fs::remove_file(codex_home.join(BOT_FILE));
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn defaults_are_disabled() {
let settings = TelegramSettings::parse("");
assert!(!settings.enabled);
assert!(settings.allowed_chat_ids.is_empty());
assert_eq!(settings.notify, NotifySettings::default());
}
#[test]
fn edits_keep_other_settings() {
let home = tempfile::tempdir().unwrap();
std::fs::write(home.path().join(CONFIG_FILE), "model = \"m\"\n").unwrap();
add_allowed_chat(home.path(), 42).unwrap();
add_allowed_chat(home.path(), 42).unwrap();
set_enabled(home.path(), true).unwrap();
let text = std::fs::read_to_string(home.path().join(CONFIG_FILE)).unwrap();
assert!(text.contains("model = \"m\""));
let settings = TelegramSettings::load(home.path());
assert!(settings.enabled);
assert_eq!(settings.allowed_chat_ids, vec![42]);
}
}

View File

@@ -0,0 +1,163 @@
//! Message text: session tags, splitting to Telegram's limit, short summaries.
use std::path::Path;
/// Telegram accepts up to 4096 characters per message; keep a margin for the tag.
pub const MESSAGE_LIMIT: usize = 4000;
/// A turn summary is cut after this many characters (at most three messages).
pub const SUMMARY_LIMIT: usize = 3 * MESSAGE_LIMIT;
/// Context tokens always present (system prompt, tools), as in the TUI status bar.
const BASELINE_TOKENS: i64 = 12_000;
/// `[<cwd basename> · <model>]`.
pub fn session_tag(cwd: &Path, model: &str) -> String {
let dir = cwd
.file_name()
.and_then(|name| name.to_str())
.filter(|name| !name.is_empty())
.unwrap_or("/");
if model.is_empty() {
format!("[{dir}]")
} else {
format!("[{dir} · {model}]")
}
}
/// `model` without directory and extension when it looks like a model file path.
pub fn short_model_name(model: &str) -> String {
const EXTENSIONS: [&str; 6] = ["gguf", "ggml", "bin", "safetensors", "onnx", "mlx"];
let path = Path::new(model);
let is_file = path
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| EXTENSIONS.iter().any(|known| ext.eq_ignore_ascii_case(known)));
if !is_file && !model.starts_with('/') && !model.starts_with("~/") {
return model.to_string();
}
path.file_stem()
.and_then(|stem| stem.to_str())
.filter(|stem| !stem.is_empty())
.unwrap_or(model)
.to_string()
}
/// `text` cut to `limit` characters with a trailing ellipsis.
pub fn truncate(text: &str, limit: usize) -> String {
if text.chars().count() <= limit {
return text.to_string();
}
let mut out: String = text.chars().take(limit.saturating_sub(1)).collect();
out.push('…');
out
}
/// Splits `text` into parts of at most `limit` characters, preferring line breaks, then
/// spaces, and cutting inside a word only when nothing else fits.
pub fn split_message(text: &str, limit: usize) -> Vec<String> {
let limit = limit.max(1);
let mut parts = Vec::new();
let mut rest: Vec<char> = text.chars().collect();
while rest.len() > limit {
let window = &rest[..limit];
let cut = window
.iter()
.rposition(|c| *c == '\n')
.or_else(|| window.iter().rposition(|c| c.is_whitespace()))
.filter(|cut| *cut > 0)
.unwrap_or(limit);
let part: String = rest[..cut].iter().collect();
let part = part.trim_end().to_string();
if !part.is_empty() {
parts.push(part);
}
let skip = if cut < rest.len() && rest[cut].is_whitespace() {
cut + 1
} else {
cut
};
rest.drain(..skip);
}
let last: String = rest.into_iter().collect();
if !last.trim().is_empty() || parts.is_empty() {
parts.push(last);
}
parts
}
/// Used share of the context window, in percent, as shown in the TUI.
pub fn context_used_percent(tokens_in_context: i64, context_window: i64) -> Option<i64> {
if context_window <= BASELINE_TOKENS {
return None;
}
let effective = (context_window - BASELINE_TOKENS) as f64;
let used = (tokens_in_context - BASELINE_TOKENS).max(0) as f64;
Some(((used / effective) * 100.0).clamp(0.0, 100.0).round() as i64)
}
/// `+a −b` line counts of a unified diff.
pub fn diff_counts(diff: &str) -> (usize, usize) {
let mut added = 0;
let mut removed = 0;
for line in diff.lines() {
if line.starts_with("+++") || line.starts_with("---") {
continue;
}
if line.starts_with('+') {
added += 1;
} else if line.starts_with('-') {
removed += 1;
}
}
(added, removed)
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn split_prefers_line_breaks_and_keeps_everything() {
let text = "alpha beta\ngamma delta\nepsilon";
assert_eq!(
split_message(text, 12),
vec!["alpha beta", "gamma delta", "epsilon"]
);
assert_eq!(split_message("short", 12), vec!["short"]);
assert_eq!(split_message("", 12), vec![""]);
}
#[test]
fn split_cuts_long_words_and_counts_characters() {
let text = "è".repeat(25);
let parts = split_message(&text, 10);
assert_eq!(parts.len(), 3);
assert!(parts.iter().all(|part| part.chars().count() <= 10));
assert_eq!(parts.concat(), text);
}
#[test]
fn split_respects_the_telegram_limit() {
let text = "parola ".repeat(2000);
let parts = split_message(&text, MESSAGE_LIMIT);
assert!(parts.len() > 1);
assert!(parts.iter().all(|part| part.chars().count() <= MESSAGE_LIMIT));
assert_eq!(parts.join(" ").split_whitespace().count(), 2000);
}
#[test]
fn tags_and_names() {
assert_eq!(
session_tag(Path::new("/Users/a/progetto"), "Qwen 3.6"),
"[progetto · Qwen 3.6]"
);
assert_eq!(short_model_name("/models/qwen3.6-q4.gguf"), "qwen3.6-q4");
assert_eq!(short_model_name("vendor/model"), "vendor/model");
assert_eq!(context_used_percent(12_000, 112_000), Some(0));
assert_eq!(context_used_percent(62_000, 112_000), Some(50));
assert_eq!(truncate("abcdef", 4), "abc…");
assert_eq!(diff_counts("--- a\n+++ b\n+x\n-y\n+z\n ctx"), (2, 1));
}
}

View File

@@ -0,0 +1,481 @@
//! Bridge tests against a mock Telegram server and a fake app-server connection.
use std::collections::VecDeque;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicI64;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use akode_app_server_protocol::JSONRPCMessage;
use akode_app_server_protocol::JSONRPCNotification;
use akode_app_server_protocol::JSONRPCRequest;
use akode_app_server_protocol::JSONRPCResponse;
use akode_app_server_protocol::RequestId;
use akode_config::types::AuthCredentialsStoreMode;
use akode_telegram::api::TelegramApi;
use akode_telegram::bridge::BridgeConnection;
use akode_telegram::bridge::BridgeOptions;
use akode_telegram::bridge::run_supervisor;
use akode_telegram::pairing;
use akode_telegram::settings;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::Request;
use wiremock::Respond;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path_regex;
const TOKEN: &str = "123456:SEGRETO-di-prova";
const CHAT: i64 = 100;
struct Feed(Arc<Mutex<VecDeque<Value>>>);
impl Respond for Feed {
fn respond(&self, _request: &Request) -> ResponseTemplate {
let batch = self.0.lock().unwrap().pop_front();
match batch {
Some(batch) => ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": batch})),
None => ResponseTemplate::new(200)
.set_delay(Duration::from_millis(50))
.set_body_json(json!({"ok": true, "result": []})),
}
}
}
struct Sender(Arc<AtomicI64>);
impl Respond for Sender {
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_id": id, "chat": {"id": body["chat_id"]}, "text": body["text"]}
}))
}
}
struct Harness {
home: tempfile::TempDir,
telegram: MockServer,
feed: Arc<Mutex<VecDeque<Value>>>,
next_update: AtomicI64,
to_bridge: mpsc::UnboundedSender<JSONRPCMessage>,
from_bridge: mpsc::UnboundedReceiver<JSONRPCMessage>,
shutdown: CancellationToken,
next_server_request: AtomicI64,
}
fn write_config(home: &Path, enabled: bool) {
std::fs::write(
home.join("config.toml"),
format!(
"provider_api_key_store = \"file\"\n\n[telegram]\nenabled = {enabled}\nallowed_chat_ids = [{CHAT}]\n\n[model_providers.p.models.\"qwen\"]\ndisplay_name = \"Qwen 3.6\"\n"
),
)
.unwrap();
}
async fn mock_telegram() -> (MockServer, Arc<Mutex<VecDeque<Value>>>) {
let telegram = MockServer::start().await;
let feed = Arc::new(Mutex::new(VecDeque::new()));
Mock::given(method("POST"))
.and(path_regex(".*/getUpdates$"))
.respond_with(Feed(Arc::clone(&feed)))
.mount(&telegram)
.await;
Mock::given(method("POST"))
.and(path_regex(".*/sendMessage$"))
.respond_with(Sender(Arc::new(AtomicI64::new(1000))))
.mount(&telegram)
.await;
Mock::given(method("POST"))
.and(path_regex(".*/(editMessageText|answerCallbackQuery|getMe)$"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": true})))
.mount(&telegram)
.await;
(telegram, feed)
}
fn options(home: &Path, telegram: &MockServer) -> BridgeOptions {
BridgeOptions {
codex_home: home.to_path_buf(),
api_base: telegram.uri(),
settings_poll: Duration::from_millis(100),
long_poll_secs: 0,
}
}
impl Harness {
async fn start() -> Self {
let home = tempfile::tempdir().unwrap();
write_config(home.path(), true);
settings::save_token(home.path(), AuthCredentialsStoreMode::File, TOKEN).unwrap();
let (telegram, feed) = mock_telegram().await;
let (to_bridge, from_server) = mpsc::unbounded_channel();
let (to_server, from_bridge) = mpsc::unbounded_channel();
let connection = Arc::new(Mutex::new(Some(BridgeConnection {
to_server,
from_server,
})));
let shutdown = CancellationToken::new();
tokio::spawn(run_supervisor(
options(home.path(), &telegram),
Box::new(move || {
let connection = connection.lock().unwrap().take();
Box::pin(async move { connection })
}),
shutdown.clone(),
));
let mut harness = Self {
home,
telegram,
feed,
next_update: AtomicI64::new(1),
to_bridge,
from_bridge,
shutdown,
next_server_request: AtomicI64::new(1),
};
harness.handshake().await;
harness
}
async fn next_from_bridge(&mut self) -> JSONRPCMessage {
tokio::time::timeout(Duration::from_secs(5), self.from_bridge.recv())
.await
.expect("bridge message in time")
.expect("bridge connected")
}
async fn expect_request(&mut self, expected: &str) -> JSONRPCRequest {
loop {
if let JSONRPCMessage::Request(request) = self.next_from_bridge().await
&& request.method == expected
{
return request;
}
}
}
fn respond(&self, id: RequestId, result: Value) {
self.to_bridge
.send(JSONRPCMessage::Response(JSONRPCResponse { id, result }))
.unwrap();
}
fn notify(&self, method: &str, params: Value) {
self.to_bridge
.send(JSONRPCMessage::Notification(JSONRPCNotification {
method: method.to_string(),
params: Some(params),
}))
.unwrap();
}
fn server_request(&self, method: &str, params: Value) -> RequestId {
let id = RequestId::Integer(self.next_server_request.fetch_add(1, Ordering::SeqCst));
self.to_bridge
.send(JSONRPCMessage::Request(JSONRPCRequest {
id: id.clone(),
method: method.to_string(),
params: Some(params),
trace: None,
}))
.unwrap();
id
}
async fn handshake(&mut self) {
let init = self.expect_request("initialize").await;
let params = init.params.clone().unwrap();
assert_eq!(params["clientInfo"]["name"], "akode-telegram");
self.respond(init.id, json!({}));
let list = self.expect_request("thread/loaded/list").await;
self.respond(list.id, json!({"data": [], "nextCursor": null}));
}
fn start_thread(&self, id: &str, cwd: &str) {
self.notify("thread/started", json!({"thread": thread_json(id, cwd)}));
}
fn push_update(&self, mut update: Value) {
update["update_id"] = json!(self.next_update.fetch_add(1, Ordering::SeqCst));
self.feed.lock().unwrap().push_back(json!([update]));
}
async fn calls(&self, api_method: &str) -> Vec<Value> {
self.telegram
.received_requests()
.await
.unwrap_or_default()
.into_iter()
.filter(|request| request.url.path().ends_with(&format!("/{api_method}")))
.map(|request| serde_json::from_slice(&request.body).unwrap_or_default())
.collect()
}
async fn wait_for_calls(&self, api_method: &str, count: usize) -> Vec<Value> {
for _ in 0..100 {
let calls = self.calls(api_method).await;
if calls.len() >= count {
return calls;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
panic!("expected {count} {api_method} calls, got {:?}", self.calls(api_method).await);
}
/// Lets the bridge process queued input before asserting that nothing happened.
async fn settle(&mut self) -> Vec<JSONRPCMessage> {
tokio::time::sleep(Duration::from_millis(400)).await;
let mut seen = Vec::new();
while let Ok(message) = self.from_bridge.try_recv() {
seen.push(message);
}
seen
}
}
impl Drop for Harness {
fn drop(&mut self) {
self.shutdown.cancel();
}
}
fn thread_json(id: &str, cwd: &str) -> Value {
json!({
"id": id, "sessionId": id, "forkedFromId": null, "parentThreadId": null,
"preview": "", "ephemeral": false, "projectId": null, "modelProvider": "p",
"model": "qwen", "reasoningEffort": null, "createdAt": 0, "updatedAt": 0,
"recencyAt": null, "status": {"type": "idle"}, "path": null, "cwd": cwd,
"cliVersion": "0", "originator": null, "source": "cli", "canAcceptDirectInput": null,
"threadSource": null, "agentNickname": null, "agentRole": null, "gitInfo": null,
"name": null, "turns": [],
})
}
fn turn_json(id: &str, status: &str) -> Value {
json!({"id": id, "items": [], "status": status, "error": null, "startedAt": null,
"completedAt": null, "durationMs": 2000})
}
fn text_message(chat: i64, text: &str, reply_to: Option<i64>) -> Value {
let mut message = json!({"message_id": 1, "chat": {"id": chat}, "text": text});
if let Some(reply_to) = reply_to {
message["reply_to_message"] = json!({"message_id": reply_to, "chat": {"id": chat}});
}
json!({"message": message})
}
fn callback(chat: i64, data: &str) -> Value {
json!({"callback_query": {"id": "cb", "data": data,
"message": {"message_id": 1000, "chat": {"id": chat}}}})
}
fn command_approval(thread: &str) -> Value {
json!({"threadId": thread, "turnId": "turn-1", "itemId": "item-1", "startedAtMs": 0,
"command": "rm -rf build", "cwd": "/tmp/alfa"})
}
#[tokio::test]
async fn ignores_chats_outside_the_allowlist() {
let mut h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa");
h.server_request("item/commandExecution/requestApproval", command_approval("t1"));
h.wait_for_calls("sendMessage", 1).await;
h.push_update(text_message(999, "rm -rf /", None));
h.push_update(text_message(999, "/sessioni", None));
h.push_update(callback(999, "a:1:y"));
let seen = h.settle().await;
assert!(
seen.iter().all(|m| !matches!(m, JSONRPCMessage::Response(_) | JSONRPCMessage::Request(_))),
"an unknown chat reached the server: {seen:?}"
);
let sends = h.calls("sendMessage").await;
assert!(sends.iter().all(|send| send["chat_id"] == json!(CHAT)));
assert!(h.calls("answerCallbackQuery").await.is_empty());
// The allowed chat is served.
h.push_update(text_message(CHAT, "ciao", None));
let start = h.expect_request("turn/start").await;
assert_eq!(start.params.unwrap()["threadId"], "t1");
}
#[tokio::test]
async fn pairing_adds_the_chat_that_sends_the_code() {
let h = Harness::start().await;
let code = pairing::start(h.home.path()).unwrap();
h.push_update(text_message(555, "123", None));
h.push_update(text_message(555, &code, None));
let sends = h.wait_for_calls("sendMessage", 1).await;
assert_eq!(sends[0]["chat_id"], json!(555));
assert_eq!(sends[0]["text"], json!(pairing::PAIRED_REPLY));
assert_eq!(
settings::TelegramSettings::load(h.home.path()).allowed_chat_ids,
vec![CHAT, 555]
);
assert_eq!(pairing::pending_code(h.home.path()), None);
}
#[tokio::test]
async fn approval_answered_on_telegram_wins() {
let mut h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa");
let id = h.server_request("item/commandExecution/requestApproval", command_approval("t1"));
let sends = h.wait_for_calls("sendMessage", 1).await;
let text = sends[0]["text"].as_str().unwrap();
assert!(text.starts_with("[alfa · Qwen 3.6] 🔐"), "{text}");
assert!(text.contains("rm -rf build"));
assert_eq!(sends[0]["reply_markup"]["inline_keyboard"][0].as_array().unwrap().len(), 3);
h.push_update(callback(CHAT, "a:1:y"));
let response = loop {
if let JSONRPCMessage::Response(response) = h.next_from_bridge().await {
break response;
}
};
assert_eq!(response.id, id);
assert_eq!(response.result, json!({"decision": "accept"}));
let edits = h.wait_for_calls("editMessageText", 1).await;
assert!(edits[0]["text"].as_str().unwrap().ends_with("✅ approvato da Telegram"));
// The server tells everyone it is resolved; the Mac side cannot answer any more.
h.notify("serverRequest/resolved", json!({"threadId": "t1", "requestId": id}));
h.push_update(callback(CHAT, "a:1:n"));
let seen = h.settle().await;
assert!(seen.iter().all(|m| !matches!(m, JSONRPCMessage::Response(_))));
assert_eq!(h.calls("editMessageText").await.len(), 1);
let answers = h.wait_for_calls("answerCallbackQuery", 2).await;
assert_eq!(answers[1]["text"], "Già risolta.");
}
#[tokio::test]
async fn approval_answered_on_the_mac_wins() {
let mut h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa");
let id = h.server_request("item/commandExecution/requestApproval", command_approval("t1"));
h.wait_for_calls("sendMessage", 1).await;
h.notify("serverRequest/resolved", json!({"threadId": "t1", "requestId": id}));
h.notify(
"item/started",
json!({"threadId": "t1", "turnId": "turn-1", "startedAtMs": 0, "item": {
"type": "commandExecution", "id": "item-1", "command": "rm -rf build",
"cwd": "/tmp/alfa", "processId": null, "source": "agent", "status": "inProgress",
"commandActions": [], "aggregatedOutput": null, "exitCode": null, "durationMs": null}}),
);
let edits = h.wait_for_calls("editMessageText", 2).await;
assert!(edits[0]["text"].as_str().unwrap().ends_with("☑️ risposto dal Mac"));
assert!(edits[1]["text"].as_str().unwrap().ends_with("✅ approvato dal Mac"));
h.push_update(callback(CHAT, "a:1:y"));
let seen = h.settle().await;
assert!(
seen.iter().all(|m| !matches!(m, JSONRPCMessage::Response(_))),
"Telegram answered a resolved request: {seen:?}"
);
}
#[tokio::test]
async fn replies_go_to_the_session_they_answer() {
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")}));
h.notify(
"item/completed",
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(text_message(CHAT, "continua", Some(1000)));
let start = h.expect_request("turn/start").await;
let params = start.params.unwrap();
assert_eq!(params["threadId"], "t2");
assert_eq!(params["input"][0]["text"], "continua");
// Without a reply and with two sessions the bridge asks which one.
h.push_update(text_message(CHAT, "e adesso?", None));
let seen = h.settle().await;
assert!(seen.iter().all(|m| !matches!(m, JSONRPCMessage::Request(_))));
// `/usa 1` picks the first session; a busy session is steered.
h.push_update(text_message(CHAT, "/usa 1", None));
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-9", "inProgress")}));
h.settle().await;
h.push_update(text_message(CHAT, "aggiungi i test", None));
let steer = h.expect_request("turn/steer").await;
let params = steer.params.unwrap();
assert_eq!(params["threadId"], "t1");
assert_eq!(params["expectedTurnId"], "turn-9");
}
#[tokio::test]
async fn long_summaries_are_split_to_the_telegram_limit() {
let h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa");
let long = "riga di risultato\n".repeat(500);
h.notify(
"item/completed",
json!({"threadId": "t1", "turnId": "turn-1", "completedAtMs": 0, "item": {
"type": "agentMessage", "id": "m1", "text": long}}),
);
h.notify("turn/completed", json!({"threadId": "t1", "turn": turn_json("turn-1", "completed")}));
let sends = h.wait_for_calls("sendMessage", 3).await;
assert!(sends.iter().all(|s| s["text"].as_str().unwrap().chars().count() <= 4096));
let joined: String = sends.iter().map(|s| s["text"].as_str().unwrap()).collect::<Vec<_>>().join("\n");
assert_eq!(joined.matches("riga di risultato").count(), 500);
}
#[tokio::test]
async fn the_token_stays_out_of_config_and_errors() {
let h = Harness::start().await;
let config = std::fs::read_to_string(h.home.path().join("config.toml")).unwrap();
assert!(!config.contains(TOKEN));
// Errors carry no URL, so no token.
let api = TelegramApi::with_base_url("http://127.0.0.1:9", TOKEN);
let err = api.get_me().await.unwrap_err();
assert!(!err.to_string().contains("SEGRETO"), "{err}");
assert!(!format!("{api:?}").contains("SEGRETO"));
}
#[tokio::test]
async fn nothing_is_polled_while_disabled() {
let home = tempfile::tempdir().unwrap();
write_config(home.path(), false);
settings::save_token(home.path(), AuthCredentialsStoreMode::File, TOKEN).unwrap();
let (telegram, _feed) = mock_telegram().await;
let connects = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&connects);
let shutdown = CancellationToken::new();
let task = tokio::spawn(run_supervisor(
options(home.path(), &telegram),
Box::new(move || {
counter.fetch_add(1, Ordering::SeqCst);
Box::pin(async { None })
}),
shutdown.clone(),
));
tokio::time::sleep(Duration::from_millis(600)).await;
shutdown.cancel();
task.await.unwrap();
assert_eq!(connects.load(Ordering::SeqCst), 0);
assert!(telegram.received_requests().await.unwrap_or_default().is_empty());
}