Files
imeai-aKode/akode-rs/telegram/tests/bridge.rs
2026-11-12 08:21:25 +01:00

482 lines
18 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 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());
}