diff --git a/crates/axe-core/src/config.rs b/crates/axe-core/src/config.rs index 2b38457..1595b21 100644 --- a/crates/axe-core/src/config.rs +++ b/crates/axe-core/src/config.rs @@ -837,6 +837,12 @@ pub struct Telegram { /// portal link Telegram shows (view, goal and task links): off, none. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub web_login: bool, + /// A "thinking" status in the owner's private chats: while a woken bot + /// has not yet answered, it also streams a `sendRichMessageDraft` with a + /// `` block (Bot API 10.1), shown as an animated status + /// line. Off (the default): `typing` only, as before. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub thinking_status: bool, } /// The retired `telegram.retro` table (one global retro slot, and a home diff --git a/crates/axe-telegram/src/telegram.rs b/crates/axe-telegram/src/telegram.rs index 3f7c08d..195fe57 100644 --- a/crates/axe-telegram/src/telegram.rs +++ b/crates/axe-telegram/src/telegram.rs @@ -51,6 +51,13 @@ pub const DOWNLOAD_LIMIT: u64 = 20 * 1024 * 1024; const TOAST_LIMIT: usize = 200; /// `typing` lasts 5 s or less; a live run's chats get it again this often. const TYPING_REFRESH: Duration = Duration::from_secs(4); +/// `[telegram] thinking_status`: the `sendRichMessageDraft` id of the +/// status line (non-zero; one per chat, so a change of text is animated). +const THINKING_DRAFT: i64 = 1; +/// The status line from an accepted owner message until its run starts. +pub const THINKING_WAKING: &str = "Waking up…"; +/// The status line while the woken run is live and has not answered. +pub const THINKING_WORKING: &str = "Working…"; /// Reaction set on every accepted owner message. pub const ACK_EMOJI: &str = "👀"; /// About one message per second per chat. @@ -573,6 +580,8 @@ pub struct Api { token: String, agent: ureq::Agent, poll_agent: ureq::Agent, + /// When a message last went out to each chat ([`Api::note_sent`]). + sent: Mutex>, } impl Api { @@ -588,9 +597,29 @@ impl Api { token: token.to_string(), agent: agent(120), poll_agent: agent(poll_timeout + 15), + sent: Mutex::new(HashMap::new()), } } + /// Records a successful `send*` of a message to `chat` (not a chat + /// action or a draft): Telegram clears a draft when the bot sends one. + fn note_sent(&self, method: &str, chat: Option) { + let draft = matches!( + method, + "sendChatAction" | "sendMessageDraft" | "sendRichMessageDraft" + ); + if let (true, false, Some(c)) = (method.starts_with("send"), draft, chat) { + let mut m = self.sent.lock().unwrap_or_else(|e| e.into_inner()); + m.insert(c, Instant::now()); + } + } + + /// When a message last went out to `chat` from this process. + fn last_sent(&self, chat: i64) -> Option { + let m = self.sent.lock().unwrap_or_else(|e| e.into_inner()); + m.get(&chat).copied() + } + fn clean(&self, s: &str) -> String { s.replace(&self.token, "") } @@ -651,7 +680,11 @@ impl Api { } else { &self.agent }; - self.finish(method, agent.post(&url).send_json(params.clone())) + let r = self.finish(method, agent.post(&url).send_json(params.clone())); + if r.is_ok() { + self.note_sent(method, params["chat_id"].as_i64()); + } + r } /// Uploads one file with multipart/form-data. @@ -686,7 +719,7 @@ impl Api { body.extend_from_slice(bytes); body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); let url = format!("{}/bot{}/{method}", self.base, self.token); - self.finish( + let r = self.finish( method, self.agent .post(&url) @@ -695,7 +728,12 @@ impl Api { &format!("multipart/form-data; boundary={boundary}"), ) .send_bytes(&body), - ) + ); + if r.is_ok() { + let chat = fields.iter().find(|(k, _)| *k == "chat_id"); + self.note_sent(method, chat.and_then(|(_, v)| v.parse().ok())); + } + r } /// Downloads `file_path` from `getFile`, refusing more than `limit` bytes. @@ -756,6 +794,11 @@ pub struct TgBot { web: Option, /// `[telegram] web_login`: `/web` replies with a login link. web_login: bool, + /// `[telegram] thinking_status`: a draft status line besides `typing`. + thinking: bool, + /// When the owner's last accepted message or press in each chat (and + /// thread) arrived; its status line shows until the bot next sends there. + woke: Mutex), Instant>>, } #[derive(Default)] @@ -963,6 +1006,8 @@ impl Gateway { id: Mutex::new(None), web: web.clone(), web_login: cfg.web_login, + thinking: cfg.thinking_status, + woke: Mutex::new(HashMap::new()), }), ); } @@ -1488,7 +1533,7 @@ impl Gateway { voice_ack(b, store, chat, m["message_thread_id"].as_i64(), tg_id, msg); } } - b.typing(chat, m["message_thread_id"].as_i64()); + b.accepted(store, chat, m["message_thread_id"].as_i64()); } Ok(()) } @@ -1565,7 +1610,7 @@ impl Gateway { if let Some(t) = tg_msg { self.mark_selected(b, store, chat, t, target.as_ref(), &label); } - b.typing(chat, thread); + b.accepted(store, chat, thread); Ok(()) } @@ -3073,10 +3118,20 @@ impl Gateway { } } +/// The `sendRichMessageDraft` parameters of the status line `text` (plain +/// text, escaped here) in `chat`. +pub fn thinking_draft(chat: i64, text: &str) -> Value { + let html = format!("{}", html_escape(text)); + json!({"chat_id": chat, "draft_id": THINKING_DRAFT, "rich_message": {"html": html}}) +} + /// Keeps `typing` showing while the bot has a live run: about every /// [`TYPING_REFRESH`] in each chat whose message or button woke that run /// (wakes claimed at start or delivered through the hook). It stops when the /// run ends; runs without a chat wake (schedules, self-wakes) show nothing. +/// With `[telegram] thinking_status` each refresh also streams the +/// [`THINKING_WORKING`] status line to a private chat still awaiting the +/// bot's reply ([`TgBot::awaits_reply`]). fn typing_loop(b: &TgBot, store: &dyn Axe) { let mut last: HashMap<(i64, Option), Instant> = HashMap::new(); while !store.stopping() { @@ -3092,6 +3147,9 @@ fn typing_loop(b: &TgBot, store: &dyn Axe) { .is_none_or(|t| t.elapsed() >= TYPING_REFRESH); if due { b.typing(chat, thread); + if b.awaits_reply(chat, thread) { + b.thinking(chat, thread, THINKING_WORKING); + } last.insert((chat, thread), Instant::now()); } } @@ -3874,6 +3932,52 @@ impl TgBot { Ok(()) } + /// An owner message or press was accepted in `chat`: `typing`, and with + /// `[telegram] thinking_status` the status line in a private chat + /// ([`THINKING_WORKING`] when a run for it is already live). + fn accepted(&self, store: &dyn Axe, chat: i64, thread: Option) { + self.typing(chat, thread); + if !self.thinking || chat <= 0 { + return; + } + let mut woke = self.woke.lock().unwrap_or_else(|e| e.into_inner()); + woke.insert((chat, thread), Instant::now()); + drop(woke); + let live = store.live_chats(&self.name()).unwrap_or_default(); + let text = if live.contains(&(chat, thread)) { + THINKING_WORKING + } else { + THINKING_WAKING + }; + self.thinking(chat, thread, text); + } + + /// With `[telegram] thinking_status`: the owner's last message or press + /// in this private chat came after the bot's last message there. + fn awaits_reply(&self, chat: i64, thread: Option) -> bool { + if !self.thinking || chat <= 0 { + return false; + } + let woke = self.woke.lock().unwrap_or_else(|e| e.into_inner()); + let Some(w) = woke.get(&(chat, thread)).copied() else { + return false; + }; + self.api.last_sent(chat).is_none_or(|s| s < w) + } + + /// The status line: a `sendRichMessageDraft` (private chats only, a + /// 30-second preview Telegram clears when the bot sends a message) of + /// one `` block, best effort. `text` is plain (no markup). + fn thinking(&self, chat: i64, thread: Option, text: &str) { + let mut p = thinking_draft(chat, text); + if let Some(t) = thread { + p["message_thread_id"] = json!(t); + } + if let Err(e) = self.api.call("sendRichMessageDraft", &p) { + eprintln!("telegram: bot {}: {e}", self.name()); + } + } + /// `sendChatAction typing`, best effort. fn typing(&self, chat: i64, thread: Option) { let mut p = json!({"chat_id": chat, "action": "typing"}); diff --git a/crates/axe/tests/telegram.rs b/crates/axe/tests/telegram.rs index b907842..4b80614 100644 --- a/crates/axe/tests/telegram.rs +++ b/crates/axe/tests/telegram.rs @@ -971,6 +971,92 @@ fn typing_is_refreshed_while_a_woken_run_is_live() { assert_eq!(rig.stub.calls("sendChatAction").len(), n, "typing stopped"); } +/// Claims bot `cos`'s due wake: its run is live until [`bot::finish`]. +fn start_run(rig: &Rig) -> (rusqlite::Connection, i64) { + let mut conn = rig.db(); + let tx = conn.transaction().unwrap(); + let c = bot::claim(&tx, "cos", None, "c1", "d", "g", axe::remote::epoch() + 30) + .unwrap() + .expect("the message wake is due"); + tx.commit().unwrap(); + (conn, c.run) +} + +#[test] +fn thinking_status_off_sends_typing_only() { + let rig = Rig::new(); + rig.stub.push(text_msg(30, 50, OWNER, OWNER, "hello")); + rig.stub.wait_confirmed(30); + let _run = start_run(&rig); + wait_for("typing refreshes", 30, || { + rig.stub.calls("sendChatAction").len() >= 3 + }); + // Today's calls, unchanged: the exact typing payload and no draft. + for c in rig.stub.calls("sendChatAction") { + assert_eq!(c.params, json!({"chat_id": OWNER, "action": "typing"})); + } + assert!(rig.stub.calls("sendRichMessageDraft").is_empty()); + assert!(rig.stub.calls("sendMessageDraft").is_empty()); +} + +#[test] +fn thinking_status_on_streams_a_thinking_draft_until_the_bot_replies() { + let rig = Rig::with("thinking_status = true"); + let drafts = || rig.stub.calls("sendRichMessageDraft"); + let draft = |text: &str| { + json!({"chat_id": OWNER, "draft_id": 1, + "rich_message": {"html": format!("{text}")}}) + }; + // Accepted: typing as before, plus the waking status line. + rig.stub.push(text_msg(30, 50, OWNER, OWNER, "hello")); + rig.stub.wait_confirmed(30); + wait_for("waking draft", 20, || drafts().len() == 1); + assert_eq!(drafts()[0].params, draft("Waking up…")); + assert_eq!(rig.stub.calls("sendChatAction").len(), 1); + + // The live run: each typing refresh also streams the working line. + let (conn, run) = start_run(&rig); + wait_for("working drafts", 30, || drafts().len() >= 3); + for c in &drafts()[1..] { + assert_eq!(c.params, draft("Working…")); + } + for c in rig.stub.calls("sendChatAction") { + assert_eq!(c.params, json!({"chat_id": OWNER, "action": "typing"})); + } + + // The bot answers: Telegram clears the draft, and no new one follows + // while typing goes on. + rig.tg_ok(&["send", "done"]); + let n = drafts().len(); + let t = rig.stub.calls("sendChatAction").len(); + wait_for("typing goes on", 30, || { + rig.stub.calls("sendChatAction").len() >= t + 2 + }); + assert_eq!(drafts().len(), n, "no draft after the reply"); + + // A group gets typing only: drafts are for private chats. + rig.stub + .push(text_msg(31, 51, OWNER, GROUP, "in the group")); + rig.stub.wait_confirmed(31); + wait_for("group typing", 20, || { + rig.stub + .calls("sendChatAction") + .iter() + .any(|c| c.params["chat_id"] == GROUP) + }); + assert!(drafts().iter().all(|c| c.params["chat_id"] == OWNER)); + bot::finish( + &conn, + run, + Some(0), + "exit", + None, + None, + axe::remote::epoch(), + ) + .unwrap(); +} + #[test] fn unauthorized_group_membership_makes_the_bot_leave() { let rig = Rig::new(); diff --git a/docs/design/bots.md b/docs/design/bots.md index 59b0c9c..dfbfbe6 100644 --- a/docs/design/bots.md +++ b/docs/design/bots.md @@ -214,6 +214,13 @@ commands. `/node` is the node's latest sample, the same for every bot budget-style bars, runs by kind, one versions line; no quote block). Which bot runs and its services and schedules stay in that bot's `/status`, so the two never repeat. `/web` replies in the owner's private chat with a one-time web login link, only with `[telegram] web_login = true` (off by default, for Telegram-only installs; `Gateway::web_reply` in `telegram.rs`, the key in `config.rs`). The same key gates every other portal link Telegram shows (view links, board goal and task links, a form's task): `Gateway::new` drops the public URL when it is off. +`[telegram] thinking_status = true` (off by default, task 2528, store doc +`harvis/research/20261203-telegram-rich-entities.md`) adds a status line next to +`typing`. In a private chat it is a `sendRichMessageDraft` with one +`` block, "Waking up…" on accept and "Working…" on each typing +refresh. It stops once the bot sends to that chat (`TgBot::awaits_reply`); +Telegram clears the draft then, or after 30 s. The server adds it, so the +model writes no markup. ### Board diff --git a/docs/user/primitives/bot.md b/docs/user/primitives/bot.md index edd8e57..7efe41b 100644 --- a/docs/user/primitives/bot.md +++ b/docs/user/primitives/bot.md @@ -39,6 +39,12 @@ Links to the web portal in Telegram (command replies, goal and task links on the board pin, a form's task) appear only with `[telegram] web_login` on; off, the default, none do. Blob links and sealed form buttons are not portal links. One gate: `Gateway::new` in `crates/axe-telegram/src/telegram.rs`. +While a bot works on the owner's message, the chat shows Telegram's `typing` +status. With `[telegram] thinking_status = true` (off by default), the +owner's private chat also shows an animated status line, "Waking up…" and +then "Working…", until the bot's next message there. Groups get `typing` +only, and a client without draft support shows `typing` only. See +`TgBot::accepted` and `typing_loop` in `crates/axe-telegram/src/telegram.rs`. The bot protocol (runs, wakes, memory, authority, Telegram) is built in; bundles in the [store](store.md) only add opinions. diff --git a/docs/user/reference/config.md b/docs/user/reference/config.md index 7f5e3f4..81eb835 100644 --- a/docs/user/reference/config.md +++ b/docs/user/reference/config.md @@ -12,6 +12,11 @@ names aligned when they run on different machines. Unknown keys fail validation. keys still load and are reported once at server start: `[telegram] web_url` (the board pin has no buttons or web links) and `[telegram.retro]` (set per bot). +Opt-in `[telegram]` switches, all off by default: `web_login` (the `/web` +command and every portal link in Telegram) and `thinking_status` (an +animated "Working…" status line in the owner's private chat while a woken +bot has not answered yet, made with `sendRichMessageDraft`, Bot API 10.1; +see [bots](../primitives/bot.md)). `crates/axe-core/src/config.rs` defines every table, default and check; `axe config` validates and prints the resolved file, including the built-in agents.