Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/axe-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
/// `<tg-thinking>` 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
Expand Down
114 changes: 109 additions & 5 deletions crates/axe-telegram/src/telegram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<HashMap<i64, Instant>>,
}

impl Api {
Expand All @@ -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<i64>) {
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<Instant> {
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, "<token>")
}
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -756,6 +794,11 @@ pub struct TgBot {
web: Option<String>,
/// `[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<HashMap<(i64, Option<i64>), Instant>>,
}

#[derive(Default)]
Expand Down Expand Up @@ -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()),
}),
);
}
Expand Down Expand Up @@ -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(())
}
Expand Down Expand Up @@ -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(())
}

Expand Down Expand Up @@ -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!("<tg-thinking>{}</tg-thinking>", 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<i64>), Instant> = HashMap::new();
while !store.stopping() {
Expand All @@ -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());
}
}
Expand Down Expand Up @@ -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<i64>) {
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<i64>) -> 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 `<tg-thinking>` block, best effort. `text` is plain (no markup).
fn thinking(&self, chat: i64, thread: Option<i64>, 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<i64>) {
let mut p = json!({"chat_id": chat, "action": "typing"});
Expand Down
86 changes: 86 additions & 0 deletions crates/axe/tests/telegram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!("<tg-thinking>{text}</tg-thinking>")}})
};
// 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();
Expand Down
7 changes: 7 additions & 0 deletions docs/design/bots.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<tg-thinking>` 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

Expand Down
6 changes: 6 additions & 0 deletions docs/user/primitives/bot.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions docs/user/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading