Files
imeai-aKode/akode-rs/telegram/tests/bridge.rs
andrea.difonzo 973acc59c9 aKode 0.3.1: Shift+Tab a tre modalità e topic di Telegram più puliti
- Shift+Tab: default, plan, accesso completo (preset di /permissions,
  saltato se i requisiti non lo permettono; uscendo tornano i permessi
  di prima). Modalità sotto il riquadro di scrittura, a sinistra, e in
  /stato su Telegram.
- Telegram: topic creato al primo turno; sessioni chiuse senza turni
  perdono il topic, le altre diventano «(chiusa)» con nuovi tentativi;
  topic di «Nuova chat» assegnati con i pulsanti, i comandi lì ricevono
  risposta nella chat principale; pulizia all'avvio.
- Versione 0.3.1 e novità nel README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:46:19 +01:00

1063 lines
44 KiB
Rust

//! 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 akode_telegram::text::contains_emoji;
use akode_telegram::topics;
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: Arc<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();
}
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 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(".*/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|deleteForumTopic|sendMessageDraft|setMessageReaction)$",
))
.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,
draft_interval: Duration::from_millis(600),
}
}
impl Harness {
async fn start() -> Self {
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);
settings::save_token(home.path(), AuthCredentialsStoreMode::File, TOKEN).unwrap();
let (telegram, feed) = mock_telegram(topics).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()
}
/// 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> {
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 {
callback_on(chat, data, 1000)
}
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 {
json!({"threadId": thread, "turnId": "turn-1", "itemId": "item-1", "startedAtMs": 0,
"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]
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"));
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, "/sessioni", None));
// 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;
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());
// 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.
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] Approvazione richiesta: comando"), "{text}");
assert!(text.contains("rm -rf build"));
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, &button(&sends[0], "Approva")));
let response = next_response(&mut h).await;
assert_eq!(response.id, id);
assert_eq!(response.result, json!({"decision": "accept"}));
let edits = h.wait_for_calls("editMessageText", 1).await;
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; nobody can answer any more.
h.notify("serverRequest/resolved", json!({"threadId": "t1", "requestId": id}));
h.push_update(callback(CHAT, &button(&sends[0], "Rifiuta")));
let seen = h.settle().await;
assert!(seen.iter().all(|m| !is_response(m)));
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"));
let sends = 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_eq!(labels(&edits[0]), vec![vec!["Risposto dal Mac"]]);
assert_eq!(labels(&edits[1]), vec![vec!["Approvato dal Mac"]]);
h.push_update(callback(CHAT, &button(&sends[0], "Approva")));
let seen = h.settle().await;
assert!(
seen.iter().all(|m| !is_response(m)),
"Telegram answered a resolved request: {seen:?}"
);
}
#[tokio::test]
async fn topics_are_created_mapped_and_reused_after_a_restart() {
let home;
{
let h = Harness::with_topics().await;
home = Arc::clone(&h.home);
h.start_thread("t1", "/tmp/alfa");
let mut h = h;
h.settle().await;
assert!(h.calls("createForumTopic").await.is_empty(), "no topic before the first turn");
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-1", "inProgress")}));
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 day = home.path().join("sessions/2026/11/12");
std::fs::create_dir_all(&day).unwrap();
std::fs::write(day.join("rollout-2026-11-12T10-00-00-t1.jsonl"), "").unwrap();
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("t2", "/tmp/beta");
for thread in ["t1", "t2"] {
h.notify("turn/started", json!({"threadId": thread, "turn": turn_json("turn-0", "inProgress")}));
h.notify("turn/completed", json!({"threadId": thread, "turn": turn_json("turn-0", "completed")}));
}
h.wait_for_calls("createForumTopic", 2).await;
// Let the outbox store both topics.
h.settle().await;
let base = h.calls("sendMessage").await.len();
h.push_update(topic_message(CHAT, 501, "continua"));
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");
// 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", base + 1).await;
assert_eq!(sends[base]["message_thread_id"], 500);
assert!(sends[base]["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", base + 2).await;
let list = &sends[base + 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 = list_message_id(&h, base + 1).await;
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(), base + 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));
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;
assert!(seen.iter().all(|m| !matches!(m, JSONRPCMessage::Request(_))));
// `/aiuto` explains how to enable topics.
h.push_update(text_message(CHAT, "/aiuto", None));
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;
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.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-1", "inProgress")}));
h.wait_for_calls("createForumTopic", 1).await;
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;
h.respond(steer.id, json!({"turnId": "turn-1"}));
complete_turn(&h, "t1", "turn-1", "Fatto.");
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]
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(false).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());
}
fn saved_topics(home: &Path) -> Value {
serde_json::from_str(&std::fs::read_to_string(home.join(topics::TOPICS_FILE)).unwrap()).unwrap()
}
fn start_response(id: &str, cwd: &str) -> Value {
json!({"thread": thread_json(id, cwd), "model": "qwen", "modelProvider": "p",
"serviceTier": null, "cwd": cwd, "approvalPolicy": "never",
"approvalsReviewer": "user", "sandbox": {"type": "dangerFullAccess"},
"reasoningEffort": null})
}
#[tokio::test]
async fn a_session_without_turns_gets_no_topic_and_its_topic_is_deleted_on_close() {
let mut h = Harness::with_topics().await;
h.start_thread("t1", "/tmp/alfa");
h.settle().await;
assert!(h.calls("createForumTopic").await.is_empty());
// An error creates the topic even without a turn.
h.notify("error", json!({"threadId": "t1", "turnId": "x", "willRetry": false,
"error": {"message": "server spento", "codexErrorInfo": null, "additionalDetails": null}}));
h.wait_for_calls("createForumTopic", 1).await;
h.wait_for_calls("sendMessage", 1).await;
h.notify("thread/closed", json!({"threadId": "t1"}));
let deleted = h.wait_for_calls("deleteForumTopic", 1).await;
assert_eq!(deleted[0]["message_thread_id"], 500);
h.settle().await;
assert!(h.calls("editForumTopic").await.is_empty(), "deleted, not renamed");
assert_eq!(saved_topics(h.home.path())["topics"], json!([]));
}
#[tokio::test]
async fn a_failed_close_rename_is_retried() {
let h = Harness::with_topics().await;
Mock::given(method("POST"))
.and(path_regex(".*/editForumTopic$"))
.respond_with(ResponseTemplate::new(500).set_body_json(
json!({"ok": false, "error_code": 500, "description": "Internal Server Error"}),
))
.up_to_n_times(1)
.with_priority(1)
.mount(&h.telegram)
.await;
h.start_thread("t1", "/tmp/alfa");
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-1", "inProgress")}));
complete_turn(&h, "t1", "turn-1", "Fatto.");
h.wait_for_calls("sendMessage", 1).await;
h.notify("thread/closed", json!({"threadId": "t1"}));
let renames = h.wait_for_calls("editForumTopic", 2).await;
assert_eq!(renames[1]["name"], "alfa · Qwen 3.6 (chiusa)");
tokio::time::sleep(Duration::from_millis(200)).await;
let saved = saved_topics(h.home.path());
assert_eq!(saved["topics"][0]["name"], "alfa · Qwen 3.6 (chiusa)");
assert!(saved["topics"][0].get("pending_name").is_none(), "{saved}");
assert!(h.calls("deleteForumTopic").await.is_empty());
}
#[tokio::test]
async fn a_command_in_a_stray_topic_is_answered_in_the_main_chat_and_the_topic_deleted() {
let h = Harness::with_topics().await;
h.start_thread("t1", "/tmp/alfa");
h.push_update(topic_message(CHAT, 777, "/sessioni"));
let sends = h.wait_for_calls("sendMessage", 1).await;
assert!(sends[0].get("message_thread_id").is_none(), "{}", sends[0]);
let deleted = h.wait_for_calls("deleteForumTopic", 1).await;
assert_eq!(deleted[0]["message_thread_id"], 777);
assert!(h.calls("createForumTopic").await.is_empty());
}
#[tokio::test]
async fn plain_text_in_a_stray_topic_picks_its_session() {
let mut h = Harness::with_topics().await;
h.start_thread("t1", "/tmp/alfa");
h.settle().await;
// A new session in the cwd of the most recent one takes the topic.
h.push_update(topic_message(CHAT, 778, "ciao"));
let sends = h.wait_for_calls("sendMessage", 1).await;
assert_eq!(sends[0]["message_thread_id"], 778);
assert_eq!(labels(&sends[0]), vec![vec!["alfa · Qwen 3.6"], vec!["Nuova sessione"]]);
h.push_update(callback(CHAT, &button(&sends[0], "Nuova sessione")));
let start = h.expect_request("thread/start").await;
assert_eq!(start.params.clone().unwrap()["cwd"], "/tmp/alfa");
h.respond(start.id, start_response("t3", "/tmp/alfa"));
let turn = h.expect_request("turn/start").await;
let params = turn.params.unwrap();
assert_eq!(params["threadId"], "t3");
assert_eq!(params["input"][0]["text"], "ciao");
let renames = h.wait_for_calls("editForumTopic", 1).await;
assert_eq!(renames[0]["message_thread_id"], 778);
assert_eq!(renames[0]["name"], "alfa · Qwen 3.6");
// An existing session without a topic takes the next one.
h.push_update(topic_message(CHAT, 779, "ancora"));
let sends = h.wait_for_calls("sendMessage", 2).await;
h.push_update(callback(CHAT, &button(&sends[1], "alfa · Qwen 3.6")));
let turn = h.expect_request("turn/start").await;
assert_eq!(turn.params.unwrap()["threadId"], "t1");
tokio::time::sleep(Duration::from_millis(200)).await;
let saved = saved_topics(h.home.path());
let threads: Vec<(String, i64)> = saved["topics"]
.as_array()
.unwrap()
.iter()
.map(|e| (e["session"].as_str().unwrap().to_string(), e["thread"].as_i64().unwrap()))
.collect();
assert_eq!(threads, vec![("t3".to_string(), 778), ("t1".to_string(), 779)]);
assert!(h.calls("createForumTopic").await.is_empty());
assert!(h.calls("deleteForumTopic").await.is_empty());
}
#[tokio::test]
async fn startup_drops_empty_gone_sessions_and_reapplies_pending_renames() {
let home = Arc::new(tempfile::tempdir().unwrap());
let day = home.path().join("sessions/2026/11/12");
std::fs::create_dir_all(&day).unwrap();
std::fs::write(day.join("rollout-2026-11-12T10-00-00-s2.jsonl"), "").unwrap();
std::fs::write(day.join("rollout-2026-11-12T10-00-00-s4.jsonl"), "").unwrap();
std::fs::write(
home.path().join(topics::TOPICS_FILE),
json!({"topics": [
{"chat_id": CHAT, "session": "s1", "thread": 601, "name": "alfa · Qwen 3.6"},
{"chat_id": CHAT, "session": "s2", "thread": 602, "name": "beta · Qwen 3.6",
"pending_name": "beta · Qwen 3.6 (chiusa)"},
// Already renamed «(chiusa)» but never had a turn: deleted all the same.
{"chat_id": CHAT, "session": "s3", "thread": 603, "name": "gamma · Qwen 3.6 (chiusa)"},
// Closed with a turn and nothing pending: kept as it is.
{"chat_id": CHAT, "session": "s4", "thread": 604, "name": "delta · Qwen 3.6 (chiusa)"},
], "recent_cwds": []})
.to_string(),
)
.unwrap();
let h = Harness::start_with(Arc::clone(&home), true).await;
let deleted = h.wait_for_calls("deleteForumTopic", 2).await;
let mut threads: Vec<i64> = deleted.iter().map(|d| d["message_thread_id"].as_i64().unwrap()).collect();
threads.sort_unstable();
assert_eq!(threads, vec![601, 603]);
let renames = h.wait_for_calls("editForumTopic", 1).await;
assert_eq!(renames[0]["message_thread_id"], 602);
assert_eq!(renames[0]["name"], "beta · Qwen 3.6 (chiusa)");
tokio::time::sleep(Duration::from_millis(200)).await;
let saved = saved_topics(home.path());
assert_eq!(
saved["topics"],
json!([
{"chat_id": CHAT, "session": "s2", "thread": 602, "name": "beta · Qwen 3.6 (chiusa)"},
{"chat_id": CHAT, "session": "s4", "thread": 604, "name": "delta · Qwen 3.6 (chiusa)"},
])
);
assert_eq!(h.calls("editForumTopic").await.len(), 1, "s4 is not renamed again");
}
/// The message id the mock gave to the `index`-th sendMessage (ids start at 1000).
async fn list_message_id(_h: &Harness, index: usize) -> i64 {
1000 + index as i64
}
fn settings_updated(thread: &str, mode: &str, sandbox: &str) -> Value {
json!({"threadId": thread, "threadSettings": {
"cwd": "/tmp/alfa", "approvalPolicy": "never", "approvalsReviewer": "user",
"sandboxPolicy": {"type": sandbox}, "activePermissionProfile": null,
"model": "qwen", "modelProvider": "p", "serviceTier": null, "effort": null,
"summary": null, "personality": null,
"collaborationMode": {"mode": mode, "settings": {"model": "qwen",
"reasoning_effort": null, "developer_instructions": null}}}})
}
#[tokio::test]
async fn status_reports_the_session_mode() {
let h = Harness::start().await;
h.start_thread("t1", "/tmp/alfa");
let cases = [
("default", "dangerFullAccess", "Modalità: accesso completo"),
("plan", "dangerFullAccess", "Modalità: plan"),
("default", "readOnly", "Modalità: default"),
];
for (index, (mode, sandbox, expected)) in cases.into_iter().enumerate() {
h.notify("thread/settings/updated", settings_updated("t1", mode, sandbox));
h.push_update(text_message(CHAT, "/stato", None));
let sends = h.wait_for_calls("sendMessage", index + 1).await;
let text = sends[index]["text"].as_str().unwrap();
assert!(text.contains(expected), "{text}");
}
}