Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

31g telegram-closed-card-in-flight: edit a card that closed on its way as soon as it arrives (#918)

Oleksandr Ivanchenko75851a90da5c
diff --git a/src/db/telegram.rs b/src/db/telegram.rs
index cdfae3f8..da122ece 100644
--- a/src/db/telegram.rs
+++ b/src/db/telegram.rs
@@ -550,6 +550,14 @@ impl Database {
Ok(r.rows_affected() == 1)
}
+ /// Closes an open ask and returns it as it was closed: `None` for every caller but the one that
+ /// closed it. One statement, so it and [`Self::telegram_ask_sent`] agree on who edits a card
+ /// closed around the time it was sent: the closer when the id was already stored (its
+ /// `message_id` is set), the sender otherwise (it reads `closed`).
+ pub async fn telegram_close_open_ask(&self, id: &str) -> Result<Option<TelegramAsk>, DbError> {
+ Ok(sqlx::query_as::<_, TelegramAsk>("UPDATE telegram_asks SET state = 'closed' WHERE id = ? AND state = 'open' RETURNING *").bind(id).fetch_optional(&self.pool).await?)
+ }
+
pub async fn telegram_reopen_ask(&self, id: &str) -> Result<(), DbError> {
sqlx::query("UPDATE telegram_asks SET state = 'open' WHERE id = ?").bind(id).execute(&self.pool).await?;
Ok(())
diff --git a/src/server/telegram/bridge.rs b/src/server/telegram/bridge.rs
index 381ce1a1..1aab3c74 100644
--- a/src/server/telegram/bridge.rs
+++ b/src/server/telegram/bridge.rs
@@ -444,16 +444,10 @@ async fn on_question(state: &AppState, q: &Value) {
let Some(space) = state.db.space_of_kwant(kwant).await.ok().flatten() else { return };
let space = space.as_str().to_string();
if status != "open" {
- let line = match (status, q["answered_via"].as_str()) {
- ("answered", Some("telegram")) => return,
- ("answered", _) => format!("{TEAL_CHECK} Answered in kwant · {}", hhmm(state).await),
- _ => format!("<i>{}</i>", text::escape(copy::NO_LONGER_WAITING)),
- };
+ let Some(line) = question_line(state, status, q["answered_via"].as_str()).await else { return };
for ask in state.db.telegram_asks_for("question", id).await.unwrap_or_default() {
- if ask.state == "open" && state.db.telegram_close_ask(&ask.id).await.unwrap_or(false) {
- if let Some(r) = runner(state, &ask.space_id) {
- edit_answered(state, &r, &ask, &line).await;
- }
+ if ask.state == "open" {
+ close_and_edit(state, &ask, &line).await;
}
}
return;
@@ -552,11 +546,8 @@ async fn on_human_step(state: &AppState, step: &Value) {
let (Some(id), Some(status), Some(kwant)) = (step["id"].as_str(), step["status"].as_str(), step["kwant_id"].as_str()) else { return };
if status != "open" {
for ask in state.db.telegram_asks_for("alert", id).await.unwrap_or_default() {
- if ask.state == "open" && state.db.telegram_close_ask(&ask.id).await.unwrap_or(false) {
- if let Some(r) = runner(state, &ask.space_id) {
- let line = if status == "done" { format!("{TEAL_CHECK} Done in kwant · {}", hhmm(state).await) } else { format!("<i>{}</i>", text::escape(copy::NO_LONGER_WAITING)) };
- edit_answered(state, &r, &ask, &line).await;
- }
+ if ask.state == "open" {
+ close_and_edit(state, &ask, &step_line(state, status).await).await;
}
}
return;
@@ -646,14 +637,73 @@ pub async fn approval_answered(state: &AppState, id: &str, via: Option<&str>) {
async fn approval_closed(state: &AppState, id: &str, line: &str) {
for ask in state.db.telegram_asks_for("approval", id).await.unwrap_or_default() {
- if ask.state == "open" && state.db.telegram_close_ask(&ask.id).await.unwrap_or(false) {
- if let Some(r) = runner(state, &ask.space_id) {
- edit_answered(state, &r, &ask, line).await;
- }
+ if ask.state == "open" {
+ close_and_edit(state, &ask, line).await;
}
}
}
+/// Closes an open ask its source closed (answered in kwant, or no longer waiting) and edits its
+/// Telegram copy to `line`. A copy still on its way has no message id yet: the sender edits it
+/// once its id is stored ([`ask_sent`]), so it never keeps live buttons.
+async fn close_and_edit(state: &AppState, ask: &TelegramAsk, line: &str) {
+ // The row as it was closed, not as it was read: its id may have been stored in between
+ let Ok(Some(closed)) = state.db.telegram_close_open_ask(&ask.id).await else { return };
+ if let Some(r) = runner(state, &closed.space_id) {
+ edit_answered(state, &r, &closed, line).await;
+ }
+}
+
+/// The line a question's Telegram copy gets once the question isn't open; `None` when it was
+/// answered from Telegram (the answer edited it).
+async fn question_line(state: &AppState, status: &str, via: Option<&str>) -> Option<String> {
+ match (status, via) {
+ ("answered", Some("telegram")) => None,
+ ("answered", _) => Some(format!("{TEAL_CHECK} Answered in kwant · {}", hhmm(state).await)),
+ _ => Some(format!("<i>{}</i>", text::escape(copy::NO_LONGER_WAITING))),
+ }
+}
+
+/// The line a human step's alert gets once the step isn't open.
+async fn step_line(state: &AppState, status: &str) -> String {
+ if status == "done" {
+ format!("{TEAL_CHECK} Done in kwant · {}", hhmm(state).await)
+ } else {
+ format!("<i>{}</i>", text::escape(copy::NO_LONGER_WAITING))
+ }
+}
+
+/// The line an approval's Telegram copy gets once it closed: "Answered in kwant" for a person's
+/// answer there, "No longer waiting" for a card nobody answered (its turn ended, it expired), as
+/// [`approval_answered`] and the `ApprovalWithdrawn` listener say. `None` when it was answered from
+/// Telegram (the tap edited it).
+async fn approval_line(state: &AppState, approval_id: &str) -> Option<String> {
+ let a = state.db.get_approval(approval_id).await.ok().flatten();
+ match a {
+ Some(a) if RuntimeEvent::is_answer(Some(a.status.as_str())) => match a.answered_via.as_deref() {
+ Some("telegram") => None,
+ _ => Some(format!("{TEAL_CHECK} Answered in kwant · {}", hhmm(state).await)),
+ },
+ _ => Some(format!("<i>{}</i>", text::escape(copy::NO_LONGER_WAITING))),
+ }
+}
+
+/// The line for an ask its source closed, read from the source as it is now.
+async fn closed_line(state: &AppState, ask: &TelegramAsk) -> Option<String> {
+ match ask.kind.as_str() {
+ "approval" => approval_line(state, &ask.ref_id).await,
+ "question" => {
+ let q = state.db.get_question(&ask.ref_id).await.ok().flatten()?;
+ question_line(state, &q.status, q.answered_via.as_deref()).await
+ }
+ "alert" => {
+ let step = state.db.get_human_step(&ask.ref_id).await.ok().flatten()?;
+ Some(step_line(state, &step.status).await)
+ }
+ _ => None,
+ }
+}
+
/// The person turned Allow approvals off: the switch goes off and every Allow once button still out
/// stops counting at once, in the database (`telegram_set_allow(false)` disarms them all). Their
/// messages are edited to link-only when kwant can reach Telegram; offline the edit is skipped, and
@@ -671,10 +721,18 @@ pub async fn allow_off(state: &AppState, space: &str) {
}
}
-/// An ask has just been sent and its Telegram id stored (`ask` is the row after that). If it went
-/// out with Allow once but the switch went off while it was on its way, nothing could edit it then,
-/// so it becomes link-only now.
+/// 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);
+/// - 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>) {
+ if ask.state == "closed" {
+ 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:"))));
diff --git a/tests/support/mock_telegram.rs b/tests/support/mock_telegram.rs
index fe21ca56..4938d81e 100644
--- a/tests/support/mock_telegram.rs
+++ b/tests/support/mock_telegram.rs
@@ -20,6 +20,8 @@
//! token); a revoked one answers 401.
//! - [`MockTelegram::fault`] queues error answers for one method of one bot.
//! - Every call is kept with its JSON body ([`MockTelegram::calls`]).
+//! - [`MockTelegram::hold`] makes the next call of one method with a given text wait until the
+//! test releases it (a message still on its way to Telegram).
#![allow(dead_code)]
@@ -116,6 +118,19 @@ struct BotState {
updates: VecDeque<Value>,
calls: Vec<Call>,
faults: HashMap<String, VecDeque<(u16, Value)>>,
+ /// (method, text it contains, gate): the next such call waits on the gate ([`MockTelegram::hold`]).
+ holds: Vec<(String, String, Arc<tokio::sync::Notify>)>,
+ /// (method, body) of calls waiting on a hold, kept as calls only once released.
+ held: Vec<(String, Value)>,
+}
+
+/// A held call: [`Held::release`] lets it through.
+pub struct Held(Arc<tokio::sync::Notify>);
+
+impl Held {
+ pub fn release(&self) {
+ self.0.notify_one();
+ }
}
#[derive(Default)]
@@ -175,6 +190,15 @@ async fn handle(State(inner): State<Arc<Inner>>, Path((bot, method)): Path<(Stri
return reply(tg_error(404, "Not Found"));
};
let body: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
+ // A held call waits for the test (seen in `held` meanwhile), then is answered as usual
+ let gate = inner.bots.lock().unwrap().get_mut(&token).and_then(|b| {
+ let i = b.holds.iter().position(|(m, t, _)| *m == method && body["text"].as_str().is_some_and(|x| x.contains(t.as_str())))?;
+ b.held.push((method.clone(), body.clone()));
+ Some(b.holds.remove(i).2)
+ });
+ if let Some(gate) = gate {
+ gate.notified().await;
+ }
// getUpdates may wait for an update; everything else answers at once
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
loop {
@@ -260,6 +284,29 @@ impl MockTelegram {
}
}
+ /// The next call of `method` whose `text` contains `text` waits, unanswered (and not yet in
+ /// [`Self::calls`]), until the returned [`Held`] is released.
+ pub fn hold(&self, bot: &Bot, method: &str, text: &str) -> Held {
+ let gate = Arc::new(tokio::sync::Notify::new());
+ self.inner.bots.lock().unwrap().get_mut(&bot.token).expect("a mock bot").holds.push((method.to_string(), text.to_string(), gate.clone()));
+ Held(gate)
+ }
+
+ /// Waits (up to 60 s) until a call of `method` whose `text` contains `text` is waiting on a
+ /// hold; its body.
+ pub async fn wait_held(&self, bot: &Bot, method: &str, text: &str) -> Value {
+ for _ in 0..600 {
+ let found = self.inner.bots.lock().unwrap().get(&bot.token).and_then(|b| {
+ b.held.iter().find(|(m, body)| m == method && body["text"].as_str().is_some_and(|x| x.contains(text))).map(|(_, body)| body.clone())
+ });
+ if let Some(body) = found {
+ return body;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("no held {method} with {text:?}");
+ }
+
/// Queues an update (its `update_id` is added) and returns the id.
pub fn inject(&self, bot: &Bot, mut update: Value) -> i64 {
let id = {
diff --git a/tests/telegram_test.rs b/tests/telegram_test.rs
index eea81d45..9b1cd18a 100644
--- a/tests/telegram_test.rs
+++ b/tests/telegram_test.rs
@@ -1021,6 +1021,84 @@ async fn a_closed_card_says_where_and_how_it_was_answered() {
tg.wait_edit(&bot, |c| c.message_id() == card.message_id() && c.text().contains("No longer waiting")).await;
}
+/// Waits (up to 10 s) until every Telegram copy of `kind`/`id` is closed, and checks it closed
+/// while still on its way (no Telegram id stored yet).
+async fn closed_on_its_way(env: &Env, kind: &str, id: &str) {
+ for _ in 0..100 {
+ let asks = env.state.db.telegram_asks_for(kind, id).await.unwrap();
+ if !asks.is_empty() && asks.iter().all(|a| a.state == "closed") {
+ assert!(asks.iter().all(|a| a.message_id.is_none()), "closed after it arrived, not on its way: {asks:?}");
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("the {kind} copy of {id} never closed");
+}
+
+// 31g (main red at 5f3b4ef8): a card that closes while it is still on its way to Telegram has no
+// message id to edit yet. Once it arrives it is edited at once: its buttons go and it says what
+// its source says, never keeping a live Allow once
+#[tokio::test]
+async fn a_card_closed_on_its_way_is_edited_when_it_arrives() {
+ let env = setup().await;
+ let tg = mock_telegram::shared();
+ let bot = paired(&env, tg, 62).await;
+ let (s, _) = call(&env.app, "PATCH", BASE, Some(json!({"allow_approvals": true}))).await;
+ assert_eq!(s, StatusCode::OK);
+ let mut events = env.state.event_sender.subscribe();
+
+ // Denied in kwant while its card is on its way: "Answered in kwant"
+ let held = tg.hold(&bot, "sendMessage", "<code>flight_deny</code>");
+ let (deny_id, rx) = approval(&env, json!({"source": "mcp", "tool": "flight_deny", "server": "files"})).await;
+ tg.wait_held(&bot, "sendMessage", "<code>flight_deny</code>").await;
+ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{deny_id}/resolve"), Some(json!({"decision": "deny"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(matches!(tokio::time::timeout(Duration::from_secs(20), rx).await.unwrap().unwrap(), ApprovalDecision::Deny));
+ closed_on_its_way(&env, "approval", &deny_id).await;
+ held.release();
+ let card = tg.wait_send(&bot, |c| c.text().contains("<code>flight_deny</code>")).await;
+ assert!(card.callbacks().iter().any(|c| c.starts_with("a:")), "it went out with Allow once: {:?}", card.callbacks());
+ let edited = tg.wait_edit(&bot, |c| c.message_id() == card.message_id()).await;
+ assert!(edited.text().contains("✓ Answered in kwant · "), "{}", edited.text());
+ assert!(edited.buttons().is_empty(), "no live Allow once: {:?}", edited.buttons());
+ let denied = card.message_id();
+
+ // Its turn ended while its card was on its way: "No longer waiting"
+ let held = tg.hold(&bot, "sendMessage", "<code>flight_ends</code>");
+ let waiting = ask_through_the_approver(&env, "turn-tg-flight", "flight_ends", false);
+ tg.wait_held(&bot, "sendMessage", "<code>flight_ends</code>").await;
+ let ended_id = env.state.broker.pending_ids().await.into_iter().next().expect("the card waits");
+ waiting.abort();
+ assert_eq!(withdrawn(&mut events, &ended_id).await, (None, Some("cancelled".into())));
+ closed_on_its_way(&env, "approval", &ended_id).await;
+ held.release();
+ let card = tg.wait_send(&bot, |c| c.text().contains("<code>flight_ends</code>")).await;
+ let edited = tg.wait_edit(&bot, |c| c.message_id() == card.message_id()).await;
+ assert!(edited.text().contains("No longer waiting"), "{}", edited.text());
+ assert!(edited.buttons().is_empty(), "no live Allow once: {:?}", edited.buttons());
+ let ended = card.message_id();
+
+ // A question answered in kwant while its copy was on its way: "Answered in kwant"
+ let held = tg.hold(&bot, "sendMessage", "Flight question?");
+ let q = ask(&env, "Flight question?", &["Yes", "No"]).await;
+ tg.wait_held(&bot, "sendMessage", "Flight question?").await;
+ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{}/answer", q.id), Some(json!({"choice": 0}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ closed_on_its_way(&env, "question", &q.id).await;
+ held.release();
+ let msg = tg.wait_send(&bot, |c| c.text().contains("Flight question?")).await;
+ let edited = tg.wait_edit(&bot, |c| c.message_id() == msg.message_id()).await;
+ assert!(edited.text().contains("✓ Answered in kwant · "), "{}", edited.text());
+ assert!(edited.buttons().is_empty());
+
+ // Each was edited once
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ for id in [denied, ended, msg.message_id()] {
+ let edits = tg.calls_of(&bot, "editMessageText").into_iter().filter(|c| c.message_id() == id).count();
+ assert_eq!(edits, 1, "message {id} edited once");
+ }
+}
+
// --- Stuck: the spending stop (Rigel's F-D1) -------------------------------------------------
/// The spending-stop notifications sent so far: (space_id, title, body).