aKode 0.3.1: Shift+Tab a tre modalità e topic di Telegram più puliti
- Shift+Tab: default, plan, accesso completo (preset di /permissions, saltato se i requisiti non lo permettono; uscendo tornano i permessi di prima). Modalità sotto il riquadro di scrittura, a sinistra, e in /stato su Telegram. - Telegram: topic creato al primo turno; sessioni chiuse senza turni perdono il topic, le altre diventano «(chiusa)» con nuovi tentativi; topic di «Nuova chat» assegnati con i pulsanti, i comandi lì ricevono risposta nella chat principale; pulizia all'avvio. - Versione 0.3.1 e novità nel README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -401,6 +401,12 @@ impl TelegramApi {
|
||||
self.call_unit("editForumTopic", body).await
|
||||
}
|
||||
|
||||
/// Deletes a topic with all its messages (supergroups and private chats).
|
||||
pub async fn delete_forum_topic(&self, chat_id: i64, thread: i64) -> Result<(), ApiError> {
|
||||
let body = json!({ "chat_id": chat_id, "message_thread_id": thread });
|
||||
self.call_unit("deleteForumTopic", body).await
|
||||
}
|
||||
|
||||
/// Streams a partial message (a temporary preview, replaced by the next message).
|
||||
pub async fn send_message_draft(
|
||||
&self,
|
||||
|
||||
@@ -84,7 +84,9 @@ use crate::settings::load_token;
|
||||
use crate::settings::set_toggle;
|
||||
use crate::text;
|
||||
use crate::text::Rich;
|
||||
use crate::topics::TopicEntry;
|
||||
use crate::topics::Topics;
|
||||
use crate::topics::has_rollout;
|
||||
|
||||
/// Channels of one internal app-server connection.
|
||||
pub struct BridgeConnection {
|
||||
@@ -220,6 +222,10 @@ struct Session {
|
||||
reactions: Vec<(i64, i64)>,
|
||||
/// The running turn was asked for from Telegram: its answer is always sent.
|
||||
from_telegram: bool,
|
||||
/// The session had a turn (its topic is created lazily, at the first one).
|
||||
had_turn: bool,
|
||||
/// `default`, `plan` or `accesso completo` (as cycled with Shift+Tab in the TUI).
|
||||
mode: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
@@ -260,14 +266,22 @@ enum Action {
|
||||
NewSessionMenu,
|
||||
NewSession(String),
|
||||
SendTo { pending: u64, thread_id: String },
|
||||
/// Gives an unmapped topic to a session (`None`: a new one in `cwd`) and sends the text.
|
||||
Adopt {
|
||||
pending: u64,
|
||||
thread_id: Option<String>,
|
||||
cwd: Option<String>,
|
||||
},
|
||||
Toggle(Toggle),
|
||||
}
|
||||
|
||||
/// A main-chat message waiting for the user to pick its session.
|
||||
/// A message waiting for the user to pick its session.
|
||||
struct PendingText {
|
||||
chat_id: i64,
|
||||
message_id: i64,
|
||||
text: String,
|
||||
/// Written in this unmapped topic (created by the user with «Nuova chat»).
|
||||
topic: Option<i64>,
|
||||
}
|
||||
|
||||
enum Pending {
|
||||
@@ -277,6 +291,8 @@ enum Pending {
|
||||
NewThread {
|
||||
chat_id: i64,
|
||||
thread: Option<i64>,
|
||||
/// A message written in an unmapped topic: that topic becomes the session's.
|
||||
adopt: Option<PendingText>,
|
||||
},
|
||||
Start {
|
||||
chat_id: i64,
|
||||
@@ -556,6 +572,7 @@ impl Bridge {
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
self.clean_topics(&list.data);
|
||||
for thread_id in list.data {
|
||||
if self.session(&thread_id).is_some() {
|
||||
continue;
|
||||
@@ -578,10 +595,15 @@ impl Bridge {
|
||||
.map_err(|err| err.to_string())
|
||||
}) {
|
||||
let model = response.model.clone();
|
||||
self.add_session(&response.thread, Some(model));
|
||||
let mode = session_mode(None, &response.sandbox);
|
||||
self.add_session(&response.thread, Some(model), mode);
|
||||
}
|
||||
}
|
||||
Pending::NewThread { chat_id, thread } => {
|
||||
Pending::NewThread {
|
||||
chat_id,
|
||||
thread,
|
||||
adopt,
|
||||
} => {
|
||||
let origin = Origin { chat_id, thread };
|
||||
match result.and_then(|value| {
|
||||
serde_json::from_value::<ThreadStartResponse>(value)
|
||||
@@ -589,14 +611,26 @@ impl Bridge {
|
||||
}) {
|
||||
Ok(response) => {
|
||||
let model = response.model.clone();
|
||||
self.add_session(&response.thread, Some(model));
|
||||
let name = self.topic_name(&response.thread.id);
|
||||
let mode = session_mode(None, &response.sandbox);
|
||||
self.add_session(&response.thread, Some(model), mode);
|
||||
let thread_id = response.thread.id.clone();
|
||||
if let Some(text) = adopt {
|
||||
self.adopt_topic(text, &thread_id);
|
||||
return;
|
||||
}
|
||||
let name = self.topic_name(&thread_id);
|
||||
let note = if self.topics_enabled() {
|
||||
format!("Nuova sessione avviata: {name}. Scrivi nel suo topic.")
|
||||
format!(
|
||||
"Nuova sessione avviata: {name}. Rispondi a questo messaggio con la \
|
||||
prima richiesta: il topic della sessione nasce con il primo turno."
|
||||
)
|
||||
} else {
|
||||
format!("Nuova sessione avviata: {name}.")
|
||||
format!(
|
||||
"Nuova sessione avviata: {name}. Rispondi a questo messaggio con la \
|
||||
prima richiesta."
|
||||
)
|
||||
};
|
||||
self.say(origin, ¬e);
|
||||
self.say_with(origin, Rich::plain(note), None, Tag::Session(thread_id));
|
||||
}
|
||||
Err(err) => self.say(origin, &format!("Sessione non avviata: {err}")),
|
||||
}
|
||||
@@ -678,7 +712,7 @@ impl Bridge {
|
||||
}
|
||||
}
|
||||
|
||||
fn add_session(&mut self, thread: &Thread, model: Option<String>) {
|
||||
fn add_session(&mut self, thread: &Thread, model: Option<String>, mode: &'static str) {
|
||||
if thread.parent_thread_id.is_some() || self.session(&thread.id).is_some() {
|
||||
return;
|
||||
}
|
||||
@@ -701,10 +735,13 @@ impl Bridge {
|
||||
plan: None,
|
||||
reactions: Vec::new(),
|
||||
from_telegram: false,
|
||||
had_turn: !thread.turns.is_empty(),
|
||||
mode,
|
||||
});
|
||||
self.lock_topics()
|
||||
.remember_cwd(&thread.cwd.to_path_buf().display().to_string());
|
||||
self.ensure_topics(&thread.id);
|
||||
// An existing topic gets its name back; a new one waits for the first turn.
|
||||
self.ensure_topics(&thread.id, false);
|
||||
self.refresh_session_lists();
|
||||
}
|
||||
|
||||
@@ -742,37 +779,84 @@ impl Bridge {
|
||||
format!("[{}]", self.topic_name(thread_id))
|
||||
}
|
||||
|
||||
/// Asks the outbox to create or rename the session's topic in every chat.
|
||||
fn ensure_topics(&self, thread_id: &str) {
|
||||
/// Asks the outbox to rename the session's topic in every chat and, with `create`, to
|
||||
/// create it when missing.
|
||||
fn ensure_topics(&self, thread_id: &str, create: bool) {
|
||||
let name = self.topic_name(thread_id);
|
||||
for chat_id in &self.settings.allowed_chat_ids {
|
||||
self.post(Outbox::Topic {
|
||||
chat_id: *chat_id,
|
||||
session: thread_id.to_string(),
|
||||
name: name.clone(),
|
||||
create: true,
|
||||
create,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The session is gone: its topic is deleted when the session never had a turn,
|
||||
/// otherwise renamed to «… (chiusa)».
|
||||
fn close_topics(&self, thread_id: &str) {
|
||||
let Some(session) = self.session(thread_id) else {
|
||||
return;
|
||||
};
|
||||
let empty = !session.had_turn && !has_rollout(&self.options.codex_home, thread_id);
|
||||
let name = closed_name(&self.topic_name(thread_id));
|
||||
for chat_id in &self.settings.allowed_chat_ids {
|
||||
let thread = self.lock_topics().entry(*chat_id, thread_id).map(|e| e.thread);
|
||||
match thread {
|
||||
Some(thread) if empty => self.post(Outbox::DeleteTopic {
|
||||
chat_id: *chat_id,
|
||||
thread,
|
||||
session: Some(thread_id.to_string()),
|
||||
fallback_name: Some(name.clone()),
|
||||
}),
|
||||
Some(_) => self.post(Outbox::Topic {
|
||||
chat_id: *chat_id,
|
||||
session: thread_id.to_string(),
|
||||
name: name.clone(),
|
||||
create: false,
|
||||
}),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// At start: topics of sessions that are gone without ever having a turn are deleted,
|
||||
/// renames that Telegram never confirmed are sent again.
|
||||
fn clean_topics(&self, loaded: &[String]) {
|
||||
let entries = self.lock_topics().entries();
|
||||
for entry in entries {
|
||||
if !self.settings.is_allowed(entry.chat_id)
|
||||
|| loaded.iter().any(|id| id == &entry.session)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !has_rollout(&self.options.codex_home, &entry.session) {
|
||||
self.post(Outbox::DeleteTopic {
|
||||
chat_id: entry.chat_id,
|
||||
thread: entry.thread,
|
||||
session: Some(entry.session.clone()),
|
||||
fallback_name: Some(closed_name(&entry.name)),
|
||||
});
|
||||
} else if let Some(name) = entry.pending_name {
|
||||
self.post(Outbox::Topic {
|
||||
chat_id: entry.chat_id,
|
||||
session: entry.session,
|
||||
name,
|
||||
create: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_notification(&mut self, notification: ServerNotification) {
|
||||
match notification {
|
||||
ServerNotification::ThreadStarted(started) => {
|
||||
let model = started.thread.model.clone();
|
||||
self.add_session(&started.thread, model);
|
||||
self.add_session(&started.thread, model, MODE_DEFAULT);
|
||||
}
|
||||
ServerNotification::ThreadClosed(closed) => {
|
||||
let name = text::closed_topic_name(&self.topic_name(&closed.thread_id));
|
||||
if self.session(&closed.thread_id).is_some() {
|
||||
for chat_id in &self.settings.allowed_chat_ids {
|
||||
self.post(Outbox::Topic {
|
||||
chat_id: *chat_id,
|
||||
session: closed.thread_id.clone(),
|
||||
name: name.clone(),
|
||||
create: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.close_topics(&closed.thread_id);
|
||||
self.sessions
|
||||
.retain(|session| session.thread_id != closed.thread_id);
|
||||
self.refresh_session_lists();
|
||||
@@ -783,10 +867,14 @@ impl Bridge {
|
||||
return;
|
||||
};
|
||||
let cwd = settings.cwd.to_path_buf();
|
||||
session.mode = session_mode(
|
||||
serde_json::to_value(settings.collaboration_mode.mode).ok(),
|
||||
&settings.sandbox_policy,
|
||||
);
|
||||
if session.model != settings.model || session.cwd != cwd {
|
||||
session.model = settings.model;
|
||||
session.cwd = cwd;
|
||||
self.ensure_topics(&updated.thread_id);
|
||||
self.ensure_topics(&updated.thread_id, false);
|
||||
self.refresh_session_lists();
|
||||
}
|
||||
}
|
||||
@@ -805,6 +893,8 @@ impl Bridge {
|
||||
session.active_turn = Some(started.turn.id);
|
||||
session.last_message = None;
|
||||
session.stream = None;
|
||||
session.had_turn = true;
|
||||
self.ensure_topics(&started.thread_id, true);
|
||||
}
|
||||
self.refresh_session_lists();
|
||||
}
|
||||
@@ -1345,7 +1435,7 @@ impl Bridge {
|
||||
tag: Tag,
|
||||
) {
|
||||
if self.session(thread_id).is_some() {
|
||||
self.ensure_topics(thread_id);
|
||||
self.ensure_topics(thread_id, true);
|
||||
}
|
||||
let dest = Dest::Session {
|
||||
id: thread_id.to_string(),
|
||||
@@ -1610,6 +1700,7 @@ impl Bridge {
|
||||
Pending::NewThread {
|
||||
chat_id,
|
||||
thread: origin.thread,
|
||||
adopt: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1627,6 +1718,45 @@ impl Bridge {
|
||||
self.add_route(text.chat_id, text.message_id, thread_id.clone());
|
||||
self.send_user_text(text.chat_id, &thread_id, text.text, Some(text.message_id));
|
||||
}
|
||||
Action::Adopt {
|
||||
pending,
|
||||
thread_id,
|
||||
cwd,
|
||||
} => {
|
||||
let Some(text) = self.pending_texts.remove(&pending) else {
|
||||
self.answer(callback_id, "Messaggio già inviato.");
|
||||
return;
|
||||
};
|
||||
match (thread_id, cwd) {
|
||||
(Some(thread_id), _) => {
|
||||
if self.session(&thread_id).is_none() {
|
||||
self.pending_texts.insert(pending, text);
|
||||
self.answer(callback_id, "Sessione chiusa.");
|
||||
return;
|
||||
}
|
||||
let name = self.topic_name(&thread_id);
|
||||
self.answer(callback_id, &format!("Inviato a {name}."));
|
||||
self.adopt_topic(text, &thread_id);
|
||||
}
|
||||
(None, cwd) => {
|
||||
self.answer(callback_id, "Avvio la sessione.");
|
||||
self.request(
|
||||
|request_id| ClientRequest::ThreadStart {
|
||||
request_id,
|
||||
params: ThreadStartParams {
|
||||
cwd,
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
Pending::NewThread {
|
||||
chat_id,
|
||||
thread: origin.thread,
|
||||
adopt: Some(text),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Action::Toggle(toggle) => {
|
||||
let value = !toggle.get(&self.settings);
|
||||
if let Err(err) = set_toggle(&self.options.codex_home, toggle, value) {
|
||||
@@ -1705,6 +1835,10 @@ impl Bridge {
|
||||
.find(|((chat, id), _)| *chat == chat_id && *id == replied.message_id)
|
||||
.map(|(_, thread_id)| thread_id.clone())
|
||||
});
|
||||
if let Some(stray) = topic.filter(|_| topic_session.is_none() && replied.is_none()) {
|
||||
self.on_stray_topic(chat_id, stray, message.message_id, trimmed, body.clone());
|
||||
return;
|
||||
}
|
||||
let target = topic_session.or(replied);
|
||||
if is_command {
|
||||
let target = target.filter(|thread_id| self.session(thread_id).is_some());
|
||||
@@ -1730,24 +1864,130 @@ impl Bridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// Several sessions and no topic: asks with buttons where the message goes.
|
||||
fn choose_session_for(&mut self, origin: Origin, message_id: i64, text: String) {
|
||||
fn store_pending(&mut self, text: PendingText) -> u64 {
|
||||
self.next_pending_text += 1;
|
||||
let pending = self.next_pending_text;
|
||||
self.pending_texts.insert(
|
||||
pending,
|
||||
PendingText {
|
||||
chat_id: origin.chat_id,
|
||||
message_id,
|
||||
text,
|
||||
},
|
||||
);
|
||||
self.pending_texts.insert(pending, text);
|
||||
while self.pending_texts.len() > 50 {
|
||||
let Some(oldest) = self.pending_texts.keys().min().copied() else {
|
||||
break;
|
||||
};
|
||||
self.pending_texts.remove(&oldest);
|
||||
}
|
||||
pending
|
||||
}
|
||||
|
||||
/// A message in a topic that belongs to no session: the user made it with «Nuova chat»,
|
||||
/// and Telegram named it after the text. A command is answered in the main chat and the
|
||||
/// topic deleted; plain text asks which session the topic is for.
|
||||
fn on_stray_topic(&mut self, chat_id: i64, topic: i64, message_id: i64, trimmed: &str, body: String) {
|
||||
if trimmed.starts_with('/') {
|
||||
let origin = Origin {
|
||||
chat_id,
|
||||
thread: None,
|
||||
};
|
||||
self.on_command(origin, trimmed, None);
|
||||
self.post(Outbox::DeleteTopic {
|
||||
chat_id,
|
||||
thread: topic,
|
||||
session: None,
|
||||
fallback_name: None,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let pending = self.store_pending(PendingText {
|
||||
chat_id,
|
||||
message_id,
|
||||
text: body,
|
||||
topic: Some(topic),
|
||||
});
|
||||
let threads: Vec<String> = self.sessions.iter().map(|s| s.thread_id.clone()).collect();
|
||||
let mut rows = Vec::new();
|
||||
for thread_id in threads {
|
||||
let label = self.topic_name(&thread_id);
|
||||
let token = self.register(Action::Adopt {
|
||||
pending,
|
||||
thread_id: Some(thread_id),
|
||||
cwd: None,
|
||||
});
|
||||
rows.push(vec![Button::callback(label, token)]);
|
||||
}
|
||||
let cwd = self
|
||||
.lock_topics()
|
||||
.recent_cwds()
|
||||
.first()
|
||||
.cloned()
|
||||
.or_else(|| self.sessions.last().map(|s| s.cwd.display().to_string()));
|
||||
if let Some(cwd) = cwd {
|
||||
let token = self.register(Action::Adopt {
|
||||
pending,
|
||||
thread_id: None,
|
||||
cwd: Some(cwd),
|
||||
});
|
||||
rows.push(vec![Button::callback("Nuova sessione", token)]);
|
||||
}
|
||||
let origin = Origin {
|
||||
chat_id,
|
||||
thread: Some(topic),
|
||||
};
|
||||
if rows.is_empty() {
|
||||
self.say(origin, "Nessuna sessione di aKode attiva. Avvia una sessione dal Mac.");
|
||||
return;
|
||||
}
|
||||
self.say_with(
|
||||
origin,
|
||||
Rich::plain("A quale sessione appartiene questo topic?"),
|
||||
Some(rows),
|
||||
Tag::None,
|
||||
);
|
||||
}
|
||||
|
||||
/// Maps the topic of `text` to `thread_id` and sends the text there. When the session
|
||||
/// already has its own topic, the text goes to it and the extra topic is deleted.
|
||||
fn adopt_topic(&mut self, text: PendingText, thread_id: &str) {
|
||||
let Some(topic) = text.topic else {
|
||||
return;
|
||||
};
|
||||
let existing = self
|
||||
.lock_topics()
|
||||
.entry(text.chat_id, thread_id)
|
||||
.map(|entry| entry.thread)
|
||||
.filter(|thread| *thread != topic);
|
||||
if existing.is_some() {
|
||||
self.post(Outbox::DeleteTopic {
|
||||
chat_id: text.chat_id,
|
||||
thread: topic,
|
||||
session: None,
|
||||
fallback_name: None,
|
||||
});
|
||||
self.send_user_text(text.chat_id, thread_id, text.text, None);
|
||||
return;
|
||||
}
|
||||
self.lock_topics().insert(TopicEntry {
|
||||
chat_id: text.chat_id,
|
||||
session: thread_id.to_string(),
|
||||
thread: topic,
|
||||
name: String::new(),
|
||||
pending_name: None,
|
||||
});
|
||||
self.post(Outbox::Topic {
|
||||
chat_id: text.chat_id,
|
||||
session: thread_id.to_string(),
|
||||
name: self.topic_name(thread_id),
|
||||
create: false,
|
||||
});
|
||||
self.add_route(text.chat_id, text.message_id, thread_id.to_string());
|
||||
self.send_user_text(text.chat_id, thread_id, text.text, Some(text.message_id));
|
||||
}
|
||||
|
||||
/// Several sessions and no topic: asks with buttons where the message goes.
|
||||
fn choose_session_for(&mut self, origin: Origin, message_id: i64, text: String) {
|
||||
let pending = self.store_pending(PendingText {
|
||||
chat_id: origin.chat_id,
|
||||
message_id,
|
||||
text,
|
||||
topic: None,
|
||||
});
|
||||
let threads: Vec<String> = self.sessions.iter().map(|s| s.thread_id.clone()).collect();
|
||||
let mut rows = Vec::new();
|
||||
for thread_id in threads {
|
||||
@@ -1871,8 +2111,9 @@ impl Bridge {
|
||||
);
|
||||
if self.topics_enabled() {
|
||||
text.push_str(
|
||||
"Ogni sessione ha il suo topic: scrivi nel topic per parlare con quella sessione. \
|
||||
Nella chat principale rispondi a un messaggio della sessione.",
|
||||
"Ogni sessione ha il suo topic dal primo turno: scrivi nel topic per parlare con \
|
||||
quella sessione. Nella chat principale rispondi a un messaggio della sessione. \
|
||||
In una nuova chat di Telegram ti chiedo a quale sessione appartiene.",
|
||||
);
|
||||
} else {
|
||||
text.push_str(
|
||||
@@ -2062,15 +2303,42 @@ impl Bridge {
|
||||
return "Sessione chiusa.".to_string();
|
||||
};
|
||||
format!(
|
||||
"{} · {}\nCartella: {}",
|
||||
"{} · {}\nModalità: {}\nCartella: {}",
|
||||
self.topic_name(thread_id),
|
||||
self.session_line(session),
|
||||
session.mode,
|
||||
session.cwd.display()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of the running answer, as shown in a draft.
|
||||
const MODE_DEFAULT: &str = "default";
|
||||
|
||||
/// The session mode as the TUI shows it: plan, full access (no sandbox) or default.
|
||||
fn session_mode(mode: Option<serde_json::Value>, sandbox: &impl serde::Serialize) -> &'static str {
|
||||
let plan = mode.is_some_and(|mode| mode == "plan");
|
||||
let full = serde_json::to_value(sandbox)
|
||||
.ok()
|
||||
.is_some_and(|sandbox| sandbox["type"] == "dangerFullAccess");
|
||||
if plan {
|
||||
"plan"
|
||||
} else if full {
|
||||
"accesso completo"
|
||||
} else {
|
||||
MODE_DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
/// «… (chiusa)», once.
|
||||
fn closed_name(name: &str) -> String {
|
||||
if name.ends_with("(chiusa)") {
|
||||
name.to_string()
|
||||
} else {
|
||||
text::closed_topic_name(name)
|
||||
}
|
||||
}
|
||||
|
||||
fn draft_tail(text: &str) -> String {
|
||||
let count = text.chars().count();
|
||||
if count <= DRAFT_TAIL {
|
||||
|
||||
@@ -30,6 +30,9 @@ pub(crate) const COMMANDS: [(&str, &str); 6] = [
|
||||
("aiuto", "Come si usa il bot"),
|
||||
];
|
||||
|
||||
/// Tries of one topic rename before it is left for the next start.
|
||||
const RENAME_ATTEMPTS: u32 = 3;
|
||||
|
||||
/// Draft text limit (Telegram accepts 4096 characters).
|
||||
const DRAFT_LIMIT: usize = 4000;
|
||||
|
||||
@@ -79,6 +82,14 @@ pub(crate) enum Outbox {
|
||||
name: String,
|
||||
create: bool,
|
||||
},
|
||||
/// Deletes a topic with its messages. With `session` the map entry goes too; when
|
||||
/// Telegram refuses, the topic is renamed to `fallback_name` instead.
|
||||
DeleteTopic {
|
||||
chat_id: i64,
|
||||
thread: i64,
|
||||
session: Option<String>,
|
||||
fallback_name: Option<String>,
|
||||
},
|
||||
Draft {
|
||||
chat_id: i64,
|
||||
session: String,
|
||||
@@ -216,6 +227,15 @@ impl OutboxTask {
|
||||
name,
|
||||
create,
|
||||
} => self.topic(chat_id, &session, &name, create).await,
|
||||
Outbox::DeleteTopic {
|
||||
chat_id,
|
||||
thread,
|
||||
session,
|
||||
fallback_name,
|
||||
} => {
|
||||
self.delete_topic(chat_id, thread, session.as_deref(), fallback_name.as_deref())
|
||||
.await;
|
||||
}
|
||||
Outbox::Draft {
|
||||
chat_id,
|
||||
session,
|
||||
@@ -293,11 +313,8 @@ impl OutboxTask {
|
||||
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(entry) if entry.name != name || entry.pending_name.is_some() => {
|
||||
self.rename(chat_id, session, entry.thread, name).await;
|
||||
}
|
||||
Some(_) => {}
|
||||
None if create => match self.api.create_forum_topic(chat_id, name).await {
|
||||
@@ -306,6 +323,7 @@ impl OutboxTask {
|
||||
session: session.to_string(),
|
||||
thread: topic.message_thread_id,
|
||||
name: name.to_string(),
|
||||
pending_name: None,
|
||||
}),
|
||||
Err(ApiError::Network(err)) => {
|
||||
warn!("telegram: createForumTopic failed, retrying later: {err}");
|
||||
@@ -320,6 +338,64 @@ impl OutboxTask {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renames a topic, retrying failures; a rename still failing is kept as pending in the
|
||||
/// map and applied again when the bridge starts.
|
||||
async fn rename(&self, chat_id: i64, session: &str, thread: i64, name: &str) -> bool {
|
||||
lock(&self.topics).set_pending_name(chat_id, session, name);
|
||||
for attempt in 1..=RENAME_ATTEMPTS {
|
||||
let err = match self.api.edit_forum_topic(chat_id, thread, name).await {
|
||||
Ok(()) => {
|
||||
lock(&self.topics).set_name(chat_id, session, name);
|
||||
return true;
|
||||
}
|
||||
Err(err) if mentions(&err, &["not modified"]) => {
|
||||
lock(&self.topics).set_name(chat_id, session, name);
|
||||
return true;
|
||||
}
|
||||
Err(err) => err,
|
||||
};
|
||||
warn!("telegram: editForumTopic failed (attempt {attempt}/{RENAME_ATTEMPTS}): {err}");
|
||||
if is_bad_request(&err) && mentions(&err, &["not found", "invalid"]) {
|
||||
// The user deleted the topic.
|
||||
lock(&self.topics).remove(chat_id, session);
|
||||
return false;
|
||||
}
|
||||
if err.is_unauthorized() || attempt == RENAME_ATTEMPTS {
|
||||
break;
|
||||
}
|
||||
let wait = err.retry_after().unwrap_or(attempt as u64).min(30);
|
||||
tokio::time::sleep(Duration::from_secs(wait)).await;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
async fn delete_topic(
|
||||
&self,
|
||||
chat_id: i64,
|
||||
thread: i64,
|
||||
session: Option<&str>,
|
||||
fallback_name: Option<&str>,
|
||||
) {
|
||||
if chat_id <= 0 {
|
||||
return;
|
||||
}
|
||||
let result = self.with_retry(|| self.api.delete_forum_topic(chat_id, thread)).await;
|
||||
match result {
|
||||
Ok(()) => {}
|
||||
Err(err) if mentions(&err, &["not found"]) => {}
|
||||
Err(err) => {
|
||||
warn!("telegram: deleteForumTopic failed: {err}");
|
||||
if let (Some(session), Some(name)) = (session, fallback_name) {
|
||||
self.rename(chat_id, session, thread, name).await;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(session) = session {
|
||||
lock(&self.topics).remove(chat_id, session);
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(
|
||||
&self,
|
||||
chat_id: i64,
|
||||
|
||||
@@ -21,6 +21,9 @@ pub struct TopicEntry {
|
||||
pub session: String,
|
||||
pub thread: i64,
|
||||
pub name: String,
|
||||
/// A rename not yet confirmed by Telegram, applied again at the next start.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pending_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
@@ -102,14 +105,33 @@ impl Topics {
|
||||
self.save();
|
||||
}
|
||||
|
||||
pub fn set_name(&mut self, chat_id: i64, session: &str, name: &str) {
|
||||
if let Some(entry) = self
|
||||
.file
|
||||
/// Every mapped topic.
|
||||
pub fn entries(&self) -> Vec<TopicEntry> {
|
||||
self.file.topics.clone()
|
||||
}
|
||||
|
||||
fn entry_mut(&mut self, chat_id: i64, session: &str) -> Option<&mut TopicEntry> {
|
||||
self.file
|
||||
.topics
|
||||
.iter_mut()
|
||||
.find(|entry| entry.chat_id == chat_id && entry.session == session)
|
||||
{
|
||||
}
|
||||
|
||||
/// Records a confirmed rename.
|
||||
pub fn set_name(&mut self, chat_id: i64, session: &str, name: &str) {
|
||||
if let Some(entry) = self.entry_mut(chat_id, session) {
|
||||
entry.name = name.to_string();
|
||||
entry.pending_name = None;
|
||||
self.save();
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a rename before asking Telegram, so a failed one is retried at the next start.
|
||||
pub fn set_pending_name(&mut self, chat_id: i64, session: &str, name: &str) {
|
||||
if let Some(entry) = self.entry_mut(chat_id, session)
|
||||
&& entry.pending_name.as_deref() != Some(name)
|
||||
{
|
||||
entry.pending_name = Some(name.to_string());
|
||||
self.save();
|
||||
}
|
||||
}
|
||||
@@ -137,11 +159,45 @@ impl Topics {
|
||||
}
|
||||
}
|
||||
|
||||
/// The session has a rollout file under `AKODE_HOME`, that is it ever had a turn.
|
||||
pub fn has_rollout(codex_home: &Path, session: &str) -> bool {
|
||||
fn walk(dir: &Path, session: &str, depth: u8) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return false;
|
||||
};
|
||||
entries.flatten().any(|entry| {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
depth > 0 && walk(&path, session, depth - 1)
|
||||
} else {
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.starts_with("rollout-") && name.contains(session))
|
||||
}
|
||||
})
|
||||
}
|
||||
!session.is_empty()
|
||||
&& ["sessions", "archived_sessions"]
|
||||
.iter()
|
||||
.any(|dir| walk(&codex_home.join(dir), session, 4))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn rollouts_are_found_by_session_id() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let day = home.path().join("sessions/2026/11/12");
|
||||
std::fs::create_dir_all(&day).unwrap();
|
||||
std::fs::write(day.join("rollout-2026-11-12T10-00-00-abc-123.jsonl"), "").unwrap();
|
||||
assert!(has_rollout(home.path(), "abc-123"));
|
||||
assert!(!has_rollout(home.path(), "def-456"));
|
||||
assert!(!has_rollout(home.path(), ""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_survives_a_reload() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
@@ -151,7 +207,9 @@ mod tests {
|
||||
session: "t1".to_string(),
|
||||
thread: 77,
|
||||
name: "alfa · Qwen".to_string(),
|
||||
pending_name: None,
|
||||
});
|
||||
topics.set_pending_name(1, "t1", "alfa · Qwen (chiusa)");
|
||||
topics.remember_cwd("/a");
|
||||
topics.remember_cwd("/b");
|
||||
topics.remember_cwd("/a");
|
||||
@@ -160,6 +218,12 @@ mod tests {
|
||||
topics.enabled = true;
|
||||
assert_eq!(topics.thread_for(1, "t1"), Some(77));
|
||||
assert_eq!(topics.session_for(1, 77), Some("t1"));
|
||||
assert_eq!(
|
||||
topics.entry(1, "t1").and_then(|e| e.pending_name.clone()).as_deref(),
|
||||
Some("alfa · Qwen (chiusa)")
|
||||
);
|
||||
topics.set_name(1, "t1", "alfa · Qwen (chiusa)");
|
||||
assert_eq!(topics.entry(1, "t1").unwrap().pending_name, None);
|
||||
assert_eq!(topics.recent_cwds(), ["/a".to_string(), "/b".to_string()]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ async fn mock_telegram(topics: bool) -> (MockServer, Arc<Mutex<VecDeque<Value>>>
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(
|
||||
".*/(editMessageText|answerCallbackQuery|setMyCommands|editForumTopic|sendMessageDraft|setMessageReaction)$",
|
||||
".*/(editMessageText|answerCallbackQuery|setMyCommands|editForumTopic|deleteForumTopic|sendMessageDraft|setMessageReaction)$",
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": true})))
|
||||
.mount(&telegram)
|
||||
@@ -541,6 +541,10 @@ async fn topics_are_created_mapped_and_reused_after_a_restart() {
|
||||
let h = Harness::with_topics().await;
|
||||
home = Arc::clone(&h.home);
|
||||
h.start_thread("t1", "/tmp/alfa");
|
||||
let mut h = h;
|
||||
h.settle().await;
|
||||
assert!(h.calls("createForumTopic").await.is_empty(), "no topic before the first turn");
|
||||
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-1", "inProgress")}));
|
||||
let topics = h.wait_for_calls("createForumTopic", 1).await;
|
||||
assert_eq!(topics[0]["chat_id"], json!(CHAT));
|
||||
assert_eq!(topics[0]["name"], "alfa · Qwen 3.6");
|
||||
@@ -570,6 +574,9 @@ async fn topics_are_created_mapped_and_reused_after_a_restart() {
|
||||
}
|
||||
|
||||
// A new bridge on the same home writes into the same topic and reopens its name.
|
||||
let day = home.path().join("sessions/2026/11/12");
|
||||
std::fs::create_dir_all(&day).unwrap();
|
||||
std::fs::write(day.join("rollout-2026-11-12T10-00-00-t1.jsonl"), "").unwrap();
|
||||
let h = Harness::start_with(home, true).await;
|
||||
h.start_thread("t1", "/tmp/alfa");
|
||||
let renames = h.wait_for_calls("editForumTopic", 1).await;
|
||||
@@ -585,9 +592,14 @@ async fn topic_messages_go_to_their_session() {
|
||||
let mut h = Harness::with_topics().await;
|
||||
h.start_thread("t1", "/tmp/alfa");
|
||||
h.start_thread("t2", "/tmp/beta");
|
||||
for thread in ["t1", "t2"] {
|
||||
h.notify("turn/started", json!({"threadId": thread, "turn": turn_json("turn-0", "inProgress")}));
|
||||
h.notify("turn/completed", json!({"threadId": thread, "turn": turn_json("turn-0", "completed")}));
|
||||
}
|
||||
h.wait_for_calls("createForumTopic", 2).await;
|
||||
// Let the outbox store both topics.
|
||||
h.settle().await;
|
||||
let base = h.calls("sendMessage").await.len();
|
||||
|
||||
h.push_update(topic_message(CHAT, 501, "continua"));
|
||||
let start = h.expect_request("turn/start").await;
|
||||
@@ -597,14 +609,14 @@ async fn topic_messages_go_to_their_session() {
|
||||
|
||||
// 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"));
|
||||
let sends = h.wait_for_calls("sendMessage", base + 1).await;
|
||||
assert_eq!(sends[base]["message_thread_id"], 500);
|
||||
assert!(sends[base]["text"].as_str().unwrap().starts_with("alfa · Qwen 3.6 · libera"));
|
||||
|
||||
// The session list links each topic and refreshes in place.
|
||||
h.push_update(text_message(CHAT, "/sessioni", None));
|
||||
let sends = h.wait_for_calls("sendMessage", 2).await;
|
||||
let list = &sends[1];
|
||||
let sends = h.wait_for_calls("sendMessage", base + 2).await;
|
||||
let list = &sends[base + 1];
|
||||
assert_eq!(
|
||||
labels(list),
|
||||
vec![
|
||||
@@ -614,7 +626,7 @@ async fn topic_messages_go_to_their_session() {
|
||||
]
|
||||
);
|
||||
assert_eq!(list["reply_markup"]["inline_keyboard"][1][0]["url"], "https://t.me/akode_bot/501");
|
||||
let list_id = 1001;
|
||||
let list_id = list_message_id(&h, base + 1).await;
|
||||
h.push_update(callback_on(CHAT, &button(list, "2 · Stato"), list_id));
|
||||
let answers = h.wait_for_calls("answerCallbackQuery", 1).await;
|
||||
assert!(answers[0]["text"].as_str().unwrap().starts_with("beta · Qwen 3.6"));
|
||||
@@ -622,7 +634,7 @@ async fn topic_messages_go_to_their_session() {
|
||||
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");
|
||||
assert_eq!(h.calls("sendMessage").await.len(), base + 2, "refresh edits, never sends");
|
||||
h.push_update(callback_on(CHAT, &button(list, "1 · Stop"), list_id));
|
||||
let interrupt = h.expect_request("turn/interrupt").await;
|
||||
assert_eq!(interrupt.params.unwrap()["turnId"], "turn-9");
|
||||
@@ -726,8 +738,8 @@ async fn edited_commands_run_again_and_edited_text_is_ignored() {
|
||||
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")}));
|
||||
h.wait_for_calls("createForumTopic", 1).await;
|
||||
for word in ["Sto ", "leggendo ", "i ", "file ", "del ", "progetto."] {
|
||||
h.notify(
|
||||
"item/agentMessage/delta",
|
||||
@@ -864,3 +876,187 @@ async fn nothing_is_polled_while_disabled() {
|
||||
assert_eq!(connects.load(Ordering::SeqCst), 0);
|
||||
assert!(telegram.received_requests().await.unwrap_or_default().is_empty());
|
||||
}
|
||||
|
||||
fn saved_topics(home: &Path) -> Value {
|
||||
serde_json::from_str(&std::fs::read_to_string(home.join(topics::TOPICS_FILE)).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn start_response(id: &str, cwd: &str) -> Value {
|
||||
json!({"thread": thread_json(id, cwd), "model": "qwen", "modelProvider": "p",
|
||||
"serviceTier": null, "cwd": cwd, "approvalPolicy": "never",
|
||||
"approvalsReviewer": "user", "sandbox": {"type": "dangerFullAccess"},
|
||||
"reasoningEffort": null})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_session_without_turns_gets_no_topic_and_its_topic_is_deleted_on_close() {
|
||||
let mut h = Harness::with_topics().await;
|
||||
h.start_thread("t1", "/tmp/alfa");
|
||||
h.settle().await;
|
||||
assert!(h.calls("createForumTopic").await.is_empty());
|
||||
// An error creates the topic even without a turn.
|
||||
h.notify("error", json!({"threadId": "t1", "turnId": "x", "willRetry": false,
|
||||
"error": {"message": "server spento", "codexErrorInfo": null, "additionalDetails": null}}));
|
||||
h.wait_for_calls("createForumTopic", 1).await;
|
||||
h.wait_for_calls("sendMessage", 1).await;
|
||||
h.notify("thread/closed", json!({"threadId": "t1"}));
|
||||
let deleted = h.wait_for_calls("deleteForumTopic", 1).await;
|
||||
assert_eq!(deleted[0]["message_thread_id"], 500);
|
||||
h.settle().await;
|
||||
assert!(h.calls("editForumTopic").await.is_empty(), "deleted, not renamed");
|
||||
assert_eq!(saved_topics(h.home.path())["topics"], json!([]));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_close_rename_is_retried() {
|
||||
let h = Harness::with_topics().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(".*/editForumTopic$"))
|
||||
.respond_with(ResponseTemplate::new(500).set_body_json(
|
||||
json!({"ok": false, "error_code": 500, "description": "Internal Server Error"}),
|
||||
))
|
||||
.up_to_n_times(1)
|
||||
.with_priority(1)
|
||||
.mount(&h.telegram)
|
||||
.await;
|
||||
h.start_thread("t1", "/tmp/alfa");
|
||||
h.notify("turn/started", json!({"threadId": "t1", "turn": turn_json("turn-1", "inProgress")}));
|
||||
complete_turn(&h, "t1", "turn-1", "Fatto.");
|
||||
h.wait_for_calls("sendMessage", 1).await;
|
||||
h.notify("thread/closed", json!({"threadId": "t1"}));
|
||||
let renames = h.wait_for_calls("editForumTopic", 2).await;
|
||||
assert_eq!(renames[1]["name"], "alfa · Qwen 3.6 (chiusa)");
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let saved = saved_topics(h.home.path());
|
||||
assert_eq!(saved["topics"][0]["name"], "alfa · Qwen 3.6 (chiusa)");
|
||||
assert!(saved["topics"][0].get("pending_name").is_none(), "{saved}");
|
||||
assert!(h.calls("deleteForumTopic").await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_command_in_a_stray_topic_is_answered_in_the_main_chat_and_the_topic_deleted() {
|
||||
let h = Harness::with_topics().await;
|
||||
h.start_thread("t1", "/tmp/alfa");
|
||||
h.push_update(topic_message(CHAT, 777, "/sessioni"));
|
||||
let sends = h.wait_for_calls("sendMessage", 1).await;
|
||||
assert!(sends[0].get("message_thread_id").is_none(), "{}", sends[0]);
|
||||
let deleted = h.wait_for_calls("deleteForumTopic", 1).await;
|
||||
assert_eq!(deleted[0]["message_thread_id"], 777);
|
||||
assert!(h.calls("createForumTopic").await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plain_text_in_a_stray_topic_picks_its_session() {
|
||||
let mut h = Harness::with_topics().await;
|
||||
h.start_thread("t1", "/tmp/alfa");
|
||||
h.settle().await;
|
||||
|
||||
// A new session in the cwd of the most recent one takes the topic.
|
||||
h.push_update(topic_message(CHAT, 778, "ciao"));
|
||||
let sends = h.wait_for_calls("sendMessage", 1).await;
|
||||
assert_eq!(sends[0]["message_thread_id"], 778);
|
||||
assert_eq!(labels(&sends[0]), vec![vec!["alfa · Qwen 3.6"], vec!["Nuova sessione"]]);
|
||||
h.push_update(callback(CHAT, &button(&sends[0], "Nuova sessione")));
|
||||
let start = h.expect_request("thread/start").await;
|
||||
assert_eq!(start.params.clone().unwrap()["cwd"], "/tmp/alfa");
|
||||
h.respond(start.id, start_response("t3", "/tmp/alfa"));
|
||||
let turn = h.expect_request("turn/start").await;
|
||||
let params = turn.params.unwrap();
|
||||
assert_eq!(params["threadId"], "t3");
|
||||
assert_eq!(params["input"][0]["text"], "ciao");
|
||||
let renames = h.wait_for_calls("editForumTopic", 1).await;
|
||||
assert_eq!(renames[0]["message_thread_id"], 778);
|
||||
assert_eq!(renames[0]["name"], "alfa · Qwen 3.6");
|
||||
|
||||
// An existing session without a topic takes the next one.
|
||||
h.push_update(topic_message(CHAT, 779, "ancora"));
|
||||
let sends = h.wait_for_calls("sendMessage", 2).await;
|
||||
h.push_update(callback(CHAT, &button(&sends[1], "alfa · Qwen 3.6")));
|
||||
let turn = h.expect_request("turn/start").await;
|
||||
assert_eq!(turn.params.unwrap()["threadId"], "t1");
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let saved = saved_topics(h.home.path());
|
||||
let threads: Vec<(String, i64)> = saved["topics"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|e| (e["session"].as_str().unwrap().to_string(), e["thread"].as_i64().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(threads, vec![("t3".to_string(), 778), ("t1".to_string(), 779)]);
|
||||
assert!(h.calls("createForumTopic").await.is_empty());
|
||||
assert!(h.calls("deleteForumTopic").await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_drops_empty_gone_sessions_and_reapplies_pending_renames() {
|
||||
let home = Arc::new(tempfile::tempdir().unwrap());
|
||||
let day = home.path().join("sessions/2026/11/12");
|
||||
std::fs::create_dir_all(&day).unwrap();
|
||||
std::fs::write(day.join("rollout-2026-11-12T10-00-00-s2.jsonl"), "").unwrap();
|
||||
std::fs::write(day.join("rollout-2026-11-12T10-00-00-s4.jsonl"), "").unwrap();
|
||||
std::fs::write(
|
||||
home.path().join(topics::TOPICS_FILE),
|
||||
json!({"topics": [
|
||||
{"chat_id": CHAT, "session": "s1", "thread": 601, "name": "alfa · Qwen 3.6"},
|
||||
{"chat_id": CHAT, "session": "s2", "thread": 602, "name": "beta · Qwen 3.6",
|
||||
"pending_name": "beta · Qwen 3.6 (chiusa)"},
|
||||
// Already renamed «(chiusa)» but never had a turn: deleted all the same.
|
||||
{"chat_id": CHAT, "session": "s3", "thread": 603, "name": "gamma · Qwen 3.6 (chiusa)"},
|
||||
// Closed with a turn and nothing pending: kept as it is.
|
||||
{"chat_id": CHAT, "session": "s4", "thread": 604, "name": "delta · Qwen 3.6 (chiusa)"},
|
||||
], "recent_cwds": []})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let h = Harness::start_with(Arc::clone(&home), true).await;
|
||||
let deleted = h.wait_for_calls("deleteForumTopic", 2).await;
|
||||
let mut threads: Vec<i64> = deleted.iter().map(|d| d["message_thread_id"].as_i64().unwrap()).collect();
|
||||
threads.sort_unstable();
|
||||
assert_eq!(threads, vec![601, 603]);
|
||||
let renames = h.wait_for_calls("editForumTopic", 1).await;
|
||||
assert_eq!(renames[0]["message_thread_id"], 602);
|
||||
assert_eq!(renames[0]["name"], "beta · Qwen 3.6 (chiusa)");
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let saved = saved_topics(home.path());
|
||||
assert_eq!(
|
||||
saved["topics"],
|
||||
json!([
|
||||
{"chat_id": CHAT, "session": "s2", "thread": 602, "name": "beta · Qwen 3.6 (chiusa)"},
|
||||
{"chat_id": CHAT, "session": "s4", "thread": 604, "name": "delta · Qwen 3.6 (chiusa)"},
|
||||
])
|
||||
);
|
||||
assert_eq!(h.calls("editForumTopic").await.len(), 1, "s4 is not renamed again");
|
||||
}
|
||||
|
||||
/// The message id the mock gave to the `index`-th sendMessage (ids start at 1000).
|
||||
async fn list_message_id(_h: &Harness, index: usize) -> i64 {
|
||||
1000 + index as i64
|
||||
}
|
||||
|
||||
fn settings_updated(thread: &str, mode: &str, sandbox: &str) -> Value {
|
||||
json!({"threadId": thread, "threadSettings": {
|
||||
"cwd": "/tmp/alfa", "approvalPolicy": "never", "approvalsReviewer": "user",
|
||||
"sandboxPolicy": {"type": sandbox}, "activePermissionProfile": null,
|
||||
"model": "qwen", "modelProvider": "p", "serviceTier": null, "effort": null,
|
||||
"summary": null, "personality": null,
|
||||
"collaborationMode": {"mode": mode, "settings": {"model": "qwen",
|
||||
"reasoning_effort": null, "developer_instructions": null}}}})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_reports_the_session_mode() {
|
||||
let h = Harness::start().await;
|
||||
h.start_thread("t1", "/tmp/alfa");
|
||||
let cases = [
|
||||
("default", "dangerFullAccess", "Modalità: accesso completo"),
|
||||
("plan", "dangerFullAccess", "Modalità: plan"),
|
||||
("default", "readOnly", "Modalità: default"),
|
||||
];
|
||||
for (index, (mode, sandbox, expected)) in cases.into_iter().enumerate() {
|
||||
h.notify("thread/settings/updated", settings_updated("t1", mode, sandbox));
|
||||
h.push_update(text_message(CHAT, "/stato", None));
|
||||
let sends = h.wait_for_calls("sendMessage", index + 1).await;
|
||||
let text = sends[index]["text"].as_str().unwrap();
|
||||
assert!(text.contains(expected), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user