Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
31r telegram-unpair-clears-cards: Unpair and /stop clear the buttons on cards in the chat (#935)
Oleksandr Ivanchenko5567e14cc333
diff --git a/src/db/telegram.rs b/src/db/telegram.rsindex da122ece..72514d9d 100644--- a/src/db/telegram.rs+++ b/src/db/telegram.rs@@ -315,8 +315,12 @@ impl Database {}/// Ends the pairing (Unpair, /stop). The pairing is kept for `undo_until` so Undo can bring- /// it back; the approvals switch goes off either way (A23).- pub async fn telegram_unpair(&self, space: &str, undo_until: Option<DateTime<Utc>>) -> Result<Option<TelegramLink>, DbError> {+ /// it back; the approvals switch goes off either way (A23). Every ask closes with Allow once+ /// off. The asks that were open are returned as they were closed, with `allow` as it was (so+ /// the caller knows which went out with Allow once) and the Telegram message id they had at+ /// that moment: the caller edits those that have one, and the sender edits the others once+ /// their id is stored (31r, see [`Self::telegram_ask_sent`]).+ pub async fn telegram_unpair(&self, space: &str, undo_until: Option<DateTime<Utc>>) -> Result<Option<(TelegramLink, Vec<TelegramAsk>)>, DbError> {let Some(link) = self.telegram_link(space).await? else { return Ok(None) };if !link.is_paired() {return Ok(None);@@ -339,8 +343,14 @@ impl Database {.bind(PAIRED).execute(&self.pool).await?;- sqlx::query("UPDATE telegram_asks SET state = 'closed' WHERE space_id = ?").bind(space).execute(&self.pool).await?;- Ok(Some(link))+ let mut tx = self.pool.begin().await?;+ let closed = sqlx::query_as::<_, TelegramAsk>("UPDATE telegram_asks SET state = 'closed' WHERE space_id = ? AND state = 'open' RETURNING *")+ .bind(space)+ .fetch_all(&mut *tx)+ .await?;+ sqlx::query("UPDATE telegram_asks SET allow = 0 WHERE space_id = ? AND allow = 1").bind(space).execute(&mut *tx).await?;+ tx.commit().await?;+ Ok(Some((link, closed)))}/// Undo of an Unpair within its window. The approvals switch stays off.diff --git a/src/server/telegram/bridge.rs b/src/server/telegram/bridge.rsindex 1aab3c74..8fe9b22c 100644--- a/src/server/telegram/bridge.rs+++ b/src/server/telegram/bridge.rs@@ -144,8 +144,9 @@ pub async fn handle_update(state: &AppState, runner: &Runner, u: &Value) {return;};if is_command(text, "stop") {- if state.db.telegram_unpair(&runner.space, None).await.ok().flatten().is_some() {+ if let Some((_, closed)) = state.db.telegram_unpair(&runner.space, None).await.ok().flatten() {runner.enqueue(chat_id, plain(copy::UNPAIRED));+ unpaired(state, &runner.space, closed).await;emit_status(state, &runner.space);}return;@@ -721,21 +722,69 @@ pub async fn allow_off(state: &AppState, space: &str) {}}+/// Unpair or /stop closed `closed` (the asks that were open, as they were closed, `allow` as it+/// was): the cards already in the chat lose the buttons a tap would answer with, so none looks+/// like it can still be answered there (31r). An approval sent with Allow once becomes link-only,+/// as when Allow approvals goes off: the bot still waits in kwant. A question keeps its text and+/// says it was unpaired. An approval sent link-only and a human step's alert have only the Open in+/// kwant link, which still holds: they stay as they are. Offline the edit is skipped; a tap is+/// refused either way (the ask is closed).+///+/// A card still on its way has no message id yet, so it can't be edited here: the sender edits it+/// as soon as its id is stored ([`ask_sent`]).+pub async fn unpaired(state: &AppState, space: &str, closed: Vec<TelegramAsk>) {+ let Some(r) = runner(state, space) else { return };+ for ask in closed.iter().filter(|a| a.message_id.is_some()) {+ if ask.kind == "question" || (ask.kind == "approval" && ask.allow) {+ unpaired_card(state, &r, ask).await;+ }+ }+}++/// A question or an approval that went out with Allow once, after Unpair or /stop.+async fn unpaired_card(state: &AppState, r: &Runner, ask: &TelegramAsk) {+ if ask.kind == "approval" {+ return link_only(state, r, ask, &approval_details(state, ask).await).await;+ }+ let Ok(Some(link)) = state.db.telegram_link(&ask.space_id).await else { return };+ let html = format!("{}\n\n<i>{}</i>", ask.text, text::escape(copy::UNPAIRED));+ edit(state, r, ask, html, open_markup(state, &link, &ask.space_id, None).await);+}++/// Whether an ask's source still waits for the person in kwant (the approval pending, the question+/// or human step open), read as it is now.+async fn still_waiting(state: &AppState, ask: &TelegramAsk) -> bool {+ match ask.kind.as_str() {+ "approval" => state.db.get_approval(&ask.ref_id).await.ok().flatten().is_some_and(|a| a.status == "pending"),+ "question" => state.db.get_question(&ask.ref_id).await.ok().flatten().is_some_and(|q| q.status == "open"),+ "alert" => state.db.get_human_step(&ask.ref_id).await.ok().flatten().is_some_and(|s| s.status == "open"),+ _ => false,+ }+}+/// An ask has just been sent and its Telegram id stored (`ask` is the row after that). Nothing/// could edit it while it was on its way, so what changed meanwhile is edited now:-/// - closed (answered in kwant, its turn ended): its buttons go and it gets the line its source-/// says ([`close_and_edit`] left it to the sender);+/// - closed by Unpair or /stop and still waiting in kwant, with the space still unpaired: what+/// [`unpaired`] does to the cards already in the chat (31r): a question or an approval sent+/// with Allow once gets the unpaired form, any other card stays as sent;+/// - closed otherwise (answered in kwant, its turn ended): its buttons go and it gets the line its+/// source says ([`close_and_edit`] left it to the sender);/// - sent with Allow once but the switch went off: it becomes link-only.pub async fn ask_sent(state: &AppState, r: &Runner, ask: &TelegramAsk, markup: Option<&Value>) {+ let sent_armed = markup+ .and_then(|m| m["inline_keyboard"].as_array())+ .is_some_and(|rows| rows.iter().filter_map(Value::as_array).flatten().any(|b| b["callback_data"].as_str().is_some_and(|d| d.starts_with("a:"))));if ask.state == "closed" {- if let Some(line) = closed_line(state, ask).await {+ let not_paired = state.db.telegram_link(&ask.space_id).await.ok().flatten().is_some_and(|l| !l.is_paired());+ if not_paired && still_waiting(state, ask).await {+ if ask.kind == "question" || (ask.kind == "approval" && sent_armed) {+ unpaired_card(state, r, ask).await;+ }+ } else if let Some(line) = closed_line(state, ask).await {edit_answered(state, r, ask, &line).await;}return;}- let sent_armed = markup- .and_then(|m| m["inline_keyboard"].as_array())- .is_some_and(|rows| rows.iter().filter_map(Value::as_array).flatten().any(|b| b["callback_data"].as_str().is_some_and(|d| d.starts_with("a:"))));if sent_armed && ask.kind == "approval" && ask.state == "open" && !ask.allow {link_only(state, r, ask, &approval_details(state, ask).await).await;}diff --git a/src/server/telegram/routes.rs b/src/server/telegram/routes.rsindex 2ff88555..dcf12157 100644--- a/src/server/telegram/routes.rs+++ b/src/server/telegram/routes.rs@@ -219,11 +219,12 @@ pub async fn unpair(State(state): State<AppState>, headers: HeaderMap, Scope(spa}let space = space.as_str().to_string();let until = crate::clock::now() + chrono::Duration::seconds(UNDO_SECS);- match state.db.telegram_unpair(&space, Some(until)).await {- Ok(Some(_)) => {}+ let closed = match state.db.telegram_unpair(&space, Some(until)).await {+ Ok(Some((_, closed))) => closed,Ok(None) => return fail(StatusCode::CONFLICT, "not_paired", "Telegram isn't paired."),Err(e) => return db_error(e),- }+ };+ bridge::unpaired(&state, &space, closed).await;emit_status(&state, &space);Json(view(&state, &space).await).into_response()}diff --git a/tests/telegram_test.rs b/tests/telegram_test.rsindex 6979a8a5..0175f71a 100644--- a/tests/telegram_test.rs+++ b/tests/telegram_test.rs@@ -823,6 +823,110 @@ async fn unpair_undo_and_disconnect() {assert_eq!((s, v["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("no_token")));}+/// The asks in the space, as the database has them now.+async fn asks_of(env: &Env, kind: &str, id: &str) -> Vec<kwnt::db::telegram::TelegramAsk> {+ env.state.db.telegram_asks_for(kind, id).await.unwrap()+}++/// Each of `ids` was edited exactly once (after a pause for a second edit to show up).+async fn edited_once(tg: &mock_telegram::MockTelegram, bot: &Bot, ids: &[i64]) {+ tokio::time::sleep(Duration::from_millis(800)).await;+ for id in ids {+ let edits: Vec<_> = tg.calls_of(bot, "editMessageText").into_iter().filter(|c| c.message_id() == *id).collect();+ assert_eq!(edits.len(), 1, "message {id} edited once: {edits:?}");+ }+}++// 31r (Juno's 31j finding): Unpair closes every ask in the space. The cards already in the chat+// lose their buttons at once, and no Allow once on them counts: an approval says "Approve it in+// kwant." (the bot is still waiting there), a question says it was unpaired, and a card that went+// out link-only stays as it was+#[tokio::test]+async fn unpair_clears_the_buttons_on_cards_already_in_the_chat() {+ let env = setup().await;+ let tg = mock_telegram::shared();+ let bot = paired(&env, tg, 70).await;+ let (s, _) = call(&env.app, "PATCH", BASE, Some(json!({"allow_approvals": true}))).await;+ assert_eq!(s, StatusCode::OK);++ let (id, mut rx) = approval(&env, json!({"source": "mcp", "tool": "unpair_card", "server": "files"})).await;+ let card = tg.wait_send(&bot, |c| c.text().contains("<code>unpair_card</code>")).await;+ assert!(card.callbacks().iter().any(|c| c.starts_with("a:")), "it went out with Allow once: {:?}", card.callbacks());+ let q = ask(&env, "Unpair question?", &["Yes", "No"]).await;+ let qmsg = tg.wait_send(&bot, |c| c.text().contains("Unpair question?")).await;+ assert!(!qmsg.callbacks().is_empty(), "it went out with answer buttons");+ // Sent link-only (a command is never allowed from Telegram): nothing on it to take back+ let (shell_id, _shell_rx) = approval(&env, json!({"source": "local_shell", "tool": "Bash"})).await;+ let shell = tg.wait_send(&bot, |c| c.text().contains("<code>Bash</code>")).await;+ assert!(shell.callbacks().is_empty(), "{:?}", shell.buttons());+ for (kind, ref_id) in [("approval", &id), ("question", &q.id), ("approval", &shell_id)] {+ wait_for("the card's id stored", || async { asks_of(&env, kind, ref_id).await.iter().all(|a| a.message_id.is_some()) }).await;+ }++ let (s, v) = call(&env.app, "POST", &format!("{BASE}/unpair"), None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let asks = asks_of(&env, "approval", &id).await;+ assert!(asks.iter().all(|a| a.state == "closed" && !a.allow), "closed with Allow once off: {asks:?}");++ let edited = tg.wait_edit(&bot, |c| c.message_id() == card.message_id()).await;+ assert!(edited.callbacks().is_empty(), "no live Allow once: {:?}", edited.buttons());+ assert!(edited.text().ends_with("<i>Approve it in kwant.</i>"), "{}", edited.text());+ let edited = tg.wait_edit(&bot, |c| c.message_id() == qmsg.message_id()).await;+ assert!(edited.callbacks().is_empty(), "no answer buttons: {:?}", edited.buttons());+ assert!(edited.text().contains("Unpair question?"), "keeps its text: {}", edited.text());+ assert!(edited.text().ends_with("<i>Unpaired. Pair again from kwant › Connections.</i>"), "{}", edited.text());+ edited_once(tg, &bot, &[card.message_id(), qmsg.message_id()]).await;+ let shell_edits = tg.calls_of(&bot, "editMessageText").into_iter().filter(|c| c.message_id() == shell.message_id()).count();+ assert_eq!(shell_edits, 0, "the link-only card stays as sent, no second \"Approve it in kwant.\"");++ // Nothing was answered: the bot still waits in kwant+ assert_eq!(env.state.db.get_approval(&id).await.unwrap().unwrap().status, "pending");+ assert!(rx.try_recv().is_err(), "nothing decided");+ assert_eq!(env.state.db.get_question(&q.id).await.unwrap().unwrap().status, "open");+}++// 31r: /stop does the same from the chat, also for a card still on its way when it came: once that+// card arrives it is made link-only, not "No longer waiting" (the bot is still waiting in kwant)+#[tokio::test]+async fn stop_clears_the_buttons_also_on_a_card_on_its_way() {+ let env = setup().await;+ let tg = mock_telegram::shared();+ let bot = paired(&env, tg, 71).await;+ let (s, _) = call(&env.app, "PATCH", BASE, Some(json!({"allow_approvals": true}))).await;+ assert_eq!(s, StatusCode::OK);++ let (sent_id, _rx) = approval(&env, json!({"source": "mcp", "tool": "stop_sent", "server": "files"})).await;+ let sent = tg.wait_send(&bot, |c| c.text().contains("<code>stop_sent</code>")).await;+ assert!(sent.callbacks().iter().any(|c| c.starts_with("a:")), "it went out with Allow once: {:?}", sent.callbacks());+ wait_for("the card's id stored", || async { asks_of(&env, "approval", &sent_id).await.iter().all(|a| a.message_id.is_some()) }).await;++ let held = tg.hold(&bot, "sendMessage", "<code>stop_flight</code>");+ let (flight_id, _rx2) = approval(&env, json!({"source": "mcp", "tool": "stop_flight", "server": "files"})).await;+ tg.wait_held(&bot, "sendMessage", "<code>stop_flight</code>").await;+ tg.text(&bot, &PERSON, "/stop");+ wait_for("unpaired", || async { status(&env).await["state"] == "token_saved" }).await;+ closed_on_its_way(&env, "approval", &flight_id).await;+ for id in [&sent_id, &flight_id] {+ let asks = asks_of(&env, "approval", id).await;+ assert!(asks.iter().all(|a| a.state == "closed" && !a.allow), "closed with Allow once off: {asks:?}");+ }+ held.release();++ let edited = tg.wait_edit(&bot, |c| c.message_id() == sent.message_id()).await;+ assert!(edited.callbacks().is_empty(), "no live Allow once: {:?}", edited.buttons());+ assert!(edited.text().ends_with("<i>Approve it in kwant.</i>"), "{}", edited.text());+ let flight = tg.wait_send(&bot, |c| c.text().contains("<code>stop_flight</code>") && c.body.get("__sent_id").is_some()).await;+ assert!(flight.callbacks().iter().any(|c| c.starts_with("a:")), "it went out with Allow once: {:?}", flight.callbacks());+ let edited = tg.wait_edit(&bot, |c| c.message_id() == flight.message_id()).await;+ assert!(edited.callbacks().is_empty(), "no live Allow once: {:?}", edited.buttons());+ assert!(edited.text().ends_with("<i>Approve it in kwant.</i>"), "{}", edited.text());+ tg.wait_send(&bot, |c| c.text() == "Unpaired. Pair again from kwant › Connections.").await;+ edited_once(tg, &bot, &[sent.message_id(), flight.message_id()]).await;+ for id in [&sent_id, &flight_id] {+ assert_eq!(env.state.db.get_approval(id).await.unwrap().unwrap().status, "pending");+ }+}+#[tokio::test]async fn a_revoked_token_stops_and_says_so() {let env = setup().await;