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:
andrea.difonzo
2026-11-12 12:46:19 +01:00
parent b04b36fa53
commit 973acc59c9
80 changed files with 1430 additions and 417 deletions

View File

@@ -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}");
}
}