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

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

View File

@@ -34,6 +34,7 @@ akode-app-server-daemon = { workspace = true }
akode-app-server-protocol = { workspace = true }
akode-arg0 = { workspace = true }
akode-install-context = { workspace = true }
akode-telegram = { workspace = true }
akode-update = { workspace = true }
akode-config = { workspace = true }
akode-context-fragments = { workspace = true }

View File

@@ -3397,6 +3397,13 @@ impl App {
AppEvent::OpenEndpointPanel => {
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 } => {
self.open_provider_models(provider_id);
}

View File

@@ -1644,6 +1644,9 @@ pub(crate) enum AppEvent {
/// Open the endpoint, model and per-model settings panel (`/endpoint`).
OpenEndpointPanel,
/// Open the Telegram bot setup panel (`/telegram`).
OpenTelegramPanel,
/// List the models of another configured provider for `/model`.
OpenProviderModels {
provider_id: String,

View File

@@ -554,6 +554,7 @@ fn parent_owned_command_is_allowed(command: SlashCommand, args: &str) -> bool {
| SlashCommand::Theme
| SlashCommand::Setup
| SlashCommand::Endpoint
| SlashCommand::Telegram
| SlashCommand::Pets
| SlashCommand::Ps
| SlashCommand::Stop

View File

@@ -36,7 +36,8 @@ impl ChatWidget {
| SlashCommand::Statusline
| SlashCommand::Theme
| SlashCommand::Setup
| SlashCommand::Endpoint,
| SlashCommand::Endpoint
| SlashCommand::Telegram,
) => false,
InputResult::Command(_)
| InputResult::ServiceTierCommand(_)

View File

@@ -550,6 +550,9 @@ impl ChatWidget {
SlashCommand::Endpoint => {
self.app_event_tx.send(AppEvent::OpenEndpointPanel);
}
SlashCommand::Telegram => {
self.app_event_tx.send(AppEvent::OpenTelegramPanel);
}
SlashCommand::Pets => {
self.open_pets_picker();
}
@@ -1297,6 +1300,7 @@ impl ChatWidget {
| SlashCommand::Theme
| SlashCommand::Setup
| SlashCommand::Endpoint
| SlashCommand::Telegram
| SlashCommand::Tui
| SlashCommand::Pets => QueueDrain::Stop,
}

View File

@@ -165,6 +165,7 @@ mod local_settings;
mod rendered_selection;
pub use live_wrap::RowBuilder;
mod endpoint_panel;
mod telegram_panel;
mod managed_new_thread_defaults;
mod markdown;
mod markdown_render;

View File

@@ -63,6 +63,7 @@ pub enum SlashCommand {
Theme,
Setup,
Endpoint,
Telegram,
#[strum(to_string = "pets", serialize = "pet")]
Pets,
Mcp,
@@ -125,6 +126,7 @@ impl SlashCommand {
SlashCommand::Theme => "choose the interface palette or syntax highlighting theme",
SlashCommand::Setup => "add a model provider with the guided setup",
SlashCommand::Endpoint => "gestisci endpoint, modelli e parametri",
SlashCommand::Telegram => "controlla le sessioni dal bot Telegram",
SlashCommand::Pets => "choose or hide the terminal pet",
SlashCommand::Ps => "list background terminals",
SlashCommand::Stop => "stop all background terminals",
@@ -302,6 +304,7 @@ impl SlashCommand {
| SlashCommand::Theme
| SlashCommand::Setup
| SlashCommand::Endpoint
| SlashCommand::Telegram
| SlashCommand::Pets => false,
}
}

View File

@@ -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

View File

@@ -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

View File

@@ -0,0 +1,20 @@
---
source: tui/src/telegram_panel_tests.rs
expression: "render(&panel, width, 16)"
---
Telegram esc chiudi
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Bot @akode_bot
Stato attivo · connesso
Chat 123456789
Notifiche approvazioni · fine turno · errori · loop
› Cambia il token del bot
Abbina una chat
Disattiva
Rimuovi il token
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
↑↓ scegli · invio conferma · esc chiudi

View File

@@ -0,0 +1,21 @@
---
source: tui/src/telegram_panel_tests.rs
assertion_line: 46
expression: "render(&panel, width, 16)"
---
Telegram esc chiudi
────────────────────────────────────────────────────────────────────────────
Bot @akode_bot
Stato attivo · connesso
Chat 123456789
Notifiche approvazioni · fine turno · errori · loop
› Cambia il token del bot
Abbina una chat
Disattiva
Rimuovi il token
────────────────────────────────────────────────────────────────────────────
↑↓ scegli · invio conferma · esc chiudi

View File

@@ -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

View File

@@ -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

View File

@@ -0,0 +1,20 @@
---
source: tui/src/telegram_panel_tests.rs
expression: "render(&panel, width, 16)"
---
Telegram esc chiudi
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Bot non configurato
Stato disattivato
Chat nessuna abbinata
Notifiche approvazioni · fine turno · errori · loop
› Imposta il token del bot
Abbina una chat
Attiva
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
↑↓ scegli · invio conferma · esc chiudi

View File

@@ -0,0 +1,21 @@
---
source: tui/src/telegram_panel_tests.rs
assertion_line: 54
expression: "render(&panel, width, 16)"
---
Telegram esc chiudi
────────────────────────────────────────────────────────────────────────────
Bot non configurato
Stato disattivato
Chat nessuna abbinata
Notifiche approvazioni · fine turno · errori · loop
› Imposta il token del bot
Abbina una chat
Attiva
────────────────────────────────────────────────────────────────────────────
↑↓ scegli · invio conferma · esc chiudi

View File

@@ -0,0 +1,624 @@
//! `/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,
}
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),
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(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;

View File

@@ -0,0 +1,89 @@
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,
}
}
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);
}