Telegram: un topic per sessione, streaming, pulsanti e impostazioni
- Menu comandi (setMyCommands, chat private): /sessioni /nuova /stato /stop /impostazioni /aiuto; /usa rimosso. - Un topic per sessione (createForumTopic in chat privata), nome "<cartella> · <modello>", rinominato al cambio di modello e "(chiusa)" alla chiusura; mappa salvata in AKODE_HOME/telegram-topics.json. Senza topic: prefisso [cartella · modello] e scelta della sessione con pulsanti. - /sessioni con Apri (link al topic), Stato e Stop; il messaggio si aggiorna modificandolo. - Streaming con sendMessageDraft (can_stop, al massimo 1/s, stop = interrompe il turno), messaggio finale con piede "ctx · t/s · durata". - Approvazioni con pulsanti colorati, poi un pulsante disattivato con l'esito. - Piano come elenco modificato; reazioni ricevuto/fatto configurabili. - /impostazioni con interruttori Sì/No salvati in [telegram] (streaming, reactions nuovi). - Messaggi modificati: un comando modificato riparte, il testo no. - Pulsanti con token opachi lato server; allowlist anche sui pulsanti. - Nessuna emoji nei testi in uscita (test dedicato). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -63,6 +63,9 @@ pub struct User {
|
||||
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)]
|
||||
@@ -75,27 +78,61 @@ 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 {
|
||||
@@ -103,6 +140,7 @@ impl Update {
|
||||
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
|
||||
@@ -110,14 +148,78 @@ impl Update {
|
||||
.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,
|
||||
pub callback_data: 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)]
|
||||
@@ -204,7 +306,12 @@ impl TelegramApi {
|
||||
) -> Result<Vec<Update>, ApiError> {
|
||||
let mut body = json!({
|
||||
"timeout": timeout_secs,
|
||||
"allowed_updates": ["message", "callback_query"],
|
||||
"allowed_updates": [
|
||||
"message",
|
||||
"edited_message",
|
||||
"callback_query",
|
||||
"stopped_message_generation",
|
||||
],
|
||||
});
|
||||
if let Some(offset) = offset {
|
||||
body["offset"] = json!(offset);
|
||||
@@ -217,17 +324,26 @@ impl TelegramApi {
|
||||
.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,
|
||||
reply_to: Option<i64>,
|
||||
entities: &[Entity],
|
||||
buttons: Option<&[Vec<Button>]>,
|
||||
) -> Result<Message, ApiError> {
|
||||
let mut body = json!({ "chat_id": chat_id, "text": text });
|
||||
if let Some(reply_to) = reply_to {
|
||||
body["reply_parameters"] =
|
||||
json!({ "message_id": reply_to, "allow_sending_without_reply": true });
|
||||
if let Some(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 });
|
||||
@@ -235,23 +351,88 @@ impl TelegramApi {
|
||||
self.call("sendMessage", body, REQUEST_TIMEOUT).await
|
||||
}
|
||||
|
||||
/// Replaces a message's text; the inline keyboard is removed.
|
||||
/// 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 body = json!({ "chat_id": chat_id, "message_id": message_id, "text": text });
|
||||
self.call::<Value>("editMessageText", body, REQUEST_TIMEOUT)
|
||||
.await
|
||||
.map(|_| ())
|
||||
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::<Value>("answerCallbackQuery", body, REQUEST_TIMEOUT)
|
||||
.await
|
||||
.map(|_| ())
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,9 +16,11 @@
|
||||
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";
|
||||
|
||||
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}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ 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.";
|
||||
pub const PAIRED_REPLY: &str = "Chat abbinata ad aKode. Scrivi /sessioni per vedere le sessioni.";
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Pending {
|
||||
@@ -132,7 +132,7 @@ pub async fn poll_once(
|
||||
{
|
||||
paired = Some(message.chat.id);
|
||||
let _ = api
|
||||
.send_message(message.chat.id, PAIRED_REPLY, None, None)
|
||||
.send_message(message.chat.id, None, PAIRED_REPLY, &[], None)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,11 +33,15 @@ impl Default for NotifySettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
#[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>,
|
||||
@@ -92,6 +96,8 @@ impl TelegramSettings {
|
||||
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),
|
||||
@@ -114,6 +120,81 @@ impl TelegramSettings {
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
@@ -204,10 +285,28 @@ pub fn save_bot_name(codex_home: &Path, username: &str) -> io::Result<()> {
|
||||
std::fs::write(codex_home.join(BOT_FILE), text)
|
||||
}
|
||||
|
||||
pub fn load_bot_name(codex_home: &Path) -> Option<String> {
|
||||
fn load_bot_file(codex_home: &Path) -> Option<serde_json::Value> {
|
||||
let text = std::fs::read_to_string(codex_home.join(BOT_FILE)).ok()?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
value["username"].as_str().map(ToString::to_string)
|
||||
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) {
|
||||
@@ -240,4 +339,18 @@ mod tests {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
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;
|
||||
|
||||
@@ -13,18 +15,118 @@ const BASELINE_TOKENS: i64 = 12_000;
|
||||
|
||||
/// `[<cwd basename> · <model>]`.
|
||||
pub fn session_tag(cwd: &Path, model: &str) -> String {
|
||||
let dir = cwd
|
||||
.file_name()
|
||||
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("/");
|
||||
if model.is_empty() {
|
||||
format!("[{dir}]")
|
||||
.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}]")
|
||||
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"];
|
||||
@@ -159,5 +261,26 @@ mod tests {
|
||||
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()]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user