Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b04b36fa53 | ||
|
|
2b8d77593d | ||
|
|
466ed04fba | ||
|
|
28bddb1b0c |
36
README.md
36
README.md
@@ -90,6 +90,32 @@ akode exec "descrivi questo progetto"
|
|||||||
|
|
||||||
**Interfaccia interattiva:** in questa fase la TUI richiede un'installazione impacchettata. Lanciata da `target/` funziona solo `akode exec`, oppure `akode --no-daemon`. L'installatore locale arriva con la fase 6.
|
**Interfaccia interattiva:** in questa fase la TUI richiede un'installazione impacchettata. Lanciata da `target/` funziona solo `akode exec`, oppure `akode --no-daemon`. L'installatore locale arriva con la fase 6.
|
||||||
|
|
||||||
|
## Controllo da Telegram
|
||||||
|
|
||||||
|
Le sessioni di aKode aperte si possono seguire e comandare dal proprio bot Telegram: un topic per ogni sessione, risposte in streaming, approvazioni con pulsanti.
|
||||||
|
|
||||||
|
1. Crea un bot con @BotFather (`/newbot`) e copia il token.
|
||||||
|
2. In @BotFather: **Bot Settings → Threaded Mode → attiva**, così ogni sessione ha il suo topic nella chat privata col bot (senza, i messaggi hanno il prefisso `[cartella · modello]`).
|
||||||
|
3. In aKode: `/telegram` → «Imposta il token» (incolla, viene verificato con `getMe`).
|
||||||
|
4. «Abbina una chat»: invia al bot il codice di 6 cifre mostrato.
|
||||||
|
5. «Attiva».
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[telegram]
|
||||||
|
enabled = true
|
||||||
|
allowed_chat_ids = [123456789]
|
||||||
|
|
||||||
|
[telegram.notify] # tutti attivi se omessi
|
||||||
|
approvals = true
|
||||||
|
turn_end = true
|
||||||
|
errors = true
|
||||||
|
loops = true
|
||||||
|
```
|
||||||
|
|
||||||
|
Il token sta nell'archivio delle chiavi (`provider_api_key_store`, id `telegram-bot`), mai in `config.toml`. Il bot serve solo le chat in `allowed_chat_ids` e ignora tutte le altre senza rispondere. Comandi (nel menu del bot): `/sessioni`, `/nuova`, `/stato`, `/stop`, `/impostazioni`, `/aiuto`; scrivendo nel topic di una sessione le si scrive (se è al lavoro il testo si aggiunge al turno o va in coda). Le approvazioni arrivano sia nella TUI sia su Telegram: vale la prima risposta e l'altra parte la vede risolta.
|
||||||
|
|
||||||
|
**Dove gira:** nel server dell'app condiviso (il daemon, avviato dalla prima sessione `akode`), quindi tutte le sessioni sono raggiungibili insieme. Telegram ammette un solo lettore per bot: chi legge tiene il lucchetto `~/.akode/telegram.lock`. Una sessione `--no-daemon` serve solo le proprie conversazioni e legge solo se il lucchetto è libero; altrimenti riprova ogni pochi secondi e subentra quando l'altro processo termina. Con `enabled = false` nessun processo contatta Telegram (l'abbinamento da `/telegram` lo contatta solo mentre è aperto). Solo `https://api.telegram.org`, long polling, nessuna porta in ingresso.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Cosa è stato tolto rispetto a Codex
|
## Cosa è stato tolto rispetto a Codex
|
||||||
@@ -101,6 +127,16 @@ akode exec "descrivi questo progetto"
|
|||||||
|
|
||||||
## Novità
|
## Novità
|
||||||
|
|
||||||
|
### 0.3.0
|
||||||
|
|
||||||
|
- Controllo da Telegram: configurazione con **/telegram** (token, abbinamento della chat, attivazione).
|
||||||
|
- Un topic per sessione (Threaded Mode), con nome «cartella · modello».
|
||||||
|
- Menu dei comandi del bot: /sessioni, /nuova, /stato, /stop, /impostazioni, /aiuto.
|
||||||
|
- Pulsanti per aprire, controllare e fermare le sessioni.
|
||||||
|
- Risposte in streaming, con contesto, token/s e durata alla fine del turno.
|
||||||
|
- Approvazioni dal Mac o da Telegram: vale la prima risposta.
|
||||||
|
- Impostazioni del bot (/impostazioni): streaming, reazioni e notifiche.
|
||||||
|
|
||||||
### 0.2.0
|
### 0.2.0
|
||||||
|
|
||||||
- Nuovo pannello **/endpoint** (Endpoint │ Modelli │ Impostazioni) con impostazioni per modello, tra cui la lunghezza del contesto; `/model` serve solo a scegliere il modello.
|
- Nuovo pannello **/endpoint** (Endpoint │ Modelli │ Impostazioni) con impostazioni per modello, tra cui la lunghezza del contesto; `/model` serve solo a scegliere il modello.
|
||||||
|
|||||||
341
akode-rs/Cargo.lock
generated
341
akode-rs/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -23,6 +23,7 @@ members = [
|
|||||||
"features",
|
"features",
|
||||||
"install-context",
|
"install-context",
|
||||||
"update",
|
"update",
|
||||||
|
"telegram",
|
||||||
"code-mode",
|
"code-mode",
|
||||||
"code-mode-host",
|
"code-mode-host",
|
||||||
"code-mode-protocol",
|
"code-mode-protocol",
|
||||||
@@ -157,7 +158,7 @@ members = [
|
|||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.2.0"
|
version = "0.3.0"
|
||||||
# Track the edition for all workspace crates in one place. Individual
|
# Track the edition for all workspace crates in one place. Individual
|
||||||
# crates can still override this value, but keeping it here means new
|
# crates can still override this value, but keeping it here means new
|
||||||
# crates created with `cargo new -w ...` automatically inherit the 2024
|
# crates created with `cargo new -w ...` automatically inherit the 2024
|
||||||
@@ -230,6 +231,7 @@ akode-features = { path = "features" }
|
|||||||
akode-feedback = { path = "feedback" }
|
akode-feedback = { path = "feedback" }
|
||||||
akode-install-context = { path = "install-context" }
|
akode-install-context = { path = "install-context" }
|
||||||
akode-update = { path = "update" }
|
akode-update = { path = "update" }
|
||||||
|
akode-telegram = { path = "telegram" }
|
||||||
akode-file-search = { path = "file-search" }
|
akode-file-search = { path = "file-search" }
|
||||||
akode-file-watcher = { path = "file-watcher" }
|
akode-file-watcher = { path = "file-watcher" }
|
||||||
akode-git-utils = { path = "git-utils" }
|
akode-git-utils = { path = "git-utils" }
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ pub use transport::ConnectionOrigin;
|
|||||||
pub use transport::DaemonShutdownAccess;
|
pub use transport::DaemonShutdownAccess;
|
||||||
pub use transport::DaemonSocketFileGuard;
|
pub use transport::DaemonSocketFileGuard;
|
||||||
pub use transport::REMOTE_CONTROL_DISABLED_ENV_VAR;
|
pub use transport::REMOTE_CONTROL_DISABLED_ENV_VAR;
|
||||||
|
pub use transport::next_connection_id;
|
||||||
pub use transport::RemoteControlDisabledByRequirements;
|
pub use transport::RemoteControlDisabledByRequirements;
|
||||||
pub use transport::RemoteControlEnableError;
|
pub use transport::RemoteControlEnableError;
|
||||||
pub use transport::RemoteControlHandle;
|
pub use transport::RemoteControlHandle;
|
||||||
|
|||||||
@@ -207,7 +207,8 @@ pub enum ConnectionOrigin {
|
|||||||
|
|
||||||
static CONNECTION_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
|
static CONNECTION_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
fn next_connection_id() -> ConnectionId {
|
/// A fresh id for a new connection, also used by internal clients such as the Telegram bridge.
|
||||||
|
pub fn next_connection_id() -> ConnectionId {
|
||||||
ConnectionId(CONNECTION_ID_COUNTER.fetch_add(1, Ordering::Relaxed))
|
ConnectionId(CONNECTION_ID_COUNTER.fetch_add(1, Ordering::Relaxed))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ akode-rmcp-client = { workspace = true }
|
|||||||
akode-rollout = { workspace = true }
|
akode-rollout = { workspace = true }
|
||||||
akode-sandboxing = { workspace = true }
|
akode-sandboxing = { workspace = true }
|
||||||
akode-state = { workspace = true }
|
akode-state = { workspace = true }
|
||||||
|
akode-telegram = { workspace = true }
|
||||||
akode-thread-store = { workspace = true }
|
akode-thread-store = { workspace = true }
|
||||||
akode-tools = { workspace = true }
|
akode-tools = { workspace = true }
|
||||||
akode-utils-absolute-path = { workspace = true }
|
akode-utils-absolute-path = { workspace = true }
|
||||||
|
|||||||
@@ -409,6 +409,54 @@ pub async fn start(mut args: InProcessStartArgs) -> IoResult<InProcessClientHand
|
|||||||
Ok(client)
|
Ok(client)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One JSON-RPC message from the in-process Telegram bridge, with the bookkeeping the
|
||||||
|
/// socket transport loop does for its connections.
|
||||||
|
async fn handle_bridge_message(
|
||||||
|
processor: &Arc<MessageProcessor>,
|
||||||
|
session: &Arc<ConnectionSessionState>,
|
||||||
|
message: akode_app_server_protocol::JSONRPCMessage,
|
||||||
|
outbound_initialized: &AtomicBool,
|
||||||
|
outbound_experimental_api_enabled: &AtomicBool,
|
||||||
|
outbound_opted_out_notification_methods: &RwLock<HashSet<String>>,
|
||||||
|
) {
|
||||||
|
use akode_app_server_protocol::JSONRPCMessage;
|
||||||
|
let bridge_id = crate::telegram_bridge::IN_PROCESS_BRIDGE_CONNECTION_ID;
|
||||||
|
match message {
|
||||||
|
JSONRPCMessage::Request(request) => {
|
||||||
|
let was_initialized = session.initialized();
|
||||||
|
processor
|
||||||
|
.process_request(
|
||||||
|
bridge_id,
|
||||||
|
request,
|
||||||
|
&crate::transport::AppServerTransport::Off,
|
||||||
|
Arc::clone(session),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
if let Ok(mut opted_out) = outbound_opted_out_notification_methods.write() {
|
||||||
|
*opted_out = session.opted_out_notification_methods();
|
||||||
|
}
|
||||||
|
outbound_experimental_api_enabled
|
||||||
|
.store(session.experimental_api_enabled(), Ordering::Release);
|
||||||
|
if !was_initialized && session.initialized() {
|
||||||
|
processor
|
||||||
|
.send_initialize_notifications_to_connection(bridge_id)
|
||||||
|
.await;
|
||||||
|
processor.connection_initialized(bridge_id).await;
|
||||||
|
outbound_initialized.store(true, Ordering::Release);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
JSONRPCMessage::Response(response) => {
|
||||||
|
processor.process_response(bridge_id, response).await;
|
||||||
|
}
|
||||||
|
JSONRPCMessage::Notification(notification) => {
|
||||||
|
processor.process_notification(notification).await;
|
||||||
|
}
|
||||||
|
JSONRPCMessage::Error(error) => {
|
||||||
|
processor.process_error(bridge_id, error).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn run_outbound_router(
|
async fn run_outbound_router(
|
||||||
mut outgoing_rx: mpsc::Receiver<OutgoingEnvelope>,
|
mut outgoing_rx: mpsc::Receiver<OutgoingEnvelope>,
|
||||||
mut outbound_connections: HashMap<ConnectionId, OutboundConnectionState>,
|
mut outbound_connections: HashMap<ConnectionId, OutboundConnectionState>,
|
||||||
@@ -477,7 +525,57 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
|||||||
let outbound_experimental_api_enabled = Arc::new(AtomicBool::new(false));
|
let outbound_experimental_api_enabled = Arc::new(AtomicBool::new(false));
|
||||||
let outbound_opted_out_notification_methods = Arc::new(RwLock::new(HashSet::new()));
|
let outbound_opted_out_notification_methods = Arc::new(RwLock::new(HashSet::new()));
|
||||||
|
|
||||||
|
// The Telegram bridge is a second, internal connection of this app-server.
|
||||||
|
let bridge_id = crate::telegram_bridge::IN_PROCESS_BRIDGE_CONNECTION_ID;
|
||||||
|
let (bridge_writer_tx, mut bridge_writer_rx) =
|
||||||
|
mpsc::channel::<QueuedOutgoingMessage>(channel_capacity);
|
||||||
|
let bridge_initialized = Arc::new(AtomicBool::new(false));
|
||||||
|
let bridge_experimental_api_enabled = Arc::new(AtomicBool::new(false));
|
||||||
|
let bridge_opted_out_notification_methods = Arc::new(RwLock::new(HashSet::new()));
|
||||||
|
let bridge_sink = Arc::new(std::sync::Mutex::new(
|
||||||
|
None::<mpsc::UnboundedSender<akode_app_server_protocol::JSONRPCMessage>>,
|
||||||
|
));
|
||||||
|
let bridge_forward = tokio::spawn({
|
||||||
|
let bridge_sink = Arc::clone(&bridge_sink);
|
||||||
|
async move {
|
||||||
|
while let Some(queued) = bridge_writer_rx.recv().await {
|
||||||
|
let sink = bridge_sink
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.clone();
|
||||||
|
if let Some(sink) = sink
|
||||||
|
&& let Some(message) =
|
||||||
|
crate::telegram_bridge::to_jsonrpc(&queued.message)
|
||||||
|
{
|
||||||
|
let _ = sink.send(message);
|
||||||
|
}
|
||||||
|
if let Some(done) = queued.write_complete_tx {
|
||||||
|
let _ = done.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let (bridge_events_tx, mut bridge_events_rx) = mpsc::unbounded_channel();
|
||||||
|
let bridge_shutdown = tokio_util::sync::CancellationToken::new();
|
||||||
|
let bridge_task = (args.session_source == SessionSource::Cli).then(|| {
|
||||||
|
crate::telegram_bridge::spawn_in_process_bridge(
|
||||||
|
args.config.codex_home.to_path_buf(),
|
||||||
|
bridge_events_tx,
|
||||||
|
bridge_shutdown.clone(),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
let mut outbound_connections = HashMap::<ConnectionId, OutboundConnectionState>::new();
|
let mut outbound_connections = HashMap::<ConnectionId, OutboundConnectionState>::new();
|
||||||
|
outbound_connections.insert(
|
||||||
|
bridge_id,
|
||||||
|
OutboundConnectionState::new(
|
||||||
|
bridge_writer_tx,
|
||||||
|
Arc::clone(&bridge_initialized),
|
||||||
|
Arc::clone(&bridge_experimental_api_enabled),
|
||||||
|
Arc::clone(&bridge_opted_out_notification_methods),
|
||||||
|
/*disconnect_sender*/ None,
|
||||||
|
),
|
||||||
|
);
|
||||||
outbound_connections.insert(
|
outbound_connections.insert(
|
||||||
IN_PROCESS_CONNECTION_ID,
|
IN_PROCESS_CONNECTION_ID,
|
||||||
OutboundConnectionState::new(
|
OutboundConnectionState::new(
|
||||||
@@ -526,9 +624,51 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
|||||||
crate::transport::ConnectionOrigin::InProcess,
|
crate::transport::ConnectionOrigin::InProcess,
|
||||||
));
|
));
|
||||||
let mut listen_for_threads = true;
|
let mut listen_for_threads = true;
|
||||||
|
let mut bridge_events_open = bridge_task.is_some();
|
||||||
|
let mut bridge_session: Option<Arc<ConnectionSessionState>> = None;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
|
event = bridge_events_rx.recv(), if bridge_events_open => {
|
||||||
|
use crate::telegram_bridge::InProcessBridgeEvent;
|
||||||
|
match event {
|
||||||
|
Some(InProcessBridgeEvent::Opened(sink)) => {
|
||||||
|
if let Some(old) = bridge_session.take() {
|
||||||
|
processor.connection_closed(bridge_id, &old).await;
|
||||||
|
}
|
||||||
|
bridge_initialized.store(false, Ordering::Release);
|
||||||
|
*bridge_sink
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sink);
|
||||||
|
bridge_session = Some(Arc::new(ConnectionSessionState::new(
|
||||||
|
crate::transport::ConnectionOrigin::InProcess,
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Some(InProcessBridgeEvent::Message(message)) => {
|
||||||
|
if let Some(bridge) = bridge_session.as_ref() {
|
||||||
|
handle_bridge_message(
|
||||||
|
&processor,
|
||||||
|
bridge,
|
||||||
|
message,
|
||||||
|
&bridge_initialized,
|
||||||
|
&bridge_experimental_api_enabled,
|
||||||
|
&bridge_opted_out_notification_methods,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(InProcessBridgeEvent::Closed) => {
|
||||||
|
bridge_initialized.store(false, Ordering::Release);
|
||||||
|
*bridge_sink
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
|
||||||
|
if let Some(old) = bridge_session.take() {
|
||||||
|
processor.connection_closed(bridge_id, &old).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => bridge_events_open = false,
|
||||||
|
}
|
||||||
|
}
|
||||||
command = processor_rx.recv() => {
|
command = processor_rx.recv() => {
|
||||||
match command {
|
match command {
|
||||||
Some(ProcessorCommand::Request(request, cancellation)) => {
|
Some(ProcessorCommand::Request(request, cancellation)) => {
|
||||||
@@ -577,11 +717,17 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
|||||||
created = thread_created_rx.recv(), if listen_for_threads => {
|
created = thread_created_rx.recv(), if listen_for_threads => {
|
||||||
match created {
|
match created {
|
||||||
Ok(thread_id) => {
|
Ok(thread_id) => {
|
||||||
let connection_ids = if session.initialized() {
|
let mut connection_ids = if session.initialized() {
|
||||||
vec![IN_PROCESS_CONNECTION_ID]
|
vec![IN_PROCESS_CONNECTION_ID]
|
||||||
} else {
|
} else {
|
||||||
Vec::<ConnectionId>::new()
|
Vec::<ConnectionId>::new()
|
||||||
};
|
};
|
||||||
|
if bridge_session
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|bridge| bridge.initialized())
|
||||||
|
{
|
||||||
|
connection_ids.push(bridge_id);
|
||||||
|
}
|
||||||
processor
|
processor
|
||||||
.try_attach_thread_listener(thread_id, connection_ids)
|
.try_attach_thread_listener(thread_id, connection_ids)
|
||||||
.await;
|
.await;
|
||||||
@@ -597,6 +743,14 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bridge_shutdown.cancel();
|
||||||
|
if let Some(task) = bridge_task {
|
||||||
|
task.abort();
|
||||||
|
}
|
||||||
|
bridge_forward.abort();
|
||||||
|
if let Some(bridge) = bridge_session.take() {
|
||||||
|
processor.connection_closed(bridge_id, &bridge).await;
|
||||||
|
}
|
||||||
processor.clear_runtime_references();
|
processor.clear_runtime_references();
|
||||||
processor.cancel_active_login().await;
|
processor.cancel_active_login().await;
|
||||||
processor
|
processor
|
||||||
|
|||||||
@@ -140,6 +140,7 @@ mod request_processors;
|
|||||||
mod request_serialization;
|
mod request_serialization;
|
||||||
mod server_request_error;
|
mod server_request_error;
|
||||||
mod skills_watcher;
|
mod skills_watcher;
|
||||||
|
mod telegram_bridge;
|
||||||
mod startup_warnings;
|
mod startup_warnings;
|
||||||
mod thread_sample;
|
mod thread_sample;
|
||||||
mod thread_state;
|
mod thread_state;
|
||||||
@@ -812,6 +813,14 @@ pub async fn run_main_with_transport_options(
|
|||||||
AppServerTransport::Off => {}
|
AppServerTransport::Off => {}
|
||||||
}
|
}
|
||||||
drop(unix_socket_startup_lock);
|
drop(unix_socket_startup_lock);
|
||||||
|
// The shared daemon serves every session it hosts to Telegram (when enabled).
|
||||||
|
let _telegram_bridge = matches!(&transport, AppServerTransport::UnixSocket { .. }).then(|| {
|
||||||
|
telegram_bridge::spawn_daemon_bridge(
|
||||||
|
codex_home.to_path_buf(),
|
||||||
|
transport_event_tx.clone(),
|
||||||
|
transport_shutdown_token.clone(),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
let remote_control_enabled = remote_control_policy == RemoteControlPolicy::Allowed
|
let remote_control_enabled = remote_control_policy == RemoteControlPolicy::Allowed
|
||||||
&& remote_control_explicitly_requested
|
&& remote_control_explicitly_requested
|
||||||
|
|||||||
@@ -1490,6 +1490,53 @@ mod tests {
|
|||||||
assert_eq!(result, Err(error));
|
assert_eq!(result, Err(error));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The TUI and the Telegram bridge both subscribe to a thread: an approval reaches
|
||||||
|
/// both, the first answer resolves it and a later answer from the other is ignored.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn approval_goes_to_every_subscriber_and_first_answer_wins() {
|
||||||
|
let (tx, mut rx) = mpsc::channel::<OutgoingEnvelope>(8);
|
||||||
|
let outgoing = Arc::new(OutgoingMessageSender::new(tx));
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
let tui = ConnectionId(1);
|
||||||
|
let telegram = ConnectionId(2);
|
||||||
|
let thread_outgoing =
|
||||||
|
ThreadScopedOutgoingMessageSender::new(outgoing.clone(), vec![tui, telegram], thread_id);
|
||||||
|
let (request_id, waiter) = thread_outgoing
|
||||||
|
.send_request(ServerRequestPayload::FileChangeRequestApproval(
|
||||||
|
FileChangeRequestApprovalParams {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
turn_id: "turn-1".to_string(),
|
||||||
|
item_id: "call-1".to_string(),
|
||||||
|
started_at_ms: 0,
|
||||||
|
reason: None,
|
||||||
|
grant_root: None,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.await;
|
||||||
|
let mut recipients = Vec::new();
|
||||||
|
for _ in 0..2 {
|
||||||
|
match rx.recv().await {
|
||||||
|
Some(OutgoingEnvelope::ToConnection { connection_id, .. }) => {
|
||||||
|
recipients.push(connection_id)
|
||||||
|
}
|
||||||
|
other => panic!("unexpected envelope: {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(recipients, vec![tui, telegram]);
|
||||||
|
|
||||||
|
outgoing
|
||||||
|
.notify_client_response(telegram, request_id.clone(), json!({"decision": "accept"}))
|
||||||
|
.await;
|
||||||
|
outgoing
|
||||||
|
.notify_client_response(tui, request_id, json!({"decision": "decline"}))
|
||||||
|
.await;
|
||||||
|
let result = timeout(Duration::from_secs(1), waiter)
|
||||||
|
.await
|
||||||
|
.expect("answered in time")
|
||||||
|
.expect("callback");
|
||||||
|
assert_eq!(result, Ok(json!({"decision": "accept"})));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn pending_requests_for_thread_returns_thread_requests_in_request_id_order() {
|
async fn pending_requests_for_thread_returns_thread_requests_in_request_id_order() {
|
||||||
let (tx, _rx) = mpsc::channel::<OutgoingEnvelope>(8);
|
let (tx, _rx) = mpsc::channel::<OutgoingEnvelope>(8);
|
||||||
|
|||||||
@@ -15,7 +15,11 @@ use crate::message_processor::ConnectionSessionState;
|
|||||||
use crate::message_processor::InitializedConnectionSessionState;
|
use crate::message_processor::InitializedConnectionSessionState;
|
||||||
use crate::transport::ConnectionOrigin;
|
use crate::transport::ConnectionOrigin;
|
||||||
|
|
||||||
const NON_ORIGINATING_CLIENT_NAMES: &[&str] = &["akode_app_server_daemon", "codex-backend"];
|
const NON_ORIGINATING_CLIENT_NAMES: &[&str] = &[
|
||||||
|
"akode_app_server_daemon",
|
||||||
|
"codex-backend",
|
||||||
|
akode_telegram::CLIENT_NAME,
|
||||||
|
];
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub(crate) struct InitializeRequestProcessor {
|
pub(crate) struct InitializeRequestProcessor {
|
||||||
|
|||||||
158
akode-rs/app-server/src/telegram_bridge.rs
Normal file
158
akode-rs/app-server/src/telegram_bridge.rs
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
//! Hosts the Telegram bridge ([`akode_telegram`]) as an internal client connection.
|
||||||
|
//!
|
||||||
|
//! The shared daemon starts it for every session it serves; an in-process (`--no-daemon`)
|
||||||
|
//! TUI starts it for its own sessions. Either way the bridge polls Telegram only while
|
||||||
|
//! `[telegram] enabled = true` and while its process holds the poll lock in `AKODE_HOME`,
|
||||||
|
//! so one bot never has two pollers.
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use akode_app_server_protocol::JSONRPCMessage;
|
||||||
|
use akode_telegram::bridge::BridgeConnection;
|
||||||
|
use akode_telegram::bridge::BridgeOptions;
|
||||||
|
use akode_telegram::bridge::Connector;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
|
use crate::outgoing_message::ConnectionId;
|
||||||
|
use crate::transport::CHANNEL_CAPACITY;
|
||||||
|
use crate::transport::ConnectionOrigin;
|
||||||
|
use crate::transport::OutgoingMessage;
|
||||||
|
use crate::transport::QueuedOutgoingMessage;
|
||||||
|
use crate::transport::TransportEvent;
|
||||||
|
|
||||||
|
/// JSON-RPC form of an outgoing message, as a socket client would read it.
|
||||||
|
pub(crate) fn to_jsonrpc(message: &OutgoingMessage) -> Option<JSONRPCMessage> {
|
||||||
|
match serde_json::to_value(message).and_then(serde_json::from_value) {
|
||||||
|
Ok(message) => Some(message),
|
||||||
|
Err(err) => {
|
||||||
|
warn!("telegram: cannot convert an outgoing message: {err}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drains the connection's writer into the bridge so the server never waits on it.
|
||||||
|
pub(crate) fn forward_writer(
|
||||||
|
mut writer_rx: mpsc::Receiver<QueuedOutgoingMessage>,
|
||||||
|
to_bridge: mpsc::UnboundedSender<JSONRPCMessage>,
|
||||||
|
) -> JoinHandle<()> {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Some(queued) = writer_rx.recv().await {
|
||||||
|
if let Some(message) = to_jsonrpc(&queued.message)
|
||||||
|
&& to_bridge.send(message).is_err()
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some(done) = queued.write_complete_tx {
|
||||||
|
let _ = done.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the bridge in the daemon: each Telegram session opens a fresh transport
|
||||||
|
/// connection, exactly like a socket client.
|
||||||
|
pub(crate) fn spawn_daemon_bridge(
|
||||||
|
codex_home: PathBuf,
|
||||||
|
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||||
|
shutdown: CancellationToken,
|
||||||
|
) -> JoinHandle<()> {
|
||||||
|
let connector: Connector = Box::new(move || {
|
||||||
|
let transport_event_tx = transport_event_tx.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
let connection_id = akode_app_server_transport::next_connection_id();
|
||||||
|
let (writer_tx, writer_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||||
|
let (to_bridge, from_server) = mpsc::unbounded_channel();
|
||||||
|
let (to_server, mut from_bridge) = mpsc::unbounded_channel::<JSONRPCMessage>();
|
||||||
|
let disconnect = CancellationToken::new();
|
||||||
|
transport_event_tx
|
||||||
|
.send(TransportEvent::ConnectionOpened {
|
||||||
|
connection_id,
|
||||||
|
origin: ConnectionOrigin::InProcess,
|
||||||
|
auth: None,
|
||||||
|
writer: writer_tx,
|
||||||
|
disconnect_sender: Some(disconnect.clone()),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.ok()?;
|
||||||
|
let forward = forward_writer(writer_rx, to_bridge);
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
() = disconnect.cancelled() => break,
|
||||||
|
message = from_bridge.recv() => {
|
||||||
|
let Some(message) = message else { break };
|
||||||
|
if transport_event_tx
|
||||||
|
.send(TransportEvent::IncomingMessage { connection_id, message })
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
forward.abort();
|
||||||
|
let _ = transport_event_tx
|
||||||
|
.send(TransportEvent::ConnectionClosed { connection_id })
|
||||||
|
.await;
|
||||||
|
});
|
||||||
|
Some(BridgeConnection {
|
||||||
|
to_server,
|
||||||
|
from_server,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
});
|
||||||
|
tokio::spawn(akode_telegram::bridge::run_supervisor(
|
||||||
|
BridgeOptions::new(codex_home),
|
||||||
|
connector,
|
||||||
|
shutdown,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Id of the bridge connection inside an in-process app-server (the client uses 0).
|
||||||
|
pub(crate) const IN_PROCESS_BRIDGE_CONNECTION_ID: ConnectionId = ConnectionId(u64::MAX);
|
||||||
|
|
||||||
|
/// Events from the bridge to the in-process processor loop.
|
||||||
|
pub(crate) enum InProcessBridgeEvent {
|
||||||
|
Opened(mpsc::UnboundedSender<JSONRPCMessage>),
|
||||||
|
Message(JSONRPCMessage),
|
||||||
|
Closed,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the bridge for an in-process app-server. The processor loop owns the
|
||||||
|
/// connection state and receives [`InProcessBridgeEvent`]s.
|
||||||
|
pub(crate) fn spawn_in_process_bridge(
|
||||||
|
codex_home: PathBuf,
|
||||||
|
events: mpsc::UnboundedSender<InProcessBridgeEvent>,
|
||||||
|
shutdown: CancellationToken,
|
||||||
|
) -> JoinHandle<()> {
|
||||||
|
let connector: Connector = Box::new(move || {
|
||||||
|
let events = events.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
let (to_bridge, from_server) = mpsc::unbounded_channel();
|
||||||
|
let (to_server, mut from_bridge) = mpsc::unbounded_channel::<JSONRPCMessage>();
|
||||||
|
events.send(InProcessBridgeEvent::Opened(to_bridge)).ok()?;
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Some(message) = from_bridge.recv().await {
|
||||||
|
if events.send(InProcessBridgeEvent::Message(message)).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = events.send(InProcessBridgeEvent::Closed);
|
||||||
|
});
|
||||||
|
Some(BridgeConnection {
|
||||||
|
to_server,
|
||||||
|
from_server,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
});
|
||||||
|
tokio::spawn(akode_telegram::bridge::run_supervisor(
|
||||||
|
BridgeOptions::new(codex_home),
|
||||||
|
connector,
|
||||||
|
shutdown,
|
||||||
|
))
|
||||||
|
}
|
||||||
@@ -555,6 +555,9 @@ pub struct ConfigToml {
|
|||||||
/// Release source and startup check for `akode update`.
|
/// Release source and startup check for `akode update`.
|
||||||
pub update: Option<UpdateConfigToml>,
|
pub update: Option<UpdateConfigToml>,
|
||||||
|
|
||||||
|
/// Telegram control of running sessions.
|
||||||
|
pub telegram: Option<crate::types::TelegramConfigToml>,
|
||||||
|
|
||||||
/// Settings for app-specific controls.
|
/// Settings for app-specific controls.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub apps: Option<AppsConfigToml>,
|
pub apps: Option<AppsConfigToml>,
|
||||||
|
|||||||
@@ -251,6 +251,38 @@ pub struct UpdateConfigToml {
|
|||||||
pub check_on_startup: Option<bool>,
|
pub check_on_startup: Option<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `[telegram]`: control of running sessions from the user's Telegram bot.
|
||||||
|
/// The bot token is never stored here: it lives in the key store under `telegram-bot`.
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
|
||||||
|
#[schemars(deny_unknown_fields)]
|
||||||
|
pub struct TelegramConfigToml {
|
||||||
|
/// When `true`, the shared app-server serves the bot. Defaults to `false`: nothing
|
||||||
|
/// contacts Telegram while disabled.
|
||||||
|
pub enabled: Option<bool>,
|
||||||
|
/// Chats served by the bot (added by pairing in `/telegram`). Others are ignored.
|
||||||
|
pub allowed_chat_ids: Option<Vec<i64>>,
|
||||||
|
/// Which events are sent to Telegram. Every level defaults to `true`.
|
||||||
|
pub notify: Option<TelegramNotifyToml>,
|
||||||
|
/// Live output of running turns (message drafts) and the plan. Defaults to `true`.
|
||||||
|
pub streaming: Option<bool>,
|
||||||
|
/// Reactions on the user's messages (received, done). Defaults to `true`.
|
||||||
|
pub reactions: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `[telegram.notify]`: which events reach Telegram.
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
|
||||||
|
#[schemars(deny_unknown_fields)]
|
||||||
|
pub struct TelegramNotifyToml {
|
||||||
|
/// Approval requests with inline buttons.
|
||||||
|
pub approvals: Option<bool>,
|
||||||
|
/// A short summary when a turn ends.
|
||||||
|
pub turn_end: Option<bool>,
|
||||||
|
/// Errors and rate-limit (429) notices.
|
||||||
|
pub errors: Option<bool>,
|
||||||
|
/// Stops of the repeated-failure guard.
|
||||||
|
pub loops: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
|
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
|
||||||
#[schemars(deny_unknown_fields)]
|
#[schemars(deny_unknown_fields)]
|
||||||
pub struct FeedbackConfigToml {
|
pub struct FeedbackConfigToml {
|
||||||
|
|||||||
@@ -4736,6 +4736,64 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"TelegramConfigToml": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "`[telegram]`: control of running sessions from the user's Telegram bot. The bot token is never stored here: it lives in the key store under `telegram-bot`.",
|
||||||
|
"properties": {
|
||||||
|
"allowed_chat_ids": {
|
||||||
|
"description": "Chats served by the bot (added by pairing in `/telegram`). Others are ignored.",
|
||||||
|
"items": {
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"enabled": {
|
||||||
|
"description": "When `true`, the shared app-server serves the bot. Defaults to `false`: nothing contacts Telegram while disabled.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"notify": {
|
||||||
|
"allOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/TelegramNotifyToml"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Which events are sent to Telegram. Every level defaults to `true`."
|
||||||
|
},
|
||||||
|
"reactions": {
|
||||||
|
"description": "Reactions on the user's messages (received, done). Defaults to `true`.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"streaming": {
|
||||||
|
"description": "Live output of running turns (message drafts) and the plan. Defaults to `true`.",
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"TelegramNotifyToml": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "`[telegram.notify]`: which events reach Telegram.",
|
||||||
|
"properties": {
|
||||||
|
"approvals": {
|
||||||
|
"description": "Approval requests with inline buttons.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"description": "Errors and rate-limit (429) notices.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"loops": {
|
||||||
|
"description": "Stops of the repeated-failure guard.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"turn_end": {
|
||||||
|
"description": "A short summary when a turn ends.",
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
"ThreadStoreToml": {
|
"ThreadStoreToml": {
|
||||||
"oneOf": [
|
"oneOf": [
|
||||||
{
|
{
|
||||||
@@ -8807,6 +8865,14 @@
|
|||||||
"description": "Suppress warnings about unstable (under development) features.",
|
"description": "Suppress warnings about unstable (under development) features.",
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
},
|
},
|
||||||
|
"telegram": {
|
||||||
|
"allOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/TelegramConfigToml"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Telegram control of running sessions."
|
||||||
|
},
|
||||||
"thread_unload_delay_secs": {
|
"thread_unload_delay_secs": {
|
||||||
"description": "Seconds a thread must have no subscribers and no activity before app-server unloads it. Defaults to 60 (1 minute); zero unloads immediately. Resolved when each thread is loaded; request config overrides apply per thread.",
|
"description": "Seconds a thread must have no subscribers and no activity before app-server unloads it. Defaults to 60 (1 minute); zero unloads immediately. Resolved when each thread is loaded; request config overrides apply per thread.",
|
||||||
"format": "uint64",
|
"format": "uint64",
|
||||||
|
|||||||
37
akode-rs/telegram/Cargo.toml
Normal file
37
akode-rs/telegram/Cargo.toml
Normal 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 }
|
||||||
438
akode-rs/telegram/src/api.rs
Normal file
438
akode-rs/telegram/src/api.rs
Normal file
@@ -0,0 +1,438 @@
|
|||||||
|
//! 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,
|
||||||
|
/// Topics in private chats are enabled for the bot (`getMe` only).
|
||||||
|
#[serde(default)]
|
||||||
|
pub has_topics_enabled: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
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 message_thread_id: Option<i64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub is_topic_message: Option<bool>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub text: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub reply_to_message: Option<Box<Message>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Message {
|
||||||
|
/// The topic the message belongs to, if any.
|
||||||
|
pub fn topic(&self) -> Option<i64> {
|
||||||
|
self.message_thread_id
|
||||||
|
.filter(|_| self.is_topic_message.unwrap_or(true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
pub struct CallbackQuery {
|
||||||
|
pub id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub from: Option<User>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub message: Option<Message>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub data: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The user pressed the stop button of a streamed draft.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
pub struct MessageGenerationStopped {
|
||||||
|
pub chat: Chat,
|
||||||
|
#[serde(default)]
|
||||||
|
pub message_thread_id: Option<i64>,
|
||||||
|
pub draft_id: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
pub struct ForumTopic {
|
||||||
|
pub message_thread_id: i64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
pub struct Update {
|
||||||
|
pub update_id: i64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub message: Option<Message>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub edited_message: Option<Message>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub callback_query: Option<CallbackQuery>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub stopped_message_generation: Option<MessageGenerationStopped>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Update {
|
||||||
|
/// Chat the update comes from.
|
||||||
|
pub fn chat_id(&self) -> Option<i64> {
|
||||||
|
self.message
|
||||||
|
.as_ref()
|
||||||
|
.or(self.edited_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)
|
||||||
|
})
|
||||||
|
.or_else(|| {
|
||||||
|
self.stopped_message_generation
|
||||||
|
.as_ref()
|
||||||
|
.map(|stopped| stopped.chat.id)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `DisabledButton`: currently an empty object.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct DisabledButton {}
|
||||||
|
|
||||||
|
/// One inline keyboard button.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Button {
|
||||||
|
pub text: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub callback_data: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub url: Option<String>,
|
||||||
|
/// `success` (green), `danger` (red) or `primary` (blue).
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub style: Option<&'static str>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub disabled: Option<DisabledButton>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Button {
|
||||||
|
pub fn callback(text: impl Into<String>, data: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
text: text.into(),
|
||||||
|
callback_data: Some(data.into()),
|
||||||
|
url: None,
|
||||||
|
style: None,
|
||||||
|
disabled: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn link(text: impl Into<String>, url: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
text: text.into(),
|
||||||
|
callback_data: None,
|
||||||
|
url: Some(url.into()),
|
||||||
|
style: None,
|
||||||
|
disabled: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A button that does nothing, used to show an outcome in place of choices.
|
||||||
|
pub fn disabled(text: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
text: text.into(),
|
||||||
|
callback_data: None,
|
||||||
|
url: None,
|
||||||
|
style: None,
|
||||||
|
disabled: Some(DisabledButton {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn styled(mut self, style: &'static str) -> Self {
|
||||||
|
self.style = Some(style);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A message entity; offsets and lengths are in UTF-16 code units.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Entity {
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub kind: &'static str,
|
||||||
|
pub offset: usize,
|
||||||
|
pub length: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
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",
|
||||||
|
"edited_message",
|
||||||
|
"callback_query",
|
||||||
|
"stopped_message_generation",
|
||||||
|
],
|
||||||
|
});
|
||||||
|
if let Some(offset) = offset {
|
||||||
|
body["offset"] = json!(offset);
|
||||||
|
}
|
||||||
|
self.call(
|
||||||
|
"getUpdates",
|
||||||
|
body,
|
||||||
|
Duration::from_secs(timeout_secs) + REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call_unit(&self, method: &str, body: Value) -> Result<(), ApiError> {
|
||||||
|
self.call::<Value>(method, body, REQUEST_TIMEOUT)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn send_message(
|
||||||
|
&self,
|
||||||
|
chat_id: i64,
|
||||||
|
thread: Option<i64>,
|
||||||
|
text: &str,
|
||||||
|
entities: &[Entity],
|
||||||
|
buttons: Option<&[Vec<Button>]>,
|
||||||
|
) -> Result<Message, ApiError> {
|
||||||
|
let mut body = json!({ "chat_id": chat_id, "text": text });
|
||||||
|
if let Some(thread) = thread {
|
||||||
|
body["message_thread_id"] = json!(thread);
|
||||||
|
}
|
||||||
|
if !entities.is_empty() {
|
||||||
|
body["entities"] = json!(entities);
|
||||||
|
}
|
||||||
|
if let Some(buttons) = buttons {
|
||||||
|
body["reply_markup"] = json!({ "inline_keyboard": buttons });
|
||||||
|
}
|
||||||
|
self.call("sendMessage", body, REQUEST_TIMEOUT).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces a message's text; without `buttons` the inline keyboard is removed.
|
||||||
|
pub async fn edit_message_text(
|
||||||
|
&self,
|
||||||
|
chat_id: i64,
|
||||||
|
message_id: i64,
|
||||||
|
text: &str,
|
||||||
|
entities: &[Entity],
|
||||||
|
buttons: Option<&[Vec<Button>]>,
|
||||||
|
) -> Result<(), ApiError> {
|
||||||
|
let mut body = json!({ "chat_id": chat_id, "message_id": message_id, "text": text });
|
||||||
|
if !entities.is_empty() {
|
||||||
|
body["entities"] = json!(entities);
|
||||||
|
}
|
||||||
|
if let Some(buttons) = buttons {
|
||||||
|
body["reply_markup"] = json!({ "inline_keyboard": buttons });
|
||||||
|
}
|
||||||
|
self.call_unit("editMessageText", body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answers a button press with a short notice shown only to the user who pressed it.
|
||||||
|
pub async fn answer_callback_query(&self, id: &str, text: &str) -> Result<(), ApiError> {
|
||||||
|
let body = json!({ "callback_query_id": id, "text": text });
|
||||||
|
self.call_unit("answerCallbackQuery", body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the command menu of private chats.
|
||||||
|
pub async fn set_my_commands(&self, commands: &[(&str, &str)]) -> Result<(), ApiError> {
|
||||||
|
let commands: Vec<Value> = commands
|
||||||
|
.iter()
|
||||||
|
.map(|(command, description)| json!({ "command": command, "description": description }))
|
||||||
|
.collect();
|
||||||
|
let body = json!({ "commands": commands, "scope": { "type": "all_private_chats" } });
|
||||||
|
self.call_unit("setMyCommands", body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_forum_topic(&self, chat_id: i64, name: &str) -> Result<ForumTopic, ApiError> {
|
||||||
|
let body = json!({ "chat_id": chat_id, "name": name });
|
||||||
|
self.call("createForumTopic", body, REQUEST_TIMEOUT).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn edit_forum_topic(
|
||||||
|
&self,
|
||||||
|
chat_id: i64,
|
||||||
|
thread: i64,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<(), ApiError> {
|
||||||
|
let body = json!({ "chat_id": chat_id, "message_thread_id": thread, "name": name });
|
||||||
|
self.call_unit("editForumTopic", body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Streams a partial message (a temporary preview, replaced by the next message).
|
||||||
|
pub async fn send_message_draft(
|
||||||
|
&self,
|
||||||
|
chat_id: i64,
|
||||||
|
thread: Option<i64>,
|
||||||
|
draft_id: i64,
|
||||||
|
text: &str,
|
||||||
|
) -> Result<(), ApiError> {
|
||||||
|
let mut body = json!({
|
||||||
|
"chat_id": chat_id,
|
||||||
|
"draft_id": draft_id,
|
||||||
|
"text": text,
|
||||||
|
"can_stop": true,
|
||||||
|
});
|
||||||
|
if let Some(thread) = thread {
|
||||||
|
body["message_thread_id"] = json!(thread);
|
||||||
|
}
|
||||||
|
self.call_unit("sendMessageDraft", body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets one standard reaction on a message, or clears it with `None`.
|
||||||
|
pub async fn set_message_reaction(
|
||||||
|
&self,
|
||||||
|
chat_id: i64,
|
||||||
|
message_id: i64,
|
||||||
|
emoji: Option<&str>,
|
||||||
|
) -> Result<(), ApiError> {
|
||||||
|
let reaction: Vec<Value> = emoji
|
||||||
|
.map(|emoji| json!({ "type": "emoji", "emoji": emoji }))
|
||||||
|
.into_iter()
|
||||||
|
.collect();
|
||||||
|
let body = json!({ "chat_id": chat_id, "message_id": message_id, "reaction": reaction });
|
||||||
|
self.call_unit("setMessageReaction", body).await
|
||||||
|
}
|
||||||
|
}
|
||||||
2174
akode-rs/telegram/src/bridge.rs
Normal file
2174
akode-rs/telegram/src/bridge.rs
Normal file
File diff suppressed because it is too large
Load Diff
32
akode-rs/telegram/src/lib.rs
Normal file
32
akode-rs/telegram/src/lib.rs
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
//! 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;
|
||||||
|
mod outbox;
|
||||||
|
pub mod pairing;
|
||||||
|
pub mod settings;
|
||||||
|
pub mod text;
|
||||||
|
pub mod topics;
|
||||||
|
|
||||||
|
/// 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";
|
||||||
46
akode-rs/telegram/src/lock.rs
Normal file
46
akode-rs/telegram/src/lock.rs
Normal 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
379
akode-rs/telegram/src/outbox.rs
Normal file
379
akode-rs/telegram/src/outbox.rs
Normal file
@@ -0,0 +1,379 @@
|
|||||||
|
//! Sends to Telegram, one call at a time, in the order the bridge queued them.
|
||||||
|
//!
|
||||||
|
//! The outbox resolves where a session message goes: into the session's topic when topics
|
||||||
|
//! are in use, otherwise into the main chat with the `[cwd · model]` tag in front. It also
|
||||||
|
//! creates and renames topics, so a topic exists before the first message that needs it.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
|
use crate::api::ApiError;
|
||||||
|
use crate::api::Button;
|
||||||
|
use crate::api::TelegramApi;
|
||||||
|
use crate::settings;
|
||||||
|
use crate::text;
|
||||||
|
use crate::text::Rich;
|
||||||
|
use crate::topics::TopicEntry;
|
||||||
|
use crate::topics::Topics;
|
||||||
|
|
||||||
|
/// The command menu of private chats.
|
||||||
|
pub(crate) const COMMANDS: [(&str, &str); 6] = [
|
||||||
|
("sessioni", "Elenco delle sessioni con Apri, Stop e Stato"),
|
||||||
|
("nuova", "Avvia una nuova sessione"),
|
||||||
|
("stato", "Stato della sessione"),
|
||||||
|
("stop", "Interrompe il turno in corso"),
|
||||||
|
("impostazioni", "Notifiche, streaming e reazioni"),
|
||||||
|
("aiuto", "Come si usa il bot"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Draft text limit (Telegram accepts 4096 characters).
|
||||||
|
const DRAFT_LIMIT: usize = 4000;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub(crate) enum Dest {
|
||||||
|
/// The main chat, or one of its topics.
|
||||||
|
Chat(Option<i64>),
|
||||||
|
/// A session: its topic, or the main chat with `tag` in front.
|
||||||
|
Session { id: String, tag: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub(crate) enum Tag {
|
||||||
|
None,
|
||||||
|
/// A session message: replies to it go to the session.
|
||||||
|
Session(String),
|
||||||
|
Approval(u64),
|
||||||
|
/// A plan message of a session, at this plan version.
|
||||||
|
Plan(String, u64),
|
||||||
|
SessionList,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) enum Outbox {
|
||||||
|
Send {
|
||||||
|
chat_id: i64,
|
||||||
|
dest: Dest,
|
||||||
|
text: Rich,
|
||||||
|
buttons: Option<Vec<Vec<Button>>>,
|
||||||
|
tag: Tag,
|
||||||
|
},
|
||||||
|
Edit {
|
||||||
|
chat_id: i64,
|
||||||
|
message_id: i64,
|
||||||
|
text: Rich,
|
||||||
|
buttons: Option<Vec<Vec<Button>>>,
|
||||||
|
/// Sent instead when Telegram refuses the edit (for example a disabled button).
|
||||||
|
fallback: Option<Rich>,
|
||||||
|
},
|
||||||
|
Answer {
|
||||||
|
callback_id: String,
|
||||||
|
text: String,
|
||||||
|
},
|
||||||
|
/// Creates the topic of `session` when missing (`create`), and renames it to `name`.
|
||||||
|
Topic {
|
||||||
|
chat_id: i64,
|
||||||
|
session: String,
|
||||||
|
name: String,
|
||||||
|
create: bool,
|
||||||
|
},
|
||||||
|
Draft {
|
||||||
|
chat_id: i64,
|
||||||
|
session: String,
|
||||||
|
tag: String,
|
||||||
|
draft_id: i64,
|
||||||
|
text: String,
|
||||||
|
},
|
||||||
|
React {
|
||||||
|
chat_id: i64,
|
||||||
|
message_id: i64,
|
||||||
|
emoji: &'static str,
|
||||||
|
},
|
||||||
|
/// Reads the bot (`getMe`: username, topics) and, with `commands`, sets the menu.
|
||||||
|
Setup { commands: bool },
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) enum Feedback {
|
||||||
|
Sent {
|
||||||
|
tag: Tag,
|
||||||
|
chat_id: i64,
|
||||||
|
message_id: i64,
|
||||||
|
},
|
||||||
|
/// `sendMessageDraft` is not available: stop streaming.
|
||||||
|
DraftFailed,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct OutboxTask {
|
||||||
|
pub api: TelegramApi,
|
||||||
|
pub topics: Arc<Mutex<Topics>>,
|
||||||
|
pub codex_home: std::path::PathBuf,
|
||||||
|
pub feedback: mpsc::UnboundedSender<Feedback>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock(topics: &Mutex<Topics>) -> std::sync::MutexGuard<'_, Topics> {
|
||||||
|
topics.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_bad_request(err: &ApiError) -> bool {
|
||||||
|
matches!(err, ApiError::Api { code: 400, .. })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mentions(err: &ApiError, words: &[&str]) -> bool {
|
||||||
|
match err {
|
||||||
|
ApiError::Api { description, .. } => {
|
||||||
|
let description = description.to_ascii_lowercase();
|
||||||
|
words.iter().any(|word| description.contains(word))
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OutboxTask {
|
||||||
|
pub async fn run(self, mut outbox: mpsc::UnboundedReceiver<Outbox>) {
|
||||||
|
while let Some(item) = outbox.recv().await {
|
||||||
|
self.process(item).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn with_retry<F, Fut>(&self, mut call: F) -> Result<(), ApiError>
|
||||||
|
where
|
||||||
|
F: FnMut() -> Fut,
|
||||||
|
Fut: std::future::Future<Output = Result<(), ApiError>>,
|
||||||
|
{
|
||||||
|
let first = call().await;
|
||||||
|
let Err(err) = first else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
if is_bad_request(&err) || err.is_unauthorized() {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
let wait = err.retry_after().unwrap_or(2).min(30);
|
||||||
|
warn!("telegram: send failed, retrying in {wait}s: {err}");
|
||||||
|
tokio::time::sleep(Duration::from_secs(wait)).await;
|
||||||
|
call().await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn process(&self, item: Outbox) {
|
||||||
|
match item {
|
||||||
|
Outbox::Send {
|
||||||
|
chat_id,
|
||||||
|
dest,
|
||||||
|
text,
|
||||||
|
buttons,
|
||||||
|
tag,
|
||||||
|
} => self.send(chat_id, dest, text, buttons, tag).await,
|
||||||
|
Outbox::Edit {
|
||||||
|
chat_id,
|
||||||
|
message_id,
|
||||||
|
text,
|
||||||
|
buttons,
|
||||||
|
fallback,
|
||||||
|
} => {
|
||||||
|
let result = self
|
||||||
|
.with_retry(|| {
|
||||||
|
self.api.edit_message_text(
|
||||||
|
chat_id,
|
||||||
|
message_id,
|
||||||
|
&text.text,
|
||||||
|
&text.entities,
|
||||||
|
buttons.as_deref(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match result {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(err) if mentions(&err, &["not modified"]) => {}
|
||||||
|
Err(err) => {
|
||||||
|
warn!("telegram: edit failed: {err}");
|
||||||
|
if let Some(fallback) = fallback
|
||||||
|
&& is_bad_request(&err)
|
||||||
|
&& let Err(err) = self
|
||||||
|
.api
|
||||||
|
.edit_message_text(
|
||||||
|
chat_id,
|
||||||
|
message_id,
|
||||||
|
&fallback.text,
|
||||||
|
&fallback.entities,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
warn!("telegram: edit failed: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Outbox::Answer { callback_id, text } => {
|
||||||
|
if let Err(err) = self.api.answer_callback_query(&callback_id, &text).await {
|
||||||
|
warn!("telegram: answerCallbackQuery failed: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Outbox::Topic {
|
||||||
|
chat_id,
|
||||||
|
session,
|
||||||
|
name,
|
||||||
|
create,
|
||||||
|
} => self.topic(chat_id, &session, &name, create).await,
|
||||||
|
Outbox::Draft {
|
||||||
|
chat_id,
|
||||||
|
session,
|
||||||
|
tag,
|
||||||
|
draft_id,
|
||||||
|
text,
|
||||||
|
} => {
|
||||||
|
let thread = lock(&self.topics).thread_for(chat_id, &session);
|
||||||
|
let text = if thread.is_some() {
|
||||||
|
text
|
||||||
|
} else {
|
||||||
|
format!("{tag}\n{text}")
|
||||||
|
};
|
||||||
|
let text = text::truncate(&text, DRAFT_LIMIT);
|
||||||
|
if let Err(err) = self
|
||||||
|
.api
|
||||||
|
.send_message_draft(chat_id, thread, draft_id, &text)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
warn!("telegram: sendMessageDraft failed, streaming off: {err}");
|
||||||
|
if !matches!(err, ApiError::Network(_)) {
|
||||||
|
let _ = self.feedback.send(Feedback::DraftFailed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Outbox::React {
|
||||||
|
chat_id,
|
||||||
|
message_id,
|
||||||
|
emoji,
|
||||||
|
} => {
|
||||||
|
if let Err(err) = self
|
||||||
|
.api
|
||||||
|
.set_message_reaction(chat_id, message_id, Some(emoji))
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
warn!("telegram: setMessageReaction failed: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Outbox::Setup { commands } => self.setup(commands).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn setup(&self, commands: bool) {
|
||||||
|
match self.api.get_me().await {
|
||||||
|
Ok(me) => {
|
||||||
|
let topics = me.has_topics_enabled == Some(true);
|
||||||
|
{
|
||||||
|
let mut store = lock(&self.topics);
|
||||||
|
store.enabled = topics;
|
||||||
|
store.bot_username = me.username.clone();
|
||||||
|
}
|
||||||
|
if let Some(username) = &me.username
|
||||||
|
&& let Err(err) = settings::save_bot_info(&self.codex_home, username, topics)
|
||||||
|
{
|
||||||
|
warn!("telegram: cannot save the bot info: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => warn!("telegram: getMe failed, topics off: {err}"),
|
||||||
|
}
|
||||||
|
if commands && let Err(err) = self.api.set_my_commands(&COMMANDS).await {
|
||||||
|
warn!("telegram: setMyCommands failed: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn topic(&self, chat_id: i64, session: &str, name: &str, create: bool) {
|
||||||
|
// Topics exist only in private chats (positive ids).
|
||||||
|
if chat_id <= 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (enabled, existing) = {
|
||||||
|
let store = lock(&self.topics);
|
||||||
|
(store.enabled, store.entry(chat_id, session).cloned())
|
||||||
|
};
|
||||||
|
if !enabled {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match existing {
|
||||||
|
Some(entry) if entry.name != name => {
|
||||||
|
match self.api.edit_forum_topic(chat_id, entry.thread, name).await {
|
||||||
|
Ok(()) => lock(&self.topics).set_name(chat_id, session, name),
|
||||||
|
Err(err) => warn!("telegram: editForumTopic failed: {err}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(_) => {}
|
||||||
|
None if create => match self.api.create_forum_topic(chat_id, name).await {
|
||||||
|
Ok(topic) => lock(&self.topics).insert(TopicEntry {
|
||||||
|
chat_id,
|
||||||
|
session: session.to_string(),
|
||||||
|
thread: topic.message_thread_id,
|
||||||
|
name: name.to_string(),
|
||||||
|
}),
|
||||||
|
Err(ApiError::Network(err)) => {
|
||||||
|
warn!("telegram: createForumTopic failed, retrying later: {err}");
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
// Topics refused: use the main chat from now on.
|
||||||
|
warn!("telegram: createForumTopic failed, topics off: {err}");
|
||||||
|
lock(&self.topics).enabled = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send(
|
||||||
|
&self,
|
||||||
|
chat_id: i64,
|
||||||
|
dest: Dest,
|
||||||
|
text: Rich,
|
||||||
|
buttons: Option<Vec<Vec<Button>>>,
|
||||||
|
tag: Tag,
|
||||||
|
) {
|
||||||
|
let (thread, prefixed) = match &dest {
|
||||||
|
Dest::Chat(thread) => (*thread, None),
|
||||||
|
Dest::Session { id, tag } => {
|
||||||
|
let thread = lock(&self.topics).thread_for(chat_id, id);
|
||||||
|
(thread, Some((id.clone(), text.prefixed(&format!("{tag} ")))))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let attempt = |thread: Option<i64>, text: &Rich| {
|
||||||
|
let text = text.clone();
|
||||||
|
let buttons = buttons.clone();
|
||||||
|
async move {
|
||||||
|
self.api
|
||||||
|
.send_message(chat_id, thread, &text.text, &text.entities, buttons.as_deref())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let first_text = match (&thread, &prefixed) {
|
||||||
|
(None, Some((_, prefixed))) => prefixed.clone(),
|
||||||
|
_ => text.clone(),
|
||||||
|
};
|
||||||
|
let mut result = attempt(thread, &first_text).await;
|
||||||
|
if let Err(err) = &result {
|
||||||
|
if thread.is_some()
|
||||||
|
&& let Some((session, prefixed)) = &prefixed
|
||||||
|
&& mentions(err, &["thread", "topic"])
|
||||||
|
{
|
||||||
|
// The user deleted the topic: forget it and use the main chat.
|
||||||
|
warn!("telegram: topic gone, writing to the main chat: {err}");
|
||||||
|
lock(&self.topics).remove(chat_id, session);
|
||||||
|
result = attempt(None, prefixed).await;
|
||||||
|
} else if !is_bad_request(err) && !err.is_unauthorized() {
|
||||||
|
let wait = err.retry_after().unwrap_or(2).min(30);
|
||||||
|
warn!("telegram: send failed, retrying in {wait}s: {err}");
|
||||||
|
tokio::time::sleep(Duration::from_secs(wait)).await;
|
||||||
|
result = attempt(thread, &first_text).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match result {
|
||||||
|
Ok(message) => {
|
||||||
|
let _ = self.feedback.send(Feedback::Sent {
|
||||||
|
tag,
|
||||||
|
chat_id,
|
||||||
|
message_id: message.message_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(err) => warn!("telegram: send failed: {err}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
175
akode-rs/telegram/src/pairing.rs
Normal file
175
akode-rs/telegram/src/pairing.rs
Normal 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, None, PAIRED_REPLY, &[], 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]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
356
akode-rs/telegram/src/settings.rs
Normal file
356
akode-rs/telegram/src/settings.rs
Normal file
@@ -0,0 +1,356 @@
|
|||||||
|
//! `[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)]
|
||||||
|
pub struct TelegramSettings {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub allowed_chat_ids: Vec<i64>,
|
||||||
|
pub notify: NotifySettings,
|
||||||
|
/// Live drafts of running turns and the plan.
|
||||||
|
pub streaming: bool,
|
||||||
|
/// Reactions on the user's messages.
|
||||||
|
pub reactions: bool,
|
||||||
|
pub key_store: AuthCredentialsStoreMode,
|
||||||
|
/// 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),
|
||||||
|
},
|
||||||
|
streaming: telegram.streaming.unwrap_or(true),
|
||||||
|
reactions: telegram.reactions.unwrap_or(true),
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TelegramSettings {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::parse("")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A yes/no option that `/impostazioni` toggles.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Toggle {
|
||||||
|
Approvals,
|
||||||
|
TurnEnd,
|
||||||
|
Errors,
|
||||||
|
Loops,
|
||||||
|
Streaming,
|
||||||
|
Reactions,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Toggle {
|
||||||
|
pub const ALL: [Toggle; 6] = [
|
||||||
|
Toggle::Approvals,
|
||||||
|
Toggle::TurnEnd,
|
||||||
|
Toggle::Errors,
|
||||||
|
Toggle::Loops,
|
||||||
|
Toggle::Streaming,
|
||||||
|
Toggle::Reactions,
|
||||||
|
];
|
||||||
|
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Toggle::Approvals => "Approvazioni",
|
||||||
|
Toggle::TurnEnd => "Fine turno",
|
||||||
|
Toggle::Errors => "Errori",
|
||||||
|
Toggle::Loops => "Loop",
|
||||||
|
Toggle::Streaming => "Streaming e piano",
|
||||||
|
Toggle::Reactions => "Reazioni",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Key path under `[telegram]`.
|
||||||
|
fn path(self) -> (Option<&'static str>, &'static str) {
|
||||||
|
match self {
|
||||||
|
Toggle::Approvals => (Some("notify"), "approvals"),
|
||||||
|
Toggle::TurnEnd => (Some("notify"), "turn_end"),
|
||||||
|
Toggle::Errors => (Some("notify"), "errors"),
|
||||||
|
Toggle::Loops => (Some("notify"), "loops"),
|
||||||
|
Toggle::Streaming => (None, "streaming"),
|
||||||
|
Toggle::Reactions => (None, "reactions"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(self, settings: &TelegramSettings) -> bool {
|
||||||
|
match self {
|
||||||
|
Toggle::Approvals => settings.notify.approvals,
|
||||||
|
Toggle::TurnEnd => settings.notify.turn_end,
|
||||||
|
Toggle::Errors => settings.notify.errors,
|
||||||
|
Toggle::Loops => settings.notify.loops,
|
||||||
|
Toggle::Streaming => settings.streaming,
|
||||||
|
Toggle::Reactions => settings.reactions,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes one toggle to `[telegram]` (or `[telegram.notify]`).
|
||||||
|
pub fn set_toggle(codex_home: &Path, toggle: Toggle, value: bool) -> io::Result<()> {
|
||||||
|
edit_config(codex_home, |table| match toggle.path() {
|
||||||
|
(None, key) => table[key] = toml_edit::value(value),
|
||||||
|
(Some(section), key) => {
|
||||||
|
if !table.get(section).is_some_and(toml_edit::Item::is_table_like) {
|
||||||
|
table[section] = toml_edit::Item::Table(toml_edit::Table::new());
|
||||||
|
}
|
||||||
|
table[section][key] = toml_edit::value(value);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn edit_config(
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_bot_file(codex_home: &Path) -> Option<serde_json::Value> {
|
||||||
|
let text = std::fs::read_to_string(codex_home.join(BOT_FILE)).ok()?;
|
||||||
|
serde_json::from_str(&text).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_bot_name(codex_home: &Path) -> Option<String> {
|
||||||
|
load_bot_file(codex_home)?["username"]
|
||||||
|
.as_str()
|
||||||
|
.map(ToString::to_string)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remembers the bot's username and whether topics in private chats are enabled, as
|
||||||
|
/// seen by the running bridge.
|
||||||
|
pub fn save_bot_info(codex_home: &Path, username: &str, topics: bool) -> io::Result<()> {
|
||||||
|
std::fs::create_dir_all(codex_home)?;
|
||||||
|
let text = serde_json::json!({ "username": username, "topics": topics }).to_string();
|
||||||
|
std::fs::write(codex_home.join(BOT_FILE), text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the bot had topics enabled when the bridge last checked.
|
||||||
|
pub fn load_bot_topics(codex_home: &Path) -> Option<bool> {
|
||||||
|
load_bot_file(codex_home)?["topics"].as_bool()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn forget_bot_name(codex_home: &Path) {
|
||||||
|
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]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn toggles_persist() {
|
||||||
|
let home = tempfile::tempdir().unwrap();
|
||||||
|
std::fs::write(home.path().join(CONFIG_FILE), "[telegram]\nenabled = true\n").unwrap();
|
||||||
|
let settings = TelegramSettings::load(home.path());
|
||||||
|
assert!(Toggle::ALL.iter().all(|toggle| toggle.get(&settings)));
|
||||||
|
set_toggle(home.path(), Toggle::Approvals, false).unwrap();
|
||||||
|
set_toggle(home.path(), Toggle::Streaming, false).unwrap();
|
||||||
|
let settings = TelegramSettings::load(home.path());
|
||||||
|
assert!(!settings.notify.approvals);
|
||||||
|
assert!(!settings.streaming);
|
||||||
|
assert!(settings.notify.turn_end && settings.reactions && settings.enabled);
|
||||||
|
}
|
||||||
|
}
|
||||||
286
akode-rs/telegram/src/text.rs
Normal file
286
akode-rs/telegram/src/text.rs
Normal file
@@ -0,0 +1,286 @@
|
|||||||
|
//! Message text: session tags, splitting to Telegram's limit, short summaries.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use crate::api::Entity;
|
||||||
|
|
||||||
|
/// 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 {
|
||||||
|
format!("[{}]", topic_name(cwd, model))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Longest session tag or topic name kept.
|
||||||
|
const NAME_LIMIT: usize = 64;
|
||||||
|
|
||||||
|
fn dir_name(cwd: &Path) -> &str {
|
||||||
|
cwd.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.filter(|name| !name.is_empty())
|
||||||
|
.unwrap_or("/")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Topic name of a session: `<cwd basename> · <model>`.
|
||||||
|
pub fn topic_name(cwd: &Path, model: &str) -> String {
|
||||||
|
let dir = dir_name(cwd);
|
||||||
|
let name = if model.is_empty() {
|
||||||
|
dir.to_string()
|
||||||
|
} else {
|
||||||
|
format!("{dir} · {model}")
|
||||||
|
};
|
||||||
|
truncate(&name, NAME_LIMIT)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Topic name of a closed session.
|
||||||
|
pub fn closed_topic_name(name: &str) -> String {
|
||||||
|
format!("{} (chiusa)", truncate(name, NAME_LIMIT))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `1m 28s`, `42s`, `1h 05m`.
|
||||||
|
pub fn format_duration(ms: i64) -> String {
|
||||||
|
let secs = (ms.max(0) + 500) / 1000;
|
||||||
|
match secs {
|
||||||
|
0..60 => format!("{secs}s"),
|
||||||
|
60..3600 => format!("{}m {:02}s", secs / 60, secs % 60),
|
||||||
|
_ => format!("{}h {:02}m", secs / 3600, (secs % 3600) / 60),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text with formatting entities, built piece by piece.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct Rich {
|
||||||
|
pub text: String,
|
||||||
|
pub entities: Vec<Entity>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Rich {
|
||||||
|
pub fn plain(text: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
text: text.into(),
|
||||||
|
entities: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push(&mut self, text: &str) -> &mut Self {
|
||||||
|
self.text.push_str(text);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends `text` covered by an entity of type `kind` (`pre`, `italic`,
|
||||||
|
/// `expandable_blockquote`, ...).
|
||||||
|
pub fn push_styled(&mut self, kind: &'static str, text: &str) -> &mut Self {
|
||||||
|
let offset = utf16_len(&self.text);
|
||||||
|
let length = utf16_len(text);
|
||||||
|
self.text.push_str(text);
|
||||||
|
if length > 0 {
|
||||||
|
self.entities.push(Entity {
|
||||||
|
kind,
|
||||||
|
offset,
|
||||||
|
length,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `prefix` in front, entities shifted accordingly.
|
||||||
|
pub fn prefixed(&self, prefix: &str) -> Self {
|
||||||
|
let shift = utf16_len(prefix);
|
||||||
|
Self {
|
||||||
|
text: format!("{prefix}{}", self.text),
|
||||||
|
entities: self
|
||||||
|
.entities
|
||||||
|
.iter()
|
||||||
|
.map(|entity| Entity {
|
||||||
|
offset: entity.offset + shift,
|
||||||
|
..entity.clone()
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn utf16_len(text: &str) -> usize {
|
||||||
|
text.encode_utf16().count()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `text` contains a pictographic emoji or an emoji presentation selector.
|
||||||
|
pub fn contains_emoji(text: &str) -> bool {
|
||||||
|
text.chars().any(|c| {
|
||||||
|
matches!(u32::from(c),
|
||||||
|
0x1F000..=0x1FAFF
|
||||||
|
| 0x2600..=0x27BF
|
||||||
|
| 0x2300..=0x23FF
|
||||||
|
| 0x2B00..=0x2BFF
|
||||||
|
| 0x2190..=0x21FF
|
||||||
|
| 0x3030 | 0x303D | 0x3297 | 0x3299
|
||||||
|
| 0xFE0F
|
||||||
|
| 0x20E3
|
||||||
|
| 0xE0020..=0xE007F)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `model` without directory and extension when it looks like a model file path.
|
||||||
|
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));
|
||||||
|
assert_eq!(topic_name(Path::new("/a/progetto"), "Qwen"), "progetto · Qwen");
|
||||||
|
assert_eq!(closed_topic_name("progetto · Qwen"), "progetto · Qwen (chiusa)");
|
||||||
|
assert_eq!(format_duration(88_000), "1m 28s");
|
||||||
|
assert_eq!(format_duration(4_000), "4s");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rich_text_offsets_are_utf16() {
|
||||||
|
let mut rich = Rich::default();
|
||||||
|
rich.push("è ").push_styled("pre", "ls");
|
||||||
|
let shifted = rich.prefixed("[x] ");
|
||||||
|
assert_eq!(shifted.text, "[x] è ls");
|
||||||
|
assert_eq!(shifted.entities[0].offset, 6);
|
||||||
|
assert_eq!(shifted.entities[0].length, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn emoji_detection() {
|
||||||
|
assert!(contains_emoji("ok \u{2705}"));
|
||||||
|
assert!(contains_emoji("\u{1F510} chiave"));
|
||||||
|
assert!(!contains_emoji("Approvato · ctx 23% — +3 \u{2212}1 … «Sì»"));
|
||||||
|
}
|
||||||
|
}
|
||||||
165
akode-rs/telegram/src/topics.rs
Normal file
165
akode-rs/telegram/src/topics.rs
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
//! One Telegram topic per aKode session, in each allowed private chat.
|
||||||
|
//!
|
||||||
|
//! The map from (chat, session) to topic is kept in `AKODE_HOME/telegram-topics.json`, so
|
||||||
|
//! a restarted bridge writes into the topics it created before instead of making new ones.
|
||||||
|
//! The file also remembers the recent working directories offered by `/nuova`.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
pub const TOPICS_FILE: &str = "telegram-topics.json";
|
||||||
|
|
||||||
|
const MAX_TOPICS: usize = 500;
|
||||||
|
const MAX_RECENT_CWDS: usize = 8;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct TopicEntry {
|
||||||
|
pub chat_id: i64,
|
||||||
|
pub session: String,
|
||||||
|
pub thread: i64,
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
|
struct StoreFile {
|
||||||
|
#[serde(default)]
|
||||||
|
topics: Vec<TopicEntry>,
|
||||||
|
#[serde(default)]
|
||||||
|
recent_cwds: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Topic map plus what the bridge learned from `getMe`.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Topics {
|
||||||
|
path: PathBuf,
|
||||||
|
file: StoreFile,
|
||||||
|
/// Topics can be used (`has_topics_enabled` and no API refusal).
|
||||||
|
pub enabled: bool,
|
||||||
|
/// The bot's username, for topic links.
|
||||||
|
pub bot_username: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Topics {
|
||||||
|
pub fn load(codex_home: &Path) -> Self {
|
||||||
|
let path = codex_home.join(TOPICS_FILE);
|
||||||
|
let file = std::fs::read_to_string(&path)
|
||||||
|
.ok()
|
||||||
|
.and_then(|text| serde_json::from_str(&text).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
Self {
|
||||||
|
path,
|
||||||
|
file,
|
||||||
|
enabled: false,
|
||||||
|
bot_username: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self) {
|
||||||
|
let Ok(text) = serde_json::to_string_pretty(&self.file) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let tmp = self.path.with_extension("json.tmp");
|
||||||
|
if let Err(err) = std::fs::write(&tmp, text).and_then(|()| std::fs::rename(&tmp, &self.path))
|
||||||
|
{
|
||||||
|
tracing::warn!("telegram: cannot save the topic map: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn entry(&self, chat_id: i64, session: &str) -> Option<&TopicEntry> {
|
||||||
|
self.file
|
||||||
|
.topics
|
||||||
|
.iter()
|
||||||
|
.find(|entry| entry.chat_id == chat_id && entry.session == session)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The topic of `session` in `chat_id`, when topics are in use.
|
||||||
|
pub fn thread_for(&self, chat_id: i64, session: &str) -> Option<i64> {
|
||||||
|
if !self.enabled {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.entry(chat_id, session).map(|entry| entry.thread)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session a topic belongs to (also for closed sessions).
|
||||||
|
pub fn session_for(&self, chat_id: i64, thread: i64) -> Option<&str> {
|
||||||
|
self.file
|
||||||
|
.topics
|
||||||
|
.iter()
|
||||||
|
.find(|entry| entry.chat_id == chat_id && entry.thread == thread)
|
||||||
|
.map(|entry| entry.session.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert(&mut self, entry: TopicEntry) {
|
||||||
|
self.file
|
||||||
|
.topics
|
||||||
|
.retain(|old| !(old.chat_id == entry.chat_id && old.session == entry.session));
|
||||||
|
self.file.topics.push(entry);
|
||||||
|
let extra = self.file.topics.len().saturating_sub(MAX_TOPICS);
|
||||||
|
self.file.topics.drain(..extra);
|
||||||
|
self.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_name(&mut self, chat_id: i64, session: &str, name: &str) {
|
||||||
|
if let Some(entry) = self
|
||||||
|
.file
|
||||||
|
.topics
|
||||||
|
.iter_mut()
|
||||||
|
.find(|entry| entry.chat_id == chat_id && entry.session == session)
|
||||||
|
{
|
||||||
|
entry.name = name.to_string();
|
||||||
|
self.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forgets a topic the user deleted.
|
||||||
|
pub fn remove(&mut self, chat_id: i64, session: &str) {
|
||||||
|
self.file
|
||||||
|
.topics
|
||||||
|
.retain(|entry| !(entry.chat_id == chat_id && entry.session == session));
|
||||||
|
self.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remember_cwd(&mut self, cwd: &str) {
|
||||||
|
if self.file.recent_cwds.first().map(String::as_str) == Some(cwd) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.file.recent_cwds.retain(|old| old != cwd);
|
||||||
|
self.file.recent_cwds.insert(0, cwd.to_string());
|
||||||
|
self.file.recent_cwds.truncate(MAX_RECENT_CWDS);
|
||||||
|
self.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn recent_cwds(&self) -> &[String] {
|
||||||
|
&self.file.recent_cwds
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use pretty_assertions::assert_eq;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn map_survives_a_reload() {
|
||||||
|
let home = tempfile::tempdir().unwrap();
|
||||||
|
let mut topics = Topics::load(home.path());
|
||||||
|
topics.insert(TopicEntry {
|
||||||
|
chat_id: 1,
|
||||||
|
session: "t1".to_string(),
|
||||||
|
thread: 77,
|
||||||
|
name: "alfa · Qwen".to_string(),
|
||||||
|
});
|
||||||
|
topics.remember_cwd("/a");
|
||||||
|
topics.remember_cwd("/b");
|
||||||
|
topics.remember_cwd("/a");
|
||||||
|
let mut topics = Topics::load(home.path());
|
||||||
|
assert_eq!(topics.thread_for(1, "t1"), None, "unused until getMe says so");
|
||||||
|
topics.enabled = true;
|
||||||
|
assert_eq!(topics.thread_for(1, "t1"), Some(77));
|
||||||
|
assert_eq!(topics.session_for(1, 77), Some("t1"));
|
||||||
|
assert_eq!(topics.recent_cwds(), ["/a".to_string(), "/b".to_string()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
866
akode-rs/telegram/tests/bridge.rs
Normal file
866
akode-rs/telegram/tests/bridge.rs
Normal file
@@ -0,0 +1,866 @@
|
|||||||
|
//! 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|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 topics = h.wait_for_calls("createForumTopic", 1).await;
|
||||||
|
assert_eq!(topics[0]["chat_id"], json!(CHAT));
|
||||||
|
assert_eq!(topics[0]["name"], "alfa · Qwen 3.6");
|
||||||
|
let commands = h.wait_for_calls("setMyCommands", 1).await;
|
||||||
|
let names: Vec<&str> = commands[0]["commands"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|c| c["command"].as_str().unwrap())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(names, ["sessioni", "nuova", "stato", "stop", "impostazioni", "aiuto"]);
|
||||||
|
assert_eq!(commands[0]["scope"]["type"], "all_private_chats");
|
||||||
|
|
||||||
|
complete_turn(&h, "t1", "turn-1", "Fatto.");
|
||||||
|
let sends = h.wait_for_calls("sendMessage", 1).await;
|
||||||
|
assert_eq!(sends[0]["message_thread_id"], 500);
|
||||||
|
assert!(sends[0]["text"].as_str().unwrap().starts_with("Fatto."), "no tag inside a topic");
|
||||||
|
let saved = std::fs::read_to_string(home.path().join(topics::TOPICS_FILE)).unwrap();
|
||||||
|
assert!(saved.contains("\"thread\": 500"), "{saved}");
|
||||||
|
|
||||||
|
h.notify("thread/closed", json!({"threadId": "t1"}));
|
||||||
|
let renames = h.wait_for_calls("editForumTopic", 1).await;
|
||||||
|
assert_eq!(renames[0]["message_thread_id"], 500);
|
||||||
|
assert_eq!(renames[0]["name"], "alfa · Qwen 3.6 (chiusa)");
|
||||||
|
h.shutdown.cancel();
|
||||||
|
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A new bridge on the same home writes into the same topic and reopens its name.
|
||||||
|
let h = Harness::start_with(home, true).await;
|
||||||
|
h.start_thread("t1", "/tmp/alfa");
|
||||||
|
let renames = h.wait_for_calls("editForumTopic", 1).await;
|
||||||
|
assert_eq!(renames[0]["name"], "alfa · Qwen 3.6");
|
||||||
|
complete_turn(&h, "t1", "turn-2", "Ancora.");
|
||||||
|
let sends = h.wait_for_calls("sendMessage", 1).await;
|
||||||
|
assert_eq!(sends[0]["message_thread_id"], 500);
|
||||||
|
assert!(h.calls("createForumTopic").await.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn topic_messages_go_to_their_session() {
|
||||||
|
let mut h = Harness::with_topics().await;
|
||||||
|
h.start_thread("t1", "/tmp/alfa");
|
||||||
|
h.start_thread("t2", "/tmp/beta");
|
||||||
|
h.wait_for_calls("createForumTopic", 2).await;
|
||||||
|
// Let the outbox store both topics.
|
||||||
|
h.settle().await;
|
||||||
|
|
||||||
|
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", 1).await;
|
||||||
|
assert_eq!(sends[0]["message_thread_id"], 500);
|
||||||
|
assert!(sends[0]["text"].as_str().unwrap().starts_with("alfa · Qwen 3.6 · libera"));
|
||||||
|
|
||||||
|
// The session list links each topic and refreshes in place.
|
||||||
|
h.push_update(text_message(CHAT, "/sessioni", None));
|
||||||
|
let sends = h.wait_for_calls("sendMessage", 2).await;
|
||||||
|
let list = &sends[1];
|
||||||
|
assert_eq!(
|
||||||
|
labels(list),
|
||||||
|
vec![
|
||||||
|
vec!["1 · Apri", "1 · Stato", "1 · Stop"],
|
||||||
|
vec!["2 · Apri", "2 · Stato", "2 · Stop"],
|
||||||
|
vec!["Aggiorna", "Nuova sessione"],
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(list["reply_markup"]["inline_keyboard"][1][0]["url"], "https://t.me/akode_bot/501");
|
||||||
|
let list_id = 1001;
|
||||||
|
h.push_update(callback_on(CHAT, &button(list, "2 · Stato"), list_id));
|
||||||
|
let answers = h.wait_for_calls("answerCallbackQuery", 1).await;
|
||||||
|
assert!(answers[0]["text"].as_str().unwrap().starts_with("beta · Qwen 3.6"));
|
||||||
|
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-9", "inProgress")}));
|
||||||
|
let edits = h.wait_for_calls("editMessageText", 1).await;
|
||||||
|
assert_eq!(edits[0]["message_id"], list_id);
|
||||||
|
assert!(edits[0]["text"].as_str().unwrap().contains("al lavoro"));
|
||||||
|
assert_eq!(h.calls("sendMessage").await.len(), 2, "refresh edits, never sends");
|
||||||
|
h.push_update(callback_on(CHAT, &button(list, "1 · Stop"), list_id));
|
||||||
|
let interrupt = h.expect_request("turn/interrupt").await;
|
||||||
|
assert_eq!(interrupt.params.unwrap()["turnId"], "turn-9");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn without_topics_messages_are_tagged_and_buttons_pick_the_session() {
|
||||||
|
let mut h = Harness::start().await;
|
||||||
|
h.start_thread("t1", "/tmp/alfa");
|
||||||
|
h.start_thread("t2", "/tmp/beta");
|
||||||
|
h.notify("turn/started", json!({"threadId": "t2", "turn": turn_json("turn-2", "inProgress")}));
|
||||||
|
complete_turn(&h, "t2", "turn-2", "Fatto: test verdi.");
|
||||||
|
let sends = h.wait_for_calls("sendMessage", 1).await;
|
||||||
|
let text = sends[0]["text"].as_str().unwrap();
|
||||||
|
assert!(text.starts_with("[beta · Qwen 3.6] Fatto: test verdi."), "{text}");
|
||||||
|
assert!(text.ends_with("2s"), "footer: {text}");
|
||||||
|
assert!(sends[0]["entities"].as_array().unwrap().iter().any(|e| e["type"] == "italic"));
|
||||||
|
assert!(sends[0].get("message_thread_id").is_none());
|
||||||
|
assert!(h.calls("createForumTopic").await.is_empty());
|
||||||
|
|
||||||
|
// A reply goes to the session it answers; the message gets the received reaction.
|
||||||
|
h.push_update(text_message(CHAT, "continua", Some(1000)));
|
||||||
|
let start = h.expect_request("turn/start").await;
|
||||||
|
assert_eq!(start.params.clone().unwrap()["threadId"], "t2");
|
||||||
|
h.respond(start.id, json!({"turn": turn_json("turn-3", "inProgress")}));
|
||||||
|
let reactions = h.wait_for_calls("setMessageReaction", 1).await;
|
||||||
|
assert_eq!(reactions[0]["message_id"], 1);
|
||||||
|
assert_eq!(reactions[0]["reaction"][0]["type"], "emoji");
|
||||||
|
|
||||||
|
// Without a reply and with two sessions the bridge asks with buttons.
|
||||||
|
h.push_update(text_message(CHAT, "e adesso?", None));
|
||||||
|
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.wait_for_calls("createForumTopic", 1).await;
|
||||||
|
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-1", "inProgress")}));
|
||||||
|
for word in ["Sto ", "leggendo ", "i ", "file ", "del ", "progetto."] {
|
||||||
|
h.notify(
|
||||||
|
"item/agentMessage/delta",
|
||||||
|
json!({"threadId": "t1", "turnId": "turn-1", "itemId": "m1", "delta": word}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||||
|
let drafts = h.calls("sendMessageDraft").await;
|
||||||
|
assert_eq!(drafts.len(), 1, "one draft inside the interval: {drafts:?}");
|
||||||
|
assert_eq!(drafts[0]["text"], "Sto ");
|
||||||
|
assert_eq!(drafts[0]["message_thread_id"], 500);
|
||||||
|
assert_eq!(drafts[0]["can_stop"], true);
|
||||||
|
let drafts = h.wait_for_calls("sendMessageDraft", 2).await;
|
||||||
|
assert_eq!(drafts[1]["text"], "Sto leggendo i file del progetto.");
|
||||||
|
assert_eq!(drafts[1]["draft_id"], drafts[0]["draft_id"]);
|
||||||
|
tokio::time::sleep(Duration::from_millis(800)).await;
|
||||||
|
assert_eq!(h.calls("sendMessageDraft").await.len(), 2, "nothing new, no draft");
|
||||||
|
|
||||||
|
let draft_id = drafts[0]["draft_id"].clone();
|
||||||
|
h.push_update(json!({"stopped_message_generation": {
|
||||||
|
"chat": {"id": CHAT}, "message_thread_id": 500, "draft_id": draft_id}}));
|
||||||
|
let interrupt = h.expect_request("turn/interrupt").await;
|
||||||
|
assert_eq!(interrupt.params.unwrap()["threadId"], "t1");
|
||||||
|
|
||||||
|
h.notify("turn/completed", json!({"threadId": "t1", "turn": turn_json("turn-1", "interrupted")}));
|
||||||
|
let sends = h.wait_for_calls("sendMessage", 1).await;
|
||||||
|
assert!(sends[0]["text"].as_str().unwrap().starts_with("Turno interrotto."));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn no_emoji_in_any_outgoing_text() {
|
||||||
|
let mut h = Harness::start().await;
|
||||||
|
h.start_thread("t1", "/tmp/alfa");
|
||||||
|
for command in ["/aiuto", "/sessioni", "/impostazioni", "/nuova", "/stato", "/stop", "/boh"] {
|
||||||
|
h.push_update(text_message(CHAT, command, None));
|
||||||
|
}
|
||||||
|
let id = h.server_request("item/commandExecution/requestApproval", command_approval("t1"));
|
||||||
|
h.server_request(
|
||||||
|
"item/fileChange/requestApproval",
|
||||||
|
json!({"threadId": "t1", "turnId": "turn-1", "itemId": "item-2", "startedAtMs": 0,
|
||||||
|
"reason": "nuovo modulo"}),
|
||||||
|
);
|
||||||
|
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-1", "inProgress")}));
|
||||||
|
h.notify(
|
||||||
|
"turn/plan/updated",
|
||||||
|
json!({"threadId": "t1", "turnId": "turn-1", "explanation": null, "plan": [
|
||||||
|
{"step": "Leggere", "status": "completed"},
|
||||||
|
{"step": "Scrivere", "status": "inProgress"},
|
||||||
|
{"step": "Provare", "status": "pending"}]}),
|
||||||
|
);
|
||||||
|
h.notify(
|
||||||
|
"error",
|
||||||
|
json!({"threadId": "t1", "turnId": "turn-1", "willRetry": false,
|
||||||
|
"error": {"message": "Il modello ripete lo stesso comando", "codexErrorInfo": null}}),
|
||||||
|
);
|
||||||
|
h.notify(
|
||||||
|
"error",
|
||||||
|
json!({"threadId": "t1", "turnId": "turn-1", "willRetry": false,
|
||||||
|
"error": {"message": "HTTP 429", "codexErrorInfo": null}}),
|
||||||
|
);
|
||||||
|
let sends = h.wait_for_calls("sendMessage", 10).await;
|
||||||
|
let approval = sends
|
||||||
|
.iter()
|
||||||
|
.find(|send| send["text"].as_str().unwrap_or_default().contains("rm -rf build"))
|
||||||
|
.expect("approval sent")
|
||||||
|
.clone();
|
||||||
|
h.push_update(callback(CHAT, &button(&approval, "Rifiuta")));
|
||||||
|
let response = next_response(&mut h).await;
|
||||||
|
assert_eq!(response.id, id);
|
||||||
|
h.push_update(text_message(CHAT, "ciao", None));
|
||||||
|
let steer = h.expect_request("turn/steer").await;
|
||||||
|
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());
|
||||||
|
}
|
||||||
@@ -34,6 +34,7 @@ akode-app-server-daemon = { workspace = true }
|
|||||||
akode-app-server-protocol = { workspace = true }
|
akode-app-server-protocol = { workspace = true }
|
||||||
akode-arg0 = { workspace = true }
|
akode-arg0 = { workspace = true }
|
||||||
akode-install-context = { workspace = true }
|
akode-install-context = { workspace = true }
|
||||||
|
akode-telegram = { workspace = true }
|
||||||
akode-update = { workspace = true }
|
akode-update = { workspace = true }
|
||||||
akode-config = { workspace = true }
|
akode-config = { workspace = true }
|
||||||
akode-context-fragments = { workspace = true }
|
akode-context-fragments = { workspace = true }
|
||||||
|
|||||||
@@ -3397,6 +3397,13 @@ impl App {
|
|||||||
AppEvent::OpenEndpointPanel => {
|
AppEvent::OpenEndpointPanel => {
|
||||||
self.run_endpoint_panel(tui, app_server).await;
|
self.run_endpoint_panel(tui, app_server).await;
|
||||||
}
|
}
|
||||||
|
AppEvent::OpenTelegramPanel => {
|
||||||
|
let codex_home = self.config.codex_home.to_path_buf();
|
||||||
|
if let Err(err) = crate::telegram_panel::run_telegram_panel(tui, codex_home).await {
|
||||||
|
self.chat_widget
|
||||||
|
.add_error_message(format!("Pannello Telegram non disponibile: {err}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
AppEvent::OpenProviderModels { provider_id } => {
|
AppEvent::OpenProviderModels { provider_id } => {
|
||||||
self.open_provider_models(provider_id);
|
self.open_provider_models(provider_id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1644,6 +1644,9 @@ pub(crate) enum AppEvent {
|
|||||||
/// Open the endpoint, model and per-model settings panel (`/endpoint`).
|
/// Open the endpoint, model and per-model settings panel (`/endpoint`).
|
||||||
OpenEndpointPanel,
|
OpenEndpointPanel,
|
||||||
|
|
||||||
|
/// Open the Telegram bot setup panel (`/telegram`).
|
||||||
|
OpenTelegramPanel,
|
||||||
|
|
||||||
/// List the models of another configured provider for `/model`.
|
/// List the models of another configured provider for `/model`.
|
||||||
OpenProviderModels {
|
OpenProviderModels {
|
||||||
provider_id: String,
|
provider_id: String,
|
||||||
|
|||||||
@@ -554,6 +554,7 @@ fn parent_owned_command_is_allowed(command: SlashCommand, args: &str) -> bool {
|
|||||||
| SlashCommand::Theme
|
| SlashCommand::Theme
|
||||||
| SlashCommand::Setup
|
| SlashCommand::Setup
|
||||||
| SlashCommand::Endpoint
|
| SlashCommand::Endpoint
|
||||||
|
| SlashCommand::Telegram
|
||||||
| SlashCommand::Pets
|
| SlashCommand::Pets
|
||||||
| SlashCommand::Ps
|
| SlashCommand::Ps
|
||||||
| SlashCommand::Stop
|
| SlashCommand::Stop
|
||||||
|
|||||||
@@ -36,7 +36,8 @@ impl ChatWidget {
|
|||||||
| SlashCommand::Statusline
|
| SlashCommand::Statusline
|
||||||
| SlashCommand::Theme
|
| SlashCommand::Theme
|
||||||
| SlashCommand::Setup
|
| SlashCommand::Setup
|
||||||
| SlashCommand::Endpoint,
|
| SlashCommand::Endpoint
|
||||||
|
| SlashCommand::Telegram,
|
||||||
) => false,
|
) => false,
|
||||||
InputResult::Command(_)
|
InputResult::Command(_)
|
||||||
| InputResult::ServiceTierCommand(_)
|
| InputResult::ServiceTierCommand(_)
|
||||||
|
|||||||
@@ -550,6 +550,9 @@ impl ChatWidget {
|
|||||||
SlashCommand::Endpoint => {
|
SlashCommand::Endpoint => {
|
||||||
self.app_event_tx.send(AppEvent::OpenEndpointPanel);
|
self.app_event_tx.send(AppEvent::OpenEndpointPanel);
|
||||||
}
|
}
|
||||||
|
SlashCommand::Telegram => {
|
||||||
|
self.app_event_tx.send(AppEvent::OpenTelegramPanel);
|
||||||
|
}
|
||||||
SlashCommand::Pets => {
|
SlashCommand::Pets => {
|
||||||
self.open_pets_picker();
|
self.open_pets_picker();
|
||||||
}
|
}
|
||||||
@@ -1297,6 +1300,7 @@ impl ChatWidget {
|
|||||||
| SlashCommand::Theme
|
| SlashCommand::Theme
|
||||||
| SlashCommand::Setup
|
| SlashCommand::Setup
|
||||||
| SlashCommand::Endpoint
|
| SlashCommand::Endpoint
|
||||||
|
| SlashCommand::Telegram
|
||||||
| SlashCommand::Tui
|
| SlashCommand::Tui
|
||||||
| SlashCommand::Pets => QueueDrain::Stop,
|
| SlashCommand::Pets => QueueDrain::Stop,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -165,6 +165,7 @@ mod local_settings;
|
|||||||
mod rendered_selection;
|
mod rendered_selection;
|
||||||
pub use live_wrap::RowBuilder;
|
pub use live_wrap::RowBuilder;
|
||||||
mod endpoint_panel;
|
mod endpoint_panel;
|
||||||
|
mod telegram_panel;
|
||||||
mod managed_new_thread_defaults;
|
mod managed_new_thread_defaults;
|
||||||
mod markdown;
|
mod markdown;
|
||||||
mod markdown_render;
|
mod markdown_render;
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ pub enum SlashCommand {
|
|||||||
Theme,
|
Theme,
|
||||||
Setup,
|
Setup,
|
||||||
Endpoint,
|
Endpoint,
|
||||||
|
Telegram,
|
||||||
#[strum(to_string = "pets", serialize = "pet")]
|
#[strum(to_string = "pets", serialize = "pet")]
|
||||||
Pets,
|
Pets,
|
||||||
Mcp,
|
Mcp,
|
||||||
@@ -125,6 +126,7 @@ impl SlashCommand {
|
|||||||
SlashCommand::Theme => "choose the interface palette or syntax highlighting theme",
|
SlashCommand::Theme => "choose the interface palette or syntax highlighting theme",
|
||||||
SlashCommand::Setup => "add a model provider with the guided setup",
|
SlashCommand::Setup => "add a model provider with the guided setup",
|
||||||
SlashCommand::Endpoint => "gestisci endpoint, modelli e parametri",
|
SlashCommand::Endpoint => "gestisci endpoint, modelli e parametri",
|
||||||
|
SlashCommand::Telegram => "controlla le sessioni dal bot Telegram",
|
||||||
SlashCommand::Pets => "choose or hide the terminal pet",
|
SlashCommand::Pets => "choose or hide the terminal pet",
|
||||||
SlashCommand::Ps => "list background terminals",
|
SlashCommand::Ps => "list background terminals",
|
||||||
SlashCommand::Stop => "stop all background terminals",
|
SlashCommand::Stop => "stop all background terminals",
|
||||||
@@ -302,6 +304,7 @@ impl SlashCommand {
|
|||||||
| SlashCommand::Theme
|
| SlashCommand::Theme
|
||||||
| SlashCommand::Setup
|
| SlashCommand::Setup
|
||||||
| SlashCommand::Endpoint
|
| SlashCommand::Endpoint
|
||||||
|
| SlashCommand::Telegram
|
||||||
| SlashCommand::Pets => false,
|
| SlashCommand::Pets => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/telegram_panel_tests.rs
|
||||||
|
expression: "render(&panel, width, 16)"
|
||||||
|
---
|
||||||
|
Telegram · abbinamento esc chiudi
|
||||||
|
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
Invia questo codice al bot da Telegram:
|
||||||
|
|
||||||
|
482 913
|
||||||
|
|
||||||
|
In attesa del messaggio… il codice scade fra 10 minuti.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
esc annulla
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/telegram_panel_tests.rs
|
||||||
|
assertion_line: 78
|
||||||
|
expression: "render(&panel, width, 16)"
|
||||||
|
---
|
||||||
|
Telegram · abbinamento esc chiudi
|
||||||
|
────────────────────────────────────────────────────────────────────────────
|
||||||
|
Invia questo codice al bot da Telegram:
|
||||||
|
|
||||||
|
482 913
|
||||||
|
|
||||||
|
In attesa del messaggio… il codice scade fra 10 minuti.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────
|
||||||
|
esc annulla
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/telegram_panel_tests.rs
|
||||||
|
assertion_line: 47
|
||||||
|
expression: "render(&panel, width, 16)"
|
||||||
|
---
|
||||||
|
Telegram esc chiudi
|
||||||
|
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
Bot @akode_bot
|
||||||
|
Stato attivo · connesso
|
||||||
|
Chat 123456789
|
||||||
|
Notifiche approvazioni · fine turno · errori · loop
|
||||||
|
Opzioni streaming sì · reazioni sì
|
||||||
|
Topic non attivi: @BotFather › il bot › Bot Settings › Threaded Mode
|
||||||
|
|
||||||
|
› Cambia il token del bot
|
||||||
|
Abbina una chat
|
||||||
|
Disattiva
|
||||||
|
Rimuovi il token
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
↑↓ scegli · invio conferma · esc chiudi
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/telegram_panel_tests.rs
|
||||||
|
assertion_line: 47
|
||||||
|
expression: "render(&panel, width, 16)"
|
||||||
|
---
|
||||||
|
Telegram esc chiudi
|
||||||
|
────────────────────────────────────────────────────────────────────────────
|
||||||
|
Bot @akode_bot
|
||||||
|
Stato attivo · connesso
|
||||||
|
Chat 123456789
|
||||||
|
Notifiche approvazioni · fine turno · errori · loop
|
||||||
|
Opzioni streaming sì · reazioni sì
|
||||||
|
Topic non attivi: @BotFather › il bot › Bot Settings › Threaded Mode
|
||||||
|
|
||||||
|
› Cambia il token del bot
|
||||||
|
Abbina una chat
|
||||||
|
Disattiva
|
||||||
|
Rimuovi il token
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────
|
||||||
|
↑↓ scegli · invio conferma · esc chiudi
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/telegram_panel_tests.rs
|
||||||
|
expression: text
|
||||||
|
---
|
||||||
|
Telegram · token del bot esc chiudi
|
||||||
|
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
Incolla il token che @BotFather ti ha dato per il bot.
|
||||||
|
|
||||||
|
Token •••••••••••••••••••••• (22 caratteri)
|
||||||
|
|
||||||
|
Il token resta nell'archivio delle chiavi, mai in config.toml.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
invio verifica e salva · esc indietro
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/telegram_panel_tests.rs
|
||||||
|
expression: text
|
||||||
|
---
|
||||||
|
Telegram · token del bot esc chiudi
|
||||||
|
────────────────────────────────────────────────────────────────────────────
|
||||||
|
Incolla il token che @BotFather ti ha dato per il bot.
|
||||||
|
|
||||||
|
Token •••••••••••••••••••••• (22 caratteri)
|
||||||
|
|
||||||
|
Il token resta nell'archivio delle chiavi, mai in config.toml.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────
|
||||||
|
invio verifica e salva · esc indietro
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/telegram_panel_tests.rs
|
||||||
|
assertion_line: 55
|
||||||
|
expression: "render(&panel, width, 16)"
|
||||||
|
---
|
||||||
|
Telegram esc chiudi
|
||||||
|
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
Bot non configurato
|
||||||
|
Stato disattivato
|
||||||
|
Chat nessuna abbinata
|
||||||
|
Notifiche approvazioni · fine turno · errori · loop
|
||||||
|
Opzioni streaming sì · reazioni sì
|
||||||
|
Topic da verificare (si vede col bot attivo)
|
||||||
|
|
||||||
|
› Imposta il token del bot
|
||||||
|
Abbina una chat
|
||||||
|
Attiva
|
||||||
|
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
↑↓ scegli · invio conferma · esc chiudi
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/telegram_panel_tests.rs
|
||||||
|
assertion_line: 55
|
||||||
|
expression: "render(&panel, width, 16)"
|
||||||
|
---
|
||||||
|
Telegram esc chiudi
|
||||||
|
────────────────────────────────────────────────────────────────────────────
|
||||||
|
Bot non configurato
|
||||||
|
Stato disattivato
|
||||||
|
Chat nessuna abbinata
|
||||||
|
Notifiche approvazioni · fine turno · errori · loop
|
||||||
|
Opzioni streaming sì · reazioni sì
|
||||||
|
Topic da verificare (si vede col bot attivo)
|
||||||
|
|
||||||
|
› Imposta il token del bot
|
||||||
|
Abbina una chat
|
||||||
|
Attiva
|
||||||
|
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────
|
||||||
|
↑↓ scegli · invio conferma · esc chiudi
|
||||||
646
akode-rs/tui/src/telegram_panel.rs
Normal file
646
akode-rs/tui/src/telegram_panel.rs
Normal file
@@ -0,0 +1,646 @@
|
|||||||
|
//! `/telegram`: bot token, chat pairing, enable/disable and status.
|
||||||
|
//!
|
||||||
|
//! The bridge itself runs in the app-server (see `akode_telegram`); this screen only edits
|
||||||
|
//! `[telegram]` in config.toml and the token in the key store. It contacts Telegram only
|
||||||
|
//! when the user verifies a token (`getMe`) or pairs a chat.
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::Duration;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use akode_telegram::api::TelegramApi;
|
||||||
|
use akode_telegram::lock::PollLock;
|
||||||
|
use akode_telegram::pairing;
|
||||||
|
use akode_telegram::settings;
|
||||||
|
use akode_telegram::settings::TelegramSettings;
|
||||||
|
use crossterm::event::KeyCode;
|
||||||
|
use crossterm::event::KeyEvent;
|
||||||
|
use crossterm::event::KeyEventKind;
|
||||||
|
use crossterm::event::KeyModifiers;
|
||||||
|
use futures::StreamExt;
|
||||||
|
use futures::future::LocalBoxFuture;
|
||||||
|
use futures::stream::FuturesUnordered;
|
||||||
|
use ratatui::buffer::Buffer;
|
||||||
|
use ratatui::layout::Rect;
|
||||||
|
use ratatui::style::Style;
|
||||||
|
use ratatui::style::Stylize;
|
||||||
|
use ratatui::text::Line;
|
||||||
|
use ratatui::text::Span;
|
||||||
|
use ratatui::widgets::Widget;
|
||||||
|
use ratatui::widgets::WidgetRef;
|
||||||
|
|
||||||
|
use crate::style::StatusTone;
|
||||||
|
use crate::style::accent_color;
|
||||||
|
use crate::style::status_style;
|
||||||
|
use crate::tui::FrameRequester;
|
||||||
|
use crate::ui_theme::truncate_line;
|
||||||
|
use crate::width::display_width;
|
||||||
|
|
||||||
|
const INDENT: u16 = 2;
|
||||||
|
const LABEL_WIDTH: usize = 12;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
enum Mode {
|
||||||
|
Menu,
|
||||||
|
Token(String),
|
||||||
|
Pairing(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Action {
|
||||||
|
Token,
|
||||||
|
Pair,
|
||||||
|
Toggle,
|
||||||
|
Remove,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Event {
|
||||||
|
TokenChecked(Result<(String, String), String>),
|
||||||
|
Paired(Result<i64, String>),
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Notice {
|
||||||
|
Ok(String),
|
||||||
|
Error(String),
|
||||||
|
Info(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the screen shows, read from disk (or set by tests).
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub(crate) struct TelegramStatus {
|
||||||
|
pub(crate) settings: TelegramSettings,
|
||||||
|
pub(crate) has_token: bool,
|
||||||
|
pub(crate) bot_name: Option<String>,
|
||||||
|
pub(crate) connected: bool,
|
||||||
|
/// Topics in private chats, as the bridge last saw them (`None`: not checked yet).
|
||||||
|
pub(crate) topics: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TelegramStatus {
|
||||||
|
fn load(codex_home: &std::path::Path) -> Self {
|
||||||
|
let settings = TelegramSettings::load(codex_home);
|
||||||
|
let has_token = settings::load_token(codex_home, settings.key_store).is_some();
|
||||||
|
// A held poll lock means a bridge is polling right now.
|
||||||
|
let connected = settings.enabled && has_token && PollLock::try_acquire(codex_home).is_none();
|
||||||
|
Self {
|
||||||
|
bot_name: settings::load_bot_name(codex_home),
|
||||||
|
topics: settings::load_bot_topics(codex_home),
|
||||||
|
settings,
|
||||||
|
has_token,
|
||||||
|
connected,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct TelegramPanel {
|
||||||
|
request_frame: FrameRequester,
|
||||||
|
codex_home: PathBuf,
|
||||||
|
status: TelegramStatus,
|
||||||
|
selected: usize,
|
||||||
|
mode: Mode,
|
||||||
|
notice: Option<Notice>,
|
||||||
|
tasks: FuturesUnordered<LocalBoxFuture<'static, Event>>,
|
||||||
|
done: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TelegramPanel {
|
||||||
|
pub(crate) fn new(
|
||||||
|
request_frame: FrameRequester,
|
||||||
|
codex_home: PathBuf,
|
||||||
|
status: TelegramStatus,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
request_frame,
|
||||||
|
codex_home,
|
||||||
|
status,
|
||||||
|
selected: 0,
|
||||||
|
mode: Mode::Menu,
|
||||||
|
notice: None,
|
||||||
|
tasks: FuturesUnordered::new(),
|
||||||
|
done: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn is_done(&self) -> bool {
|
||||||
|
self.done
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh(&mut self) {
|
||||||
|
self.status = TelegramStatus::load(&self.codex_home);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actions(&self) -> Vec<(Action, &'static str)> {
|
||||||
|
let mut actions = vec![
|
||||||
|
(
|
||||||
|
Action::Token,
|
||||||
|
if self.status.has_token {
|
||||||
|
"Cambia il token del bot"
|
||||||
|
} else {
|
||||||
|
"Imposta il token del bot"
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(Action::Pair, "Abbina una chat"),
|
||||||
|
(
|
||||||
|
Action::Toggle,
|
||||||
|
if self.status.settings.enabled {
|
||||||
|
"Disattiva"
|
||||||
|
} else {
|
||||||
|
"Attiva"
|
||||||
|
},
|
||||||
|
),
|
||||||
|
];
|
||||||
|
if self.status.has_token {
|
||||||
|
actions.push((Action::Remove, "Rimuovi il token"));
|
||||||
|
}
|
||||||
|
actions
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn advance(&mut self) {
|
||||||
|
let event = if self.tasks.is_empty() {
|
||||||
|
std::future::pending::<Option<Event>>().await
|
||||||
|
} else {
|
||||||
|
self.tasks.next().await
|
||||||
|
};
|
||||||
|
let Some(event) = event else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match event {
|
||||||
|
Event::TokenChecked(Ok((token, username))) => {
|
||||||
|
let mode = self.status.settings.key_store;
|
||||||
|
match settings::save_token(&self.codex_home, mode, &token) {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = settings::save_bot_name(&self.codex_home, &username);
|
||||||
|
self.notice = Some(Notice::Ok(format!(
|
||||||
|
"Token verificato: bot @{username}. Ora abbina una chat."
|
||||||
|
)));
|
||||||
|
self.mode = Mode::Menu;
|
||||||
|
self.selected = 1;
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
self.notice =
|
||||||
|
Some(Notice::Error(format!("Impossibile salvare il token: {err}")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::TokenChecked(Err(err)) => {
|
||||||
|
self.notice = Some(Notice::Error(format!("Token non valido: {err}")));
|
||||||
|
}
|
||||||
|
Event::Paired(Ok(chat_id)) => {
|
||||||
|
self.mode = Mode::Menu;
|
||||||
|
self.notice = Some(Notice::Ok(format!("Chat {chat_id} abbinata.")));
|
||||||
|
self.selected = 2;
|
||||||
|
}
|
||||||
|
Event::Paired(Err(err)) => {
|
||||||
|
self.mode = Mode::Menu;
|
||||||
|
pairing::cancel(&self.codex_home);
|
||||||
|
self.notice = Some(Notice::Error(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.refresh();
|
||||||
|
self.request_frame.schedule_frame();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn activate(&mut self, action: Action) {
|
||||||
|
self.notice = None;
|
||||||
|
match action {
|
||||||
|
Action::Token => self.mode = Mode::Token(String::new()),
|
||||||
|
Action::Pair => self.start_pairing(),
|
||||||
|
Action::Toggle => {
|
||||||
|
let enable = !self.status.settings.enabled;
|
||||||
|
if enable && !self.status.has_token {
|
||||||
|
self.notice = Some(Notice::Error("Prima imposta il token del bot.".into()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if enable && self.status.settings.allowed_chat_ids.is_empty() {
|
||||||
|
self.notice = Some(Notice::Error("Prima abbina almeno una chat.".into()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match settings::set_enabled(&self.codex_home, enable) {
|
||||||
|
Ok(()) => {
|
||||||
|
self.notice = Some(Notice::Ok(if enable {
|
||||||
|
"Attivato: le sessioni rispondono su Telegram entro pochi secondi."
|
||||||
|
.to_string()
|
||||||
|
} else {
|
||||||
|
"Disattivato: nessun contatto con Telegram.".to_string()
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
self.notice =
|
||||||
|
Some(Notice::Error(format!("Impossibile scrivere config.toml: {err}")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::Remove => {
|
||||||
|
let mode = self.status.settings.key_store;
|
||||||
|
let result = settings::delete_token(&self.codex_home, mode)
|
||||||
|
.map_err(|err| err.to_string())
|
||||||
|
.and_then(|()| {
|
||||||
|
settings::set_enabled(&self.codex_home, false).map_err(|e| e.to_string())
|
||||||
|
});
|
||||||
|
settings::forget_bot_name(&self.codex_home);
|
||||||
|
self.notice = Some(match result {
|
||||||
|
Ok(()) => Notice::Ok("Token rimosso, bot disattivato.".to_string()),
|
||||||
|
Err(err) => Notice::Error(format!("Rimozione non riuscita: {err}")),
|
||||||
|
});
|
||||||
|
self.selected = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_pairing(&mut self) {
|
||||||
|
let Some(token) =
|
||||||
|
settings::load_token(&self.codex_home, self.status.settings.key_store)
|
||||||
|
else {
|
||||||
|
self.notice = Some(Notice::Error("Prima imposta il token del bot.".into()));
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let code = match pairing::start(&self.codex_home) {
|
||||||
|
Ok(code) => code,
|
||||||
|
Err(err) => {
|
||||||
|
self.notice = Some(Notice::Error(format!("Abbinamento non avviato: {err}")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.mode = Mode::Pairing(code);
|
||||||
|
let home = self.codex_home.clone();
|
||||||
|
let before = self.status.settings.allowed_chat_ids.clone();
|
||||||
|
self.tasks.push(Box::pin(async move {
|
||||||
|
Event::Paired(wait_for_pairing(home, token, before).await)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn submit_token(&mut self, token: String) {
|
||||||
|
let token = token.trim().to_string();
|
||||||
|
if token.is_empty() {
|
||||||
|
self.notice = Some(Notice::Error("Incolla il token di @BotFather.".into()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.notice = Some(Notice::Info("Verifica del token con Telegram…".into()));
|
||||||
|
self.tasks.push(Box::pin(async move {
|
||||||
|
let api = TelegramApi::new(&token);
|
||||||
|
Event::TokenChecked(match api.get_me().await {
|
||||||
|
Ok(user) => Ok((token, user.username.unwrap_or(user.first_name))),
|
||||||
|
Err(err) => Err(err.to_string()),
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_key_event(&mut self, key: KeyEvent) {
|
||||||
|
if key.kind == KeyEventKind::Release {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
|
||||||
|
self.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match &mut self.mode {
|
||||||
|
Mode::Menu => match key.code {
|
||||||
|
KeyCode::Esc | KeyCode::Char('q') => self.close(),
|
||||||
|
KeyCode::Up | KeyCode::Char('k') => {
|
||||||
|
self.selected = self.selected.saturating_sub(1);
|
||||||
|
}
|
||||||
|
KeyCode::Down | KeyCode::Char('j') => {
|
||||||
|
self.selected = (self.selected + 1).min(self.actions().len() - 1);
|
||||||
|
}
|
||||||
|
KeyCode::Enter => {
|
||||||
|
if let Some((action, _)) = self.actions().get(self.selected).copied() {
|
||||||
|
self.activate(action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
},
|
||||||
|
Mode::Token(input) => match key.code {
|
||||||
|
KeyCode::Esc => {
|
||||||
|
self.mode = Mode::Menu;
|
||||||
|
self.notice = None;
|
||||||
|
}
|
||||||
|
KeyCode::Backspace => {
|
||||||
|
input.pop();
|
||||||
|
}
|
||||||
|
KeyCode::Enter => {
|
||||||
|
let token = input.clone();
|
||||||
|
self.submit_token(token);
|
||||||
|
}
|
||||||
|
KeyCode::Char(c) if !c.is_control() => input.push(c),
|
||||||
|
_ => {}
|
||||||
|
},
|
||||||
|
Mode::Pairing(_) => {
|
||||||
|
if key.code == KeyCode::Esc {
|
||||||
|
self.tasks = FuturesUnordered::new();
|
||||||
|
pairing::cancel(&self.codex_home);
|
||||||
|
self.mode = Mode::Menu;
|
||||||
|
self.notice = Some(Notice::Info("Abbinamento annullato.".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.request_frame.schedule_frame();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_paste(&mut self, pasted: String) {
|
||||||
|
if let Mode::Token(input) = &mut self.mode {
|
||||||
|
input.extend(pasted.trim().chars().filter(|c| !c.is_control()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close(&mut self) {
|
||||||
|
if matches!(self.mode, Mode::Pairing(_)) {
|
||||||
|
pairing::cancel(&self.codex_home);
|
||||||
|
}
|
||||||
|
self.tasks = FuturesUnordered::new();
|
||||||
|
self.done = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body_lines(&self, width: usize) -> Vec<Line<'static>> {
|
||||||
|
let accent = Style::default().fg(accent_color());
|
||||||
|
let field = |label: &str, value: Span<'static>| -> Line<'static> {
|
||||||
|
let label = format!("{label:<LABEL_WIDTH$}");
|
||||||
|
truncate_line(Line::from(vec![label.dim(), value]), width)
|
||||||
|
};
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
match &self.mode {
|
||||||
|
Mode::Menu => {
|
||||||
|
let status = &self.status;
|
||||||
|
lines.push(field(
|
||||||
|
"Bot",
|
||||||
|
match (&status.bot_name, status.has_token) {
|
||||||
|
(Some(name), true) => Span::from(format!("@{name}")),
|
||||||
|
(None, true) => Span::from("token salvato"),
|
||||||
|
_ => "non configurato".dim(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
lines.push(field(
|
||||||
|
"Stato",
|
||||||
|
if !status.settings.enabled {
|
||||||
|
"disattivato".dim()
|
||||||
|
} else if status.connected {
|
||||||
|
Span::styled("attivo · connesso", status_style(StatusTone::Success))
|
||||||
|
} else {
|
||||||
|
Span::styled(
|
||||||
|
"attivo · non connesso (parte con la prima sessione)",
|
||||||
|
status_style(StatusTone::Attention),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
));
|
||||||
|
let chats = &status.settings.allowed_chat_ids;
|
||||||
|
lines.push(field(
|
||||||
|
"Chat",
|
||||||
|
if chats.is_empty() {
|
||||||
|
"nessuna abbinata".dim()
|
||||||
|
} else {
|
||||||
|
Span::from(
|
||||||
|
chats
|
||||||
|
.iter()
|
||||||
|
.map(ToString::to_string)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", "),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
));
|
||||||
|
let notify = status.settings.notify;
|
||||||
|
let levels: Vec<&str> = [
|
||||||
|
(notify.approvals, "approvazioni"),
|
||||||
|
(notify.turn_end, "fine turno"),
|
||||||
|
(notify.errors, "errori"),
|
||||||
|
(notify.loops, "loop"),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(on, name)| on.then_some(name))
|
||||||
|
.collect();
|
||||||
|
lines.push(field(
|
||||||
|
"Notifiche",
|
||||||
|
if levels.is_empty() {
|
||||||
|
"nessuna".dim()
|
||||||
|
} else {
|
||||||
|
Span::from(levels.join(" · "))
|
||||||
|
},
|
||||||
|
));
|
||||||
|
lines.push(field(
|
||||||
|
"Opzioni",
|
||||||
|
Span::from(format!(
|
||||||
|
"streaming {} · reazioni {}",
|
||||||
|
if status.settings.streaming { "sì" } else { "no" },
|
||||||
|
if status.settings.reactions { "sì" } else { "no" },
|
||||||
|
)),
|
||||||
|
));
|
||||||
|
lines.push(field(
|
||||||
|
"Topic",
|
||||||
|
match status.topics {
|
||||||
|
Some(true) => Span::from("uno per sessione"),
|
||||||
|
Some(false) => Span::styled(
|
||||||
|
"non attivi: @BotFather › il bot › Bot Settings › Threaded Mode",
|
||||||
|
status_style(StatusTone::Attention),
|
||||||
|
),
|
||||||
|
None => "da verificare (si vede col bot attivo)".dim(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
lines.push(Line::from(""));
|
||||||
|
for (index, (_, label)) in self.actions().into_iter().enumerate() {
|
||||||
|
let line = if index == self.selected {
|
||||||
|
Line::from(vec![Span::styled("› ", accent), Span::styled(label, accent.bold())])
|
||||||
|
} else {
|
||||||
|
Line::from(vec![" ".into(), label.into()])
|
||||||
|
};
|
||||||
|
lines.push(truncate_line(line, width));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Mode::Token(input) => {
|
||||||
|
lines.push(truncate_line(
|
||||||
|
Line::from("Incolla il token che @BotFather ti ha dato per il bot."),
|
||||||
|
width,
|
||||||
|
));
|
||||||
|
lines.push(Line::from(""));
|
||||||
|
let shown = if input.is_empty() {
|
||||||
|
"▏".dim()
|
||||||
|
} else {
|
||||||
|
Span::from(format!(
|
||||||
|
"{} ({} caratteri)",
|
||||||
|
"•".repeat(input.chars().count().min(24)),
|
||||||
|
input.chars().count()
|
||||||
|
))
|
||||||
|
};
|
||||||
|
lines.push(field("Token", shown));
|
||||||
|
lines.push(Line::from(""));
|
||||||
|
lines.push(truncate_line(
|
||||||
|
"Il token resta nell'archivio delle chiavi, mai in config.toml."
|
||||||
|
.dim()
|
||||||
|
.into(),
|
||||||
|
width,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Mode::Pairing(code) => {
|
||||||
|
lines.push(truncate_line(
|
||||||
|
Line::from("Invia questo codice al bot da Telegram:"),
|
||||||
|
width,
|
||||||
|
));
|
||||||
|
lines.push(Line::from(""));
|
||||||
|
let spaced = format!("{} {}", &code[..3], &code[3..]);
|
||||||
|
lines.push(Line::from(vec![
|
||||||
|
" ".into(),
|
||||||
|
Span::styled(spaced, accent.bold()),
|
||||||
|
]));
|
||||||
|
lines.push(Line::from(""));
|
||||||
|
lines.push(truncate_line(
|
||||||
|
"In attesa del messaggio… il codice scade fra 10 minuti."
|
||||||
|
.dim()
|
||||||
|
.into(),
|
||||||
|
width,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hints(&self) -> Vec<(&'static str, &'static str)> {
|
||||||
|
match self.mode {
|
||||||
|
Mode::Menu => vec![("↑↓", "scegli"), ("invio", "conferma"), ("esc", "chiudi")],
|
||||||
|
Mode::Token(_) => vec![("invio", "verifica e salva"), ("esc", "indietro")],
|
||||||
|
Mode::Pairing(_) => vec![("esc", "annulla")],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Waits until the code arrives: polls Telegram itself while no bridge holds the poll lock,
|
||||||
|
/// otherwise lets the running bridge accept it and watches the config.
|
||||||
|
async fn wait_for_pairing(
|
||||||
|
home: PathBuf,
|
||||||
|
token: String,
|
||||||
|
before: Vec<i64>,
|
||||||
|
) -> Result<i64, String> {
|
||||||
|
let api = TelegramApi::new(&token);
|
||||||
|
let deadline = Instant::now() + pairing::PAIRING_TTL;
|
||||||
|
let mut offset = None;
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
let now = TelegramSettings::load(&home);
|
||||||
|
if let Some(id) = now.allowed_chat_ids.iter().find(|id| !before.contains(id)) {
|
||||||
|
return Ok(*id);
|
||||||
|
}
|
||||||
|
if pairing::pending_code(&home).is_none() {
|
||||||
|
return Err("Codice scaduto o troppi tentativi errati: riprova.".to_string());
|
||||||
|
}
|
||||||
|
match PollLock::try_acquire(&home) {
|
||||||
|
Some(_lock) => match pairing::poll_once(&api, &home, &mut offset, 2).await {
|
||||||
|
Ok(Some(id)) => return Ok(id),
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(err) if err.is_unauthorized() => return Err(err.to_string()),
|
||||||
|
Err(_) => tokio::time::sleep(Duration::from_secs(2)).await,
|
||||||
|
},
|
||||||
|
None => tokio::time::sleep(Duration::from_secs(1)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err("Codice scaduto: riprova.".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hint_line(parts: &[(&str, &str)], width: usize) -> Line<'static> {
|
||||||
|
let mut spans: Vec<Span<'static>> = Vec::new();
|
||||||
|
for (index, (key, action)) in parts.iter().enumerate() {
|
||||||
|
if index > 0 {
|
||||||
|
spans.push(" · ".dim());
|
||||||
|
}
|
||||||
|
spans.push(Span::from((*key).to_string()));
|
||||||
|
spans.push(format!(" {action}").dim());
|
||||||
|
}
|
||||||
|
truncate_line(Line::from(spans), width)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WidgetRef for &TelegramPanel {
|
||||||
|
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
|
||||||
|
if area.width <= 2 * INDENT + 10 || area.height < 8 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let x = area.x + INDENT;
|
||||||
|
let width = area.width - 2 * INDENT;
|
||||||
|
let w = usize::from(width);
|
||||||
|
let bottom = area.y + area.height;
|
||||||
|
let put = |line: Line<'static>, y: u16, buf: &mut Buffer| {
|
||||||
|
if y < bottom {
|
||||||
|
line.render(Rect::new(x, y, width, 1), buf);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let accent = Style::default().fg(accent_color());
|
||||||
|
let title = match self.mode {
|
||||||
|
Mode::Menu => "Telegram",
|
||||||
|
Mode::Token(_) => "Telegram · token del bot",
|
||||||
|
Mode::Pairing(_) => "Telegram · abbinamento",
|
||||||
|
};
|
||||||
|
let close = "esc chiudi";
|
||||||
|
let gap = w
|
||||||
|
.saturating_sub(display_width(title) + display_width(close))
|
||||||
|
.max(2);
|
||||||
|
put(
|
||||||
|
truncate_line(
|
||||||
|
Line::from(vec![
|
||||||
|
Span::styled(title, accent.bold()),
|
||||||
|
" ".repeat(gap).into(),
|
||||||
|
close.dim(),
|
||||||
|
]),
|
||||||
|
w,
|
||||||
|
),
|
||||||
|
area.y,
|
||||||
|
buf,
|
||||||
|
);
|
||||||
|
let rule = Line::from("─".repeat(w).dim());
|
||||||
|
put(rule.clone(), area.y + 1, buf);
|
||||||
|
let footer_top = bottom.saturating_sub(3);
|
||||||
|
let body_top = area.y + 2;
|
||||||
|
for (row, line) in self
|
||||||
|
.body_lines(w)
|
||||||
|
.into_iter()
|
||||||
|
.take(usize::from(footer_top.saturating_sub(body_top)))
|
||||||
|
.enumerate()
|
||||||
|
{
|
||||||
|
put(line, body_top + row as u16, buf);
|
||||||
|
}
|
||||||
|
let notice = match &self.notice {
|
||||||
|
Some(Notice::Ok(text)) => Span::styled(text.clone(), status_style(StatusTone::Success)),
|
||||||
|
Some(Notice::Error(text)) => {
|
||||||
|
Span::styled(text.clone(), status_style(StatusTone::Failure))
|
||||||
|
}
|
||||||
|
Some(Notice::Info(text)) => text.clone().dim(),
|
||||||
|
None => Span::from(""),
|
||||||
|
};
|
||||||
|
put(truncate_line(Line::from(notice), w), footer_top, buf);
|
||||||
|
put(rule, footer_top + 1, buf);
|
||||||
|
put(hint_line(&self.hints(), w), footer_top + 2, buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the panel full screen until it closes.
|
||||||
|
pub(crate) async fn run_telegram_panel(
|
||||||
|
tui: &mut crate::tui::Tui,
|
||||||
|
codex_home: PathBuf,
|
||||||
|
) -> color_eyre::eyre::Result<()> {
|
||||||
|
use crate::tui::TuiEvent;
|
||||||
|
let status = TelegramStatus::load(&codex_home);
|
||||||
|
let mut panel = TelegramPanel::new(tui.frame_requester(), codex_home, status);
|
||||||
|
tui.draw(u16::MAX, |frame| {
|
||||||
|
frame.render_widget_ref(&panel, frame.area());
|
||||||
|
})?;
|
||||||
|
tui.discard_pending_input_before_interactive_screen()?;
|
||||||
|
let events = tui.event_stream();
|
||||||
|
tokio::pin!(events);
|
||||||
|
while !panel.is_done() {
|
||||||
|
tokio::select! {
|
||||||
|
() = panel.advance() => {}
|
||||||
|
event = events.next() => {
|
||||||
|
let Some(event) = event else { break };
|
||||||
|
tui.screen_size_for_event(&event)?;
|
||||||
|
match event {
|
||||||
|
TuiEvent::Key(key) => panel.handle_key_event(key),
|
||||||
|
TuiEvent::Paste(text) => panel.handle_paste(text),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tui.draw(u16::MAX, |frame| {
|
||||||
|
frame.render_widget_ref(&panel, frame.area());
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
tui.terminal.clear()?;
|
||||||
|
tui.frame_requester().schedule_frame();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "telegram_panel_tests.rs"]
|
||||||
|
mod tests;
|
||||||
90
akode-rs/tui/src/telegram_panel_tests.rs
Normal file
90
akode-rs/tui/src/telegram_panel_tests.rs
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
use super::*;
|
||||||
|
use pretty_assertions::assert_eq;
|
||||||
|
|
||||||
|
fn status() -> TelegramStatus {
|
||||||
|
TelegramStatus {
|
||||||
|
settings: TelegramSettings {
|
||||||
|
enabled: true,
|
||||||
|
allowed_chat_ids: vec![123_456_789],
|
||||||
|
..TelegramSettings::default()
|
||||||
|
},
|
||||||
|
has_token: true,
|
||||||
|
bot_name: Some("akode_bot".to_string()),
|
||||||
|
connected: true,
|
||||||
|
topics: Some(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn panel(status: TelegramStatus) -> TelegramPanel {
|
||||||
|
let home = std::env::temp_dir().join("akode-telegram-panel-tests-unused");
|
||||||
|
TelegramPanel::new(FrameRequester::test_dummy(), home, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(panel: &TelegramPanel, width: u16, height: u16) -> String {
|
||||||
|
let area = Rect::new(0, 0, width, height);
|
||||||
|
let mut buf = Buffer::empty(area);
|
||||||
|
panel.render_ref(area, &mut buf);
|
||||||
|
(0..height)
|
||||||
|
.map(|y| {
|
||||||
|
(0..width)
|
||||||
|
.map(|x| buf[(x, y)].symbol().to_string())
|
||||||
|
.collect::<String>()
|
||||||
|
.trim_end()
|
||||||
|
.to_string()
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key(code: KeyCode) -> KeyEvent {
|
||||||
|
KeyEvent::new(code, KeyModifiers::NONE)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn telegram_panel_status_snapshots() {
|
||||||
|
let panel = panel(status());
|
||||||
|
for width in [80, 120] {
|
||||||
|
insta::assert_snapshot!(format!("telegram_panel_status_{width}"), render(&panel, width, 16));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn telegram_panel_unconfigured_snapshots() {
|
||||||
|
let panel = panel(TelegramStatus::default());
|
||||||
|
for width in [80, 120] {
|
||||||
|
insta::assert_snapshot!(
|
||||||
|
format!("telegram_panel_unconfigured_{width}"),
|
||||||
|
render(&panel, width, 16)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn telegram_panel_token_is_masked() {
|
||||||
|
let mut panel = panel(TelegramStatus::default());
|
||||||
|
panel.handle_key_event(key(KeyCode::Enter));
|
||||||
|
panel.handle_paste("123456:SEGRETO-del-bot".to_string());
|
||||||
|
for width in [80, 120] {
|
||||||
|
let text = render(&panel, width, 16);
|
||||||
|
assert!(!text.contains("SEGRETO"), "{text}");
|
||||||
|
insta::assert_snapshot!(format!("telegram_panel_token_{width}"), text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn telegram_panel_pairing_snapshots() {
|
||||||
|
let mut panel = panel(status());
|
||||||
|
panel.mode = Mode::Pairing("482913".to_string());
|
||||||
|
for width in [80, 120] {
|
||||||
|
insta::assert_snapshot!(
|
||||||
|
format!("telegram_panel_pairing_{width}"),
|
||||||
|
render(&panel, width, 16)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn menu_offers_remove_only_with_a_token() {
|
||||||
|
assert_eq!(panel(TelegramStatus::default()).actions().len(), 3);
|
||||||
|
assert_eq!(panel(status()).actions().len(), 4);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user