From c755fc757446aa8bf1f2a1362ced213253f97e00 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:57:29 +0000 Subject: [PATCH 1/5] Addons can react to their own earlier posts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A react op may name an earlier post of the addon's in the same chat, by its op ID, in "post" (with "chat"), instead of a ref: for a chat game's ⏰ on its question with 5 seconds left. It's resolved as replyTo is, and follows the same permission, rate and lease rules as other reactions. An unknown post fails the op, without retry. feature.Message gets Bot, for the bot's own message: Signal reacts with the bot's own account as the target author, Telegram by message_id. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- addon/schema.json | 12 ++--- addon/schema_test.go | 11 +++++ addon/server.go | 2 +- addon/types.go | 8 +++- docs/FILES_LINKS_TOOLS_MCP.md | 2 +- internal/bot/bot.go | 6 ++- internal/bot/fakes_test.go | 9 +++- internal/bot/host.go | 2 +- internal/bot/host_test.go | 19 +++++++- internal/feature/feature.go | 4 +- internal/features/mcp/outbox.go | 47 +++++++++++++++----- internal/features/mcp/watch_test.go | 68 +++++++++++++++++++++++++++++ internal/signal/client_test.go | 25 +++++++++++ internal/signal/send.go | 12 ++++- internal/telegram/send.go | 6 +-- internal/telegram/telegram_test.go | 8 +++- 16 files changed, 210 insertions(+), 31 deletions(-) diff --git a/addon/schema.json b/addon/schema.json index fc189bc..cece2b6 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -99,22 +99,24 @@ "properties": { "id": {"description": "Unique among the addon's ops, for as long as the bot may read it again.", "type": "string", "minLength": 1}, "op": {"enum": ["post", "react", "unwatch"]}, - "chat": {"description": "A post's or unwatch's chat.", "type": "string", "pattern": "^c_[a-z2-7]{26}$"}, + "chat": {"description": "A post's or unwatch's chat, or that of the post a reaction with post is for.", "type": "string", "pattern": "^c_[a-z2-7]{26}$"}, "text": {"description": "A post's text, with {u_…} placeholders the bot fills in with names; at most 4000 characters, names filled in. A post with neither text nor images is dropped.", "type": "string"}, "images": {"description": "A post's images: at most 2, and 2 MiB in all.", "type": "array", "items": {"$ref": "#/$defs/Image"}, "maxItems": 2}, "audio": {"description": "A post's clip to play, MP3, at most 2 MiB: sent with no title of its own. A post with audio is never merged with another.", "$ref": "#/$defs/Audio"}, - "ref": {"description": "The message a reaction is for: a context's ref.", "type": "string", "pattern": "^r_[a-z2-7]{26}$"}, + "ref": {"description": "The message a reaction is for: a context's ref. A reaction has ref or post, not both.", "type": "string", "pattern": "^r_[a-z2-7]{26}$"}, "emoji": {"description": "A reaction's: one emoji.", "type": "string", "minLength": 1}, "watch": {"description": "The ID of the watch an unwatch ends.", "type": "string", "minLength": 1, "maxLength": 64}, - "replyTo": {"description": "A post's: the ID of an earlier post op of the addon's, such as a question, so the post is sent as a reply to it. The bot remembers the ID of each post op it sent (every op of a merged post), with its chat, for 24 hours, the last 256 IDs; a post whose replyTo it doesn't know, or that was sent in another chat, is sent as an ordinary post. A post with replyTo is never merged with another.", "type": "string", "minLength": 1} + "replyTo": {"description": "A post's: the ID of an earlier post op of the addon's, such as a question, so the post is sent as a reply to it. The bot remembers the ID of each post op it sent (every op of a merged post), with its chat, for 24 hours, the last 256 IDs; a post whose replyTo it doesn't know, or that was sent in another chat, is sent as an ordinary post. A post with replyTo is never merged with another.", "type": "string", "minLength": 1}, + "post": {"description": "A reaction's, in place of ref: the ID of an earlier post op of the addon's in chat, as replyTo names it, so the bot reacts to its own message, such as with ⏰ when a question's time runs out. A reaction to a post the bot doesn't remember sending in chat, such as one not sent yet, is dropped.", "type": "string", "minLength": 1} }, "required": ["id", "op"], "additionalProperties": false, "allOf": [ {"if": {"properties": {"op": {"const": "post"}}}, "then": {"required": ["chat"], "anyOf": [{"required": ["text"], "properties": {"text": {"pattern": "\\S"}}}, {"required": ["images"], "properties": {"images": {"minItems": 1}}}, {"required": ["audio"]}]}}, - {"if": {"properties": {"op": {"const": "react"}}}, "then": {"required": ["ref", "emoji"]}}, + {"if": {"properties": {"op": {"const": "react"}}}, "then": {"required": ["emoji"], "if": {"required": ["post"]}, "then": {"required": ["chat"], "not": {"required": ["ref"]}}, "else": {"required": ["ref"]}}}, {"if": {"properties": {"op": {"const": "unwatch"}}}, "then": {"required": ["chat", "watch"]}}, - {"if": {"required": ["replyTo"]}, "then": {"properties": {"op": {"const": "post"}}}} + {"if": {"required": ["replyTo"]}, "then": {"properties": {"op": {"const": "post"}}}}, + {"if": {"required": ["post"]}, "then": {"properties": {"op": {"const": "react"}}}} ] }, "Audio": { diff --git a/addon/schema_test.go b/addon/schema_test.go index a3fc029..eddac01 100644 --- a/addon/schema_test.go +++ b/addon/schema_test.go @@ -321,6 +321,10 @@ func validate(root, s map[string]any, v any, at string) error { return err } } + case "not": + if validate(root, kv.(map[string]any), v, at) == nil { + return fmt.Errorf("%s: matches not %v", at, kv) + } case "then", "else": default: return fmt.Errorf("%s: the test's validator doesn't know %q", at, k) @@ -427,6 +431,7 @@ func TestSchemaSamples(t *testing.T) { {"Op", Op{ID: "6", Op: "post", Chat: chatID, Audio: &Audio{Data: "SUQz", MimeType: "audio/mpeg"}}}, {"Op", Op{ID: "3", Op: "react", Ref: refID, Emoji: "🎯"}}, {"Op", Op{ID: "4", Op: "unwatch", Chat: chatID, Watch: "r1"}}, + {"Op", Op{ID: "7", Op: "react", Chat: chatID, Post: "a1b2.1", Emoji: "⏰"}}, {"Op", Op{ID: "6", Op: "post", Chat: chatID, Text: "It was Paris.", ReplyTo: "a1b2.1"}}, {"Page", Page{Cursor: "a1b2.4", Ops: []Op{post}}}, {"Page", Page{Cursor: "a1b2.0", More: true, Ops: []Op{}}}, @@ -480,6 +485,12 @@ func TestSchemaSamples(t *testing.T) { {"Op", "a replyTo that isn't a string", map[string]any{"id": "1", "op": "post", "chat": chatID, "text": "hi", "replyTo": 1}}, {"Op", "a reaction with a replyTo", Op{ID: "1", Op: "react", Ref: refID, Emoji: "🎯", ReplyTo: "a1b2.1"}}, {"Op", "an unwatch with a replyTo", Op{ID: "1", Op: "unwatch", Chat: chatID, Watch: "r1", ReplyTo: "a1b2.1"}}, + {"Op", "a reaction with neither ref nor post", Op{ID: "1", Op: "react", Chat: chatID, Emoji: "⏰"}}, + {"Op", "a reaction with both ref and post", Op{ID: "1", Op: "react", Ref: refID, Chat: chatID, Post: "a1b2.1", Emoji: "⏰"}}, + {"Op", "a reaction to a post without its chat", Op{ID: "1", Op: "react", Post: "a1b2.1", Emoji: "⏰"}}, + {"Op", "a reaction to a post without an emoji", Op{ID: "1", Op: "react", Chat: chatID, Post: "a1b2.1"}}, + {"Op", "a reaction to an empty post ID", map[string]any{"id": "1", "op": "react", "chat": chatID, "post": "", "emoji": "⏰"}}, + {"Op", "a post op with a post", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Post: "a1b2.1"}}, {"Page", "no cursor", map[string]any{"more": false, "ops": []any{}}}, {"Page", "a bad op", Page{Cursor: "x.1", Ops: []Op{{ID: "1", Op: "post"}}}}, {"Held", "no time", map[string]any{"op": post}}, diff --git a/addon/server.go b/addon/server.go index 23a796e..dd0c03f 100644 --- a/addon/server.go +++ b/addon/server.go @@ -257,7 +257,7 @@ func (s *Server) Queue(ops ...Op) error { } // QueueIDs is Queue, returning the ID it gave each op, in order, such as -// for a later post's ReplyTo. +// for a later post's ReplyTo or a reaction's Post. func (s *Server) QueueIDs(ops ...Op) (ids []string, err error) { for _, o := range ops { switch { diff --git a/addon/types.go b/addon/types.go index 98d9cdc..1bfc514 100644 --- a/addon/types.go +++ b/addon/types.go @@ -129,14 +129,18 @@ func Text(s string) Result { return Result{Content: []Content{{Type: "text", Tex type Op struct { ID string `json:"id"` Op string `json:"op"` // "post", "react" or "unwatch" - Chat string `json:"chat,omitempty"` // a post's or unwatch's chat pseudonym + Chat string `json:"chat,omitempty"` // a post's, unwatch's or reaction-to-a-post's chat pseudonym Text string `json:"text,omitempty"` // a post's, with {u_…} placeholders the bot fills in with names Images []Image `json:"images,omitempty"` // a post's: at most 2, 2 MB in all - Ref string `json:"ref,omitempty"` // a reaction's message + Ref string `json:"ref,omitempty"` // a reaction's message: a context's ref; or else Post Emoji string `json:"emoji,omitempty"` // a reaction's Watch string `json:"watch,omitempty"` // the ID of the watch an unwatch ends ReplyTo string `json:"replyTo,omitempty"` // a post's: the ID of an earlier post of the addon's in the same chat, which it is sent as a reply to Audio *Audio `json:"audio,omitempty"` // a post's: one clip to play, MP3, at most 2 MB + // Post is a reaction's, in place of Ref: the ID of an earlier post of + // the addon's in Chat, as ReplyTo names it, so the bot reacts to its + // own message, such as ⏰ on a question whose time runs out. + Post string `json:"post,omitempty"` } // Audio is a clip in a post, sent to play, with no title of its own: on diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 7b5a916..7d0447e 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -146,7 +146,7 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. - **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round πŸ˜‰"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot (in a DM, every message, as the chat is the player's own with the bot), such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. A watch with `"reactions": true` also takes reactions put on, or taken off, the command's answer and the addon's posts while it lasts, each a call of its tool with `{"reaction": emoji, "removed": true|false}` and the reactor's context, such as a game's players joining by reacting to its intro. A watch's `over` text answers, for an hour after the watch ends, a message to the bot that replies to one of the addon's messages it knew, in place of the model ("That game is over."), so a late answer isn't played along with. On Telegram the bot sees reactions only where it is an admin. - **Model.** With `model`, an addon may ask the bot's model for text, through MCP's standard sampling request (`sampling/createMessage`): it sends the prompt, and the bot runs it on its own model, with its own key, and sends back the answer. The addon needs no key or provider of its own. The bot offers this only to an addon with `model`, and only while it has a model; MCP suggests a person approve each request, and here the `model` setting is that approval. Each request names the chat it is for, one the addon may post in now, and is charged to that chat's `DAILY_BUDGET`: one over its budget is refused, and so is one past `per_hour`. A request is text only, at most 16 messages and 32 KB, with one in flight per addon at a time. Only its outcome, time, size, tokens and cost are logged, never the prompt or the answer. -- **Outbox.** An addon posts when it likes by queueing posts (text, up to 2 pictures, or one MP3 clip to play, which shows no title: a voice message on Telegram, `clip.mp3` on Signal), reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. +- **Outbox.** An addon posts when it likes by queueing posts (text, up to 2 pictures, or one MP3 clip to play, which shows no title: a voice message on Telegram, `clip.mp3` on Signal), reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. A reaction can likewise go on one of the addon's own earlier posts, named by its ID (`post`, with its `chat`, in place of `ref`), such as ⏰ on a question when time is nearly up; one on a post the bot doesn't remember sending there, such as one not sent yet, is dropped. - **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. An addon that keeps files takes its directory from `STATE_DIR` (`GEO_STATE_DIR`) and creates it itself, mode 0700. Unless the bot's environment sets it, the bot sets it to `addons/` in the bot's state directory (`/var/lib/private/signalbot/addons/geo`, or `/data/addons/geo` in Docker), so an addon's files are kept with the bot's; it creates nothing there itself. With `STATE_DIRECTORY` unset, or a server name that isn't only letters, digits, `.`, `_` and `-` (up to 64, not starting with `.`), there is no default, and the addon falls back on its own. - **Logs.** The bot logs an addon's commands, calls and drops by name, outcome, time and size, never what was said. An addon's stderr is counted ("addon geo wrote 3 lines (210 bytes) to stderr", at most once a minute and once more when it exits), never logged, since it may echo a message. To debug an addon, run it on its own with stderr going to your own file. - **State.** The bot keeps an addon's watches, the messages they took, the chats it may post in, how far it has read its outbox and the posts a later one may reply to in `mcp.json`, so a restart of either doesn't lose a round. See [PRIVACY.md](../PRIVACY.md#addons). diff --git a/internal/bot/bot.go b/internal/bot/bot.go index ebe7dee..7b28012 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -286,7 +286,11 @@ func refs(msgs ...feature.Message) []chats.Ref { // gone reports whether m was deleted, or replaced by a later edit, since it // arrived. func (b *Bot) gone(m feature.Message) bool { - return b.chats.Gone(m.Chat.Key(), ref(m.Sender, m.Timestamp), version(m)) + sender := m.Sender + if m.Bot { + sender = botSender + } + return b.chats.Gone(m.Chat.Key(), ref(sender, m.Timestamp), version(m)) } // replaced forgets the versions of the message an edit replaces, in history diff --git a/internal/bot/fakes_test.go b/internal/bot/fakes_test.go index d16d2c0..129db95 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -99,9 +99,14 @@ func (n *fakeNet) Send(chat feature.Chat, text string, images []feature.Picture, return []int64{5000 + n.sends.Add(1)} } -// React is sent as "react to @". +// React is sent as "react to @", the sender +// "bot" for the bot's own message. func (n *fakeNet) React(chat feature.Chat, msg feature.Message, emoji string) { - n.sent <- sent{chat: chat, text: fmt.Sprintf("react %s to %s@%d", emoji, msg.Sender, msg.Timestamp)} + sender := msg.Sender + if msg.Bot { + sender = "bot" + } + n.sent <- sent{chat: chat, text: fmt.Sprintf("react %s to %s@%d", emoji, sender, msg.Timestamp)} } func (n *fakeNet) Typing(feature.Chat) func() { diff --git a/internal/bot/host.go b/internal/bot/host.go index 63c8247..29f2cae 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -232,7 +232,7 @@ func mergeReactions(waiting, m Received) Received { w.Reactions = slices.Clone(w.Reactions) for _, r := range m.(Reacted).Reactions { w.Reactions = slices.DeleteFunc(w.Reactions, func(x Reaction) bool { - return x.Message.Sender == r.Message.Sender && x.Message.Timestamp == r.Message.Timestamp + return x.Message.Sender == r.Message.Sender && x.Message.Bot == r.Message.Bot && x.Message.Timestamp == r.Message.Timestamp }) if len(w.Reactions) >= maxReactions { logx.Warnf("dropped a reaction: %d already wait in its chat", maxReactions) diff --git a/internal/bot/host_test.go b/internal/bot/host_test.go index de103d8..91868d0 100644 --- a/internal/bot/host_test.go +++ b/internal/bot/host_test.go @@ -862,7 +862,7 @@ func TestFailedSendDropped(t *testing.T) { // The bot's reactions wait at low priority: merged into one item, a later // one on the same message replacing the earlier, sent after what waited // with them, dropped first to make room, and skipped for a message deleted -// since. +// since, the bot's own too. func TestReact(t *testing.T) { h := start(t, options{}) group := feature.Chat{GroupID: groupID} @@ -925,6 +925,23 @@ func TestReact(t *testing.T) { if strings.Contains(h.logs.String(), "dropped a message") { t.Fatalf("logs:\n%s", h.logs) } + + // The bot's own message: reacted to, unless deleted while it waited. + h.holdModel() + h.receive(atBot("and again")) + h.eventually("the request", func() bool { return len(h.requests()) == 6 }) + own := func(ts int64) feature.Message { return feature.Message{Chat: group, Timestamp: ts, Bot: true} } + h.b.React(group, own(8), "⏰") + h.b.React(group, own(10), "⏰") + h.net.handle(Deleted{Chat: group, Bot: true, Sent: 8, At: 9}) + h.release() + for _, want := range []string{"ok", "react ⏰ to bot@10"} { + if s := h.nextSend(); s.text != want { + t.Fatalf("sent %q, want %q", s.text, want) + } + } + h.settle() + h.noSend() } // Outside a tool, CallAPI is made only for a ctx charged to a chat: it is diff --git a/internal/feature/feature.go b/internal/feature/feature.go index 35a0be2..4438287 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -57,6 +57,7 @@ type Message struct { Timestamp int64 // when it was sent, by the sender's clock, as the network names it; 0 for one the bot made, such as a scheduled post. An edit keeps the original's Edited int64 // for an edit of the message sent at Timestamp, which it replaces, when it was edited; 0 for an original Addressed bool // it mentions the bot, replies to it, starts (in a group) with one of the bot's commands, or is a DM from an allowed sender + Bot bool // for React: the bot's own message, whose Timestamp an OnSent gave; Sender is unused } // Quote is the message another one replies to, as the replier's app sent it. @@ -288,7 +289,8 @@ type Host interface { // the chat's mailbox at low priority: unless msg was deleted or edited // since, and unless the reaction is dropped to make room. chat mirrors // the network's React; msg's own Chat is ignored. A message the bot - // made (Timestamp 0) can't be reacted to; nothing happens. + // made (Timestamp 0) can't be reacted to; nothing happens. One the bot + // sent, with Bot set, can be. React(chat Chat, msg Message, emoji string) // Groups lists the groups the bot shares with user. Groups(ctx context.Context, user string) ([]Group, error) diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index e23188e..30cb2a8 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -240,17 +240,11 @@ func (a *addon) apply(o ext.Op) (why string) { if !a.cfg.React { return "reactions not allowed" } - a.mu.Lock() - r, ok := a.refs[o.Ref] - l, leased := a.leases[a.chatID(r.msg.Chat)] - a.mu.Unlock() - switch { - case !ok || !now.Before(r.expires): - return "reactions to an unknown message" - case !leased || !now.Before(l.Expires) || !a.allows(r.msg.Chat): - return "for a chat without a lease" + msg, why := a.reactTo(o, now) + if why != "" { + return why } - if why := a.react(r.msg, o.Emoji); why != "" { + if why := a.react(msg, o.Emoji); why != "" { return "reactions " + why } case "unwatch": @@ -261,6 +255,39 @@ func (a *addon) apply(o ext.Op) (why string) { return "" } +// reactTo is the message a react op is for: one the bot passed the addon, +// by its ref, or the addon's own post, by its op's ID, as a replyTo names +// it; or why there is none the addon may react to. +func (a *addon) reactTo(o ext.Op, now time.Time) (feature.Message, string) { + a.mu.Lock() + defer a.mu.Unlock() + var msg feature.Message + switch { + case (o.Ref == "") == (o.Post == ""): + return msg, "malformed reactions" + case o.Ref != "": + r, ok := a.refs[o.Ref] + if !ok || !now.Before(r.expires) { + return msg, "reactions to an unknown message" + } + msg = r.msg + default: + p, ok := a.posted[o.Post] + l, leased := a.leases[o.Chat] + switch { + case !ok || p.Chat != o.Chat || !now.Before(p.Expires): + return msg, "reactions to an unknown post" + case !leased: + return msg, "for a chat without a lease" + } + msg = feature.Message{Chat: l.Chat, Timestamp: p.Sent, Bot: true} + } + if l, leased := a.leases[a.chatID(msg.Chat)]; !leased || !now.Before(l.Expires) || !a.allows(msg.Chat) { + return msg, "for a chat without a lease" + } + return msg, "" +} + // waitsToPost reports whether the post op called id was dropped and waits // to be posted again. a.mu is held. func (a *addon) waitsToPost(id string) bool { diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index a91cc96..16b59ba 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -789,6 +789,74 @@ func TestOutboxReplies(t *testing.T) { } } +// A reaction can go on the addon's own post, named by its op's ID, as a +// reaction to the bot's own message at the post's first timestamp: only one +// sent in that chat and remembered, with one of ref or post, with the react +// permission, a lease, and within the rate. +func TestOutboxReactToPost(t *testing.T) { + cfg := everything + cfg.Rate = rateConfig{1, 3} + a, now := unitAddon(cfg) + h := featuretest.New() + a.host = h + a.lease(inA) + a.lease(inB) + idA, idB := a.chatID(inA), a.chatID(inB) + if why := a.apply(ext.Op{ID: "q", Op: "post", Chat: idA, Text: "Question"}); why != "" { + t.Fatal(why) + } + h.Posts()[0].OnSent([]int64{100, 101}, false) + react := func(id, chat, post, ref string) string { + return a.apply(ext.Op{ID: id, Op: "react", Chat: chat, Post: post, Ref: ref, Emoji: "⏰"}) + } + if why := react("1", idA, "q", ""); why != "" { + t.Fatal(why) + } + if r := h.Reactions(); len(r) != 1 || r[0].Chat != inA || r[0].Emoji != "⏰" || !r[0].Message.Bot || r[0].Message.Timestamp != 100 || r[0].Message.Sender != "" { + t.Fatalf("reactions %+v", r) + } + for _, c := range []struct{ id, chat, post, ref, why string }{ + {"2", idA, "nope", "", "reactions to an unknown post"}, + {"3", idB, "q", "", "reactions to an unknown post"}, // sent in another chat + {"4", idA, "", "", "malformed reactions"}, + {"5", idA, "q", "r_" + strings.Repeat("a", 26), "malformed reactions"}, + } { + if why := react(c.id, c.chat, c.post, c.ref); why != c.why { + t.Errorf("%s: %q, want %q", c.id, why, c.why) + } + } + // One more within the rate (the post took a token), then none. + if why := react("6", idA, "q", ""); why != "" { + t.Fatal(why) + } + if why := react("7", idA, "q", ""); why != "reactions over the rate limit" { + t.Fatalf("past the rate: %q", why) + } + // Without a lease. + delete(a.leases, idA) + if why := react("8", idA, "q", ""); why != "for a chat without a lease" { + t.Fatalf("without a lease: %q", why) + } + if n := len(h.Reactions()); n != 2 { + t.Fatalf("%d reactions", n) + } + // Once the post is too old to be remembered. + *now = now.Add(postedLife) + a.lease(inA) + if why := react("9", idA, "q", ""); why != "reactions to an unknown post" { + t.Fatalf("an old post: %q", why) + } + // Without the react permission. + cfg.React = false + a, _ = unitAddon(cfg) + a.host = h + a.lease(inA) + a.rememberPosted(idA, []string{"q"}, []int64{100}) + if why := react("10", idA, "q", ""); why != "reactions not allowed" { + t.Fatalf("without react: %q", why) + } +} + // A reply whose post was dropped before it was sent waits for it, without // counting a try, and is sent after it, as a reply to it. func TestOutboxReplyWaitsForDropped(t *testing.T) { diff --git a/internal/signal/client_test.go b/internal/signal/client_test.go index d681c37..e3f9cd2 100644 --- a/internal/signal/client_test.go +++ b/internal/signal/client_test.go @@ -328,6 +328,31 @@ func TestSendAndTyping(t *testing.T) { }) } +// A reaction names its message by author and timestamp: the bot's own +// message by the bot's account, once signal-cli has said which it is. +func TestReact(t *testing.T) { + log := captureLogs(t) + group := feature.Chat{GroupID: groupID} + early := newClient(newFake(t).sock, nil, nil) + early.React(group, feature.Message{Timestamp: 1001, Bot: true}, "⏰") + if !strings.Contains(log.String(), "reaction failed: the bot's account isn't known yet") { + t.Fatalf("log %q", log.String()) + } + f := newFake(t) + c := newClient(f.sock, nil, nil) + run(t, c, f) + c.React(group, feature.Message{Sender: aliceID, Timestamp: 7}, "πŸ‘") + c.React(group, feature.Message{Timestamp: 1001, Bot: true}, "⏰") + eventually(t, "two reactions", func() bool { return len(f.calls("sendReaction")) == 2 }) + r := f.calls("sendReaction") + if r[0]["targetAuthor"] != aliceID || r[0]["targetTimestamp"] != float64(7) || r[0]["emoji"] != "πŸ‘" || r[0]["groupId"] != groupID { + t.Errorf("reaction %v", r[0]) + } + if r[1]["targetAuthor"] != botID || r[1]["targetTimestamp"] != float64(1001) || r[1]["emoji"] != "⏰" || r[1]["groupId"] != groupID { + t.Errorf("reaction to the bot's own %v", r[1]) + } +} + func TestUnmatchedAndBadFramesAreLogged(t *testing.T) { for _, tc := range []struct{ name, line, want string }{ {"rpc error", `{"jsonrpc":"2.0","error":{"code":-1,"message":"Failed to send message"},"id":7}`, "Failed to send message"}, diff --git a/internal/signal/send.go b/internal/signal/send.go index ae91607..934ec7c 100644 --- a/internal/signal/send.go +++ b/internal/signal/send.go @@ -150,10 +150,18 @@ func (c *Client) send(chat feature.Chat, text string, mentions, styles, attachme // which takes longer with attachments. var sendTimeout = time.Minute -// React puts emoji on msg, as a reaction from the bot. +// React puts emoji on msg, as a reaction from the bot. The bot's own +// message is its account's, so not until signal-cli says which that is. func (c *Client) React(chat feature.Chat, msg feature.Message, emoji string) { + author := msg.Sender + if msg.Bot { + if author = c.self(); author == "" { + logx.Errorf("reaction failed: the bot's account isn't known yet") + return + } + } p := target(chat) - p["emoji"], p["targetAuthor"], p["targetTimestamp"] = emoji, msg.Sender, msg.Timestamp + p["emoji"], p["targetAuthor"], p["targetTimestamp"] = emoji, author, msg.Timestamp if err := c.write(c.nextID.Add(1), "sendReaction", p); err != nil { logx.Errorf("reaction failed: %v", err) } diff --git a/internal/telegram/send.go b/internal/telegram/send.go index d801559..3ee08c2 100644 --- a/internal/telegram/send.go +++ b/internal/telegram/send.go @@ -300,9 +300,9 @@ func (c *Client) sendVoice(ctx context.Context, ch feature.Chat, audio []byte, r return m.MessageID, err } -// React puts emoji on msg, as a reaction from the bot. Telegram allows only -// some emoji as reactions, so one it refuses as such is sent as a message -// instead. +// React puts emoji on msg, as a reaction from the bot: by its message ID, +// which the bot's own messages have too. Telegram allows only some emoji as +// reactions, so one it refuses as such is sent as a message instead. func (c *Client) React(ch feature.Chat, msg feature.Message, emoji string) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() diff --git a/internal/telegram/telegram_test.go b/internal/telegram/telegram_test.go index 4cddf9a..a9f8d82 100644 --- a/internal/telegram/telegram_test.go +++ b/internal/telegram/telegram_test.go @@ -383,7 +383,8 @@ func TestSendReply(t *testing.T) { } } -// A reaction Telegram refuses is sent as a message. +// A reaction names its message by ID, the bot's own too; one Telegram +// refuses is sent as a message. func TestReact(t *testing.T) { f := newFake(t) c := connected(f.client()) @@ -392,6 +393,11 @@ func TestReact(t *testing.T) { if r := f.callsTo("setMessageReaction"); len(r) != 1 || r[0].Params["message_id"] != float64(42) { t.Fatalf("reactions %v", r) } + own := feature.Message{Chat: msg.Chat, Timestamp: 43, Bot: true} // the bot's own, by its message ID + c.React(own.Chat, own, "⏰") + if r := f.callsTo("setMessageReaction"); len(r) != 2 || r[1].Params["message_id"] != float64(43) { + t.Fatalf("reactions %v", r) + } f.errs["setMessageReaction"] = `{"ok":false,"error_code":400,"description":"Bad Request: REACTION_INVALID"}` c.React(msg.Chat, msg, "🫠") if s := f.callsTo("sendMessage"); len(s) != 1 || s[0].Params["text"] != "🫠" { From 7bb1d03194bebf1ba009b8b3da28beeda9efcdd0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:52:09 +0000 Subject: [PATCH 2/5] An addon's cancelled sampling request frees its place at once The bot serves one sampling request per addon at a time, and a request the addon cancels keeps its model call running to the end, to be charged. Until now it also kept the place, so the addon's next request was refused as busy for up to sampleTimeout (2 minutes): a quiz called off while it was being written blocked the next one. Now the call runs on but the addon may ask again at once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- internal/features/mcp/conn.go | 3 +++ internal/features/mcp/sample_test.go | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/internal/features/mcp/conn.go b/internal/features/mcp/conn.go index b76d2b1..da22436 100644 --- a/internal/features/mcp/conn.go +++ b/internal/features/mcp/conn.go @@ -352,7 +352,10 @@ func (c *stdioConn) dispatch(line []byte) { json.Unmarshal(line, &p) c.mu.Lock() if s := c.serving; s != nil && bytes.Equal(bytes.TrimSpace(p.Params.RequestID), s.id) { + // The work it started may run on (a model call is finished and + // charged), but the addon may send its next request now. s.cancel() + c.serving = nil } c.mu.Unlock() case m.Method == "notifications/resources/updated" && c.updated != nil: diff --git a/internal/features/mcp/sample_test.go b/internal/features/mcp/sample_test.go index 49265f7..f4545b3 100644 --- a/internal/features/mcp/sample_test.go +++ b/internal/features/mcp/sample_test.go @@ -512,6 +512,12 @@ func TestServeRequests(t *testing.T) { t.Fatalf("second in flight: %s", got) } c.dispatch([]byte(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"q.2"}}`)) + c.mu.Lock() + free := c.serving == nil // at once: a model call it started runs on, but the addon may ask again + c.mu.Unlock() + if !free { + t.Error("a cancelled request still holds the place") + } if err := <-ended; !errors.Is(err, context.Canceled) { t.Fatalf("ended with %v", err) } From aec8b506225efc75cf3e945df3c4265fac34f039 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 13:04:50 +0000 Subject: [PATCH 3/5] Log why a model request gave no answer "a model request: no answer" now says why: the error the API put in its answer (OpenRouter's, for a provider that failed part way), its finish_reason, no choices, or an unreadable answer. Never the prompt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- internal/features/mcp/sample.go | 37 +++++++++++++++++++++++++--- internal/features/mcp/sample_test.go | 29 ++++++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/internal/features/mcp/sample.go b/internal/features/mcp/sample.go index 0ad6803..b94c4c9 100644 --- a/internal/features/mcp/sample.go +++ b/internal/features/mcp/sample.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "math" + "strings" "sync" "time" @@ -170,15 +171,30 @@ func (a *addon) ask(ctx context.Context, params json.RawMessage) (*answer, int, Message struct { Content *string `json:"content"` } `json:"message"` - FinishReason string `json:"finish_reason"` + FinishReason string `json:"finish_reason"` + Error *apiError `json:"error"` // OpenRouter's, for a provider that failed part way } `json:"choices"` + Error *apiError `json:"error"` Usage struct { Tokens int `json:"completion_tokens"` Cost *float64 `json:"cost"` } `json:"usage"` } - if json.Unmarshal(data, &r) != nil || len(r.Choices) == 0 || r.Choices[0].Message.Content == nil { - return nil, size, "no answer", &rpcError{Code: -32603, Message: "the model gave no answer"} + if err := json.Unmarshal(data, &r); err != nil || len(r.Choices) == 0 || r.Choices[0].Message.Content == nil { + why := "no answer" + switch { + case err != nil: + why += " (unreadable)" + case len(r.Choices) > 0 && r.Choices[0].Error != nil: + why += " (" + r.Choices[0].Error.String() + ")" + case r.Error != nil: + why += " (" + r.Error.String() + ")" + case len(r.Choices) == 0: + why += " (no choices)" + default: + why += " (finish " + txt.Clamp(cmp.Or(r.Choices[0].FinishReason, "none"), 40) + ")" + } + return nil, size, why, &rpcError{Code: -32603, Message: "the model gave no answer"} } c := r.Choices[0] res := &answer{ @@ -197,6 +213,21 @@ func (a *addon) ask(ctx context.Context, params json.RawMessage) (*answer, int, return res, size, "", nil } +// apiError is an error the model's API puts in a 200 answer: its code +// and message, which say what failed, never what was asked. +type apiError struct { + Code any `json:"code"` + Message string `json:"message"` +} + +// String is e's code and message, short, for the log. +func (e *apiError) String() string { + if e.Code == nil { + return txt.Clamp("error: "+strings.TrimSpace(e.Message), 120) + } + return txt.Clamp(strings.TrimSpace(fmt.Sprintf("error %v: %s", e.Code, e.Message)), 120) +} + // stopReason is a completion's finish_reason as MCP names it. func stopReason(finish string) string { switch finish { diff --git a/internal/features/mcp/sample_test.go b/internal/features/mcp/sample_test.go index f4545b3..2f97db5 100644 --- a/internal/features/mcp/sample_test.go +++ b/internal/features/mcp/sample_test.go @@ -657,3 +657,32 @@ func TestPackageAddonReplies(t *testing.T) { } eventually(t, "the reaction", func() bool { return len(h.Reactions()) == 1 }) } + +// An answer with no text is no answer, and the log says why: the error +// the API put in it, or its finish_reason, never the prompt. +func TestSampleNoAnswer(t *testing.T) { + for _, tc := range []struct{ body, why string }{ + {`{"choices":[{"message":{"content":null},"finish_reason":"error","error":{"code":502,"message":"Upstream error"}}],"usage":{"completion_tokens":0}}`, "no answer (error 502: Upstream error)"}, + {`{"error":{"message":"Provider returned error"}}`, "no answer (error: Provider returned error)"}, + {`{"choices":[]}`, "no answer (no choices)"}, + {`{"choices":[{"message":{"content":null},"finish_reason":"length"}]}`, "no answer (finish length)"}, + {`not json`, "no answer (unreadable)"}, + } { + var log logx.Buffer + restore := logx.SetOutput(&log, &log, true) + a, h, _ := sampler(&modelConfig{PerHour: 30, MaxTokens: 100}) + body := tc.body + h.API = func(context.Context, string, map[string]any) (json.RawMessage, error) { + return json.RawMessage(body), nil + } + a.lease(inA) + _, rerr := a.sample(context.Background(), ask(a.chatID(inA), "Alice asks for the capital of Australia", 500)) + restore() + if rerr == nil || rerr.Message != "the model gave no answer" { + t.Errorf("%s: %+v", tc.body, rerr) + } + if l := log.String(); !strings.Contains(l, "a model request: "+tc.why+" in ") || strings.Contains(l, "Alice") { + t.Errorf("%s: log %q", tc.body, l) + } + } +} From 578a212da95b7a5b6b2d82f48c9542fafb5536cf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 13:39:50 +0000 Subject: [PATCH 4/5] Addons: standing leases, silent posts, buttons, keyboards, edits For EcoBridge (ecobot's features as an addon) and any addon like it: - announce (addon block): leases made by the addon's direct commands don't expire, so it can post an alert days later, within chats. - silent (post): Telegram's disable_notification; ignored on Signal. - buttons + onPress (post, edit): an inline keyboard on Telegram; a press calls the addon's bot-only onPress tool with {press, post} and the presser's context, its text the toast. Posts with buttons are remembered 30 days (newest 1000), so old buttons still work. - keyboard / removeKeyboard (post): Telegram's persistent reply keyboard in a DM; a message exactly a label runs that key's command. - edit op: replaces an earlier post's text, picture and buttons (Telegram editMessage*; Signal edits text, or posts a new picture). - Capability buttons in initialize: true where the network shows them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- PRIVACY.md | 12 +- TECHNICAL.md | 6 +- addon/schema.json | 57 +- addon/schema_test.go | 41 ++ addon/server.go | 11 + addon/server_test.go | 31 ++ addon/types.go | 51 +- docs/CONFIGURATION.md | 2 +- docs/FILES_LINKS_TOOLS_MCP.md | 6 +- internal/bot/answer.go | 8 +- internal/bot/bot.go | 52 +- internal/bot/buttons_test.go | 167 ++++++ internal/bot/fakes_test.go | 21 +- internal/bot/host.go | 61 ++- internal/bot/keys.go | 103 ++++ internal/bot/received.go | 9 + internal/feature/feature.go | 43 ++ internal/feature/featuretest/featuretest.go | 21 + internal/features/mcp/addon.go | 12 +- internal/features/mcp/addon_test.go | 2 +- internal/features/mcp/buttons.go | 229 ++++++++ internal/features/mcp/buttons_test.go | 553 ++++++++++++++++++++ internal/features/mcp/direct.go | 2 +- internal/features/mcp/keep.go | 5 +- internal/features/mcp/mcp.go | 25 +- internal/features/mcp/outbox.go | 205 ++++++-- internal/features/mcp/sample.go | 1 + internal/features/mcp/sample_test.go | 22 +- internal/features/mcp/watch.go | 28 +- internal/features/mcp/watch_test.go | 24 +- internal/kit/state/state.go | 13 +- internal/kit/state/state_test.go | 2 +- internal/signal/client_test.go | 10 +- internal/signal/markdown_test.go | 4 +- internal/signal/send.go | 62 ++- internal/signal/send_test.go | 39 +- internal/telegram/buttons.go | 199 +++++++ internal/telegram/buttons_test.go | 216 ++++++++ internal/telegram/client.go | 2 +- internal/telegram/decode.go | 15 +- internal/telegram/send.go | 100 +++- internal/telegram/telegram_test.go | 38 +- 42 files changed, 2320 insertions(+), 190 deletions(-) create mode 100644 internal/bot/buttons_test.go create mode 100644 internal/bot/keys.go create mode 100644 internal/features/mcp/buttons.go create mode 100644 internal/features/mcp/buttons_test.go create mode 100644 internal/telegram/buttons.go create mode 100644 internal/telegram/buttons_test.go diff --git a/PRIVACY.md b/PRIVACY.md index 6f71bc0..7bd089c 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -36,7 +36,7 @@ Every request to OpenRouter tells it to use only model providers that do not col - **No swap or core dumps.** The included systemd unit and Docker command forbid both, so history cannot reach disk that way. - **Memory is freed, not wiped.** An expired message is dropped and Go's garbage collector reclaims its memory, but the bytes may linger until overwritten, and someone with root access to the host could read them from the running process. - **What features save, on disk.** Features save state only through the core, one file each in the state directory (`/var/lib/private/signalbot`), so everything the bot keeps on disk is listed here. -- **Schedules are kept on disk.** Each `/schedule` saves, in `schedules.json` in the state directory (`/var/lib/private/signalbot`), the scheduling user's ID, the group's ID and its name when scheduled (if it's for a group), the time and repeat, and the text to post, until the user deletes it with `/schedule del`. The file also keeps, for each user who has scheduled, the last schedule number they were given, so numbers are never reused; it stays after their schedules are deleted. A one-off dropped because the bot was down is deleted, and its user is told in their DM, with the first 80 characters of its text. Besides today's spending and, with an addon, `mcp.json` (both below), nothing else the bot keeps is written to disk; an addon's own `addons/` directory is the addon's (below). +- **Schedules are kept on disk.** Each `/schedule` saves, in `schedules.json` in the state directory (`/var/lib/private/signalbot`), the scheduling user's ID, the group's ID and its name when scheduled (if it's for a group), the time and repeat, and the text to post, until the user deletes it with `/schedule del`. The file also keeps, for each user who has scheduled, the last schedule number they were given, so numbers are never reused; it stays after their schedules are deleted. A one-off dropped because the bot was down is deleted, and its user is told in their DM, with the first 80 characters of its text. Besides today's spending, with an addon `mcp.json` (both below), and a Telegram DM's reply keyboard an addon set (`keyboards.json`: its labels and commands, under a SHA-256 hash of the chat, which could be matched by trying every ID, until another post takes it away), nothing else the bot keeps is written to disk; an addon's own `addons/` directory is the addon's (below). - **Today's spending, on disk.** With a daily budget (`DAILY_BUDGET`, on by default), `budget.json` in the state directory holds today's date and, for each chat that used the model today, what it spent and whether it was told it reached the limit. Chats are stored under a SHA-256 hash of their ID, so the file holds no phone numbers, account IDs or group IDs as such. A hash of a phone number could be matched by trying every number, so treat the file as you would the schedules. Each day's file replaces the last. - **Addon state, on disk.** With an MCP server configured as an addon, `mcp.json` in the state directory holds what is listed under [Addons](#addons). Without one, the file is never written. - **Recent attachments, in memory only.** So that "@bot summarise this" in reply to someone's file can fetch the original, the bot remembers, for each group message and each DM from an allowed sender with attachments, the attachments' IDs, file names, types and sizes, never their content, under the chat, sender and time. Each is forgotten after a day, or sooner when 2,000 newer messages are remembered, and a restart clears them all. On Signal the bot also keeps a copy of each picture it sent (a chart, a picture it made), content and all, for at most a day and 32 MB in all, since signal-cli keeps none: a reply quoting it then shows the model the picture rather than Signal's small thumbnail. A delete of that message from the account's linked device drops it, and a restart clears them all. @@ -89,8 +89,9 @@ An addon is a program the bot runs on its own machine, as an [MCP server](docs/F - `watch` sends the messages its watch matches (GeoGuess: map links and coordinates during a round), with the same; nothing else said in the chat. A pattern that would match ordinary chat is refused, so there is no feed of everything. A reply watch sends replies to the addon's own messages that ask the bot, such as answers to a quiz, whatever they say; - `names` adds each sender's display name. Without it, the addon writes a pseudonym where a name goes, and the bot puts in the name it last saw that person use in that chat, kept in memory for a day; - `global_ids` gives a person the same pseudonym in every chat, so the addon can link them across groups; - - `post` and `react` send nothing: they let it post and react, only in a chat where it was used in the last day; - - `model` lets it ask the bot's model, with the bot's key: the addon's prompts, and whatever it put in them from the chat, go to the model provider, as chat with the bot does, and what they cost counts toward that chat's `DAILY_BUDGET`. The bot logs only each request's outcome, time, size and cost, never the prompt or the answer. + - `post` and `react` send nothing: they let it post and react, only in a chat where it was used in the last day, or with `announce` any chat that used one of its commands, until that chat leaves `chats`; + - a press of a button under one of its posts (Telegram) sends the button's data and who pressed it, as a pseudonym, as a command does; + - `model` lets it ask the bot's model, with the bot's key: the addon's prompts, and whatever it put in them from the chat, go to the model provider, as chat with the bot does, and what they cost counts toward that chat's `DAILY_BUDGET`; only for a chat that used the addon in the last day, never one `announce` alone keeps open. The bot logs only each request's outcome, time, size and cost, never the prompt or the answer. - **What the addon keeps** is its own, outside what this page lists for the bot, in the directory its `…_STATE_DIR` names (GeoGuess: `GEO_STATE_DIR`): by default `addons/` in the state directory (`/var/lib/private/signalbot/addons/geo`), which the addon creates and writes, never the bot. Read its own documentation. - **Deletes and edits are not passed on.** A message an addon took stays with the addon if its sender later deletes it for everyone. An edit of one is passed on, as a new version. - **Taken messages are kept nowhere by the bot:** not in history, not as context (so `GROUP_CONTEXT=false` makes no difference to them), not in the log. The addon still gets them. @@ -100,11 +101,12 @@ An addon is a program the bot runs on its own machine, as an [MCP server](docs/F | Item | Kept for | |---|---| | The pseudonym secret | Until `mcp.json` is deleted, which gives everyone new pseudonyms | - | Chats an addon may post in: the chat's pseudonym and its real ID | 24 hours after the addon was last used there | + | Chats an addon may post in: the chat's pseudonym and its real ID | 24 hours after the addon was last used there; with `announce`, until the chat leaves `chats` or `announce` is turned off | | Live watches: the chat's pseudonym, the pattern, and the times of the bot's messages with the command's pictures, and for a reply watch of the addon's messages | Until the watch ends, at most `watch_max` (24 hours at most) | | Messages a watch took: the chat's ID, the sender's pseudonym and the message's time, never its text | 48 hours, so a later edit is taken too | | How far the bot has read each addon's outbox, and the last 1,000 outbox entries' IDs | Replaced on each save; dropped once the server is no longer an addon | - | An addon's last 256 posts, for a later post to reply to: the post's ID, the chat's pseudonym and the time (on Telegram, the ID) of the bot's message, never its text | 24 hours | + | An addon's last 256 posts, for a later post to reply to, react to or edit: the post's ID, the chat's pseudonym and the time (on Telegram, the ID) of the bot's message, never its text | 24 hours | + | An addon's last 1,000 posts with buttons, the same, the tool a press calls, and in a forum topic the group's and the topic's real IDs | 30 days | Refs to messages (for reactions, a day), display names (a day) and posts waiting to go out are kept in memory only. diff --git a/TECHNICAL.md b/TECHNICAL.md index d3ff075..ca9ba8f 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -62,7 +62,7 @@ Each line has a journald priority, and every priority is always written: ## Concurrency and scale -- **Reader goroutine.** The Signal client's reader parses each frame and decides "addressed?" without blocking or calling the network, then hands the bot a `bot.Received`, one of a closed set of types (`internal/bot/received.go`): `Incoming`, a message completed in its slot by its `Load` (an addressed one, or any other data message that arrived before the bot's own ID was known); `Chatter`, an unaddressed group message; `GroupChanged`; `Deleted`, a delete or a replacing edit, handled on the spot like `GroupChanged`; and `Happened` for a reaction, never passed to `OnMessage`. A member change, also a `Happened`, comes from the client's member-comparison goroutine through the same handler. The core switches on the type. `Incoming` goes to its chat's mailbox from here, and `Happened` too when an `OnEvent` hook is registered; the only other kinds there are `Outgoing`, a post the bot makes on its own (`Post`), `Reacted`, the bot's reactions (`React`), and `Posted`, a message a feature delivers, which `Network.Delivered` turns into a `Ready` (its sender's name, the bot's @name stripped, a group's members) in its slot. The bot may briefly take the chat store's lock (to queue a message or keep context). Unaddressed group messages go to the `OnMessage` hooks here. +- **Reader goroutine.** The Signal client's reader parses each frame and decides "addressed?" without blocking or calling the network, then hands the bot a `bot.Received`, one of a closed set of types (`internal/bot/received.go`): `Incoming`, a message completed in its slot by its `Load` (an addressed one, or any other data message that arrived before the bot's own ID was known); `Chatter`, an unaddressed group message; `GroupChanged`; `Deleted`, a delete or a replacing edit, handled on the spot like `GroupChanged`; `Happened` for a reaction, never passed to `OnMessage`; and on Telegram `Pressed`, a button press, which goes to its chat's mailbox when an `OnPress` hook is registered and is otherwise answered at once. A member change, also a `Happened`, comes from the client's member-comparison goroutine through the same handler. The core switches on the type. `Incoming` goes to its chat's mailbox from here, and `Happened` too when an `OnEvent` hook is registered; the only other kinds there are `Outgoing`, a post the bot makes on its own (`Post`), `Reacted`, the bot's reactions (`React`), and `Posted`, a message a feature delivers, which `Network.Delivered` turns into a `Ready` (its sender's name, the bot's @name stripped, a group's members) in its slot. The bot may briefly take the chat store's lock (to queue a message or keep context). Unaddressed group messages go to the `OnMessage` hooks here. - **Worker slots.** A fixed pool of `MAX_CONCURRENCY`. Message handling that may call the network (waiting for the account ID, contacts a message needs, sticker labels, media, the model) runs only in a slot. The contact reloads on connect and on group changes run on their own timer, one at a time, and `listAccounts` on each connection's own goroutine. Until the bot's own ID is known, a message waits for it in a slot, up to 10s. A full pool drops the message with a warning. - **Per-chat mailbox.** An addressed message, one a feature delivers, one waiting for the bot's own ID, a post the bot makes on its own, an event for an `OnEvent` hook, or the bot's reactions join its chat's mailbox (`chats.Store.Post`, generic over what it holds, so chats needn't know the bot's type); at most 4 wait, and more are dropped with a warning that says what was dropped (a message, a post or reactions). The bot's own reactions wait at low priority: those for one chat are merged into one item, handled after everything else waiting, and dropped first, with a warning, when a message needs their place, so they never cost an addressed message its place. One deleted, or replaced by an edit, before its turn is skipped (see Edits and deletes). A chat with work has one worker, holding one slot, which takes everything waiting at once, handles it in order, and exits when nothing is left, so each answer sees the ones before it. Different chats run in parallel. - **Answered together.** Messages that arrive while the worker is busy are answered as one turn, a line each (in a group with the sender's name), so "actually" and "forget it" get one reply that sees both. On its own, in order, goes a message a hook acts on (such as a command), a delivered one, a post, an event, the bot's reactions, and one that waited for the bot's ID and was not addressed after all; a run is split where it would carry more than 4 images or a second sticker. A panic loses only the message or turn that caused it, and once shutdown begins nothing more that waited starts, not even its hooks; a post still waiting then, or a hook's answer not yet sent, is told it was dropped (`OnSent`). @@ -113,6 +113,7 @@ The core's lifecycle has four stages. Each port is one stage; nothing else is a | The model is asked | `OnTurn(func(ctx, Message) Additions)`, plus `OfferTools(ToolGroup)` | a note on the message (with its own version for history), and images | | Time arrives | `At` ([Timers](#timers)) | nothing: the timer may deliver a message | | Something besides a message happens | `OnEvent(func(ctx, Event) string)` | a reply to send to the chat, without the model, or "" | +| A button under the bot's message is pressed | `OnPress(func(ctx, Press) (string, bool))` | whether the hook takes it, and an answer the presser sees for a moment | **Hook rules:** - Hooks run in feature order (`features.go`). @@ -120,13 +121,14 @@ The core's lifecycle has four stages. Each port is one stage; nothing else is a - `Answer`, `Pictures`, `OnSent` and `ToolChoice` count only on an addressed message, and `Context` only on an unaddressed one. `Done` counts on both: the hook handled the message, so it gets no answer and no model; an unaddressed one is kept nowhere, even with a `Context`, and later hooks never see it. An `Answer` and `Pictures` are sent together, with the caption rule as for a tool's pictures, and `OnSent`, if set, is called once: with the timestamps of the messages they went out in, or with dropped set when they never go out (shutdown began first, the send failed, or the answer was cut off by a panic); `OnSent` alone doesn't count, so it can't claim a message. Nothing of them is kept in history. - An `Event` is a reaction (its emoji, whether it was taken back, who wrote the message and when, and whether that was the bot) or a change in a group's members (who joined, who left, or that the bot was added), with who did it. The network decides which reach the core, as for messages: never the bot's own, in a DM only an allowed sender's, member changes only in groups. With no `OnEvent` hook the core drops events as they arrive. Otherwise each goes into its chat's mailbox and runs on a slot of its own, so a hook may block or call the network: a reaction in order with that chat's messages, a member change once the network has worked it out, which can be after messages that came later (below); the first non-empty reply is sent with `@Name` linked to the chat's known names and the event's people. Events are never logged, kept in history or shown to the model. - **Member changes on Signal:** signal-cli's group `UPDATE` says only that something changed, so the client keeps each group's members from `listGroups`, loaded once the bot's ID is known, and on an update reloads them and compares, only when the core has an `OnEvent` hook (`Network.Watch`). Updates are folded and spaced like the contact list, at most one load per 15 seconds after a contact load, so a member change can reach features after messages read later. Members already there at startup are never reported; a group the bot wasn't in is `BotAdded`; a change of name or description alone is no event. The bot's own update (from its linked phone) refreshes the members it compares with but reaches no feature. `By` is whoever sent the update, or empty when several people's updates were folded together. Each comparison updates only the groups it compares, and one whose `listGroups` call fails keeps its updates for the next. +- A `Press` (Telegram's callback query: the chat, the presser, the message and the button's data) reaches the core only from someone the network answers, as a message would, and goes into its chat's mailbox; the first `OnPress` hook that takes it answers, and a press none takes, with no hook, dropped or left at shutdown is answered with nothing, so the button stops spinning. A `Post` may carry `Markup` (silent, buttons, a DM's reply keyboard or its removal), which a network that shows it (`Network.Buttons`, Telegram) shows; the core remembers a DM's keyboard in `keyboards.json` and turns a message of exactly one of its labels into its command before the hooks run. A `Post` with `Edit` replaces the bot's earlier message through `Network.Edit`, keeping nothing in history. - `OnTurn` runs only when the model is about to be asked. **Services the host offers:** - `IntroLine(line)`, `IntroLineDM(line)`: a paragraph for the bot's introduction, placed where `INTRO` has `{more}`; with `IntroLineDM`, only in the introduction a DM gets (`Info.IntroDM`, and the prompt's rule in a DM), not a group's (`Info.Intro`). The core pads each with a blank line and never leaves two blank lines in a row. `/schedule` uses it, DM only, for `Type "/schedule" for schedules and reminders.`, since schedules are made only in a DM. - `CallAPI(ctx, path, body)`: post a JSON body to an endpoint of the model's API, such as OpenRouter's `/images` or `/chat/completions` (with the bot's own model), and get the response; the core keeps the key and the data-collection request. From a tool's Run the cost counts toward the reply; outside one the ctx must come from `ChargeTo(ctx, chat)`, and the cost counts toward that chat's daily budget, which refuses the call once spent (see the model, above). - `Env(key, def)`: a feature's own setting. The docs guardrail finds each name passed to it. -- `Store(name)`: the feature's saved state, opened while it registers: one JSON document, `.json` in the state directory (`STATE_DIRECTORY`'s first directory, or the working directory when it isn't set), with `Load(v)` (found is false when nothing is saved yet; a file that can't be read is an error, so the feature can stop the bot rather than overwrite it) and `Save(v)` (written to a temporary file, synced and renamed over the old one, at most 4 MiB, its newline included). The first `Store` call checks that the directory can be listed and written, and fails with how to fix it otherwise (for Docker's `/data`, `chown 65532`; elsewhere, the unit's `StateDirectory`), so a bot whose features save nothing needs no state directory. A name is lowercase letters, digits, `-` and `_`, up to 32, and may be opened once; `budget` is the core's (`budget.json`, written the same way). Features save files only this way (a guardrail below). +- `Store(name)`: the feature's saved state, opened while it registers: one JSON document, `.json` in the state directory (`STATE_DIRECTORY`'s first directory, or the working directory when it isn't set), with `Load(v)` (found is false when nothing is saved yet; a file that can't be read is an error, so the feature can stop the bot rather than overwrite it) and `Save(v)` (written to a temporary file, synced and renamed over the old one, at most 4 MiB, its newline included). The first `Store` call checks that the directory can be listed and written, and fails with how to fix it otherwise (for Docker's `/data`, `chown 65532`; elsewhere, the unit's `StateDirectory`), so a bot whose features save nothing needs no state directory. A name is lowercase letters, digits, `-` and `_`, up to 32, and may be opened once; `budget` and `keyboards` are the core's (`budget.json` and the DMs' reply keyboards' `keyboards.json`, written the same way). Features save files only this way (a guardrail below). - `Info()`: the bot's name, the chat network (`Network`, from `Network.Name`: `signal` or `telegram`), its version, the model ("" with no model), the API's provider (`openrouter` or ""), whether it takes images, audio and PDFs (`Audio`, `PDFs`) and can call tools, the names of the tools, as in `{tools}` (none when it can't call tools), and the introduction, in a group and in a DM. All but the name and the tools are known when features register; images, audio, PDFs and tool calling may turn off later ([Capabilities](#the-core)). - `Media(ctx, msg, i)`: the bytes of a message's image or sticker (15s). The core fills in each sticker's `Label` (its emoji and pack title) when it loads the message. - `Deliver(msg)`: act on a message as if its sender had just posted it in its chat, through the chat's mailbox. Inside the message's slot: diff --git a/addon/schema.json b/addon/schema.json index cece2b6..6586c41 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -11,7 +11,8 @@ "version": {"description": "The extension's version.", "const": 1}, "network": {"description": "The bot's chat network, as it names itself.", "type": "string", "examples": ["signal", "telegram"]}, "watchReplies": {"description": "The bot's: it takes a watch with replies. A bot without it refuses one.", "type": "boolean"}, - "watchReactions": {"description": "The bot's: it takes a watch with reactions.", "type": "boolean"} + "watchReactions": {"description": "The bot's: it takes a watch with reactions.", "type": "boolean"}, + "buttons": {"description": "The bot's: its network shows a post's buttons and keyboard (Telegram). Elsewhere they are left off.", "type": "boolean"} }, "required": ["version"] }, @@ -94,20 +95,25 @@ } }, "Op": { - "description": "One thing an addon's outbox asks the bot to do: post in a chat, react to a message, or end a watch. The bot does each ID once, so an op read again, such as after a restart, is skipped.", + "description": "One thing an addon's outbox asks the bot to do: post in a chat, edit a post, react to a message, or end a watch. The bot does each ID once, so an op read again, such as after a restart, is skipped.", "type": "object", "properties": { "id": {"description": "Unique among the addon's ops, for as long as the bot may read it again.", "type": "string", "minLength": 1}, - "op": {"enum": ["post", "react", "unwatch"]}, - "chat": {"description": "A post's or unwatch's chat, or that of the post a reaction with post is for.", "type": "string", "pattern": "^c_[a-z2-7]{26}$"}, - "text": {"description": "A post's text, with {u_…} placeholders the bot fills in with names; at most 4000 characters, names filled in. A post with neither text nor images is dropped.", "type": "string"}, - "images": {"description": "A post's images: at most 2, and 2 MiB in all.", "type": "array", "items": {"$ref": "#/$defs/Image"}, "maxItems": 2}, + "op": {"enum": ["post", "edit", "react", "unwatch"]}, + "chat": {"description": "A post's, edit's or unwatch's chat, or that of the post a reaction with post is for.", "type": "string", "pattern": "^c_[a-z2-7]{26}$"}, + "text": {"description": "A post's or edit's text, with {u_…} placeholders the bot fills in with names; at most 4000 characters, names filled in. A post with neither text nor images is dropped.", "type": "string"}, + "images": {"description": "A post's images: at most 2, and 2 MiB in all; an edit's, or a post's with buttons, a keyboard or removeKeyboard, at most 1.", "type": "array", "items": {"$ref": "#/$defs/Image"}, "maxItems": 2}, "audio": {"description": "A post's clip to play, MP3, at most 2 MiB: sent with no title of its own. A post with audio is never merged with another.", "$ref": "#/$defs/Audio"}, "ref": {"description": "The message a reaction is for: a context's ref. A reaction has ref or post, not both.", "type": "string", "pattern": "^r_[a-z2-7]{26}$"}, "emoji": {"description": "A reaction's: one emoji.", "type": "string", "minLength": 1}, "watch": {"description": "The ID of the watch an unwatch ends.", "type": "string", "minLength": 1, "maxLength": 64}, "replyTo": {"description": "A post's: the ID of an earlier post op of the addon's, such as a question, so the post is sent as a reply to it. The bot remembers the ID of each post op it sent (every op of a merged post), with its chat, for 24 hours, the last 256 IDs; a post whose replyTo it doesn't know, or that was sent in another chat, is sent as an ordinary post. A post with replyTo is never merged with another.", "type": "string", "minLength": 1}, - "post": {"description": "A reaction's, in place of ref: the ID of an earlier post op of the addon's in chat, as replyTo names it, so the bot reacts to its own message, such as with ⏰ when a question's time runs out. A reaction to a post the bot doesn't remember sending in chat, such as one not sent yet, is dropped.", "type": "string", "minLength": 1} + "post": {"description": "A reaction's, in place of ref: the ID of an earlier post op of the addon's in chat, as replyTo names it, so the bot reacts to its own message, such as with ⏰ when a question's time runs out. An edit's: the post whose text, image and buttons it replaces (all three: an edit without buttons takes them away); on Telegram in place, on Signal the text in place, or with an image as a new message, which later edits and reactions then name. Edits follow a post's rules: the post permission, a lease and the rate. A reaction to or an edit of a post the bot doesn't remember sending in chat, such as one not sent yet, is dropped, as is an edit of a post merged with others or sent as more than one message, or on Signal one past a day or 10 edits. A post with buttons is remembered for 30 days, the newest 1,000.", "type": "string", "minLength": 1}, + "silent": {"description": "A post's: sent without a notification, on Telegram; Signal ignores it.", "type": "boolean"}, + "buttons": {"description": "A post's or edit's rows of buttons under it, where the bot's capability has buttons; elsewhere they are left off. Each press calls onPress.", "type": "array", "minItems": 1, "maxItems": 5, "items": {"type": "array", "minItems": 1, "maxItems": 5, "items": {"$ref": "#/$defs/Button"}}}, + "onPress": {"description": "With buttons, and only with them: one of the addon's tools for the bot alone, called with each press, with Press as its arguments and the presser's context in _meta, as a direct command is. Its result's text, if any, is shown to the presser for a moment. A press needs no watch, and leases its chat.", "type": "string", "minLength": 1}, + "keyboard": {"description": "A post's, in a DM where the bot's capability has buttons: the chat's reply keyboard from now on, rows of keys. A message of exactly a key's label runs its command, as if sent.", "type": "array", "minItems": 1, "maxItems": 5, "items": {"type": "array", "minItems": 1, "maxItems": 5, "items": {"$ref": "#/$defs/Key"}}}, + "removeKeyboard": {"description": "A post's, in a DM: takes the reply keyboard away.", "type": "boolean"} }, "required": ["id", "op"], "additionalProperties": false, @@ -115,10 +121,45 @@ {"if": {"properties": {"op": {"const": "post"}}}, "then": {"required": ["chat"], "anyOf": [{"required": ["text"], "properties": {"text": {"pattern": "\\S"}}}, {"required": ["images"], "properties": {"images": {"minItems": 1}}}, {"required": ["audio"]}]}}, {"if": {"properties": {"op": {"const": "react"}}}, "then": {"required": ["emoji"], "if": {"required": ["post"]}, "then": {"required": ["chat"], "not": {"required": ["ref"]}}, "else": {"required": ["ref"]}}}, {"if": {"properties": {"op": {"const": "unwatch"}}}, "then": {"required": ["chat", "watch"]}}, + {"if": {"properties": {"op": {"const": "edit"}}}, "then": {"required": ["chat", "post"], "properties": {"images": {"maxItems": 1}}, "anyOf": [{"required": ["text"], "properties": {"text": {"pattern": "\\S"}}}, {"required": ["images"], "properties": {"images": {"minItems": 1}}}]}}, {"if": {"required": ["replyTo"]}, "then": {"properties": {"op": {"const": "post"}}}}, - {"if": {"required": ["post"]}, "then": {"properties": {"op": {"const": "react"}}}} + {"if": {"required": ["post"]}, "then": {"properties": {"op": {"enum": ["react", "edit"]}}}}, + {"if": {"required": ["buttons"]}, "then": {"required": ["onPress"], "properties": {"op": {"enum": ["post", "edit"]}, "images": {"maxItems": 1}}, "not": {"anyOf": [{"required": ["keyboard"]}, {"required": ["removeKeyboard"]}]}}}, + {"if": {"required": ["onPress"]}, "then": {"required": ["buttons"]}}, + {"if": {"anyOf": [{"required": ["silent"], "properties": {"silent": {"const": true}}}, {"required": ["keyboard"]}, {"required": ["removeKeyboard"]}, {"required": ["audio"]}]}, "then": {"properties": {"op": {"const": "post"}}}}, + {"if": {"anyOf": [{"required": ["keyboard"]}, {"required": ["removeKeyboard"]}]}, "then": {"properties": {"images": {"maxItems": 1}}}}, + {"if": {"required": ["keyboard"]}, "then": {"not": {"required": ["removeKeyboard"]}}} ] }, + "Button": { + "description": "A button under a post.", + "type": "object", + "properties": { + "label": {"description": "What it shows: at most 32 characters, with no space around them.", "type": "string", "minLength": 1, "maxLength": 32, "pattern": "^\\S([\\s\\S]*\\S)?$"}, + "data": {"description": "What a press passes back to onPress: 1 to 64 bytes in UTF-8.", "type": "string", "minLength": 1, "maxLength": 64} + }, + "required": ["label", "data"], + "additionalProperties": false + }, + "Key": { + "description": "A key of a DM's reply keyboard.", + "type": "object", + "properties": { + "label": {"description": "What it shows, and sends: at most 32 characters, with no space around them, and no two keys' the same in a keyboard.", "type": "string", "minLength": 1, "maxLength": 32, "pattern": "^\\S([\\s\\S]*\\S)?$"}, + "command": {"description": "The command a message of exactly label runs, such as \"/rain\": one of the addon's direct commands, with any arguments; at most 256 characters, on one line.", "type": "string", "pattern": "^/[^\\r\\n]*$", "maxLength": 256} + }, + "required": ["label", "command"], + "additionalProperties": false + }, + "Press": { + "description": "The arguments of a post's onPress tool when one of its buttons is pressed. The presser's context is in _meta, as a direct command's: its ref is the post pressed, for a react op.", + "type": "object", + "properties": { + "press": {"description": "The button's data.", "type": "string"}, + "post": {"description": "The ID of the post op the button is under, for an edit op's post.", "type": "string"} + }, + "required": ["press", "post"] + }, "Audio": { "description": "A clip in a post, to play.", "type": "object", diff --git a/addon/schema_test.go b/addon/schema_test.go index eddac01..5c120b8 100644 --- a/addon/schema_test.go +++ b/addon/schema_test.go @@ -52,6 +52,9 @@ var wireTypes = map[string]reflect.Type{ "Op": reflect.TypeFor[Op](), "Image": reflect.TypeFor[Image](), "Audio": reflect.TypeFor[Audio](), + "Button": reflect.TypeFor[Button](), + "Key": reflect.TypeFor[Key](), + "Press": reflect.TypeFor[Press](), "Page": reflect.TypeFor[Page](), "Held": reflect.TypeFor[Held](), @@ -432,6 +435,18 @@ func TestSchemaSamples(t *testing.T) { {"Op", Op{ID: "3", Op: "react", Ref: refID, Emoji: "🎯"}}, {"Op", Op{ID: "4", Op: "unwatch", Chat: chatID, Watch: "r1"}}, {"Op", Op{ID: "7", Op: "react", Chat: chatID, Post: "a1b2.1", Emoji: "⏰"}}, + {"Op", Op{ID: "8", Op: "post", Chat: chatID, Text: "Rain alert", Silent: true}}, + {"Op", Op{ID: "9", Op: "post", Chat: chatID, Text: "Rain", Images: []Image{{Data: "aGk=", MimeType: "image/png"}}, + Buttons: [][]Button{{{Label: "24h", Data: "rain 24h"}, {Label: "7d", Data: "rain 7d"}}}, OnPress: "period"}}, + {"Op", Op{ID: "10", Op: "post", Chat: chatID, Text: "Pick one", Keyboard: [][]Key{{{Label: "🌧 Rain", Command: "/rain"}}, {{Label: "Status", Command: "/status now"}}}}}, + {"Op", Op{ID: "11", Op: "post", Chat: chatID, Text: "Bye", RemoveKeyboard: true}}, + {"Op", Op{ID: "12", Op: "edit", Chat: chatID, Post: "a1b2.9", Text: "Rain, 7 days"}}, + {"Op", map[string]any{"id": "14", "op": "edit", "chat": chatID, "post": "a1b2.9", "text": "Rain", "silent": false}}, + {"Op", Op{ID: "15", Op: "post", Chat: chatID, Text: "Pick", Keyboard: [][]Key{{{Label: "Rain, 7 d", Command: "/rain 7d"}}}}}, + {"Op", Op{ID: "13", Op: "edit", Chat: chatID, Post: "a1b2.9", Images: []Image{{Data: "aGk=", MimeType: "image/png"}}, + Buttons: [][]Button{{{Label: strings.Repeat("Γ©", 32), Data: strings.Repeat("x", 64)}}}, OnPress: "period"}}, + {"Capability", Capability{Version: Version, Network: "telegram", Buttons: true}}, + {"Press", Press{Press: "rain 7d", Post: "a1b2.9"}}, {"Op", Op{ID: "6", Op: "post", Chat: chatID, Text: "It was Paris.", ReplyTo: "a1b2.1"}}, {"Page", Page{Cursor: "a1b2.4", Ops: []Op{post}}}, {"Page", Page{Cursor: "a1b2.0", More: true, Ops: []Op{}}}, @@ -491,6 +506,32 @@ func TestSchemaSamples(t *testing.T) { {"Op", "a reaction to a post without an emoji", Op{ID: "1", Op: "react", Chat: chatID, Post: "a1b2.1"}}, {"Op", "a reaction to an empty post ID", map[string]any{"id": "1", "op": "react", "chat": chatID, "post": "", "emoji": "⏰"}}, {"Op", "a post op with a post", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Post: "a1b2.1"}}, + {"Op", "an edit without its post", Op{ID: "1", Op: "edit", Chat: chatID, Text: "hi"}}, + {"Op", "an edit without its chat", Op{ID: "1", Op: "edit", Post: "a1b2.1", Text: "hi"}}, + {"Op", "an empty edit", Op{ID: "1", Op: "edit", Chat: chatID, Post: "a1b2.1"}}, + {"Op", "an edit of two images", Op{ID: "1", Op: "edit", Chat: chatID, Post: "a1b2.1", Images: slices.Repeat([]Image{{Data: "aGk=", MimeType: "image/png"}}, 2)}}, + {"Op", "a silent edit", Op{ID: "1", Op: "edit", Chat: chatID, Post: "a1b2.1", Text: "hi", Silent: true}}, + {"Op", "an edit with a keyboard", Op{ID: "1", Op: "edit", Chat: chatID, Post: "a1b2.1", Text: "hi", Keyboard: [][]Key{{{Label: "a", Command: "/a"}}}}}, + {"Op", "buttons without onPress", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Buttons: [][]Button{{{Label: "a", Data: "a"}}}}}, + {"Op", "onPress without buttons", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", OnPress: "period"}}, + {"Op", "buttons on a reaction", Op{ID: "1", Op: "react", Ref: refID, Emoji: "🎯", Buttons: [][]Button{{{Label: "a", Data: "a"}}}, OnPress: "p"}}, + {"Op", "six rows of buttons", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Buttons: slices.Repeat([][]Button{{{Label: "a", Data: "a"}}}, 6), OnPress: "p"}}, + {"Op", "six buttons in a row", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Buttons: [][]Button{slices.Repeat([]Button{{Label: "a", Data: "a"}}, 6)}, OnPress: "p"}}, + {"Op", "an empty row", map[string]any{"id": "1", "op": "post", "chat": chatID, "text": "hi", "buttons": []any{[]any{}}, "onPress": "p"}}, + {"Op", "a long label", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Buttons: [][]Button{{{Label: strings.Repeat("x", 33), Data: "a"}}}, OnPress: "p"}}, + {"Op", "long data", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Buttons: [][]Button{{{Label: "a", Data: strings.Repeat("x", 65)}}}, OnPress: "p"}}, + {"Op", "buttons with two images", Op{ID: "1", Op: "post", Chat: chatID, Images: slices.Repeat([]Image{{Data: "aGk=", MimeType: "image/png"}}, 2), Buttons: [][]Button{{{Label: "a", Data: "a"}}}, OnPress: "p"}}, + {"Op", "buttons and a keyboard", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Buttons: [][]Button{{{Label: "a", Data: "a"}}}, OnPress: "p", Keyboard: [][]Key{{{Label: "a", Command: "/a"}}}}}, + {"Op", "a keyboard and removeKeyboard", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Keyboard: [][]Key{{{Label: "a", Command: "/a"}}}, RemoveKeyboard: true}}, + {"Op", "a key's command that isn't one", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Keyboard: [][]Key{{{Label: "a", Command: "rain"}}}}}, + {"Op", "a silent reaction", Op{ID: "1", Op: "react", Ref: refID, Emoji: "🎯", Silent: true}}, + {"Op", "an edit with audio", Op{ID: "1", Op: "edit", Chat: chatID, Post: "a1b2.1", Text: "hi", Audio: &Audio{Data: "aGk=", MimeType: "audio/mpeg"}}}, + {"Op", "a keyboard with two images", Op{ID: "1", Op: "post", Chat: chatID, Images: slices.Repeat([]Image{{Data: "aGk=", MimeType: "image/png"}}, 2), Keyboard: [][]Key{{{Label: "a", Command: "/a"}}}}}, + {"Op", "removeKeyboard with two images", Op{ID: "1", Op: "post", Chat: chatID, Images: slices.Repeat([]Image{{Data: "aGk=", MimeType: "image/png"}}, 2), RemoveKeyboard: true}}, + {"Op", "a key's label with a space after it", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Keyboard: [][]Key{{{Label: "Rain ", Command: "/rain"}}}}}, + {"Op", "a button's label all space", Op{ID: "1", Op: "post", Chat: chatID, Text: "hi", Buttons: [][]Button{{{Label: " ", Data: "a"}}}, OnPress: "p"}}, + {"Capability", "buttons not a boolean", map[string]any{"version": 1, "buttons": "yes"}}, + {"Press", "no post", map[string]any{"press": "x"}}, {"Page", "no cursor", map[string]any{"more": false, "ops": []any{}}}, {"Page", "a bad op", Page{Cursor: "x.1", Ops: []Op{{ID: "1", Op: "post"}}}}, {"Held", "no time", map[string]any{"op": post}}, diff --git a/addon/server.go b/addon/server.go index dd0c03f..1ab0d8a 100644 --- a/addon/server.go +++ b/addon/server.go @@ -56,6 +56,7 @@ type Server struct { sampling bool // the bot offered sampling in initialize watchReplies bool // the bot takes a watch with Replies watchReacts bool // the bot takes a watch with Reactions + buttons bool // the bot shows a post's buttons and keyboard subscribed bool outbox []held // ops the bot hasn't read past, oldest first seq int64 // the last op's sequence number @@ -148,6 +149,15 @@ func (s *Server) WatchReactions() bool { return s.watchReacts } +// Buttons reports whether the bot said in initialize that its network +// shows a post's Buttons and Keyboard (Telegram). Elsewhere they are left +// off, so offer another way, such as a command. +func (s *Server) Buttons() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.buttons +} + // BotError is the bot's error answer to a request of the addon's, such as // a sampling request it refused. type BotError struct { @@ -640,6 +650,7 @@ func (s *Server) methods() map[string]handler { s.network = addon.Network s.watchReplies = addon.WatchReplies s.watchReacts = addon.WatchReactions + s.buttons = addon.Buttons s.sampling = p.Capabilities.Sampling != nil s.mu.Unlock() r := initializeResult{ProtocolVersion: Protocol, ServerInfo: serverInfo{Name: s.cfg.Name, Title: s.cfg.Title, Version: s.cfg.Version}} diff --git a/addon/server_test.go b/addon/server_test.go index 5ff2963..a339814 100644 --- a/addon/server_test.go +++ b/addon/server_test.go @@ -519,6 +519,37 @@ func TestCanSample(t *testing.T) { } } +// The bot's initialize says whether its network shows buttons, and a press +// is a call of the onPress tool with Press as its arguments. +func TestButtons(t *testing.T) { + got := make(chan Press, 1) + s := New(Config{Name: "alerts", Tools: []Tool{{Name: "period", Visibility: []string{"bot"}, + Call: func(_ context.Context, c *Context, args json.RawMessage) (Result, error) { + var p Press + if err := DecodeArgs(args, &p); err != nil || c == nil { + return Result{}, errors.New("no press") + } + got <- p + return Text("7 days"), nil + }}}}) + c := start(t, s) + initialize(c, "signal") + if s.Buttons() { + t.Error("buttons on Signal") + } + c.result("initialize", map[string]any{"protocolVersion": Protocol, "capabilities": map[string]any{ + "experimental": map[string]any{KeyAddon: Capability{Version: Version, Network: "telegram", Buttons: true}}}}, nil) + if !s.Buttons() { + t.Error("no buttons on Telegram") + } + var r Result + c.result("tools/call", map[string]any{"name": "period", "arguments": Press{Press: "rain 7d", Post: "a1.9"}, + "_meta": map[string]any{KeyContext: Context{Chat: "c_one", Sender: "u_one", Ref: "r_one"}}}, &r) + if p := <-got; p != (Press{Press: "rain 7d", Post: "a1.9"}) || len(r.Content) != 1 || r.Content[0].Text != "7 days" { + t.Errorf("press %+v, result %+v", p, r) + } +} + // Sample before Run fails at once. func TestSampleBeforeRun(t *testing.T) { if _, err := New(Config{Name: "game"}).Sample(context.Background(), "c_one", question); err == nil { diff --git a/addon/types.go b/addon/types.go index 1bfc514..db831f7 100644 --- a/addon/types.go +++ b/addon/types.go @@ -46,6 +46,7 @@ type Capability struct { Network string `json:"network,omitempty"` // the bot's chat network, as it names itself: "signal", "telegram" WatchReplies bool `json:"watchReplies,omitempty"` // the bot's: it takes a watch with Replies WatchReactions bool `json:"watchReactions,omitempty"` // the bot's: it takes a watch with Reactions + Buttons bool `json:"buttons,omitempty"` // the bot's: its network shows a post's Buttons and Keyboard (Telegram) } // Context is the message a call the bot makes came from, in the call's @@ -128,10 +129,10 @@ func Text(s string) Result { return Result{Content: []Content{{Type: "text", Tex // Op is one thing an addon's outbox asks the bot to do. type Op struct { ID string `json:"id"` - Op string `json:"op"` // "post", "react" or "unwatch" - Chat string `json:"chat,omitempty"` // a post's, unwatch's or reaction-to-a-post's chat pseudonym - Text string `json:"text,omitempty"` // a post's, with {u_…} placeholders the bot fills in with names - Images []Image `json:"images,omitempty"` // a post's: at most 2, 2 MB in all + Op string `json:"op"` // "post", "edit", "react" or "unwatch" + Chat string `json:"chat,omitempty"` // a post's, edit's, unwatch's or reaction-to-a-post's chat pseudonym + Text string `json:"text,omitempty"` // a post's or edit's, with {u_…} placeholders the bot fills in with names + Images []Image `json:"images,omitempty"` // a post's: at most 2, 2 MB in all; an edit's, or a post's with Buttons or a Keyboard, at most 1 Ref string `json:"ref,omitempty"` // a reaction's message: a context's ref; or else Post Emoji string `json:"emoji,omitempty"` // a reaction's Watch string `json:"watch,omitempty"` // the ID of the watch an unwatch ends @@ -139,8 +140,48 @@ type Op struct { Audio *Audio `json:"audio,omitempty"` // a post's: one clip to play, MP3, at most 2 MB // Post is a reaction's, in place of Ref: the ID of an earlier post of // the addon's in Chat, as ReplyTo names it, so the bot reacts to its - // own message, such as ⏰ on a question whose time runs out. + // own message, such as ⏰ on a question whose time runs out. It is + // also an edit's: the post whose text, image and buttons it replaces; + // not one merged with others or sent as more than one message. Post string `json:"post,omitempty"` + // Silent is a post's: sent without a notification where the network + // can (Telegram); Signal ignores it. + Silent bool `json:"silent,omitempty"` + // Buttons are a post's or edit's rows of buttons under it, at most 5 + // of at most 5, where the bot's Capability has Buttons; elsewhere they + // are left off. A press calls OnPress, one of the addon's tools for + // the bot alone, with Press as its arguments and the presser's context. + Buttons [][]Button `json:"buttons,omitempty"` + OnPress string `json:"onPress,omitempty"` // with Buttons, and only with them + // Keyboard is a post's, in a DM where the Capability has Buttons: the + // chat's reply keyboard from now on, rows of keys, at most 5 of at most + // 5. A message of exactly a key's label runs its command, one of the + // addon's direct commands. + // RemoveKeyboard takes it away. + Keyboard [][]Key `json:"keyboard,omitempty"` + RemoveKeyboard bool `json:"removeKeyboard,omitempty"` +} + +// Button is a button under a post. +type Button struct { + Label string `json:"label"` // at most 32 characters, no space around them + Data string `json:"data"` // what a press passes back, 1 to 64 bytes +} + +// Key is a key of a DM's reply keyboard. +type Key struct { + Label string `json:"label"` // at most 32 characters, no space around them, unique in the keyboard + Command string `json:"command"` // the addon's direct command a message of exactly Label runs, such as "/rain" +} + +// Press is the arguments of a post's OnPress tool when one of its buttons +// is pressed: the button's Data, and the ID of the post op it is under +// (an edit's Post), with the presser's context in _meta, as a direct +// command's. The result's text, if any, is shown to the presser for a +// moment. +type Press struct { + Press string `json:"press"` + Post string `json:"post"` } // Audio is a clip in a post, sent to play, with no title of its own: on diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 0532dac..afa99ce 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -27,7 +27,7 @@ Every setting, read from the environment (`/etc/signalbot.env` in the install). | `MAX_CONCURRENCY` | `32` | Conversations in flight at once; messages beyond this are dropped, with a warning | | `MCP_CONFIG` | empty | Path of an MCP servers file; see [MCP connectors](FILES_LINKS_TOOLS_MCP.md#mcp-connectors) | | `_…` | none | An [addon's](FILES_LINKS_TOOLS_MCP.md#addons) own settings, read by the addon, not the bot. An addon server gets every variable that starts with its name in capitals, anything but letters and digits as `_`, then `_` (the server `geo` gets `GEO_STATE_DIR` and the rest; `GEO_STATE_DIR`, if not set, is `addons/geo` in `STATE_DIRECTORY`, which the addon creates), plus `PATH`, `HOME` and, if set, `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE` and `SSL_CERT_DIR`, and nothing else, so none of the other settings above reach it. A server whose prefix one of the settings above starts with (such as `model` or `mcp`) is a config error. Each addon documents its own, such as [GeoGuess's](https://github.com/robdevops/GeoGuess#settings) | -| `STATE_DIRECTORY` | working directory | Where features save their state, one file each, such as `/schedule`'s `schedules.json`, `mcp.json` when an MCP server is an [addon](FILES_LINKS_TOOLS_MCP.md#addons) (and the core its `budget.json`); the bot won't start if a feature that saves can't list and write it. Set by systemd's `StateDirectory=signalbot` (`/var/lib/private/signalbot`) and by the Docker image (`/data`, which must be writable by user 65532) | +| `STATE_DIRECTORY` | working directory | Where features save their state, one file each, such as `/schedule`'s `schedules.json`, `mcp.json` when an MCP server is an [addon](FILES_LINKS_TOOLS_MCP.md#addons) (and the core its `budget.json`, and `keyboards.json` once an addon sets a Telegram DM's keyboard); the bot won't start if a feature that saves can't list and write it. Set by systemd's `StateDirectory=signalbot` (`/var/lib/private/signalbot`) and by the Docker image (`/data`, which must be writable by user 65532) | | `TOOL_LINGER_ROUNDS` | `2` | Replies a keyword-gated tool group (charts, an MCP server with `keywords`) stays offered after the last one that matched its keywords or used its tools; `0` offers it only on a matching message. Any use or match starts the count again, so a run of follow-ups keeps it. Capped at `HISTORY_MAX`. See [How tools are offered](FILES_LINKS_TOOLS_MCP.md#how-tools-are-offered) | | `TZ` | `UTC` in Docker, the host's under systemd | Time zone for `/schedule` times without an offset and for `DARKMODE` hours, e.g. `Australia/Sydney`; addons get it too, for the times they write (GeoGuess's round deadline) | diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 7d0447e..9149a2f 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -137,6 +137,7 @@ An addon written in Go can use the package [`github.com/robdevops/signalbot/addo | `global_ids` | a person has the same ID in every chat. Off, each chat gives them a different one, so the addon can't follow someone between groups | | `rate` | its posts and reactions a minute in each chat (`per_minute`, default 20), with bursts of `burst` (default 5) | | `model` | it may ask the bot's model (below): at most `per_hour` requests an hour, all chats together (default 30), each answer at most `max_tokens` tokens (default 4000, at most 32000) | +| `announce` | a chat that used one of its direct commands stays open to its posts with no expiry (still within `chats`), such as for alerts days later. Off, a chat stays open for 24 hours after it last used the addon | Each permission is off unless set. For an addon, `chats`, `dms` and these permissions are the gate: anyone in an allowed chat can use its commands, and nothing it does reaches another chat. @@ -146,10 +147,11 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. - **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round πŸ˜‰"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot (in a DM, every message, as the chat is the player's own with the bot), such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. A watch with `"reactions": true` also takes reactions put on, or taken off, the command's answer and the addon's posts while it lasts, each a call of its tool with `{"reaction": emoji, "removed": true|false}` and the reactor's context, such as a game's players joining by reacting to its intro. A watch's `over` text answers, for an hour after the watch ends, a message to the bot that replies to one of the addon's messages it knew, in place of the model ("That game is over."), so a late answer isn't played along with. On Telegram the bot sees reactions only where it is an admin. - **Model.** With `model`, an addon may ask the bot's model for text, through MCP's standard sampling request (`sampling/createMessage`): it sends the prompt, and the bot runs it on its own model, with its own key, and sends back the answer. The addon needs no key or provider of its own. The bot offers this only to an addon with `model`, and only while it has a model; MCP suggests a person approve each request, and here the `model` setting is that approval. Each request names the chat it is for, one the addon may post in now, and is charged to that chat's `DAILY_BUDGET`: one over its budget is refused, and so is one past `per_hour`. A request is text only, at most 16 messages and 32 KB, with one in flight per addon at a time. Only its outcome, time, size, tokens and cost are logged, never the prompt or the answer. -- **Outbox.** An addon posts when it likes by queueing posts (text, up to 2 pictures, or one MP3 clip to play, which shows no title: a voice message on Telegram, `clip.mp3` on Signal), reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. A reaction can likewise go on one of the addon's own earlier posts, named by its ID (`post`, with its `chat`, in place of `ref`), such as ⏰ on a question when time is nearly up; one on a post the bot doesn't remember sending there, such as one not sent yet, is dropped. +- **Outbox.** An addon posts when it likes by queueing posts (text, up to 2 pictures, or one MP3 clip to play, which shows no title: a voice message on Telegram, `clip.mp3` on Signal), reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command, a watch or a press of its buttons, in the last 24 hours (or, with `announce`, ever by one of its direct commands), and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. A reaction can likewise go on one of the addon's own earlier posts, named by its ID (`post`, with its `chat`, in place of `ref`), such as ⏰ on a question when time is nearly up; one on a post the bot doesn't remember sending there, such as one not sent yet, is dropped. A post with `silent` goes without a notification on Telegram (Signal has no silent send). +- **Buttons, keyboard and edits.** On Telegram (the bot says so in `initialize`, as `buttons`), a post may carry `buttons`, rows of `{label, data}` (at most 5 of 5; a label at most 32 characters, data 1 to 64 bytes; at most one picture), shown under it, and `onPress`, one of the addon's tools for the bot alone: a press calls it with `{"press": data, "post": }` and the presser's context, as a direct command, and shows its text, if any, for a moment. A press needs no watch, and opens the chat to the addon's posts (not to `model`, which needs a use in the last 24 hours), so buttons under a days-old alert still work. In a DM, a post may set the chat's reply `keyboard`, rows of `{label, command}` (a label with no space around it, once in the keyboard; a command one of the addon's direct commands; at most one picture): a message of exactly a label runs its command, as if typed (`removeKeyboard` takes it away); the bot keeps it in `keyboards.json`, under a SHA-256 hash of the chat, which could be matched by trying every ID. An `edit` op names an earlier post (`post`, with its `chat`) and replaces its text, picture (at most one) and buttons, under a post's rules (`post`, `rate`, an open chat): on Telegram in place (or as a new message if a picture can't go on it); on Signal the text in place, within a day of posting and up to 10 times, or with a picture as a new message. A post merged with others, or sent as more than one message (pictures in an album, or text past one message), can't be edited. Signal shows no buttons or keyboard, and leaves them off. The bot remembers a post with buttons for 30 days (its addon's newest 1,000), so its presses and edits work that long. - **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. An addon that keeps files takes its directory from `STATE_DIR` (`GEO_STATE_DIR`) and creates it itself, mode 0700. Unless the bot's environment sets it, the bot sets it to `addons/` in the bot's state directory (`/var/lib/private/signalbot/addons/geo`, or `/data/addons/geo` in Docker), so an addon's files are kept with the bot's; it creates nothing there itself. With `STATE_DIRECTORY` unset, or a server name that isn't only letters, digits, `.`, `_` and `-` (up to 64, not starting with `.`), there is no default, and the addon falls back on its own. - **Logs.** The bot logs an addon's commands, calls and drops by name, outcome, time and size, never what was said. An addon's stderr is counted ("addon geo wrote 3 lines (210 bytes) to stderr", at most once a minute and once more when it exits), never logged, since it may echo a message. To debug an addon, run it on its own with stderr going to your own file. -- **State.** The bot keeps an addon's watches, the messages they took, the chats it may post in, how far it has read its outbox and the posts a later one may reply to in `mcp.json`, so a restart of either doesn't lose a round. See [PRIVACY.md](../PRIVACY.md#addons). +- **State.** The bot keeps an addon's watches, the messages they took, the chats it may post in, how far it has read its outbox and the posts a later one may reply to, react to or edit, with their buttons, in `mcp.json`, so a restart of either doesn't lose a round. See [PRIVACY.md](../PRIVACY.md#addons). - **Docker.** The image has no shell or runtimes, so an addon must be a static binary (`CGO_ENABLED=0 go build`), mounted read-only at the same path, such as `- /opt/signalbot-addons:/opt/signalbot-addons:ro` in `compose.yaml`, so its `command` is the same under Docker and systemd (whose `ProtectSystem=strict` leaves `/opt` readable). The state directory must be writable by user 65532 for `mcp.json`, and so must any directory the addon keeps files in. Addons share the container's or unit's memory and process limits, so raise `mem_limit` or `MemoryMax` to suit; `GOMEMLIMIT` isn't passed on, so a Go addon takes its limit from its own setting (GeoGuess: `GEO_MEMLIMIT`). --- diff --git a/internal/bot/answer.go b/internal/bot/answer.go index 85833bb..84b7433 100644 --- a/internal/bot/answer.go +++ b/internal/bot/answer.go @@ -75,7 +75,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs return case act.Answer != "" || len(act.Pictures) > 0: text, _ := captioned(act.Answer, act.Pictures) - sent := b.net.Send(msg.Chat, text, act.Pictures, b.chats.Names(msg.Chat.Key()), 0, nil) + sent := b.net.Send(msg.Chat, text, act.Pictures, b.chats.Names(msg.Chat.Key()), 0, nil, feature.Markup{}) if act.OnSent != nil { act.OnSent(sent, len(sent) == 0) } @@ -90,7 +90,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs if over, left := b.budget.over(key); over { if b.budget.markTold(key) { // once a day; then a ⏳ until midnight logx.Warnf("a chat reached its daily budget; it is answered again at midnight") - b.net.Send(msg.Chat, limitNotice(left), nil, b.chats.Names(key), 0, nil) + b.net.Send(msg.Chat, limitNotice(left), nil, b.chats.Names(key), 0, nil, feature.Markup{}) } else if msg.Timestamp != 0 { // a scheduled post can't be reacted to b.net.React(msg.Chat, msg, waiting) } @@ -109,7 +109,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs for { if act.ToolChoice != "" && !b.callsTools.Load() { stop() - b.net.Send(msg.Chat, noTools, nil, b.chats.Names(key), 0, nil) + b.net.Send(msg.Chat, noTools, nil, b.chats.Names(key), 0, nil, feature.Markup{}) return } if t = b.buildTurn(msg, text); t.empty(msg) { @@ -149,7 +149,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs if errors.Is(err, model.ErrTooManyRounds) { answer = tooManyRounds } - b.net.Send(msg.Chat, answer, nil, b.chats.Names(key), 0, nil) + b.net.Send(msg.Chat, answer, nil, b.chats.Names(key), 0, nil, feature.Markup{}) return } b.followUp(key, offered, msg.Text, reply.ToolsUsed) diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 7b28012..a3bf15a 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -42,8 +42,17 @@ type Network interface { // first message sent replies to the bot's own message in chat that an // earlier Send returned it for; one the network can't find is sent // without it. audio, if not nil, is one MP3 clip sent with the text, - // as audio to play, with no title of its own. - Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64, audio []byte) (sent []int64) + // as audio to play, with no title of its own. mk is shown where the + // network can (Buttons), and left off where it can't. + Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64, audio []byte, mk feature.Markup) (sent []int64) + // Edit replaces the bot's own message in chat that Send returned sent + // for with text, pics and mk's buttons, and returns the timestamps that + // now stand for it: sent, or a new message's where the network can't + // edit it in place; none if it failed, which is logged. + Edit(chat feature.Chat, sent int64, text string, pics []feature.Picture, known map[string]string, mk feature.Markup) []int64 + // Buttons reports whether the network shows a post's Markup; it never + // blocks. + Buttons() bool // React puts emoji on msg in chat, as a reaction from the bot. React(chat feature.Chat, msg feature.Message, emoji string) Typing(chat feature.Chat) (stop func()) @@ -107,7 +116,9 @@ type Bot struct { introLines []introLine // features' lines for the introduction stores []string // the names of the saved states features opened events []func(context.Context, feature.Event) string + presses []func(context.Context, feature.Press) (string, bool) now func() time.Time // the clock history and the budget go by + keys *keyboards // each DM's reply keyboard } // New makes the bot on net and reads what the model can do, so features @@ -115,7 +126,7 @@ type Bot struct { // answered. Work in progress ends with ctx, which should outlive the // shutdown signal so that Shutdown can let replies finish. func New(ctx context.Context, cfg *config.Config, net Network) *Bot { - b := &Bot{cfg: cfg, net: net, timers: timers.New(), slots: make(chan struct{}, cfg.MaxConcurrency), ctx: ctx, now: time.Now} + b := &Bot{cfg: cfg, net: net, timers: timers.New(), slots: make(chan struct{}, cfg.MaxConcurrency), ctx: ctx, now: time.Now, keys: newKeyboards(cfg.StateDir)} b.chats = chats.New(cfg.HistoryMax, b.work, b.spawn) b.chats.SetEvicted(func(r Received) { b.dropped(r, errMadeRoom) }) b.timerCtx, b.stopTimers = context.WithCancel(ctx) @@ -186,7 +197,8 @@ func (b *Bot) Shutdown(d time.Duration) { // handle runs on the network's reader goroutine for everything received (a // member change comes from another of its goroutines), so it never blocks // or calls the network. An Incoming message and, with a hook for them, a -// Happened event go to their chat's mailbox; Chatter goes to the OnMessage +// Happened event and a Pressed button go to their chat's mailbox (a press +// with no hook is answered at once); Chatter goes to the OnMessage // hooks here, and is never logged. (Posted, Outgoing and Reacted come from // Deliver, Post and React, never from the network.) func (b *Bot) handle(r Received) { @@ -208,6 +220,13 @@ func (b *Bot) handle(r Received) { if len(b.events) > 0 { // with no hook, nothing would read it b.post(r) } + case Pressed: + r.Answer = onceAnswer(r.Answer) + if len(b.presses) == 0 { // with no hook, nothing would take it + r.Answer("") + return + } + b.post(r) case Incoming: b.post(r) } @@ -246,7 +265,7 @@ func (b *Bot) pending() chats.Ref { // and returns Send's timestamps. History is kept first so a message // arriving while the send is out lands after the turn, not before it. func (b *Bot) sendKept(key string, p chats.Ref, chat feature.Chat, text string, pics []feature.Picture, known map[string]string) []int64 { - sent := b.net.Send(chat, text, pics, known, 0, nil) + sent := b.net.Send(chat, text, pics, known, 0, nil, feature.Markup{}) b.chats.Retag(key, p.ID, botRefs(sent)) return sent } @@ -337,6 +356,9 @@ func (b *Bot) dropped(r Received, err error) { if n := len(r.Reactions); n > 1 { what = fmt.Sprintf("%d reactions", n) } + case Pressed: + what = "a press" + r.Answer("") } if errors.Is(err, chats.ErrNoSlot) { logx.Warnf("dropped %s: all %d worker slots are busy (raise MAX_CONCURRENCY)", what, b.cfg.MaxConcurrency) @@ -346,11 +368,14 @@ func (b *Bot) dropped(r Received, err error) { } // abandon tells the posts among rs, left waiting when shutdown began, that -// they were dropped. +// they were dropped, and answers the presses. func abandon(rs []Received) { for _, r := range rs { - if o, ok := r.(Outgoing); ok { - o.Post.OnSent(nil, true) + switch r := r.(type) { + case Outgoing: + r.Post.OnSent(nil, true) + case Pressed: + r.Answer("") } } } @@ -359,7 +384,7 @@ func abandon(rs []Received) { // messages are answered together, as one turn, so "actually" and "forget // it" get one reply that sees both; each run stays within one message's // picture limits. On its own goes a message a hook acts on (a command or -// an answer), a delivered one, a post, the bot's reactions, and one that +// an answer), a delivered one, a post, the bot's reactions, a press, and one that // waited for the bot's ID and was not addressed after all. A panic loses // only the message or turn that caused it, and nothing new starts once // shutdown begins; a post left waiting then, or a hook's answer not yet @@ -402,6 +427,10 @@ func (b *Bot) work(rs []Received) { case Reacted: alone(func() { b.react(r) }) return + case Pressed: + alone(func() { b.pressed(r) }) + r.Answer("") // if shutdown began first + return case Incoming: p = r default: @@ -517,6 +546,11 @@ func (b *Bot) load(r Incoming) (feature.Message, bool) { if !ok || !msg.Addressed { return msg, ok // only one that arrived before the bot's ID was known can be unaddressed } + if msg.Chat.GroupID == "" && msg.Edited == 0 && len(msg.Media) == 0 { + if cmd, ok := b.keys.command(key, msg.Text); ok { // a key of the DM's keyboard + msg.Text = cmd + } + } edit := "" if msg.Edited != 0 { edit = " (edit)" diff --git a/internal/bot/buttons_test.go b/internal/bot/buttons_test.go new file mode 100644 index 0000000..d29dc3a --- /dev/null +++ b/internal/bot/buttons_test.go @@ -0,0 +1,167 @@ +package bot + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/robdevops/signalbot/internal/config" + "github.com/robdevops/signalbot/internal/feature" +) + +// answered is a press's Answer that hands what it showed to a channel. +func answered() (func(string), chan string) { + got := make(chan string, 2) + return func(text string) { got <- text }, got +} + +func next(t *testing.T, got chan string) string { + t.Helper() + select { + case s := <-got: + return s + case <-time.After(5 * time.Second): + t.Fatal("the press wasn't answered") + return "" + } +} + +// A press goes to the OnPress hooks in its chat's slot, the first that +// takes it answering; one none takes, or with no hooks at all, is +// answered with nothing, once. +func TestPress(t *testing.T) { + var seen []feature.Press + h := start(t, options{features: func(b *Bot) { + b.OnPress(func(_ context.Context, p feature.Press) (string, bool) { + seen = append(seen, p) + return "not mine", false + }) + b.OnPress(func(_ context.Context, p feature.Press) (string, bool) { + return "7 days", p.Data == "rain 7d" + }) + }}) + p := feature.Press{Chat: feature.Chat{User: aliceID}, By: feature.Person{ID: aliceID, Name: "Alice"}, Sent: 5001, Data: "rain 7d"} + answer, got := answered() + h.net.handle(Pressed{Press: p, Answer: answer}) + if s := next(t, got); s != "7 days" { + t.Fatalf("answered %q", s) + } + p.Data = "other" + h.net.handle(Pressed{Press: p, Answer: answer}) + if s := next(t, got); s != "" { + t.Fatalf("answered %q", s) + } + h.settle() + if len(seen) != 2 || seen[0].Sent != 5001 || seen[0].By.ID != aliceID || seen[0].Chat.User != aliceID { + t.Fatalf("seen %+v", seen) + } + select { + case s := <-got: + t.Fatalf("answered twice: %q", s) + default: + } + h.noSend() + + bare := start(t, options{}) + answer, got = answered() + bare.net.handle(Pressed{Press: p, Answer: answer}) + if s := next(t, got); s != "" { + t.Fatalf("with no hook, answered %q", s) + } +} + +// An edit goes through the chat's mailbox to the network's Edit, keeping +// nothing in history; OnSent gets what stands for the message, or none if +// the edit failed, and it isn't dropped either way. +func TestEditPost(t *testing.T) { + h := start(t, options{}) + chat := feature.Chat{User: aliceID} + type result struct { + sent []int64 + dropped bool + } + got := make(chan result, 2) + onSent := func(sent []int64, dropped bool) { got <- result{sent, dropped} } + mk := feature.Markup{Buttons: [][]feature.Button{{{Label: "7d", Data: "rain 7d"}}}} + h.b.Post(feature.Post{Chat: chat, Label: "Eco", Text: "Rain, 7 days", Edit: 5001, Markup: mk, OnSent: onSent}) + s := h.nextSend() + if s.edit != 5001 || s.text != "Rain, 7 days" || len(s.markup.Buttons) != 1 { + t.Fatalf("sent %+v", s) + } + if r := <-got; !slices.Equal(r.sent, []int64{5001}) || r.dropped { + t.Fatalf("OnSent %+v", r) + } + h.net.fail.Store(true) + h.b.Post(feature.Post{Chat: chat, Text: "again", Edit: 5001, OnSent: onSent}) + if r := <-got; r.sent != nil || r.dropped { + t.Fatalf("a failed edit's OnSent %+v", r) + } + h.net.fail.Store(false) + // Nothing was kept: the model's next request has no post in it. + r, _ := h.ask(dm("hi")) + if c := contents(r); len(c) != 1 { + t.Fatalf("history %q", c) + } +} + +// A post's keyboard, in a DM on a network that shows one, makes a message +// of exactly one of its labels its command, across a restart, until a post +// takes it away. Elsewhere a label is only text. +func TestKeyboard(t *testing.T) { + dir := t.TempDir() + features := func(b *Bot) { + b.Command("rain", func(_ context.Context, _ feature.Message, args string) feature.Action { + return feature.Action{Answer: "rain " + args} + }) + } + run := func(buttons bool) *harness { + return start(t, options{features: features, buttons: buttons, cfg: func(c *config.Config) { c.StateDir = dir }}) + } + keys := [][]feature.Key{{{Label: "🌧 Rain", Command: "/rain 7d"}, {Label: "Now", Command: "/rain"}}} + alice := feature.Chat{User: aliceID} + + h := run(true) + h.b.Post(feature.Post{Chat: alice, Text: "Pick one", Markup: feature.Markup{Keyboard: keys}}) + if s := h.nextSend(); len(s.markup.Keyboard) != 1 { + t.Fatalf("sent %+v", s) + } + h.receive(dm("🌧 Rain")) + if s := h.nextSend(); s.text != "rain 7d" { + t.Fatalf("answered %q", s.text) + } + if data, err := os.ReadFile(filepath.Join(dir, "keyboards.json")); err != nil || strings.Contains(string(data), aliceID) { + t.Fatalf("saved %s, %v", data, err) + } + // In a group, a label is only text, for the model. + h.receive(atBot("🌧 Rain")) + if s := h.nextSend(); s.text != "ok" { + t.Fatalf("in a group, answered %q", s.text) + } + h.b.Shutdown(time.Second) + + h = run(true) // after a restart + h.receive(dm("Now")) + if s := h.nextSend(); s.text != "rain " { + t.Fatalf("after a restart, answered %q", s.text) + } + h.b.Post(feature.Post{Chat: alice, Text: "Bye", Markup: feature.Markup{NoKeyboard: true}}) + h.nextSend() + h.receive(dm("Now")) + if s := h.nextSend(); s.text != "ok" { + t.Fatalf("with the keyboard taken away, answered %q", s.text) + } + h.b.Shutdown(time.Second) + + // A network that shows no keyboard: none is remembered. + h = run(false) + h.b.Post(feature.Post{Chat: alice, Text: "Pick one", Markup: feature.Markup{Keyboard: keys}}) + h.nextSend() + h.receive(dm("Now")) + if s := h.nextSend(); s.text != "ok" { + t.Fatalf("on a network without keyboards, answered %q", s.text) + } +} diff --git a/internal/bot/fakes_test.go b/internal/bot/fakes_test.go index 129db95..8b33be8 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -58,6 +58,7 @@ type fakeNet struct { sends atomic.Int64 // Send calls, for their timestamps fail atomic.Bool // while set, Send fails: nothing is sent watch Watch // what Watch was told + buttons bool // it shows markup } type sent struct { @@ -66,6 +67,8 @@ type sent struct { images []feature.Picture known map[string]string reply int64 + markup feature.Markup + edit int64 // the message an Edit replaced } func (n *fakeNet) Watch(w Watch) { @@ -91,14 +94,25 @@ func (n *fakeNet) WaitID(ctx context.Context) string { // Send returns one timestamp per call, counting up from 5000, or none // while fail is set. -func (n *fakeNet) Send(chat feature.Chat, text string, images []feature.Picture, known map[string]string, replyTo int64, audio []byte) []int64 { +func (n *fakeNet) Send(chat feature.Chat, text string, images []feature.Picture, known map[string]string, replyTo int64, audio []byte, mk feature.Markup) []int64 { if n.fail.Load() { return nil } - n.sent <- sent{chat, text, images, known, replyTo} + n.sent <- sent{chat: chat, text: text, images: images, known: known, reply: replyTo, markup: mk} return []int64{5000 + n.sends.Add(1)} } +// Edit replaces the message in place, or fails while fail is set. +func (n *fakeNet) Edit(chat feature.Chat, ts int64, text string, images []feature.Picture, known map[string]string, mk feature.Markup) []int64 { + if n.fail.Load() { + return nil + } + n.sent <- sent{chat: chat, text: text, images: images, known: known, markup: mk, edit: ts} + return []int64{ts} +} + +func (n *fakeNet) Buttons() bool { return n.buttons } + // React is sent as "react to @", the sender // "bot" for the bot's own message. func (n *fakeNet) React(chat feature.Chat, msg feature.Message, emoji string) { @@ -166,6 +180,7 @@ type options struct { tools bool otherAPI bool // the fake model API is not taken for OpenRouter's waitID bool // the bot isn't connected until the test closes h.net.id + buttons bool // the network shows markup features func(*Bot) cfg func(*config.Config) } @@ -175,7 +190,7 @@ type options struct { func start(t *testing.T, o options) *harness { t.Helper() h := &harness{t: t, logs: &logx.Buffer{}, tools: o.tools, - net: &fakeNet{id: make(chan struct{}), running: make(chan struct{}), sent: make(chan sent, 64)}} + net: &fakeNet{id: make(chan struct{}), running: make(chan struct{}), sent: make(chan sent, 64), buttons: o.buttons}} t.Cleanup(logx.SetOutput(h.logs, h.logs, true)) if !o.waitID { close(h.net.id) diff --git a/internal/bot/host.go b/internal/bot/host.go index 29f2cae..b22b493 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -34,6 +34,10 @@ func (b *Bot) OnEvent(fn func(context.Context, feature.Event) string) { b.events = append(b.events, fn) } +func (b *Bot) OnPress(fn func(context.Context, feature.Press) (string, bool)) { + b.presses = append(b.presses, fn) +} + func (b *Bot) Command(name string, fn func(context.Context, feature.Message, string) feature.Action) error { if err := b.commands.Take(name); err != nil { return err @@ -93,7 +97,7 @@ func (b *Bot) Store(name string) (feature.Store, error) { } func (b *Bot) Info() feature.Info { - info := feature.Info{Name: b.net.BotName(), Network: b.net.Name(), Version: b.cfg.Version, Model: b.cfg.Model, + info := feature.Info{Name: b.net.BotName(), Network: b.net.Name(), Buttons: b.net.Buttons(), Version: b.cfg.Version, Model: b.cfg.Model, Images: b.images.Load(), Audio: b.audio.Load(), PDFs: b.files.Load(), CallsTools: b.callsTools.Load(), Tools: b.toolNames(false), Intro: b.intro(false), IntroDM: b.intro(true)} if b.ai == nil { info.Model = "" @@ -155,6 +159,9 @@ func (b *Bot) Deliver(msg feature.Message) { // once, whatever happens to it. func (b *Bot) Post(p feature.Post) { p.OnSent = once(p.OnSent) + if p.Edit != 0 { + p.Label, p.Audio, p.ReplyTo = "", nil, 0 + } switch { case b.closing.Load(), p.Text == "" && len(p.Pictures) == 0 && len(p.Audio) == 0: p.OnSent(nil, true) @@ -188,25 +195,71 @@ func (b *Bot) say(p feature.Post) { } key := p.Chat.Key() text, kept := captioned(p.Text, p.Pictures) + if p.Edit != 0 { + p.OnSent(b.net.Edit(p.Chat, p.Edit, text, p.Pictures, b.chats.Names(key), p.Markup), false) + return + } if len(p.Audio) > 0 { kept = strings.TrimSpace(kept + " [sent an audio clip]") } if p.Label == "" || b.ai == nil { // with no model, nothing would read it - sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo, p.Audio) + sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo, p.Audio, p.Markup) + b.keyboard(p, sent) p.OnSent(sent, len(sent) == 0) return } ref := b.pending() b.chats.Add(key, b.now(), 0, chats.Entry{Role: "assistant", Content: txt.Clamp("["+p.Label+"] "+kept, maxPostKept), Refs: []chats.Ref{ref}}) - sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo, p.Audio) + sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo, p.Audio, p.Markup) if len(sent) == 0 { b.chats.Withdraw(key, ref.ID) // the chat never saw it, and it may be posted again } else { b.chats.Retag(key, ref.ID, botRefs(sent)) } + b.keyboard(p, sent) p.OnSent(sent, len(sent) == 0) } +// keyboard remembers the reply keyboard a post sent in a DM set or took +// away, where the network shows one, so a message of one of its labels is +// handled as its command. +func (b *Bot) keyboard(p feature.Post, sent []int64) { + mk := p.Markup + switch { + case len(sent) == 0 || p.Chat.GroupID != "" || !b.net.Buttons(): + case mk.NoKeyboard: + b.keys.set(p.Chat.Key(), nil) + case len(mk.Keyboard) > 0: + b.keys.set(p.Chat.Key(), mk.Keyboard) + } +} + +// pressed runs the OnPress hooks for a press in its chat's slot, and +// answers it with the answer of the first that takes it, or nothing. +func (b *Bot) pressed(r Pressed) { + answer := "" + defer func() { r.Answer(answer) }() // also if a hook panics + for _, fn := range b.presses { + if a, ok := fn(b.ctx, r.Press); ok { + answer = a + return + } + } +} + +// onceAnswer is answer made safe to call more than once, the calls after +// the first doing nothing; nil does nothing. +func onceAnswer(answer func(string)) func(string) { + var o sync.Once + return func(text string) { + o.Do(func() { + if answer != nil { + answer(text) + } + }) + } +} + // maxPostKept caps what history keeps of a post. const maxPostKept = 500 @@ -276,7 +329,7 @@ func (b *Bot) event(e feature.Event) { for _, p := range people { chats.Claim(known, p.Name, p.ID) } - b.net.Send(e.Chat, reply, nil, known, 0, nil) + b.net.Send(e.Chat, reply, nil, known, 0, nil, feature.Markup{}) return } } diff --git a/internal/bot/keys.go b/internal/bot/keys.go new file mode 100644 index 0000000..11e52d5 --- /dev/null +++ b/internal/bot/keys.go @@ -0,0 +1,103 @@ +package bot + +import ( + "crypto/sha256" + "encoding/hex" + "sync" + + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/logx" + "github.com/robdevops/signalbot/internal/kit/state" +) + +// keyboards are the reply keyboards posts set in DMs: each DM's labels and +// the commands they stand for. They are saved in keyboards.json, under a +// hash of each chat's key, so the file holds no ID as such (a hash could +// be matched by trying every ID, as budget.json's); it is read when first +// needed, and a state directory that can't be written keeps them in +// memory. +type keyboards struct { + mu sync.Mutex + doc *state.Doc + loaded bool + failing bool // the last save failed, which was logged + chats map[string]map[string]string // by hashed chat key: label to command +} + +// keyboardsName is the keyboards' saved state, which no feature may open. +const keyboardsName = state.Keyboards + +// maxKeyboards caps the DMs whose keyboard is kept. +const maxKeyboards = 10000 + +func newKeyboards(dir string) *keyboards { + return &keyboards{doc: state.Open(state.Dir(dir), keyboardsName), chats: map[string]map[string]string{}} +} + +// hashKey is a chat's key as the file names it. +func hashKey(key string) string { + sum := sha256.Sum256([]byte(key)) + return hex.EncodeToString(sum[:]) +} + +// load reads the saved keyboards the first time. k.mu is held. +func (k *keyboards) load() { + if k.loaded { + return + } + k.loaded = true + var saved map[string]map[string]string + switch found, err := k.doc.Load(&saved); { + case err != nil: + logx.Warnf("%v, so the DMs' keyboards start empty", err) + case found && saved != nil: + k.chats = saved + } +} + +// command is the command a message of text stands for in the chat whose +// key is key: one of its keyboard's labels, exactly. +func (k *keyboards) command(key, text string) (string, bool) { + if text == "" { + return "", false + } + k.mu.Lock() + defer k.mu.Unlock() + k.load() + cmd, ok := k.chats[hashKey(key)][text] + return cmd, ok +} + +// set makes keys the keyboard of the chat whose key is key, or with none +// takes it away, and saves them all. +func (k *keyboards) set(key string, keys [][]feature.Key) { + k.mu.Lock() + defer k.mu.Unlock() + k.load() + h := hashKey(key) + if len(keys) == 0 { + if _, ok := k.chats[h]; !ok { + return + } + delete(k.chats, h) + } else { + if _, ok := k.chats[h]; !ok && len(k.chats) >= maxKeyboards { + logx.Warnf("a DM's keyboard isn't kept: %d already are", maxKeyboards) + return + } + m := map[string]string{} + for _, row := range keys { + for _, key := range row { + m[key.Label] = key.Command + } + } + k.chats[h] = m + } + switch err := k.doc.Save(k.chats); { + case err != nil && !k.failing: + logx.Warnf("the DMs' keyboards not saved, kept in memory until a save works: %v", err) + k.failing = true + case err == nil: + k.failing = false + } +} diff --git a/internal/bot/received.go b/internal/bot/received.go index 8093c97..c1328a4 100644 --- a/internal/bot/received.go +++ b/internal/bot/received.go @@ -55,6 +55,14 @@ type Reacted struct { Reactions []Reaction } +// Pressed is a press of a button under one of the bot's messages. Answer +// shows the presser text, if not "", for a moment; it is called once, and +// never blocks. +type Pressed struct { + Press feature.Press + Answer func(text string) +} + // Reaction is an emoji the bot puts on a message. type Reaction struct { Message feature.Message @@ -69,6 +77,7 @@ func (r GroupChanged) chat() feature.Chat { return r.Chat } func (r Deleted) chat() feature.Chat { return r.Chat } func (r Happened) chat() feature.Chat { return r.Event.Chat } func (r Posted) chat() feature.Chat { return r.Message.Chat } +func (r Pressed) chat() feature.Chat { return r.Press.Chat } // Ready is a posted message as the network readies it: its sender's name // filled in, the bot's @name stripped, and in a group its members. diff --git a/internal/feature/feature.go b/internal/feature/feature.go index 4438287..f9d5776 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -197,6 +197,7 @@ type Info struct { CallsTools bool // the model can call tools Provider string // the model API's provider, as server tools name it: "openrouter", or "" for another Network string // the chat network, as it names itself, such as "signal" or "telegram" + Buttons bool // the network shows a post's Markup: buttons, a DM's keyboard, silent sends Tools []string // the Names of every tool group with tools, in feature order; none when it can't call tools Intro string // INTRO with {name}, {model}, {tools} and {more} filled in, as in a group IntroDM string // the same in a DM, with IntroLine's DM-only lines too @@ -223,6 +224,43 @@ type Post struct { Audio []byte // one MP3 clip sent with Text, as audio to play, with no title OnSent func(sent []int64, dropped bool) // if set, called once: with the timestamps sent, or dropped ReplyTo int64 // if set, sent as a reply to the bot's own earlier message in Chat that an OnSent gave this timestamp; sent plainly if the network can't find it + Markup Markup // what it carries besides its content, where the network shows it + // Edit, if set, makes the post an edit of the bot's own earlier message + // in Chat that an OnSent gave this timestamp: its text, pictures and + // buttons replaced, in place where the network can, else sent anew. + // OnSent gets the timestamps that now stand for it; an edit the network + // refused is sent, with none. History keeps nothing of it, and Label, + // Audio and ReplyTo are unused. + Edit int64 +} + +// Markup is what a post carries besides its content, on a network that +// shows it (Info.Buttons); another sends the post without it. +type Markup struct { + Silent bool // sent without a notification + Buttons [][]Button // rows of buttons under the post's last message; a press is a Press + Keyboard [][]Key // in a DM, the chat's reply keyboard from now on + NoKeyboard bool // in a DM, the reply keyboard taken away +} + +// Button is a button under a post. Pressing it is a Press with its Data. +type Button struct { + Label string + Data string // at most 64 bytes +} + +// Key is a key of a DM's reply keyboard: a message of exactly its Label is +// handled as if Command, such as "/rain", had been sent. +type Key struct { + Label, Command string +} + +// Press is someone pressing a button under one of the bot's messages. +type Press struct { + Chat Chat + By Person // who pressed it + Sent int64 // the message the button is under, as an OnSent named it + Data string // the button's Data } // Group is a group chat. @@ -246,6 +284,11 @@ type Host interface { // messages. The first non-empty reply returned is sent to the chat, // without the model. OnEvent(func(context.Context, Event) (reply string)) + // OnPress sees each press of a button under the bot's messages, in its + // chat's slot, so it may block or call the network. The first hook + // that takes it (ok) wins; its answer, if not "", is shown to the + // presser for a moment. + OnPress(func(context.Context, Press) (answer string, ok bool)) // Command registers /name: an addressed message whose text is "/name" // or "/name args", the name in any case, gets fn's Action. A name is 1 // to 32 lowercase letters, digits, _ or -, and is refused if another diff --git a/internal/feature/featuretest/featuretest.go b/internal/feature/featuretest/featuretest.go index e856c9d..c5b25b2 100644 --- a/internal/feature/featuretest/featuretest.go +++ b/internal/feature/featuretest/featuretest.go @@ -33,6 +33,7 @@ type Host struct { messages []func(context.Context, feature.Message) feature.Action turns []func(context.Context, feature.Message) feature.Additions events []func(context.Context, feature.Event) string + presses []func(context.Context, feature.Press) (string, bool) groups []feature.ToolGroup more []string timers []*Timer @@ -93,6 +94,26 @@ func (h *Host) Event(ctx context.Context, e feature.Event) string { return "" } +func (h *Host) OnPress(fn func(context.Context, feature.Press) (string, bool)) { + h.mu.Lock() + defer h.mu.Unlock() + h.presses = append(h.presses, fn) +} + +// Press runs the OnPress hooks on p, as the core does, and returns the +// answer of the first that takes it, and whether one did. +func (h *Host) Press(ctx context.Context, p feature.Press) (string, bool) { + h.mu.Lock() + hooks := slices.Clone(h.presses) + h.mu.Unlock() + for _, fn := range hooks { + if a, ok := fn(ctx, p); ok { + return a, true + } + } + return "", false +} + // IntroLine records line; IntroLineDM records it marked " (DM only)". func (h *Host) IntroLine(line string) { h.mu.Lock() diff --git a/internal/features/mcp/addon.go b/internal/features/mcp/addon.go index 1b188f1..05ead6a 100644 --- a/internal/features/mcp/addon.go +++ b/internal/features/mcp/addon.go @@ -34,7 +34,8 @@ type addonConfig struct { Names bool `json:"names"` // the context carries the sender's display name GlobalIDs bool `json:"global_ids"` Rate rateConfig `json:"rate"` - Model *modelConfig `json:"model"` // nil: it may not ask the bot's model + Model *modelConfig `json:"model"` // nil: it may not ask the bot's model + Announce bool `json:"announce"` // a chat that used one of its direct commands stays open to its posts, with no expiry watchMax time.Duration // WatchMax, read } @@ -62,7 +63,7 @@ type rateConfig struct { // addonSettings are the keys an addon block may have, rateSettings its // rate's and modelSettings its model's. var ( - addonSettings = []string{"chats", "dms", "post", "react", "watch", "watch_max", "names", "global_ids", "rate", "model"} + addonSettings = []string{"chats", "dms", "post", "react", "watch", "watch_max", "names", "global_ids", "rate", "model", "announce"} rateSettings = []string{"per_minute", "burst"} modelSettings = []string{"per_hour", "max_tokens"} ) @@ -271,6 +272,9 @@ type addon struct { key []byte // HMAC(secret, server): its pseudonyms' key conn conn // where to call it bot map[string]bool // the tools the bot may call itself + only map[string]bool // those of them for the bot alone, which a press may call + cmds map[string]bool // its direct commands' names, which a key may run; set before it runs + buttons bool // the network shows a post's buttons and keyboard busy chan struct{} // a place for each direct call in flight now func() time.Time host feature.Host // where it posts and reacts; set before it runs @@ -321,7 +325,7 @@ func newAddon(server, title string, cfg addonConfig, secret []byte, c conn, bot busy: make(chan struct{}, maxDirect), now: time.Now, changed: func() {}, dirty: make(chan struct{}, 1), up: make(chan struct{}, 1), settled: make(chan struct{}, 1), matches: make(chan match, maxMatches), posts: newLimiter(cfg.Rate), calls: newLimiter(watchRate), asks: hourly(cfg.Model), - refs: map[string]ref{}, names: map[string]seen{}, watches: map[string][]*watch{}, claims: map[claimKey]claim{}, + only: map[string]bool{}, cmds: map[string]bool{}, refs: map[string]ref{}, names: map[string]seen{}, watches: map[string][]*watch{}, claims: map[claimKey]claim{}, leases: map[string]lease{}, tombs: map[string]time.Time{}, done: map[string]bool{}, sending: map[string]bool{}, failed: map[string]failure{}, waiting: map[string][]*outgoing{}, posted: map[string]posted{}} } @@ -373,7 +377,7 @@ func (a *addon) context(m feature.Message, at time.Time) ext.Context { delete(a.names, k) } } - a.refs[id] = ref{feature.Message{Chat: m.Chat, Sender: m.Sender, Timestamp: m.Timestamp, Edited: m.Edited}, now.Add(refLife)} + a.refs[id] = ref{feature.Message{Chat: m.Chat, Sender: m.Sender, Timestamp: m.Timestamp, Edited: m.Edited, Bot: m.Bot}, now.Add(refLife)} if m.Name != "" { a.names[m.Chat.Key()+"\x00"+user] = seen{m.Name, now.Add(nameLife)} } diff --git a/internal/features/mcp/addon_test.go b/internal/features/mcp/addon_test.go index 695084d..fe77f01 100644 --- a/internal/features/mcp/addon_test.go +++ b/internal/features/mcp/addon_test.go @@ -290,7 +290,7 @@ func TestAddonLoad(t *testing.T) { `{"mcpServers":{"model":{"command":"x","addon":{}}}}`: `: MCP server "model": an addon's settings start with MODEL_, as the bot's own MODEL_API_KEY does; rename the server`, `{"mcpServers":{"Daily":{"command":"x","addon":{}}}}`: `: MCP server "Daily": an addon's settings start with DAILY_, as the bot's own DAILY_BUDGET does; rename the server`, `{"mcpServers":{"geo":{"command":"x","chat_commands":{"geo":{"tool":"geo","direct":true}}}}}`: `: MCP server "geo": chat command "geo" is direct, which needs an addon block`, - `{"mcpServers":{"geo":{"command":"x","addon":{"chat":["all"]}}}}`: `: MCP server "geo": addon: unknown setting "chat" (settings are chats, dms, post, react, watch, watch_max, names, global_ids, rate, model)`, + `{"mcpServers":{"geo":{"command":"x","addon":{"chat":["all"]}}}}`: `: MCP server "geo": addon: unknown setting "chat" (settings are chats, dms, post, react, watch, watch_max, names, global_ids, rate, model, announce)`, `{"mcpServers":{"geo":{"command":"x","addon":{"rate":{"perMinute":1}}}}}`: `: MCP server "geo": addon rate: unknown setting "perMinute" (settings are per_minute, burst)`, `{"mcpServers":{"geo":{"command":"x","addon":{"chats":["Family"]}}}}`: `: MCP server "geo": addon chats: "Family" isn't a group ID; copy the group's ID as Signal or Telegram shows it, or use "all"`, `{"mcpServers":{"geo":{"command":"x","addon":{"chats":["all","` + groupA + `"]}}}}`: `: MCP server "geo": addon chats: "all" goes alone`, diff --git a/internal/features/mcp/buttons.go b/internal/features/mcp/buttons.go new file mode 100644 index 0000000..972e6bf --- /dev/null +++ b/internal/features/mcp/buttons.go @@ -0,0 +1,229 @@ +package mcp + +import ( + "context" + "encoding/json" + "slices" + "strings" + "time" + "unicode/utf8" + + ext "github.com/robdevops/signalbot/addon" + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/logx" + "github.com/robdevops/signalbot/internal/kit/txt" +) + +// A post's markup's limits, as addon/schema.json says: rows of buttons or +// keys, and keys or buttons in a row; a label's size in characters, a +// button's data's in bytes (Telegram's), and a key's command's in +// characters. +const ( + maxRows = 5 + maxPerRow = 5 + maxLabel = 32 + maxData = 64 + maxCommand = 256 +) + +// markup is what o carries besides its content, checked, or why it can't +// be posted. Buttons and a keyboard are left off where the network shows +// none, as is a keyboard in a group, by the network. +func (a *addon) markup(o ext.Op) (feature.Markup, string) { + mk := feature.Markup{Silent: o.Silent, NoKeyboard: o.RemoveKeyboard} + buttons, keys := len(o.Buttons) > 0, len(o.Keyboard) > 0 + switch { + case buttons != (o.OnPress != ""): + return mk, "buttons without onPress, or onPress without buttons" + case buttons && !a.only[o.OnPress]: + return mk, "an onPress that isn't one of its tools for the bot alone" + case (buttons || keys || o.RemoveKeyboard) && len(o.Images) > 1: + return mk, "buttons or a keyboard and more than one image" + case buttons && (keys || o.RemoveKeyboard), keys && o.RemoveKeyboard: + return mk, "buttons and a keyboard, or a keyboard and removeKeyboard" + case !grid(len(o.Buttons), func(i int) int { return len(o.Buttons[i]) }) || !grid(len(o.Keyboard), func(i int) int { return len(o.Keyboard[i]) }): + return mk, "more than 5 rows of 5 buttons or keys, or an empty row" + } + for _, row := range o.Buttons { + var r []feature.Button + for _, b := range row { + if !label(b.Label) || b.Data == "" || len(b.Data) > maxData { + return mk, "a button's label or data empty or too long" + } + r = append(r, feature.Button{Label: b.Label, Data: b.Data}) + } + mk.Buttons = append(mk.Buttons, r) + } + var labels []string + for _, row := range o.Keyboard { + var r []feature.Key + for _, k := range row { + if !label(k.Label) || slices.Contains(labels, k.Label) || !strings.HasPrefix(k.Command, "/") || + utf8.RuneCountInString(k.Command) > maxCommand || strings.ContainsAny(k.Command, "\r\n") { + return mk, "a key's label empty, too long or twice, or its command not a command" + } + if !a.cmds[strings.ToLower(strings.TrimPrefix(strings.Fields(k.Command)[0], "/"))] { + return mk, "a key's command not one of its commands" + } + labels = append(labels, k.Label) + r = append(r, feature.Key{Label: k.Label, Command: k.Command}) + } + mk.Keyboard = append(mk.Keyboard, r) + } + if !a.buttons { + mk.Buttons, mk.Keyboard, mk.NoKeyboard = nil, nil, false + } + return mk, "" +} + +// grid reports whether rows rows, of size(i) each, are at most maxRows of +// 1 to maxPerRow. +func grid(rows int, size func(i int) int) bool { + if rows > maxRows { + return false + } + for i := range rows { + if n := size(i); n == 0 || n > maxPerRow { + return false + } + } + return true +} + +// label reports whether s is a button's or key's label: 1 to maxLabel +// characters, with no space around them, as Telegram may trim a key's. +func label(s string) bool { + return s != "" && strings.TrimSpace(s) == s && utf8.RuneCountInString(s) <= maxLabel +} + +// edit replaces the text, image and buttons of the addon's post o.Post in +// o.Chat, if the addon may, as for a post: with the post permission, in a +// chat it has a lease in, within the rate. The post must be one it +// remembers sending there. One edited again, after it was dropped, isn't +// counted against the rate again. +func (a *addon) edit(o ext.Op, again bool) (why string) { + now := a.now() + a.mu.Lock() + p, known := a.posted[o.Post] + l, leased := a.leases[o.Chat] + a.mu.Unlock() + switch { + case !a.cfg.Post: + return "edits not allowed" + case o.Post == "" || len(o.Keyboard) > 0 || o.RemoveKeyboard || o.ReplyTo != "" || o.Audio != nil: + return "malformed edits" + case !known || p.Chat != o.Chat: + return "edits of an unknown post" + case a.uneditable(p, now) != "": + return a.uneditable(p, now) + case !leased || !l.live(now) || !a.allows(l.Chat): + return "for a chat without a lease" + case len(o.Images) > 1: + return "edits with more than one image" + } + mk, why := a.markup(o) + if why != "" { + return "edits with " + why + } + mk.Silent = false // an edit notifies no one + var b64 []string + for _, im := range o.Images { + b64 = append(b64, im.Data) + } + out := &outgoing{Post: feature.Post{Chat: l.Chat, Text: txt.Clamp(a.fill(l.Chat, strings.TrimSpace(o.Text)), maxAnswer), Pictures: a.pictures(b64), Markup: mk, Edit: p.last()}, + ops: []string{o.ID}, edits: o.Post, onPress: o.OnPress} + if len(mk.Buttons) == 0 { + out.onPress = "" + } + switch { + case out.Text == "" && len(out.Pictures) == 0: + return "empty edits" + case !again && !a.posts.allow(l.Chat.Key(), now): + return "edits over the rate limit" + } + a.send(o.Chat, out) + return "" +} + +// pressTimeout is how long a press's call may take, while the button +// spins; tests shorten it. maxToast caps the answer shown, in characters. +var pressTimeout = 10 * time.Second + +const maxToast = 200 + +// press calls the onPress tool of the addon's post whose buttons p was +// pressed under, with the button's data, the post op's ID and the +// presser's context, and returns the result's text, shown to the presser; +// ok is false if the post isn't one of the addon's it remembers. The press +// leases the chat, so the addon can answer it, such as by editing the +// post, however old the post is. Only the call's outcome, time and size +// are logged. +func (a *addon) press(ctx context.Context, p feature.Press) (answer string, ok bool) { + if !a.allows(p.Chat) || p.By.ID == "" || p.Sent == 0 { + return "", false + } + chat, now := a.chatID(p.Chat), a.now() + bare := p.Chat.GroupID != "" && !strings.Contains(p.Chat.GroupID, "/") + op, tool := "", "" + a.mu.Lock() + for id, x := range a.posted { + if x.OnPress == "" || x.last() != p.Sent || !now.Before(x.Expires) { + continue + } + if x.Chat == chat { + op, tool = id, x.OnPress + break + } + if bare && x.Topic != nil && strings.HasPrefix(x.Topic.GroupID, p.Chat.GroupID+"/") { // under an old message, which names no topic + op, tool, p.Chat = id, x.OnPress, *x.Topic + break + } + } + a.mu.Unlock() + switch { + case op == "" || !a.allows(p.Chat): + return "", false + case !a.only[tool]: + logx.Warnf("MCP server %s: a press refused: its tool isn't one for the bot alone", a.server) + return "", true + } + select { + case a.busy <- struct{}{}: + defer func() { <-a.busy }() + default: + logx.Warnf("MCP server %s: a press refused: %d calls already in flight", a.server, maxDirect) + return a.title + " is busy, try again in a moment.", true + } + a.lease(p.Chat, false) + ctx, cancel := context.WithTimeout(ctx, pressTimeout) + defer cancel() + start := time.Now() + cc := a.context(feature.Message{Chat: p.Chat, Sender: p.By.ID, Name: p.By.Name, Timestamp: p.Sent, Bot: true, Addressed: true}, now) + cc.Deadline = start.Add(pressTimeout).Unix() + res, err := a.conn.call(ctx, "tools/call", map[string]any{ + "name": tool, + "arguments": ext.Press{Press: p.Data, Post: op}, + "_meta": map[string]any{ext.KeyContext: cc}, + }) + var r toolResult + outcome := "ok" + switch { + case err != nil: + outcome = errCode(err) + case json.Unmarshal(res, &r) != nil: + outcome = "a malformed result" + case r.IsError: + outcome = "an error result" + } + logx.Infof("MCP server %s: a press called %s: %s in %dms, %d bytes", a.server, tool, outcome, time.Since(start).Milliseconds(), len(res)) + if outcome != "ok" { + return a.title + " couldn't do that just now.", true + } + var parts []string + for _, c := range r.Content { + if c.Type == "text" { + parts = append(parts, c.Text) + } + } + return txt.Clamp(a.fill(p.Chat, strings.TrimSpace(strings.Join(parts, "\n"))), maxToast-1), true +} diff --git a/internal/features/mcp/buttons_test.go b/internal/features/mcp/buttons_test.go new file mode 100644 index 0000000..08e7d17 --- /dev/null +++ b/internal/features/mcp/buttons_test.go @@ -0,0 +1,553 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + ext "github.com/robdevops/signalbot/addon" + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/feature/featuretest" +) + +// buttonsAddon is a unit addon on a network that shows buttons, whose +// tool "period" is for the bot alone and whose direct command is /rain, +// posting to h. +func buttonsAddon(cfg addonConfig) (*addon, *time.Time, *featuretest.Host) { + a, now := unitAddon(cfg) + a.only["period"], a.bot["period"], a.buttons, a.cmds["rain"] = true, true, true, true + h := featuretest.New() + a.host = h + return a, now, h +} + +var rainButtons = [][]ext.Button{{{Label: "24h", Data: "rain 24h"}, {Label: "7d", Data: "rain 7d"}}} + +// With announce, a lease a direct command made never expires, even when a +// watch's lease renews it, and is saved so; it stays within chats. Without +// announce, or once announce is taken away, a lease lasts leaseLife. +func TestAnnounce(t *testing.T) { + cfg := everything + cfg.Announce = true + a, now, _ := buttonsAddon(cfg) + a.lease(inA, true) + a.lease(inB, false) + a.lease(inA, false) // as a watch renews it + *now = now.Add(30 * 24 * time.Hour) + post := func(a *addon, id string, chat feature.Chat) string { + return a.apply(ext.Op{ID: id, Op: "post", Chat: a.chatID(chat), Text: "Rain soon"}) + } + if why := post(a, "1", inA); why != "" { + t.Fatalf("a month on: %q", why) + } + if why := post(a, "2", inB); why != "for a chat without a lease" { + t.Fatalf("a chat a watch leased: %q", why) + } + s := a.state() + if l, ok := s.Leases[a.chatID(inA)]; !ok || !l.Forever { + t.Fatalf("saved %+v", s.Leases) + } + again, later, _ := buttonsAddon(cfg) + *later = *now + again.restore(s) + if why := post(again, "3", inA); why != "" { + t.Fatalf("after a restart: %q", why) + } + cfg.Chats = []string{groupB} + outside, later, _ := buttonsAddon(cfg) + *later = *now + outside.restore(s) + if why := post(outside, "4", inA); why != "for a chat without a lease" { + t.Fatalf("outside chats: %q", why) + } + cfg = everything // announce taken away + off, later, _ := buttonsAddon(cfg) + *later = *now + off.restore(s) + if why := post(off, "5", inA); why != "for a chat without a lease" { + t.Fatalf("without announce: %q", why) + } + off.lease(inB, true) + if l := off.leases[off.chatID(inB)]; l.Forever { + t.Fatal("a lease for good without announce") + } +} + +// A post's markup goes to the host as checked: silent, buttons with a +// tool for the bot alone, a keyboard; one that breaks the limits is +// dropped, saying why. A network without buttons gets the post without +// them. +func TestOutboxMarkup(t *testing.T) { + a, now, h := buttonsAddon(everything) + a.cfg.Rate = rateConfig{60, 60} + a.posts = newLimiter(a.cfg.Rate) + a.lease(inA, false) + id := a.chatID(inA) + op := func(o ext.Op) string { + o.Op, o.Chat = "post", id + if o.Text == "" { + o.Text = "Rain" + } + return a.apply(o) + } + keys := [][]ext.Key{{{Label: "🌧 Rain", Command: "/RAIN 7d"}}} + // Each sent before the next: sent in two messages, a post's buttons + // are on the last, for 30 days. + for i, o := range []ext.Op{ + {ID: "s", Silent: true}, + {ID: "b", Buttons: rainButtons, OnPress: "period"}, + {ID: "k", Keyboard: keys}, + {ID: "r", RemoveKeyboard: true}, + } { + if why := op(o); why != "" { + t.Fatalf("%s: %q", o.ID, why) + } + h.Posts()[i].OnSent([]int64{int64(100 + 2*i), int64(101 + 2*i)}, false) + } + posts := h.Posts() + if len(posts) != 4 || !posts[0].Markup.Silent || len(posts[1].Markup.Buttons) != 1 || posts[1].Markup.Buttons[0][1] != (feature.Button{Label: "7d", Data: "rain 7d"}) || + posts[2].Markup.Keyboard[0][0] != (feature.Key{Label: "🌧 Rain", Command: "/RAIN 7d"}) || !posts[3].Markup.NoKeyboard { + t.Fatalf("posts %+v", posts) + } + if p := a.posted["b"]; p.Sent != 102 || p.Last != 103 || p.OnPress != "period" || !p.Expires.Equal(now.Add(buttonsLife)) { + t.Fatalf("remembered %+v", p) + } + if p := a.posted["s"]; p.OnPress != "" || !p.Expires.Equal(now.Add(postedLife)) { + t.Fatalf("remembered %+v", p) + } + + two := []ext.Image{{Data: tinyPNG(), MimeType: "image/png"}, {Data: tinyPNG(), MimeType: "image/png"}} + for _, c := range []struct { + o ext.Op + why string + }{ + {ext.Op{ID: "1", Buttons: rainButtons}, "posts with buttons without onPress, or onPress without buttons"}, + {ext.Op{ID: "2", OnPress: "period"}, "posts with buttons without onPress, or onPress without buttons"}, + {ext.Op{ID: "3", Buttons: rainButtons, OnPress: "guess"}, "posts with an onPress that isn't one of its tools for the bot alone"}, + {ext.Op{ID: "4", Buttons: rainButtons, OnPress: "period", Images: two}, "posts with buttons or a keyboard and more than one image"}, + {ext.Op{ID: "4k", Keyboard: keys, Images: two}, "posts with buttons or a keyboard and more than one image"}, + {ext.Op{ID: "4r", RemoveKeyboard: true, Images: two}, "posts with buttons or a keyboard and more than one image"}, + {ext.Op{ID: "5", Buttons: rainButtons, OnPress: "period", Keyboard: keys}, "posts with buttons and a keyboard, or a keyboard and removeKeyboard"}, + {ext.Op{ID: "6", Keyboard: keys, RemoveKeyboard: true}, "posts with buttons and a keyboard, or a keyboard and removeKeyboard"}, + {ext.Op{ID: "7", Buttons: slices.Repeat(rainButtons, 6), OnPress: "period"}, "posts with more than 5 rows of 5 buttons or keys, or an empty row"}, + {ext.Op{ID: "8", Buttons: [][]ext.Button{slices.Repeat(rainButtons[0], 3)}, OnPress: "period"}, "posts with more than 5 rows of 5 buttons or keys, or an empty row"}, + {ext.Op{ID: "9", Buttons: [][]ext.Button{{}}, OnPress: "period"}, "posts with more than 5 rows of 5 buttons or keys, or an empty row"}, + {ext.Op{ID: "10", Buttons: [][]ext.Button{{{Label: strings.Repeat("Γ©", 33), Data: "x"}}}, OnPress: "period"}, "posts with a button's label or data empty or too long"}, + {ext.Op{ID: "11", Buttons: [][]ext.Button{{{Label: "x", Data: strings.Repeat("Γ©", 33)}}}, OnPress: "period"}, "posts with a button's label or data empty or too long"}, + {ext.Op{ID: "12", Buttons: [][]ext.Button{{{Label: " ", Data: "x"}}}, OnPress: "period"}, "posts with a button's label or data empty or too long"}, + {ext.Op{ID: "13", Keyboard: [][]ext.Key{{{Label: "Rain", Command: "rain"}}}}, "posts with a key's label empty, too long or twice, or its command not a command"}, + {ext.Op{ID: "14", Keyboard: [][]ext.Key{{{Label: "Rain", Command: "/rain"}, {Label: "Rain", Command: "/rain 7d"}}}}, "posts with a key's label empty, too long or twice, or its command not a command"}, + {ext.Op{ID: "15", Keyboard: [][]ext.Key{{{Label: "Rain", Command: "/rain\n/status"}}}}, "posts with a key's label empty, too long or twice, or its command not a command"}, + {ext.Op{ID: "16", Keyboard: [][]ext.Key{{{Label: "Rain ", Command: "/rain"}}}}, "posts with a key's label empty, too long or twice, or its command not a command"}, + {ext.Op{ID: "17", Keyboard: [][]ext.Key{{{Label: "Forget", Command: "/forget"}}}}, "posts with a key's command not one of its commands"}, + {ext.Op{ID: "18", Keyboard: [][]ext.Key{{{Label: "Rain", Command: "/rainfall"}}}}, "posts with a key's command not one of its commands"}, + } { + if why := op(c.o); why != c.why { + t.Errorf("%s: %q, want %q", c.o.ID, why, c.why) + } + } + if n := len(h.Posts()); n != 4 { + t.Fatalf("%d posts", n) + } + + // Signal: the buttons left off, and the post remembered as a plain one. + a.buttons = false + if why := op(ext.Op{ID: "plain", Buttons: rainButtons, OnPress: "period", Keyboard: nil}); why != "" { + t.Fatal(why) + } + p := h.Posts()[4] + if len(p.Markup.Buttons) != 0 { + t.Fatalf("buttons on Signal %+v", p.Markup) + } + p.OnSent([]int64{200}, false) + if a.posted["plain"].OnPress != "" { + t.Fatalf("remembered %+v", a.posted["plain"]) + } +} + +// A post with markup is a message of its own, never merged, but silent +// posts merge with each other. +func TestOutboxMarkupNotMerged(t *testing.T) { + text := func(s string, mk feature.Markup) *outgoing { + return &outgoing{Post: feature.Post{Text: s, Markup: mk}} + } + silent := feature.Markup{Silent: true} + buttons := feature.Markup{Buttons: [][]feature.Button{{{Label: "a", Data: "a"}}}} + for _, c := range []struct { + a, b *outgoing + fits bool + }{ + {text("a", silent), text("b", silent), true}, + {text("a", silent), text("b", feature.Markup{}), false}, + {text("a", buttons), text("b", feature.Markup{}), false}, + {text("a", feature.Markup{}), text("b", feature.Markup{Keyboard: [][]feature.Key{{{Label: "a", Command: "/a"}}}}), false}, + {text("a", feature.Markup{}), text("b", feature.Markup{NoKeyboard: true}), false}, + {text("a", feature.Markup{}), &outgoing{Post: feature.Post{Text: "b", Edit: 100}}, false}, + } { + if got := c.a.fits(c.b); got != c.fits { + t.Errorf("%+v and %+v: fits %v", c.a.Markup, c.b.Markup, got) + } + } +} + +// An edit names an earlier post in its chat, and replaces its text, image +// and buttons, as a post: with the post permission, a lease and within the +// rate. Sent anew, as on Signal with an image, the post is the new message +// from then on; its buttons are remembered for 30 days from the edit. +func TestOutboxEdit(t *testing.T) { + cfg := everything + cfg.Rate = rateConfig{1, 4} + a, now, h := buttonsAddon(cfg) + *now = now.Add(time.Hour) + a.lease(inA, false) + a.lease(inB, false) + idA, idB := a.chatID(inA), a.chatID(inB) + if why := a.apply(ext.Op{ID: "q", Op: "post", Chat: idA, Text: "Rain, 24 hours"}); why != "" { + t.Fatal(why) + } + h.Posts()[0].OnSent([]int64{100}, false) + edit := func(id, chat, post string, more func(*ext.Op)) string { + o := ext.Op{ID: id, Op: "edit", Chat: chat, Post: post, Text: "Rain, 7 days {u_" + strings.Repeat("a", 26) + "}", Buttons: rainButtons, OnPress: "period"} + if more != nil { + more(&o) + } + return a.apply(o) + } + if why := edit("e1", idA, "q", nil); why != "" { + t.Fatal(why) + } + e := h.Posts()[1] + if e.Edit != 100 || e.Chat != inA || e.Text != "Rain, 7 days someone" || len(e.Markup.Buttons) != 1 || e.Label != "" { + t.Fatalf("edit %+v", e) + } + e.OnSent([]int64{100}, false) + if p := a.posted["q"]; p.Sent != 100 || p.last() != 100 || p.OnPress != "period" || !p.Expires.Equal(now.Add(buttonsLife)) { + t.Fatalf("remembered %+v", p) + } + if !a.done["e1"] { + t.Fatal("the edit isn't applied") + } + // Sent anew: the post is the new message from then on. + if why := edit("e2", idA, "q", func(o *ext.Op) { o.Images = []ext.Image{{Data: tinyPNG(), MimeType: "image/png"}} }); why != "" { + t.Fatal(why) + } + h.Posts()[2].OnSent([]int64{300}, false) + if p := a.posted["q"]; p.Sent != 300 || p.last() != 300 { + t.Fatalf("remembered %+v", p) + } + for _, c := range []struct { + id, chat, post string + more func(*ext.Op) + why string + }{ + {"x1", idA, "nope", nil, "edits of an unknown post"}, + {"x2", idB, "q", nil, "edits of an unknown post"}, + {"x3", idA, "q", func(o *ext.Op) { + o.Images = slices.Repeat([]ext.Image{{Data: tinyPNG(), MimeType: "image/png"}}, 2) + }, "edits with more than one image"}, + {"x4", idA, "q", func(o *ext.Op) { o.Text = " " }, "empty edits"}, + {"x5", idA, "q", func(o *ext.Op) { o.OnPress = "guess" }, "edits with an onPress that isn't one of its tools for the bot alone"}, + {"x6", idA, "q", func(o *ext.Op) { o.Keyboard = [][]ext.Key{{{Label: "a", Command: "/a"}}} }, "malformed edits"}, + {"x7", idA, "", nil, "malformed edits"}, + } { + if why := edit(c.id, c.chat, c.post, c.more); why != c.why { + t.Errorf("%s: %q, want %q", c.id, why, c.why) + } + } + // Within the rate: the post and two edits took three of four. + if why := edit("e3", idA, "q", nil); why != "" { + t.Fatal(why) + } + h.Posts()[3].OnSent(nil, false) // refused by the network: the post is as it was + if why := edit("e4", idA, "q", nil); why != "edits over the rate limit" { + t.Fatalf("past the rate: %q", why) + } + if p := a.posted["q"]; p.Sent != 300 { + t.Fatalf("after a refused edit %+v", p) + } + // Without a lease, or the post permission. + delete(a.leases, idA) + if why := edit("e5", idA, "q", nil); why != "for a chat without a lease" { + t.Fatalf("without a lease: %q", why) + } + a.cfg.Post = false + if why := edit("e6", idA, "q", nil); why != "edits not allowed" { + t.Fatalf("without post: %q", why) + } +} + +// An edit queued behind another edits the post as the one before left it. +func TestOutboxEditsInTurn(t *testing.T) { + a, _, h := buttonsAddon(everything) + a.lease(inA, false) + id := a.chatID(inA) + a.apply(ext.Op{ID: "q", Op: "post", Chat: id, Text: "Rain"}) + h.Posts()[0].OnSent([]int64{100}, false) + img := []ext.Image{{Data: tinyPNG(), MimeType: "image/png"}} + a.apply(ext.Op{ID: "e1", Op: "edit", Chat: id, Post: "q", Images: img}) + a.apply(ext.Op{ID: "e2", Op: "edit", Chat: id, Post: "q", Text: "Rain, 7 days"}) + if n := len(h.Posts()); n != 2 { + t.Fatalf("%d posts before the first edit was sent", n) + } + h.Posts()[1].OnSent([]int64{200}, false) // sent anew + if p := h.Posts(); len(p) != 3 || p[2].Edit != 200 { + t.Fatalf("posts %+v", p) + } +} + +// pressConn is an addon whose tools answer "7 days", or fail with fail +// set, recording each call's params. +type pressConn struct { + mu sync.Mutex + calls []map[string]any + fail bool +} + +func (c *pressConn) call(_ context.Context, _ string, params any) (json.RawMessage, error) { + c.mu.Lock() + defer c.mu.Unlock() + data, _ := json.Marshal(params) + var p map[string]any + json.Unmarshal(data, &p) + c.calls = append(c.calls, p) + if c.fail { + return nil, errors.New("down") + } + return json.RawMessage(`{"content":[{"type":"text","text":"7 days"}]}`), nil +} + +func (c *pressConn) notify(context.Context, string, any) error { return nil } + +// A press of a button under one of the addon's posts calls its onPress +// tool with the button's data and the post's ID, and the presser's +// context, whose ref is the post, and answers with the result's text. It +// needs no watch, and leases the chat, so the addon can edit the post +// however old; a post's buttons are known for 30 days. A press under +// another message isn't the addon's. +func TestPress(t *testing.T) { + cfg := everything + cfg.Names = true + a, now, h := buttonsAddon(cfg) + c := &pressConn{} + a.conn = c + a.lease(inA, false) + id := a.chatID(inA) + a.apply(ext.Op{ID: "q", Op: "post", Chat: id, Text: "Rain", Buttons: rainButtons, OnPress: "period"}) + h.Posts()[0].OnSent([]int64{101}, false) + *now = now.Add(29 * 24 * time.Hour) // the lease is long gone + alice := feature.Person{ID: "alice-id", Name: "Alice"} + ctx := context.Background() + answer, ok := a.press(ctx, feature.Press{Chat: inA, By: alice, Sent: 101, Data: "rain 7d"}) + if !ok || answer != "7 days" { + t.Fatalf("answered %q, %v", answer, ok) + } + call := c.calls[0] + cc := call["_meta"].(map[string]any)[ext.KeyContext].(map[string]any) + if call["name"] != "period" || call["arguments"].(map[string]any)["press"] != "rain 7d" || call["arguments"].(map[string]any)["post"] != "q" || + cc["chat"] != id || cc["sender"] != a.userID(inA, "alice-id") || cc["name"] != "Alice" || cc["deadline"] == nil { + t.Fatalf("call %+v", call) + } + if r := a.refs[cc["ref"].(string)]; !r.msg.Bot || r.msg.Timestamp != 101 || r.msg.Chat != inA { + t.Fatalf("its ref %+v", r) + } + // The press leased the chat: an edit follows. + if why := a.apply(ext.Op{ID: "e", Op: "edit", Chat: id, Post: "q", Text: "Rain, 7 days", Buttons: rainButtons, OnPress: "period"}); why != "" { + t.Fatal(why) + } + for _, p := range []feature.Press{ + {Chat: inA, By: alice, Sent: 100, Data: "rain 7d"}, // not the message with the buttons + {Chat: inB, By: alice, Sent: 101, Data: "rain 7d"}, // another chat + {Chat: feature.Chat{GroupID: "-100999"}, By: alice, Sent: 101, Data: "x"}, // nor one the addon is in + {Chat: inA, By: feature.Person{}, Sent: 101, Data: "rain 7d"}, // no one + {Chat: inA, By: alice, Sent: 0, Data: "rain 7d"}, // no message + {Chat: inA, By: alice, Sent: 102, Data: "rain 7d"}, // another + } { + if _, ok := a.press(ctx, p); ok { + t.Errorf("%+v taken", p) + } + } + c.fail = true + if answer, ok := a.press(ctx, feature.Press{Chat: inA, By: alice, Sent: 101, Data: "rain 7d"}); !ok || answer != "Game couldn't do that just now." { + t.Fatalf("a failed call answered %q, %v", answer, ok) + } + c.fail = false + // A tool no longer for the bot alone is refused, without a call. + a.only["period"] = false + if answer, ok := a.press(ctx, feature.Press{Chat: inA, By: alice, Sent: 101, Data: "rain 7d"}); !ok || answer != "" || len(c.calls) != 2 { + t.Fatalf("refused: %q, %v, %d calls", answer, ok, len(c.calls)) + } + a.only["period"] = true + *now = now.Add(31 * 24 * time.Hour) + if _, ok := a.press(ctx, feature.Press{Chat: inA, By: alice, Sent: 101, Data: "rain 7d"}); ok { + t.Fatal("a press under a post too old to be known") + } +} + +// Posts with buttons are known for 30 days, the newest 1,000; others for a +// day, the newest 256; both are saved, and restored. +func TestPostedKept(t *testing.T) { + a, now, _ := buttonsAddon(everything) + for i := range maxButtons + 10 { + *now = now.Add(time.Second) + a.rememberPosted(inA, []string{"b" + strings.Repeat("x", i%3) + string(rune('a'+i%26)) + time.Duration(i).String()}, []int64{int64(i + 1)}, "period") + } + for i := range maxPosted + 10 { + *now = now.Add(time.Second) + a.rememberPosted(inA, []string{"p" + time.Duration(i).String()}, []int64{int64(10000 + i)}, "") + } + plain, buttoned := 0, 0 + for _, p := range a.posted { + if p.OnPress != "" { + buttoned++ + if p.Sent <= 10 { + t.Fatalf("an old post kept: %+v", p) + } + } else { + plain++ + } + } + if plain != maxPosted || buttoned != maxButtons { + t.Fatalf("%d plain, %d with buttons", plain, buttoned) + } + s := a.state() + b, later, _ := buttonsAddon(everything) + *later = now.Add(2 * 24 * time.Hour) // the plain ones gone + b.restore(s) + if len(b.posted) != maxButtons { + t.Fatalf("restored %d", len(b.posted)) + } + for k, p := range b.posted { + if q := a.posted[k]; p != q { + t.Fatalf("restored %+v, saved %+v", p, q) + } + } +} + +// initialConn records initialize's params. +type initialConn struct{ params any } + +func (c *initialConn) call(_ context.Context, method string, params any) (json.RawMessage, error) { + if method == "initialize" { + c.params = params + } + return json.RawMessage(`{}`), nil +} + +func (c *initialConn) notify(context.Context, string, any) error { return nil } + +// The bot offers an addon buttons only on a network that shows them. +func TestInitializeButtons(t *testing.T) { + for _, c := range []struct { + self botInfo + want bool + }{ + {botInfo{network: "telegram", addon: true, buttons: true}, true}, + {botInfo{network: "signal", addon: true}, false}, + {botInfo{network: "telegram", buttons: true}, false}, // not an addon + } { + conn := &initialConn{} + if _, err := initialize(context.Background(), conn, c.self); err != nil { + t.Fatal(err) + } + capability := conn.params.(map[string]any)["capabilities"].(map[string]any)["experimental"].(map[string]any)[ext.KeyAddon].(ext.Capability) + if capability.Buttons != c.want { + t.Errorf("%+v: buttons %v", c.self, capability.Buttons) + } + } +} + +// An edit of a post merged with others, or sent in several messages, is +// refused; on a network without buttons (Signal), an edit in place keeps +// the post's first day, and only 10 are made. +func TestOutboxEditRefused(t *testing.T) { + cfg := everything + cfg.Rate = rateConfig{60, 60} + a, now, h := buttonsAddon(cfg) + a.lease(inA, false) + id := a.chatID(inA) + a.rememberPosted(inA, []string{"m1", "m2"}, []int64{100}, "") + a.rememberPosted(inA, []string{"long"}, []int64{200, 201}, "") + edit := func(n int, post string) string { + return a.apply(ext.Op{ID: "e" + strconv.Itoa(n), Op: "edit", Chat: id, Post: post, Text: "Rain"}) + } + if why := edit(1, "m1"); why != "edits of a post merged with others" { + t.Fatalf("merged: %q", why) + } + if why := edit(2, "long"); why != "edits of a post sent in several messages" { + t.Fatalf("several: %q", why) + } + + a.buttons = false + a.rememberPosted(inA, []string{"s"}, []int64{300}, "") + first := a.posted["s"].Expires + for i := range maxSignalEdits { + *now = now.Add(time.Minute) + if why := edit(10+i, "s"); why != "" { + t.Fatalf("edit %d: %q", i, why) + } + h.Posts()[len(h.Posts())-1].OnSent([]int64{300}, false) + } + if p := a.posted["s"]; !p.Expires.Equal(first) || p.Edits != maxSignalEdits { + t.Fatalf("remembered %+v", p) + } + if why := edit(30, "s"); why != "edits past the network's limit" { + t.Fatalf("an 11th edit: %q", why) + } + *now = first + if why := edit(31, "s"); why != "edits of an unknown post" { + t.Fatalf("past a day: %q", why) + } +} + +// A press under an old message in a forum topic, which names only the +// group, finds the post by its message, and acts in the topic. +func TestPressTopic(t *testing.T) { + a, now, h := buttonsAddon(everything) + c := &pressConn{} + a.conn = c + topic := feature.Chat{GroupID: telegram + "/7"} + a.lease(topic, false) + a.apply(ext.Op{ID: "q", Op: "post", Chat: a.chatID(topic), Text: "Rain", Buttons: rainButtons, OnPress: "period"}) + h.Posts()[0].OnSent([]int64{101}, false) + if p := a.posted["q"]; p.Topic == nil || *p.Topic != topic { + t.Fatalf("remembered %+v", p) + } + *now = now.Add(10 * 24 * time.Hour) + alice := feature.Person{ID: "alice-id", Name: "Alice"} + bare := feature.Chat{GroupID: telegram} + if answer, ok := a.press(context.Background(), feature.Press{Chat: bare, By: alice, Sent: 101, Data: "rain 7d"}); !ok || answer != "7 days" { + t.Fatalf("answered %q, %v", answer, ok) + } + cc := c.calls[0]["_meta"].(map[string]any)[ext.KeyContext].(map[string]any) + if cc["chat"] != a.chatID(topic) { + t.Fatalf("context %+v", cc) + } + if why := a.apply(ext.Op{ID: "e", Op: "edit", Chat: a.chatID(topic), Post: "q", Text: "Rain, 7 days"}); why != "" { + t.Fatalf("the edit after: %q", why) + } + for _, p := range []feature.Press{ + {Chat: feature.Chat{GroupID: "-100999"}, By: alice, Sent: 101, Data: "x"}, // another group + {Chat: bare, By: alice, Sent: 102, Data: "x"}, // another message + } { + if _, ok := a.press(context.Background(), p); ok { + t.Errorf("%+v taken", p) + } + } +} + +// The addon's direct commands, as registered, are the ones a key may run. +func TestKeyCommands(t *testing.T) { + a, _, h := buttonsAddon(everything) + a.cmds = map[string]bool{} + command(h, "game", "/Rain", chatCommand{Tool: "period", Direct: true}, nil, a) + command(h, "game", "ask", chatCommand{Tool: "period"}, map[string]string{"period": "game_period"}, a) + if !a.cmds["rain"] || a.cmds["ask"] || len(a.cmds) != 1 { + t.Fatalf("commands %v", a.cmds) + } +} diff --git a/internal/features/mcp/direct.go b/internal/features/mcp/direct.go index fa441c9..0e9737a 100644 --- a/internal/features/mcp/direct.go +++ b/internal/features/mcp/direct.go @@ -56,7 +56,7 @@ func (a *addon) direct(ctx context.Context, m feature.Message, name string, c ch logx.Warnf("MCP server %s: /%s refused: %d calls already in flight", a.server, name, maxDirect) return feature.Action{Answer: a.title + " is busy, try again in a moment."} } - a.lease(m.Chat) + a.lease(m.Chat, true) timeout := cmp.Or(c.timeout, directTimeout) ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() diff --git a/internal/features/mcp/keep.go b/internal/features/mcp/keep.go index 0beebe0..86dc69d 100644 --- a/internal/features/mcp/keep.go +++ b/internal/features/mcp/keep.go @@ -121,7 +121,7 @@ func (a *addon) state() addonState { s.Claims = append(s.Claims, c) } for id, l := range a.leases { - if !now.Before(l.Expires) { + if !l.live(now) { delete(a.leases, id) continue } @@ -158,7 +158,8 @@ func (a *addon) restore(s addonState) { a.mu.Lock() defer a.mu.Unlock() for id, l := range s.Leases { - if now.Before(l.Expires) { + l.Forever = l.Forever && a.cfg.Announce // until announce is taken away + if l.live(now) { a.leases[id] = l } } diff --git a/internal/features/mcp/mcp.go b/internal/features/mcp/mcp.go index a87b3a0..d5229ee 100644 --- a/internal/features/mcp/mcp.go +++ b/internal/features/mcp/mcp.go @@ -145,6 +145,14 @@ func Register(h feature.Host) error { } return "" }) + h.OnPress(func(ctx context.Context, p feature.Press) (string, bool) { + for _, a := range k.addons { + if answer, ok := a.press(ctx, p); ok { + return answer, true + } + } + return "", false + }) h.Go(k.run) } return nil @@ -290,17 +298,19 @@ type handshake struct { type botInfo struct { version string // the bot's version, "dev" if unknown network string // the chat network, as Info names it, for addons + buttons bool // the network shows a post's buttons and keyboard, for addons addon bool // the server has an addon block: offer what addons get sample bool // the addon may ask the bot's model: offer sampling } // initialize performs the MCP handshake, as self, offering signalbot's -// extension with the chat network the bot is on, reply watches to an -// addon, and sampling to one that may ask the model, and returns what the +// extension with the chat network the bot is on, reply watches and, where +// the network shows them, buttons to an addon, and sampling to one that +// may ask the model, and returns what the // server said of itself. func initialize(ctx context.Context, c conn, self botInfo) (handshake, error) { caps := map[string]any{"experimental": map[string]any{ - ext.KeyAddon: ext.Capability{Version: ext.Version, Network: self.network, WatchReplies: self.addon, WatchReactions: self.addon}, + ext.KeyAddon: ext.Capability{Version: ext.Version, Network: self.network, WatchReplies: self.addon, WatchReactions: self.addon, Buttons: self.addon && self.buttons}, }} if self.sample { caps["sampling"] = map[string]any{} @@ -380,7 +390,7 @@ func modelName(server, tool string) string { // run addons as plain servers; each addon started joins it. func start(ctx context.Context, h feature.Host, path string, servers map[string]server, k *keeper) error { info := h.Info() - base := botInfo{version: cmp.Or(info.Version, "dev"), network: info.Network} + base := botInfo{version: cmp.Or(info.Version, "dev"), network: info.Network, buttons: info.Buttons} type owner struct{ server, tool string } taken := map[string]owner{} // the model's names for tools, and whose they are var cmds []string // for the startup line @@ -449,6 +459,10 @@ func start(ctx context.Context, h feature.Host, path string, servers map[string] } } a = newAddon(name, cmp.Or(hs.title, name), *cfg.Addon, k.doc.Secret, c, bot) + for _, t := range listed { + a.only[t.Name] = t.forBot() && !t.forModel() + } + a.buttons = info.Buttons a.host, a.changed, a.dirty = h, k.changed, c.(*stdioConn).updated a.restore(k.doc.Addons[name]) gt.open(a) @@ -615,6 +629,9 @@ func command(h feature.Host, server, n string, c chatCommand, models map[string] logx.Warnf("MCP server %s: chat command skipped: %v", server, err) return "" } + if c.Direct { + a.cmds[name] = true + } return "/" + name } diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index 30cb2a8..87d4d13 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -204,22 +204,23 @@ type failure struct { } // apply does what o asks, once, and returns why it was dropped, if it was. -// A post counts as applied only once it is sent. +// A post or an edit counts as applied only once it is sent. func (a *addon) apply(o ext.Op) (why string) { if o.ID == "" { return "without an id" } now := a.now() + mailed := o.Op == "post" || o.Op == "edit" a.mu.Lock() f, failed := a.failed[o.ID] again := a.done[o.ID] || a.sending[o.ID] switch { case again: - case o.Op == "post" && failed && now.Before(f.retry): + case mailed && failed && now.Before(f.retry): again, a.missed = true, true // not yet: a later read posts it case o.Op == "post" && a.waitsToPost(o.ReplyTo): again, a.missed = true, true // after the post it replies to - case o.Op != "post": + case !mailed: a.remember(o.ID) } a.mu.Unlock() @@ -227,8 +228,12 @@ func (a *addon) apply(o ext.Op) (why string) { return "" } switch o.Op { - case "post": - why = a.post(o, failed) + case "post", "edit": + if o.Op == "post" { + why = a.post(o, failed) + } else { + why = a.edit(o, failed) + } if why != "" { a.mu.Lock() a.remember(o.ID) @@ -282,7 +287,7 @@ func (a *addon) reactTo(o ext.Op, now time.Time) (feature.Message, string) { } msg = feature.Message{Chat: l.Chat, Timestamp: p.Sent, Bot: true} } - if l, leased := a.leases[a.chatID(msg.Chat)]; !leased || !now.Before(l.Expires) || !a.allows(msg.Chat) { + if l, leased := a.leases[a.chatID(msg.Chat)]; !leased || !l.live(now) || !a.allows(msg.Chat) { return msg, "for a chat without a lease" } return msg, "" @@ -305,15 +310,22 @@ func (a *addon) post(o ext.Op, again bool) (why string) { switch { case !a.cfg.Post: return "posts not allowed" - case !ok || !now.Before(l.Expires) || !a.allows(l.Chat): + case !ok || !l.live(now) || !a.allows(l.Chat): return "for a chat without a lease" } + mk, why := a.markup(o) + if why != "" { + return "posts with " + why + } var b64 []string for _, im := range o.Images { b64 = append(b64, im.Data) } - out := &outgoing{Post: feature.Post{Chat: l.Chat, Label: a.title, Text: txt.Clamp(a.fill(l.Chat, strings.TrimSpace(o.Text)), maxAnswer), Pictures: a.pictures(b64)}, - ops: []string{o.ID}, replyTo: o.ReplyTo} + out := &outgoing{Post: feature.Post{Chat: l.Chat, Label: a.title, Text: txt.Clamp(a.fill(l.Chat, strings.TrimSpace(o.Text)), maxAnswer), Pictures: a.pictures(b64), Markup: mk}, + ops: []string{o.ID}, replyTo: o.ReplyTo, onPress: o.OnPress} + if len(mk.Buttons) == 0 { + out.onPress = "" // left off: no press can come + } if o.Audio != nil { clip, err := base64.StdEncoding.DecodeString(o.Audio.Data) if err != nil || o.Audio.MimeType != "audio/mpeg" || len(clip) == 0 || len(clip) > maxPictureBytes { @@ -331,21 +343,29 @@ func (a *addon) post(o ext.Op, again bool) (why string) { return "" } -// outgoing is a post of the addon's, the ops it carries, and the ID of -// the post op it replies to, if any. +// outgoing is a post of the addon's, or an edit, the ops it carries, the +// ID of the post op it replies to, if any, the tool a press of its buttons +// calls, and an edit's post op. type outgoing struct { feature.Post ops []string replyTo string + onPress string + edits string } // fits reports whether p can join o in one post: their pictures, and // their texts whole, so a merge never cuts a post that fit on its own. // A reply joins no other post, and none joins it, so it stays a message -// of its own and a later post a new one. +// of its own and a later post a new one; so does an edit, and a post with +// markup but for silence, which both must share. func (o *outgoing) fits(p *outgoing) bool { - if o.replyTo != "" || p.replyTo != "" || len(o.Audio) > 0 || len(p.Audio) > 0 { - return false // a reply, or a clip, is a message of its own + own := func(x *outgoing) bool { + mk := x.Markup + return x.replyTo != "" || len(x.Audio) > 0 || x.Edit != 0 || len(mk.Buttons) > 0 || len(mk.Keyboard) > 0 || mk.NoKeyboard + } + if own(o) || own(p) || o.Markup.Silent != p.Markup.Silent { + return false // a message of its own } size := 0 for _, pic := range append(slices.Clone(o.Pictures), p.Pictures...) { @@ -392,6 +412,17 @@ func (a *addon) send(id string, out *outgoing) { // and waits to be posted again waits too, and is posted after it. func (a *addon) mail(id string, out *outgoing) { p := out.Post + if out.edits != "" { // the post as it stands now, after any edit before + a.mu.Lock() + t, ok := a.posted[out.edits] + a.mu.Unlock() + if !ok || t.Chat != id || a.uneditable(t, a.now()) != "" { + a.sent(out.ops, true) // forgotten since, or no longer editable: nothing to edit + a.mailNext(id) + return + } + p.Edit = t.last() + } if out.replyTo != "" { a.mu.Lock() pending, retry := a.waitsToPost(out.replyTo), a.failed[out.replyTo].retry @@ -406,12 +437,22 @@ func (a *addon) mail(id string, out *outgoing) { } } p.OnSent = func(sent []int64, dropped bool) { - if !dropped { + switch { + case dropped: + case out.edits != "": + if len(sent) > 0 && sent[0] != p.Edit { // sent anew + a.replied(p.Chat, sent) + if len(p.Pictures) > 0 { + a.guardPosted(p.Chat, sent) + } + } + a.rememberEdit(out.edits, sent, out.onPress) + default: a.replied(p.Chat, sent) if len(p.Pictures) > 0 { a.guardPosted(p.Chat, sent) } - a.rememberPosted(id, out.ops, sent) + a.rememberPosted(p.Chat, out.ops, sent, out.onPress) } a.sent(out.ops, !dropped) a.mailNext(id) @@ -436,47 +477,133 @@ func (a *addon) mailNext(id string) { } // posted is a post op the addon sent: the pseudonym of its chat, the first -// of the timestamps it went out in, which a reply names, and until when a -// later post may reply to it. +// of the timestamps it went out in, which a reply or a reaction names, the +// last, which an edit replaces and a press of its buttons names, the tool +// such a press calls, and until when it is remembered. Shared is set when +// other ops went out in the same message, Edits counts its edits in place, +// and Topic is the forum topic a post with buttons is in, as a press under +// an old message comes from the bare group. type posted struct { - Chat string `json:"chat"` - Sent int64 `json:"sent"` - Expires time.Time `json:"expires"` + Chat string `json:"chat"` + Sent int64 `json:"sent"` + Last int64 `json:"last,omitempty"` // 0 for Sent + OnPress string `json:"onPress,omitempty"` + Expires time.Time `json:"expires"` + Shared bool `json:"shared,omitempty"` + Edits int `json:"edits,omitempty"` + Topic *feature.Chat `json:"topic,omitempty"` } -// How long a post op is remembered for a later post's replyTo, and how -// many are. +// last is the message an edit replaces and a press names. +func (p posted) last() int64 { return cmp.Or(p.Last, p.Sent) } + +// How long a post op is remembered, for a later post's replyTo, a +// reaction or an edit, and how many are: one with buttons for longer, so +// a press under a days-old post still works. const ( - postedLife = 24 * time.Hour - maxPosted = 256 + postedLife = 24 * time.Hour + maxPosted = 256 + buttonsLife = 30 * 24 * time.Hour + maxButtons = 1000 ) -// rememberPosted records that the post carrying ops went out in the chat whose -// pseudonym is chat, first as sent[0], so a later post may reply to it. -func (a *addon) rememberPosted(chat string, ops []string, sent []int64) { +// rememberPosted records that the post carrying ops went out in chat, as +// sent, so a later post may reply to it, react to it or edit it, and a +// press of its buttons, if it has any, calls onPress. +func (a *addon) rememberPosted(chat feature.Chat, ops []string, sent []int64, onPress string) { if len(sent) == 0 { return } until := a.now().Add(postedLife) + var topic *feature.Chat + if onPress != "" { + until = a.now().Add(buttonsLife) + if strings.Contains(chat.GroupID, "/") { + topic = &chat + } + } + id := a.chatID(chat) a.mu.Lock() - for _, id := range ops { - a.posted[id] = posted{Chat: chat, Sent: sent[0], Expires: until} + for _, op := range ops { + a.posted[op] = posted{Chat: id, Sent: sent[0], Last: sent[len(sent)-1], OnPress: onPress, Expires: until, Shared: len(ops) > 1, Topic: topic} } a.trimPosted() a.mu.Unlock() } -// trimPosted forgets the posts that expire soonest past maxPosted. a.mu is -// held. +// rememberEdit records that the post op called id was edited, now standing +// as sent (a new message where the network sent the edit anew), with +// buttons whose press calls onPress, if any. It is remembered afresh from +// now, but for an edit in place where the network shows no buttons +// (Signal), whose apps show edits only within a day of the first sending. +func (a *addon) rememberEdit(id string, sent []int64, onPress string) { + if len(sent) == 0 { + return // refused: the post is as it was + } + until := a.now().Add(postedLife) + if onPress != "" { + until = a.now().Add(buttonsLife) + } + a.mu.Lock() + if p, ok := a.posted[id]; ok { + switch { + case sent[0] != p.last(): // a new message + p.Sent, p.Edits = sent[0], 0 + case !a.buttons: + until = p.Expires + fallthrough + default: + p.Edits++ + } + p.Last, p.OnPress, p.Expires = sent[len(sent)-1], onPress, until + a.posted[id] = p + a.trimPosted() + } + a.mu.Unlock() +} + +// maxSignalEdits is how many edits of a message Signal's apps show. +const maxSignalEdits = 10 + +// uneditable is why the addon's post p can't be edited at now, or "". +func (a *addon) uneditable(p posted, now time.Time) string { + switch { + case !now.Before(p.Expires): + return "edits of an unknown post" + case p.Shared: + return "edits of a post merged with others" + case p.Sent != p.last(): + return "edits of a post sent in several messages" + case !a.buttons && p.Edits >= maxSignalEdits: + return "edits past the network's limit" + } + return "" +} + +// trimPosted forgets the posts that expire soonest past maxPosted without +// buttons and maxButtons with. a.mu is held. func (a *addon) trimPosted() { - if len(a.posted) <= maxPosted { - return + var plain, buttoned []string + for id, p := range a.posted { + if p.OnPress != "" { + buttoned = append(buttoned, id) + } else { + plain = append(plain, id) + } } - ids := slices.SortedFunc(maps.Keys(a.posted), func(x, y string) int { - return cmp.Or(a.posted[x].Expires.Compare(a.posted[y].Expires), strings.Compare(x, y)) - }) - for _, id := range ids[:len(ids)-maxPosted] { - delete(a.posted, id) + for _, c := range []struct { + ids []string + max int + }{{plain, maxPosted}, {buttoned, maxButtons}} { + if len(c.ids) <= c.max { + continue + } + slices.SortFunc(c.ids, func(x, y string) int { + return cmp.Or(a.posted[x].Expires.Compare(a.posted[y].Expires), strings.Compare(x, y)) + }) + for _, id := range c.ids[:len(c.ids)-c.max] { + delete(a.posted, id) + } } } diff --git a/internal/features/mcp/sample.go b/internal/features/mcp/sample.go index b94c4c9..243a1e2 100644 --- a/internal/features/mcp/sample.go +++ b/internal/features/mcp/sample.go @@ -138,6 +138,7 @@ func (a *addon) ask(ctx context.Context, params json.RawMessage) (*answer, int, a.mu.Lock() l, ok := a.leases[req.Meta.Chat] a.mu.Unlock() + // A lease's day, not announce's for good: announce opens no sampling. if req.Meta.Chat == "" || !ok || !now.Before(l.Expires) || !a.allows(l.Chat) { return nil, size, "refused: no chat", &rpcError{Code: -32602, Message: "_meta needs the chat that pays, one the addon may post in now"} } diff --git a/internal/features/mcp/sample_test.go b/internal/features/mcp/sample_test.go index 2f97db5..86305be 100644 --- a/internal/features/mcp/sample_test.go +++ b/internal/features/mcp/sample_test.go @@ -64,7 +64,7 @@ func TestSample(t *testing.T) { var log logx.Buffer t.Cleanup(logx.SetOutput(&log, &log, true)) a, h, bodies := sampler(&modelConfig{PerHour: 30, MaxTokens: 100}) - a.lease(inA) + a.lease(inA, false) res, rerr := a.sample(context.Background(), ask(a.chatID(inA), "Alice asks for the capital of Australia", 500)) if rerr != nil { t.Fatal(rerr) @@ -104,11 +104,11 @@ func TestSampleRefused(t *testing.T) { } } a, h, bodies := sampler(nil) - a.lease(inA) + a.lease(inA, false) refused(a, ask(a.chatID(inA), "hi", 10), -32601) a, h, bodies = sampler(&modelConfig{PerHour: 2, MaxTokens: 100}) - a.lease(inA) + a.lease(inA, false) chat := a.chatID(inA) h.Bot.Model = "" refused(a, ask(chat, "hi", 10), -32601) @@ -145,13 +145,19 @@ func TestSampleRefused(t *testing.T) { // A chat the addon is no longer allowed in. a, _, _ = sampler(&modelConfig{PerHour: 2, MaxTokens: 100}) - a.lease(inA) + a.lease(inA, false) a.cfg.Chats = []string{groupB} refused(a, ask(a.chatID(inA), "hi", 10), -32602) + // A chat announce keeps open, past its lease's day: no sampling. + a, _, _ = sampler(&modelConfig{PerHour: 2, MaxTokens: 100}) + a.cfg.Announce = true + a.leases[a.chatID(inA)] = lease{Chat: inA, Expires: a.now().Add(-time.Hour), Forever: true} + refused(a, ask(a.chatID(inA), "hi", 10), -32602) + // The model failing, as when the chat is over its daily budget. a, h, _ = sampler(&modelConfig{PerHour: 2, MaxTokens: 100}) - a.lease(inA) + a.lease(inA, false) h.API = func(context.Context, string, map[string]any) (json.RawMessage, error) { return nil, errors.New("the chat has reached its daily budget") } @@ -397,7 +403,7 @@ func TestPackageAddonNoSample(t *testing.T) { // a gate opened with no addon is refused, not called unsupported. func TestSampleGate(t *testing.T) { a, _, _ := sampler(&modelConfig{PerHour: 30, MaxTokens: 100}) - a.lease(inA) + a.lease(inA, false) g := &gate{ready: make(chan struct{})} got := make(chan *rpcError, 1) go func() { @@ -434,7 +440,7 @@ func TestSampleGate(t *testing.T) { // to the chat, and gets no answer. func TestSampleCancelledCharges(t *testing.T) { a, h, _ := sampler(&modelConfig{PerHour: 30, MaxTokens: 100}) - a.lease(inA) + a.lease(inA, false) ctx, cancel := context.WithCancel(context.Background()) api := h.API var callErr error @@ -675,7 +681,7 @@ func TestSampleNoAnswer(t *testing.T) { h.API = func(context.Context, string, map[string]any) (json.RawMessage, error) { return json.RawMessage(body), nil } - a.lease(inA) + a.lease(inA, false) _, rerr := a.sample(context.Background(), ask(a.chatID(inA), "Alice asks for the capital of Australia", 500)) restore() if rerr == nil || rerr.Message != "the model gave no answer" { diff --git a/internal/features/mcp/watch.go b/internal/features/mcp/watch.go index 5739fac..f5af3c3 100644 --- a/internal/features/mcp/watch.go +++ b/internal/features/mcp/watch.go @@ -73,10 +73,24 @@ type claim struct { Expires time.Time `json:"expires"` } -// lease is a chat an addon may post and react in, until it expires. +// lease is a chat an addon may post and react in, until it expires, or +// with Forever (the addon's announce) for good. type lease struct { Chat feature.Chat `json:"chat"` Expires time.Time `json:"expires"` + Forever bool `json:"forever,omitempty"` +} + +// live reports whether the lease lets the addon post at now. +func (l lease) live(now time.Time) bool { return l.Forever || now.Before(l.Expires) } + +// leaseLocked lets the addon post in chat for the next leaseLife, or with +// forever for good, as a lease for good already does while the addon may +// announce. a.mu is held. +func (a *addon) leaseLocked(chat feature.Chat, now time.Time, forever bool) { + id := a.chatID(chat) + forever = a.cfg.Announce && (forever || a.leases[id].Forever) + a.leases[id] = lease{Chat: chat, Expires: now.Add(leaseLife), Forever: forever} } // match is a message a watch took, for the watch worker. @@ -110,7 +124,7 @@ func (a *addon) reacted(e feature.Event) bool { } } if tool != "" { - a.leases[a.chatID(e.Chat)] = lease{e.Chat, now.Add(leaseLife)} + a.leaseLocked(e.Chat, now, false) } a.mu.Unlock() if tool == "" { @@ -133,11 +147,11 @@ const ( maxTries = 3 ) -// lease lets the addon post in chat for the next leaseLife. -func (a *addon) lease(chat feature.Chat) { - id := a.chatID(chat) +// lease lets the addon post in chat for the next leaseLife, or, with +// forever and the addon's announce, for good. +func (a *addon) lease(chat feature.Chat, forever bool) { a.mu.Lock() - a.leases[id] = lease{chat, a.now().Add(leaseLife)} + a.leaseLocked(chat, a.now(), forever) a.mu.Unlock() a.changed() } @@ -322,7 +336,7 @@ func (a *addon) claim(m feature.Message) feature.Action { if _, ok := a.claims[c]; !ok { a.claims[c] = claim{c, got.tool, now.Unix(), now.Add(claimLife)} } - a.leases[a.chatID(m.Chat)] = lease{m.Chat, now.Add(leaseLife)} + a.leaseLocked(m.Chat, now, false) a.mu.Unlock() a.changed() select { diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index 16b59ba..bd9df6a 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -597,7 +597,7 @@ func TestOutboxDelivery(t *testing.T) { a, now := unitAddon(cfg) h := featuretest.New() a.host = h - a.lease(inA) + a.lease(inA, false) id := a.chatID(inA) pic := []ext.Image{{Data: tinyPNG(), MimeType: "image/png"}} postOp := func(n string, images []ext.Image) ext.Op { @@ -652,7 +652,7 @@ func TestOutboxMergeKeepsTexts(t *testing.T) { a, _ := unitAddon(everything) h := featuretest.New() a.host = h - a.lease(inA) + a.lease(inA, false) id := a.chatID(inA) long := strings.Repeat("Γ©", 3000) for i, text := range []string{"first", long, long} { @@ -685,8 +685,8 @@ func TestOutboxReplies(t *testing.T) { a, now := unitAddon(cfg) h := featuretest.New() a.host = h - a.lease(inA) - a.lease(inB) + a.lease(inA, false) + a.lease(inB, false) idA, idB := a.chatID(inA), a.chatID(inB) n := 0 post := func(chat, text, replyTo string) ext.Op { @@ -760,7 +760,7 @@ func TestOutboxReplies(t *testing.T) { // 24 hours on, forgotten. *now = now.Add(postedLife) - a.lease(inA) + a.lease(inA, false) apply(post(idA, "Too late", question.ID)) if len(a.state().Posted) != 0 { t.Fatalf("kept %+v", a.state().Posted) @@ -799,8 +799,8 @@ func TestOutboxReactToPost(t *testing.T) { a, now := unitAddon(cfg) h := featuretest.New() a.host = h - a.lease(inA) - a.lease(inB) + a.lease(inA, false) + a.lease(inB, false) idA, idB := a.chatID(inA), a.chatID(inB) if why := a.apply(ext.Op{ID: "q", Op: "post", Chat: idA, Text: "Question"}); why != "" { t.Fatal(why) @@ -842,7 +842,7 @@ func TestOutboxReactToPost(t *testing.T) { } // Once the post is too old to be remembered. *now = now.Add(postedLife) - a.lease(inA) + a.lease(inA, false) if why := react("9", idA, "q", ""); why != "reactions to an unknown post" { t.Fatalf("an old post: %q", why) } @@ -850,8 +850,8 @@ func TestOutboxReactToPost(t *testing.T) { cfg.React = false a, _ = unitAddon(cfg) a.host = h - a.lease(inA) - a.rememberPosted(idA, []string{"q"}, []int64{100}) + a.lease(inA, false) + a.rememberPosted(inA, []string{"q"}, []int64{100}, "") if why := react("10", idA, "q", ""); why != "reactions not allowed" { t.Fatalf("without react: %q", why) } @@ -863,7 +863,7 @@ func TestOutboxReplyWaitsForDropped(t *testing.T) { a, now := unitAddon(everything) h := featuretest.New() a.host = h - a.lease(inA) + a.lease(inA, false) id := a.chatID(inA) waiting := ext.Op{ID: "w", Op: "post", Chat: id, Text: "Waiting"} question := ext.Op{ID: "q", Op: "post", Chat: id, Text: "Question"} @@ -1257,7 +1257,7 @@ func TestOutboxAudio(t *testing.T) { a, _ := unitAddon(cfg) h := featuretest.New() a.host = h - a.lease(inA) + a.lease(inA, false) id := a.chatID(inA) clip := base64.StdEncoding.EncodeToString([]byte("ID3 clip")) for _, o := range []ext.Op{ diff --git a/internal/kit/state/state.go b/internal/kit/state/state.go index b0f3a53..909f453 100644 --- a/internal/kit/state/state.go +++ b/internal/kit/state/state.go @@ -21,20 +21,23 @@ import ( // feature can't fill the disk: 4 MiB. const MaxBytes = 4 << 20 -// Reserved is the core's own saved state, the daily budget, which no -// feature may open. -const Reserved = "budget" +// Reserved and Keyboards are the core's own saved states, the daily +// budget and the DMs' reply keyboards, which no feature may open. +const ( + Reserved = "budget" + Keyboards = "keyboards" +) // namePattern is what a saved state may be called: it names a file. var namePattern = regexp.MustCompile(`^[a-z0-9_-]{1,32}$`) // CheckName fails unless name is a feature's to open: lowercase letters, -// digits, - and _, up to 32, and not Reserved. +// digits, - and _, up to 32, and not the core's. func CheckName(name string) error { switch { case !namePattern.MatchString(name): return fmt.Errorf("a saved state can't be called %q: use lowercase letters, digits, - and _, up to 32", txt.Clamp(name, 40)) - case name == Reserved: + case name == Reserved || name == Keyboards: return fmt.Errorf("a saved state can't be called %q: it is the core's", name) } return nil diff --git a/internal/kit/state/state_test.go b/internal/kit/state/state_test.go index aaf5feb..7227d26 100644 --- a/internal/kit/state/state_test.go +++ b/internal/kit/state/state_test.go @@ -88,7 +88,7 @@ func TestCheck(t *testing.T) { // A name is a safe file name, and the core's is refused. func TestCheckName(t *testing.T) { - for name, ok := range map[string]bool{"notes": true, "a-b_c9": true, "budget": false, "../x": false, "Notes": false, "": false, strings.Repeat("a", 33): false} { + for name, ok := range map[string]bool{"notes": true, "a-b_c9": true, "budget": false, "keyboards": false, "../x": false, "Notes": false, "": false, strings.Repeat("a", 33): false} { if err := CheckName(name); (err == nil) != ok { t.Errorf("%q: %v", name, err) } diff --git a/internal/signal/client_test.go b/internal/signal/client_test.go index e3f9cd2..2e23db3 100644 --- a/internal/signal/client_test.go +++ b/internal/signal/client_test.go @@ -280,10 +280,10 @@ func TestSendAndTyping(t *testing.T) { run(t, c, f) group, dm := feature.Chat{GroupID: groupID}, feature.Chat{User: aliceID} png := []byte("\x89PNG\r\n\x1a\n") - if ts := c.Send(group, "@signalbot hi @Alice", []feature.Picture{{Data: png, Name: "NVDA vs AMD, 1 month"}, {Data: png}}, map[string]string{"alice": aliceID}, 0, nil); !slices.Equal(ts, []int64{1001}) { + if ts := c.Send(group, "@signalbot hi @Alice", []feature.Picture{{Data: png, Name: "NVDA vs AMD, 1 month"}, {Data: png}}, map[string]string{"alice": aliceID}, 0, nil, feature.Markup{}); !slices.Equal(ts, []int64{1001}) { t.Fatalf("sent %v", ts) } - c.Send(dm, "plain @Alice", nil, nil, 0, nil) + c.Send(dm, "plain @Alice", nil, nil, 0, nil, feature.Markup{}) eventually(t, "two sends", func() bool { return len(f.calls("send")) == 2 }) s := f.calls("send") if s[0]["groupId"] != groupID || s[0]["message"] != "hi @Alice" || fmt.Sprint(s[0]["mention"]) != "[3:6:"+aliceID+"]" || @@ -297,7 +297,7 @@ func TestSendAndTyping(t *testing.T) { t.Errorf("a plain send quotes: %v", s) } // A reply quotes the bot's own message by its timestamp. - c.Send(group, "the answer", nil, nil, 1001, nil) + c.Send(group, "the answer", nil, nil, 1001, nil, feature.Markup{}) eventually(t, "the reply", func() bool { return len(f.calls("send")) == 3 }) if r := f.calls("send")[2]; r["quoteTimestamp"] != float64(1001) || r["quoteAuthor"] != botID || r["message"] != "the answer" || r["groupId"] != groupID { t.Errorf("reply send %v", r) @@ -500,11 +500,11 @@ func TestSendResults(t *testing.T) { f := newFake(t) c := newClient(f.sock, nil, nil) run(t, c, f) - if ts := c.Send(feature.Chat{User: aliceID}, strings.Repeat("word ", 500), nil, nil, 0, nil); len(ts) != 1 { + if ts := c.Send(feature.Chat{User: aliceID}, strings.Repeat("word ", 500), nil, nil, 0, nil, feature.Markup{}); len(ts) != 1 { t.Fatalf("a long reply returned %v", ts) } f.set("send", `{"timestamp":77,"results":[{"type":"NETWORK_FAILURE"}]}`) - if ts := c.Send(feature.Chat{User: aliceID}, "hi", nil, nil, 0, nil); !slices.Equal(ts, []int64{77}) { + if ts := c.Send(feature.Chat{User: aliceID}, "hi", nil, nil, 0, nil, feature.Markup{}); !slices.Equal(ts, []int64{77}) { t.Fatalf("returned %v", ts) } if !strings.Contains(logs.String(), "signal-cli send not delivered: NETWORK_FAILURE") { diff --git a/internal/signal/markdown_test.go b/internal/signal/markdown_test.go index 4f8e63b..334e0a3 100644 --- a/internal/signal/markdown_test.go +++ b/internal/signal/markdown_test.go @@ -84,7 +84,7 @@ func TestSendStyles(t *testing.T) { f := newFake(t) c := newClient(f.sock, nil, nil) run(t, c, f) - c.Send(feature.Chat{User: aliceID}, "**\U0001F389 big** news, @Alice: see `x`", nil, map[string]string{"alice": "u-a"}, 0, nil) + c.Send(feature.Chat{User: aliceID}, "**\U0001F389 big** news, @Alice: see `x`", nil, map[string]string{"alice": "u-a"}, 0, nil, feature.Markup{}) eventually(t, "a send", func() bool { return len(f.calls("send")) == 1 }) s := f.calls("send")[0] if s["message"] != "\U0001F389 big news, @Alice: see x" { @@ -96,7 +96,7 @@ func TestSendStyles(t *testing.T) { if got := fmt.Sprint(s["mention"]); got != "[13:6:u-a]" { t.Errorf("mentions %v", got) } - c.Send(feature.Chat{User: aliceID}, "plain", nil, nil, 0, nil) + c.Send(feature.Chat{User: aliceID}, "plain", nil, nil, 0, nil, feature.Markup{}) eventually(t, "a second send", func() bool { return len(f.calls("send")) == 2 }) if _, ok := f.calls("send")[1]["textStyle"]; ok { t.Errorf("styles on plain text") diff --git a/internal/signal/send.go b/internal/signal/send.go index 934ec7c..47ea58b 100644 --- a/internal/signal/send.go +++ b/internal/signal/send.go @@ -36,8 +36,9 @@ func (c *Client) Prompt() string { // @name, made a real mention, and with the images, each named after its // Name or else image_, quoting the bot's own message sent at // replyTo if it isn't 0. A failure is logged, as is a message signal-cli -// says it could not deliver. -func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64, audio []byte) (sent []int64) { +// says it could not deliver. Signal shows none of mk: no buttons, no +// keyboard, and no silent send. +func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64, audio []byte, _ feature.Markup) (sent []int64) { if n := utf8.RuneCountInString(text); n > maxReply { logx.Warnf("reply truncated from %d chars", n) } @@ -61,14 +62,7 @@ func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, kn attachments = append(attachments, "data:audio/mpeg;filename=clip.mp3;base64,"+base64.StdEncoding.EncodeToString(audio)) } msg, ok := prepare(text, c.BotName()) - if id := c.self(); id != "" && chat.GroupID != "" { // in a group, "@" and its own name mentions the bot - k := maps.Clone(known) - if k == nil { - k = map[string]string{} - } - k[txt.SafeName(c.BotName())] = id - known = k - } + known = c.withSelf(chat, known) if !ok && len(attachments) == 0 { logx.Warnf("empty reply, nothing sent") return nil @@ -91,6 +85,45 @@ func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, kn return sent } +// Buttons reports that Signal shows no Markup. +func (c *Client) Buttons() bool { return false } + +// Edit replaces the text of the bot's own message sent at sent, as Signal's +// apps edit one, keeping its timestamp; with pics, which an edit can't +// change, they and the text are sent as a new message instead. mk is left +// off, as Send leaves it. +func (c *Client) Edit(chat feature.Chat, sent int64, text string, pics []feature.Picture, known map[string]string, mk feature.Markup) []int64 { + if len(pics) > 0 { + return c.Send(chat, text, pics, known, 0, nil, mk) + } + msg, ok := prepare(text, c.BotName()) + if !ok { + logx.Warnf("empty edit, nothing sent") + return nil + } + known = c.withSelf(chat, known) + body := string(msg.Runes) + if _, err := c.post(chat, body, mentions(body, known), textStyles(msg), nil, 0, sent); err != nil { + logx.Errorf("edit failed: %v", err) + return nil + } + return []int64{sent} +} + +// withSelf is known with, in a group, the bot's own name for its account, +// so "@" and its name mentions it. +func (c *Client) withSelf(chat feature.Chat, known map[string]string) map[string]string { + if id := c.self(); id != "" && chat.GroupID != "" { + k := maps.Clone(known) + if k == nil { + k = map[string]string{} + } + k[txt.SafeName(c.BotName())] = id + return k + } + return known +} + // fileName is name made safe as a file name in a data URI: characters that // file systems or the URI reserve are dropped, spaces are collapsed, and it is // cut to 80 characters. @@ -113,11 +146,20 @@ func fileName(name string) string { // still has the message, so a recipient whose app doesn't shows the quote // as not found, and the reply still goes. func (c *Client) send(chat feature.Chat, text string, mentions, styles, attachments []string, quote int64) (int64, error) { + return c.post(chat, text, mentions, styles, attachments, quote, 0) +} + +// post is send, and with edit an edit of the bot's own message sent then +// (signal-cli's editTimestamp). +func (c *Client) post(chat feature.Chat, text string, mentions, styles, attachments []string, quote, edit int64) (int64, error) { p := target(chat) p["message"] = text if self := c.self(); quote != 0 && self != "" { p["quoteTimestamp"], p["quoteAuthor"] = quote, self } + if edit != 0 { + p["editTimestamp"] = edit + } if len(mentions) > 0 { p["mention"] = mentions } diff --git a/internal/signal/send_test.go b/internal/signal/send_test.go index 8201d17..3a14583 100644 --- a/internal/signal/send_test.go +++ b/internal/signal/send_test.go @@ -17,7 +17,7 @@ func TestSendOneMessageAndCaps(t *testing.T) { c := newClient(f.sock, nil, nil) run(t, c, f) dm := feature.Chat{User: aliceID} - c.Send(dm, strings.Repeat("z ", 6000), []feature.Picture{{Data: []byte("PNG")}}, nil, 0, nil) + c.Send(dm, strings.Repeat("z ", 6000), []feature.Picture{{Data: []byte("PNG")}}, nil, 0, nil, feature.Markup{}) eventually(t, "a send", func() bool { return len(f.calls("send")) == 1 }) if s := f.calls("send")[0]; s["attachments"] == nil || len([]rune(s["message"].(string))) != maxReply || !strings.HasSuffix(s["message"].(string), "[…truncated]") { t.Errorf("send %d chars, attachments %v", len([]rune(fmt.Sprint(s["message"]))), s["attachments"] != nil) @@ -25,13 +25,13 @@ func TestSendOneMessageAndCaps(t *testing.T) { if !strings.Contains(logs.String(), "reply truncated from 12000 chars") { t.Errorf("logs %q", logs) } - c.Send(dm, " ", nil, nil, 0, nil) - c.Send(dm, "", []feature.Picture{{Data: []byte("PNG")}}, nil, 0, nil) + c.Send(dm, " ", nil, nil, 0, nil, feature.Markup{}) + c.Send(dm, "", []feature.Picture{{Data: []byte("PNG")}}, nil, 0, nil, feature.Markup{}) eventually(t, "the pictures alone", func() bool { return len(f.calls("send")) == 2 }) if s := f.calls("send")[1]; s["message"] != "" || s["attachments"] == nil { t.Errorf("pictures sent as %v", s) } - newClient("x", nil, nil).Send(dm, "secret words", nil, nil, 0, nil) + newClient("x", nil, nil).Send(dm, "secret words", nil, nil, 0, nil, feature.Markup{}) if out := logs.String(); !strings.Contains(out, "empty reply, nothing sent") || !strings.Contains(out, "send failed: not connected") || strings.Contains(out, "secret") { t.Errorf("logs %q", out) } @@ -77,10 +77,39 @@ func TestSendAudio(t *testing.T) { f := newFake(t) c := newClient(f.sock, nil, nil) run(t, c, f) - c.Send(feature.Chat{User: aliceID}, "🎡 Song 1", nil, nil, 0, []byte("ID3 clip")) + c.Send(feature.Chat{User: aliceID}, "🎡 Song 1", nil, nil, 0, []byte("ID3 clip"), feature.Markup{}) eventually(t, "a send", func() bool { return len(f.calls("send")) == 1 }) att, _ := f.calls("send")[0]["attachments"].([]any) if len(att) != 1 || att[0] != "data:audio/mpeg;filename=clip.mp3;base64,SUQzIGNsaXA=" { t.Errorf("attachments %v", att) } } + +// An edit without pictures replaces the text of the bot's message in place +// (editTimestamp), keeping its timestamp; with pictures, which an edit +// can't change, it is a new message. Signal shows no buttons. +func TestEdit(t *testing.T) { + captureLogs(t) + f := newFake(t) + c := newClient(f.sock, nil, nil) + run(t, c, f) + group := feature.Chat{GroupID: groupID} + mk := feature.Markup{Buttons: [][]feature.Button{{{Label: "7d", Data: "rain 7d"}}}} + if c.Buttons() { + t.Error("Signal shows buttons") + } + if ts := c.Edit(group, 900, "**Rain**, 7 days", nil, nil, mk); len(ts) != 1 || ts[0] != 900 { + t.Fatalf("edit %v", ts) + } + eventually(t, "the edit", func() bool { return len(f.calls("send")) == 1 }) + if s := f.calls("send")[0]; s["editTimestamp"] != float64(900) || s["message"] != "Rain, 7 days" || s["groupId"] != groupID || s["textStyle"] == nil { + t.Errorf("edit %v", s) + } + if ts := c.Edit(group, 900, "Rain", []feature.Picture{{Data: []byte("PNG")}}, nil, mk); len(ts) != 1 || ts[0] == 900 { + t.Fatalf("an edit with a picture %v", ts) + } + eventually(t, "the new message", func() bool { return len(f.calls("send")) == 2 }) + if s := f.calls("send")[1]; s["editTimestamp"] != nil || s["attachments"] == nil { + t.Errorf("an edit with a picture %v", s) + } +} diff --git a/internal/telegram/buttons.go b/internal/telegram/buttons.go new file mode 100644 index 0000000..2134448 --- /dev/null +++ b/internal/telegram/buttons.go @@ -0,0 +1,199 @@ +package telegram + +import ( + "context" + "encoding/json" + "errors" + "strconv" + "strings" + "time" + + "github.com/robdevops/signalbot/internal/bot" + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/logx" + "github.com/robdevops/signalbot/internal/kit/mdstyle" +) + +// callbackQuery is a press of a button under one of the bot's messages. +type callbackQuery struct { + ID string `json:"id"` + From *user `json:"from"` + Message *message `json:"message"` // the message the button is under; only its chat and ID if it is old + Data string `json:"data"` +} + +// Buttons reports that Telegram shows a post's Markup. +func (c *Client) Buttons() bool { return true } + +// pressed is a press as the core gets it: in a DM, only from someone the bot +// answers, and in a group, only while it answers there. A press it drops is +// answered at once, so the button stops spinning. +func (c *Client) pressed(q *callbackQuery) (bot.Received, bool) { + answer := func(text string) { go c.answerPress(q.ID, text) } + if q.From == nil || q.Message == nil || q.Data == "" || id(q.From.ID) == c.selfID() { + answer("") + return nil, false + } + ch := chatOf(q.Message) + if ch.GroupID == "" && !c.allowed[id(q.From.ID)] || ch.GroupID != "" && !c.answers(id(q.Message.Chat.ID)) { + answer("") + return nil, false + } + return bot.Pressed{Press: feature.Press{Chat: ch, By: c.person(q.From), Sent: q.Message.MessageID, Data: q.Data}, Answer: answer}, true +} + +// maxToast caps what a press's answer shows, Telegram's limit, in UTF-16 +// units. +const maxToast = 200 + +// toast is text cut to fit maxToast, with "…" if it was cut. +func toast(text string) string { + rs := []rune(text) + u := mdstyle.UTF16At(rs) + if u[len(rs)] <= maxToast { + return text + } + n := len(rs) + for u[n] > maxToast-1 { + n-- + } + return string(rs[:n]) + "…" +} + +// answerPress answers the press called queryID, showing text, if not "", +// for a moment. +func (c *Client) answerPress(queryID, text string) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + p := map[string]any{"callback_query_id": queryID} + if text = strings.TrimSpace(text); text != "" { + p["text"] = toast(text) + } + err := c.call(ctx, "answerCallbackQuery", p, nil) + if _, ok := p["text"]; ok && refused(err) { // the text refused: the button must still stop spinning + delete(p, "text") + err = c.call(ctx, "answerCallbackQuery", p, nil) + } + if err != nil { + logx.Warnf("telegram: answering a press failed: %v", err) + } +} + +// Edit replaces the bot's own message sent: with pics, its photo, the first +// of them (editMessageMedia), and its caption; without, its text, or for a +// message with a photo its caption. mk's buttons go under it; an edit +// without them takes them away, and one with no text and no pictures +// changes only them. Text past a message's or a caption's limit is cut. +// Telegram's "not modified" counts as done. A picture Telegram won't put +// on the message, such as one with none, goes in a new message, as on +// Signal. It returns sent, the new message's IDs, or none if the edit +// failed, which is logged. +func (c *Client) Edit(ch feature.Chat, sent int64, text string, pics []feature.Picture, known map[string]string, mk feature.Markup) []int64 { + t := mdstyle.Parse(text, true).Trim() + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + d := c.dest(ch) + var rm any + if len(mk.Buttons) > 0 { + rm = inlineKeyboard(mk.Buttons) + } + cut := func(limit int) mdstyle.Text { + if parts := mdstyle.Split(t, limit); len(parts) > 0 { + return parts[0] + } + return mdstyle.Text{} + } + var err error + switch { + case len(pics) > 0: + err = c.editMedia(ctx, d.chat, sent, pics[0].Data, cut(maxCaption), known, rm) + if refused(err) && !notModified(err) { + cancel() + return c.Send(ch, text, pics[:1], known, 0, nil, feature.Markup{Buttons: mk.Buttons}) + } + case len(t.Runes) > 0: + params := map[string]any{"chat_id": d.chat, "message_id": sent, "text": string(cut(maxChars).Runes), "entities": entities(cut(maxChars), known)} + if rm != nil { + params["reply_markup"] = rm + } + err = c.editCall(ctx, d.chat, "editMessageText", params, "entities") + if noText(err) { // a photo's message: its caption + p := cut(maxCaption) + delete(params, "text") + delete(params, "entities") + params["caption"], params["caption_entities"] = string(p.Runes), entities(p, known) + err = c.editCall(ctx, d.chat, "editMessageCaption", params, "caption_entities") + } + default: + params := map[string]any{"chat_id": d.chat, "message_id": sent} + if rm != nil { + params["reply_markup"] = rm + } + err = c.editCall(ctx, d.chat, "editMessageReplyMarkup", params, "") + } + if err != nil && !notModified(err) { + logx.Errorf("edit failed: %v", err) + return nil + } + return []int64{sent} +} + +// editCall makes an edit with params, again without ents (its entities' +// key) if Telegram refuses them. +func (c *Client) editCall(ctx context.Context, chat, method string, params map[string]any, ents string) error { + send := func() error { return c.call(ctx, method, params, nil) } + move := func(to string) { params["chat_id"] = to } + err := c.retrying(ctx, chat, move, send) + if ents != "" && refusedEntities(err) { + delete(params, ents) + err = c.retrying(ctx, chat, move, send) + } + return err +} + +// editMedia replaces message sent's photo with photo, captioned, and its +// buttons with rm, again without the caption's entities if Telegram +// refuses them. +func (c *Client) editMedia(ctx context.Context, chat string, sent int64, photo []byte, caption mdstyle.Text, known map[string]string, rm any) error { + media := map[string]any{"type": "photo", "media": "attach://p0", "caption": string(caption.Runes)} + if ents := entities(caption, known); len(ents) > 0 { + media["caption_entities"] = ents + } + fields := map[string]string{"chat_id": chat, "message_id": strconv.FormatInt(sent, 10)} + if rm != nil { + j, _ := json.Marshal(rm) + fields["reply_markup"] = string(j) + } + send := func() error { + mj, _ := json.Marshal(media) + fields["media"] = string(mj) + return c.upload(ctx, "editMessageMedia", fields, map[string][]byte{"p0": photo}, nil) + } + move := func(to string) { fields["chat_id"] = to } + err := c.retrying(ctx, chat, move, send) + if refusedEntities(err) { + delete(media, "caption_entities") + err = c.retrying(ctx, chat, move, send) + } + return err +} + +// refused reports whether err is Telegram refusing a request as bad. +func refused(err error) bool { + var ae *apiError + return errors.As(err, &ae) && ae.Code == 400 +} + +// noText reports whether err is Telegram refusing to edit the text of a +// message that has none, such as a photo's. +func noText(err error) bool { + var ae *apiError + return errors.As(err, &ae) && ae.Code == 400 && strings.Contains(strings.ToLower(ae.Desc), "no text") +} + +// notModified reports whether err is Telegram saying an edit changes +// nothing. +func notModified(err error) bool { + var ae *apiError + return errors.As(err, &ae) && ae.Code == 400 && strings.Contains(strings.ToLower(ae.Desc), "not modified") +} diff --git a/internal/telegram/buttons_test.go b/internal/telegram/buttons_test.go new file mode 100644 index 0000000..9d80f66 --- /dev/null +++ b/internal/telegram/buttons_test.go @@ -0,0 +1,216 @@ +package telegram + +import ( + "context" + "encoding/json" + "reflect" + "slices" + "strings" + "testing" + "unicode/utf16" + + "github.com/robdevops/signalbot/internal/bot" + "github.com/robdevops/signalbot/internal/feature" +) + +// Getting updates asks for button presses too. +func TestPollsPresses(t *testing.T) { + f := newFake(t) + c := connected(f.client()) + c.poll(context.Background(), 0) + kinds, _ := f.callsTo("getUpdates")[0].Params["allowed_updates"].([]any) + if !slices.Contains(kinds, any("callback_query")) { + t.Fatalf("allowed_updates %v", kinds) + } +} + +// A press is the core's from someone it answers, with the message's ID and +// the button's data, and its Answer shows a toast; any other press is +// answered at once, with nothing. +func TestPressed(t *testing.T) { + f := newFake(t) + c := connected(f.client("1111111")) + c.groupAllowed(context.Background(), groupS) // Alice is in it + press := func(from, chat string) (bot.Received, bool) { + return c.event(parse(t, `{"update_id":1,"callback_query":{"id":"q1",`+from+`,"message":{"message_id":500,`+chat+`,"date":1},"data":"rain 7d"}}`)) + } + r, ok := press(fromA, inDM) + p, isPress := r.(bot.Pressed) + if !ok || !isPress || p.Press.Chat != (feature.Chat{User: "1111111"}) || p.Press.Sent != 500 || p.Press.Data != "rain 7d" || p.Press.By.ID != "1111111" || p.Press.By.Name != "Alice Ames" { + t.Fatalf("press %+v", r) + } + p.Answer("7 days " + strings.Repeat("x", 300)) + waitCalls(t, f, "answerCallbackQuery", 1) + a := f.callsTo("answerCallbackQuery")[0].Params + if a["callback_query_id"] != "q1" || !strings.HasPrefix(a["text"].(string), "7 days x") || len([]rune(a["text"].(string))) > maxToast { + t.Fatalf("answer %v", a) + } + if r, ok := press(fromA, inGroup); !ok || r.(bot.Pressed).Press.Chat.GroupID != groupS { + t.Fatalf("in a group %+v", r) + } + // Bob may not DM the bot, so his press is answered and dropped. + if _, ok := press(`"from":{"id":2222222,"first_name":"Bob"}`, `"chat":{"id":2222222,"type":"private"}`); ok { + t.Fatal("a stranger's press") + } + waitCalls(t, f, "answerCallbackQuery", 2) + if a := f.callsTo("answerCallbackQuery")[1].Params; a["text"] != nil { + t.Fatalf("a stranger's press answered %v", a) + } +} + +// Buttons go on the post's last message as an inline keyboard; a DM's +// keyboard as a persistent reply keyboard, or taken away; silent posts go +// without a notification. A group gets no reply keyboard. +func TestSendMarkup(t *testing.T) { + f := newFake(t) + f.results["sendPhoto"] = `{"message_id":601}` + f.results["sendVoice"] = `{"message_id":701}` + c := connected(f.client()) + buttons := feature.Markup{Silent: true, Buttons: [][]feature.Button{{{Label: "24h", Data: "rain 24h"}, {Label: "7d", Data: "rain 7d"}}}} + inline := `{"inline_keyboard":[[{"callback_data":"rain 24h","text":"24h"},{"callback_data":"rain 7d","text":"7d"}]]}` + asJSON := func(v any) string { + if s, ok := v.(string); ok { + return s + } + b, _ := json.Marshal(v) + return string(b) + } + + // Text past a message's limit: the buttons on the last part. + c.Send(feature.Chat{GroupID: groupS}, strings.Repeat("word ", 1000), nil, nil, 0, nil, buttons) + msgs := f.callsTo("sendMessage") + if len(msgs) != 2 || msgs[0].Params["reply_markup"] != nil || asJSON(msgs[1].Params["reply_markup"]) != inline { + t.Fatalf("parts %d, markup %v", len(msgs), msgs) + } + for _, m := range msgs { + if m.Params["disable_notification"] != true { + t.Fatalf("not silent: %v", m.Params) + } + } + + // A photo with its caption: the buttons on the photo. + png := []byte("\x89PNG\r\n\x1a\n") + c.Send(feature.Chat{User: "1111111"}, "Rain", []feature.Picture{{Data: png}}, nil, 0, nil, buttons) + ph := f.callsTo("sendPhoto") + if len(ph) != 1 || ph[0].Params["reply_markup"] != inline || ph[0].Params["disable_notification"] != "true" || len(f.callsTo("sendMessage")) != 2 { + t.Fatalf("photo %+v", ph) + } + + // An album, silent too. + f.results["sendMediaGroup"] = `[{"message_id":602},{"message_id":603}]` + c.Send(feature.Chat{User: "1111111"}, "Rain", []feature.Picture{{Data: png}, {Data: png}}, nil, 0, nil, feature.Markup{Silent: true}) + if mg := f.callsTo("sendMediaGroup"); len(mg) != 1 || mg[0].Params["disable_notification"] != "true" { + t.Fatalf("album %+v", mg) + } + + // A clip alone: the buttons on it. + c.Send(feature.Chat{User: "1111111"}, "", nil, nil, 0, []byte("ID3"), buttons) + if v := f.callsTo("sendVoice"); len(v) != 1 || v[0].Params["reply_markup"] != inline || v[0].Params["disable_notification"] != "true" { + t.Fatalf("voice %+v", v) + } + + // A DM's keyboard, then none; a group gets neither. + keys := feature.Markup{Keyboard: [][]feature.Key{{{Label: "🌧 Rain", Command: "/rain"}}}} + c.Send(feature.Chat{User: "1111111"}, "Pick", nil, nil, 0, nil, keys) + c.Send(feature.Chat{User: "1111111"}, "Bye", nil, nil, 0, nil, feature.Markup{NoKeyboard: true}) + c.Send(feature.Chat{GroupID: groupS}, "Pick", nil, nil, 0, nil, keys) + msgs = f.callsTo("sendMessage")[2:] + if got := asJSON(msgs[0].Params["reply_markup"]); got != `{"is_persistent":true,"keyboard":[[{"text":"🌧 Rain"}]],"resize_keyboard":true}` { + t.Errorf("keyboard %s", got) + } + if got := asJSON(msgs[1].Params["reply_markup"]); got != `{"remove_keyboard":true}` { + t.Errorf("no keyboard %s", got) + } + if msgs[2].Params["reply_markup"] != nil || msgs[0].Params["disable_notification"] != nil { + t.Errorf("in a group %v", msgs[2].Params) + } +} + +// An edit replaces a message's text, a photo's caption when it has no +// text, or its photo, with the buttons given, and with none only its +// buttons; "not modified" is done, and a refusal fails it. +func TestEdit(t *testing.T) { + captureLogs(t) + f := newFake(t) + c := connected(f.client()) + dm := feature.Chat{User: "1111111"} + buttons := feature.Markup{Buttons: [][]feature.Button{{{Label: "7d", Data: "rain 7d"}}}} + inline := map[string]any{"inline_keyboard": []any{[]any{map[string]any{"text": "7d", "callback_data": "rain 7d"}}}} + + if got := c.Edit(dm, 500, "**Rain**, 7 days", nil, nil, buttons); !reflect.DeepEqual(got, []int64{500}) { + t.Fatalf("edit %v", got) + } + e := f.callsTo("editMessageText") + if len(e) != 1 || e[0].Params["text"] != "Rain, 7 days" || e[0].Params["message_id"] != float64(500) || e[0].Params["chat_id"] != "1111111" || + !reflect.DeepEqual(e[0].Params["reply_markup"], inline) || e[0].Params["entities"] == nil { + t.Fatalf("editMessageText %+v", e) + } + + // A photo's message has no text: its caption, without buttons now. + f.errs["editMessageText"] = `{"ok":false,"error_code":400,"description":"Bad Request: there is no text in the message to edit"}` + if got := c.Edit(dm, 501, "Rain", nil, nil, feature.Markup{}); !reflect.DeepEqual(got, []int64{501}) { + t.Fatalf("caption edit %v", got) + } + if e := f.callsTo("editMessageCaption"); len(e) != 1 || e[0].Params["caption"] != "Rain" || e[0].Params["reply_markup"] != nil || e[0].Params["text"] != nil { + t.Fatalf("editMessageCaption %+v", e) + } + + // A new photo. + png := []byte("\x89PNG\r\n\x1a\n") + c.Edit(dm, 502, "Rain", []feature.Picture{{Data: png}}, nil, buttons) + m := f.callsTo("editMessageMedia") + if len(m) != 1 || string(m[0].Files["p0"]) != string(png) || m[0].Params["message_id"] != "502" || + !strings.Contains(m[0].Params["media"].(string), `"caption":"Rain"`) || !strings.Contains(m[0].Params["reply_markup"].(string), "rain 7d") { + t.Fatalf("editMessageMedia %+v", m) + } + + // No text, no photo: only the buttons. + c.Edit(dm, 503, "", nil, nil, buttons) + if r := f.callsTo("editMessageReplyMarkup"); len(r) != 1 || !reflect.DeepEqual(r[0].Params["reply_markup"], inline) { + t.Fatalf("editMessageReplyMarkup %+v", r) + } + + // Not modified is done; another refusal fails. + f.errs["editMessageText"] = `{"ok":false,"error_code":400,"description":"Bad Request: message is not modified"}` + if got := c.Edit(dm, 500, "same", nil, nil, feature.Markup{}); !reflect.DeepEqual(got, []int64{500}) { + t.Fatalf("not modified %v", got) + } + f.errs["editMessageText"] = `{"ok":false,"error_code":400,"description":"Bad Request: message to edit not found"}` + if got := c.Edit(dm, 499, "gone", nil, nil, feature.Markup{}); got != nil { + t.Fatalf("a refused edit %v", got) + } + + // A photo for a message Telegram won't put one on: a new message, with + // the buttons. + f.errs["editMessageMedia"] = `{"ok":false,"error_code":400,"description":"Bad Request: there is no media in the message to edit"}` + f.results["sendPhoto"] = `{"message_id":601}` + if got := c.Edit(dm, 504, "Rain", []feature.Picture{{Data: png}}, nil, buttons); !reflect.DeepEqual(got, []int64{601}) { + t.Fatalf("a photo sent anew %v", got) + } + if ph := f.callsTo("sendPhoto"); len(ph) != 1 || !strings.Contains(ph[0].Params["reply_markup"].(string), "rain 7d") || ph[0].Params["disable_notification"] != nil { + t.Fatalf("sendPhoto %+v", ph) + } +} + +// A press's answer past Telegram's limit, in UTF-16 units, is cut to fit; +// one Telegram refuses is answered again without text, so the button stops +// spinning. +func TestAnswerPress(t *testing.T) { + captureLogs(t) + f := newFake(t) + c := connected(f.client()) + c.answerPress("q1", strings.Repeat("🌧", 150)) + got := f.callsTo("answerCallbackQuery")[0].Params["text"].(string) + if n := len(utf16.Encode([]rune(got))); n > maxToast || !strings.HasSuffix(got, "…") { + t.Fatalf("%d units: %q", n, got) + } + if s := strings.Repeat("🌧", 100); toast(s) != s { + t.Fatal("a toast that fits, cut") + } + f.errs["answerCallbackQuery"] = `{"ok":false,"error_code":400,"description":"Bad Request: MESSAGE_TOO_LONG"}` + c.answerPress("q2", "Rain") + a := f.callsTo("answerCallbackQuery") + if len(a) != 3 || a[1].Params["text"] != "Rain" || a[2].Params["text"] != nil { + t.Fatalf("answers %+v", a) + } +} diff --git a/internal/telegram/client.go b/internal/telegram/client.go index dcffd2a..a85903e 100644 --- a/internal/telegram/client.go +++ b/internal/telegram/client.go @@ -299,7 +299,7 @@ func (c *Client) hello(ctx context.Context) error { func (c *Client) poll(ctx context.Context, offset int64) ([]update, error) { ctx, cancel := context.WithTimeout(ctx, pollWait+20*time.Second) defer cancel() - kinds := []string{"message", "edited_message", "my_chat_member"} + kinds := []string{"message", "edited_message", "my_chat_member", "callback_query"} if c.watch.Load() { kinds = append(kinds, "message_reaction", "chat_member") } diff --git a/internal/telegram/decode.go b/internal/telegram/decode.go index 2b7e182..130f946 100644 --- a/internal/telegram/decode.go +++ b/internal/telegram/decode.go @@ -21,12 +21,13 @@ import ( // update is one getUpdates result: the parts the bot reads. type update struct { - UpdateID int64 `json:"update_id"` - Message *message `json:"message"` - EditedMessage *message `json:"edited_message"` - MessageReaction *reactionUpd `json:"message_reaction"` - MyChatMember *memberUpd `json:"my_chat_member"` - ChatMember *memberUpd `json:"chat_member"` + UpdateID int64 `json:"update_id"` + Message *message `json:"message"` + EditedMessage *message `json:"edited_message"` + MessageReaction *reactionUpd `json:"message_reaction"` + MyChatMember *memberUpd `json:"my_chat_member"` + ChatMember *memberUpd `json:"chat_member"` + CallbackQuery *callbackQuery `json:"callback_query"` } type user struct { @@ -203,6 +204,8 @@ func (c *Client) event(u update) (bot.Received, bool) { return c.membership(u.ChatMember) case u.MessageReaction != nil && c.watch.Load(): return c.reacted(u.MessageReaction) + case u.CallbackQuery != nil: + return c.pressed(u.CallbackQuery) } return nil, false } diff --git a/internal/telegram/send.go b/internal/telegram/send.go index 3ee08c2..2f87531 100644 --- a/internal/telegram/send.go +++ b/internal/telegram/send.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "maps" "net/http" "strconv" "strings" @@ -49,9 +50,11 @@ type sentMsg struct { // under its own text, each @Name in known (lowercased name to ID) a text // mention, split at Telegram's limit, the pictures first with the reply as // their caption when it fits, the first message a reply to the bot's own -// message replyTo if it isn't 0 (sent anyway if that message is gone). It -// returns the IDs of the messages sent. A failure is logged. -func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64, audio []byte) (sent []int64) { +// message replyTo if it isn't 0 (sent anyway if that message is gone). mk's +// buttons, or in a DM its keyboard, go on the last message, which can't be +// an album, and with Silent every message is sent without a notification. +// It returns the IDs of the messages sent. A failure is logged. +func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64, audio []byte, mk feature.Markup) (sent []int64) { if n := utf8.RuneCountInString(text); n > maxReply { logx.Warnf("reply truncated from %d chars", n) } @@ -76,7 +79,11 @@ func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, know c := t caption = &c } - ids, err := c.sendPhotos(ctx, ch, pics, caption, known, replyTo) + var last any // the markup, if nothing follows the photo + if (caption != nil || len(t.Runes) == 0) && len(audio) == 0 { + last = markup(ch, mk) + } + ids, err := c.sendPhotos(ctx, ch, pics, caption, known, replyTo, mk.Silent, last) if err != nil { logx.Errorf("send failed: pictures: %v", err) // the text still goes } else if caption != nil { @@ -87,7 +94,11 @@ func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, know } } if len(audio) > 0 { // a voice message: it shows no title or performer - id, err := c.sendVoice(ctx, ch, audio, replyTo) + var last any // the markup, if no text follows the clip + if len(t.Runes) == 0 { + last = markup(ch, mk) + } + id, err := c.sendVoice(ctx, ch, audio, replyTo, mk.Silent, last) if err != nil { logx.Errorf("send failed: audio: %v", err) // the text still goes } else { @@ -99,13 +110,19 @@ func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, know logx.Warnf("empty reply, nothing sent") return nil } - for _, p := range parts { + for i, p := range parts { var m sentMsg d := c.dest(ch) params := d.params(map[string]any{"text": string(p.Runes), "entities": entities(p, known)}) if replyTo != 0 { params["reply_parameters"] = replyParams(replyTo) } + if mk.Silent { + params["disable_notification"] = true + } + if rm := markup(ch, mk); rm != nil && i == len(parts)-1 { + params["reply_markup"] = rm + } send := func() error { return c.call(ctx, "sendMessage", params, &m) } move := func(to string) { params["chat_id"] = to } err := c.retrying(ctx, d.chat, move, send) @@ -122,6 +139,40 @@ func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, know return sent } +// markup is mk as Telegram's reply_markup: its buttons as an inline +// keyboard, or in a DM its keyboard as a persistent reply keyboard, or that +// keyboard taken away; nil for none. +func markup(ch feature.Chat, mk feature.Markup) any { + switch { + case len(mk.Buttons) > 0: + return inlineKeyboard(mk.Buttons) + case ch.GroupID != "": + case len(mk.Keyboard) > 0: + rows := make([][]map[string]string, len(mk.Keyboard)) + for i, row := range mk.Keyboard { + for _, k := range row { + rows[i] = append(rows[i], map[string]string{"text": k.Label}) + } + } + return map[string]any{"keyboard": rows, "resize_keyboard": true, "is_persistent": true} + case mk.NoKeyboard: + return map[string]bool{"remove_keyboard": true} + } + return nil +} + +// inlineKeyboard is buttons as Telegram's InlineKeyboardMarkup, each +// button's Data its callback_data. +func inlineKeyboard(buttons [][]feature.Button) map[string]any { + rows := make([][]map[string]string, len(buttons)) + for i, row := range buttons { + for _, b := range row { + rows[i] = append(rows[i], map[string]string{"text": b.Label, "callback_data": b.Data}) + } + } + return map[string]any{"inline_keyboard": rows} +} + // replyParams are Telegram's reply_parameters for a reply to the message // id in the same chat, sent without the reply if that message is gone. func replyParams(id int64) map[string]any { @@ -222,9 +273,10 @@ func utf16Slice(rs []rune, u []int, start, n int) []rune { // sendPhotos sends pics, one as a photo or several as an album, with // caption on the first, without its entities if Telegram refuses them, as -// a reply to replyTo if it isn't 0, and returns the IDs of the messages -// sent. -func (c *Client) sendPhotos(ctx context.Context, ch feature.Chat, pics []feature.Picture, caption *mdstyle.Text, known map[string]string, replyTo int64) ([]int64, error) { +// a reply to replyTo if it isn't 0, without a notification if silent, and +// with rm as one photo's reply_markup if not nil (an album takes none), and +// returns the IDs of the messages sent. +func (c *Client) sendPhotos(ctx context.Context, ch feature.Chat, pics []feature.Picture, caption *mdstyle.Text, known map[string]string, replyTo int64, silent bool, rm any) ([]int64, error) { pics = pics[:min(len(pics), 10)] // an album's limit files := map[string][]byte{} for i, p := range pics { @@ -234,14 +286,22 @@ func (c *Client) sendPhotos(ctx context.Context, ch feature.Chat, pics []feature if caption != nil { ents = append(ents, entities(*caption, known)...) } - ids, err := c.sendPhotosOnce(ctx, ch, pics, files, caption, ents, replyTo) + extra := map[string]string{} + if silent { + extra["disable_notification"] = "true" + } + if rm != nil && len(pics) == 1 { + j, _ := json.Marshal(rm) + extra["reply_markup"] = string(j) + } + ids, err := c.sendPhotosOnce(ctx, ch, pics, files, caption, ents, replyTo, extra) if caption != nil && len(ents) > 0 && refusedEntities(err) { - ids, err = c.sendPhotosOnce(ctx, ch, pics, files, caption, []outEntity{}, replyTo) + ids, err = c.sendPhotosOnce(ctx, ch, pics, files, caption, []outEntity{}, replyTo, extra) } return ids, err } -func (c *Client) sendPhotosOnce(ctx context.Context, ch feature.Chat, pics []feature.Picture, files map[string][]byte, caption *mdstyle.Text, ents []outEntity, replyTo int64) ([]int64, error) { +func (c *Client) sendPhotosOnce(ctx context.Context, ch feature.Chat, pics []feature.Picture, files map[string][]byte, caption *mdstyle.Text, ents []outEntity, replyTo int64, extra map[string]string) ([]int64, error) { text := "" if caption != nil { text = string(caption.Runes) @@ -270,6 +330,7 @@ func (c *Client) sendPhotosOnce(ctx context.Context, ch feature.Chat, pics []fea rj, _ := json.Marshal(replyParams(replyTo)) fields["reply_parameters"] = string(rj) } + maps.Copy(fields, extra) err := c.retrying(ctx, d.chat, func(to string) { fields["chat_id"] = to }, func() error { return c.upload(ctx, method, fields, files, out) }) if err != nil { return nil, err @@ -285,14 +346,23 @@ func (c *Client) sendPhotosOnce(ctx context.Context, ch feature.Chat, pics []fea } // sendVoice sends audio, an MP3 clip, as a voice message, which plays in -// the chat and shows no title or performer, and returns its message ID. -func (c *Client) sendVoice(ctx context.Context, ch feature.Chat, audio []byte, replyTo int64) (int64, error) { +// the chat and shows no title or performer, without a notification if +// silent and with rm as its reply_markup if not nil, and returns its +// message ID. +func (c *Client) sendVoice(ctx context.Context, ch feature.Chat, audio []byte, replyTo int64, silent bool, rm any) (int64, error) { d := c.dest(ch) fields := d.fields(map[string]string{}) if replyTo != 0 { rj, _ := json.Marshal(replyParams(replyTo)) fields["reply_parameters"] = string(rj) } + if silent { + fields["disable_notification"] = "true" + } + if rm != nil { + j, _ := json.Marshal(rm) + fields["reply_markup"] = string(j) + } var m sentMsg err := c.retrying(ctx, d.chat, func(to string) { fields["chat_id"] = to }, func() error { return c.upload(ctx, "sendVoice", fields, map[string][]byte{"voice": audio}, &m) @@ -313,7 +383,7 @@ func (c *Client) React(ch feature.Chat, msg feature.Message, emoji string) { switch { case err == nil: case errors.As(err, &ae) && ae.Code == 400 && strings.Contains(ae.Desc, "REACTION_INVALID"): - c.Send(ch, emoji, nil, nil, 0, nil) + c.Send(ch, emoji, nil, nil, 0, nil, feature.Markup{}) default: logx.Errorf("reaction failed: %v", err) } diff --git a/internal/telegram/telegram_test.go b/internal/telegram/telegram_test.go index a9f8d82..636709d 100644 --- a/internal/telegram/telegram_test.go +++ b/internal/telegram/telegram_test.go @@ -296,7 +296,7 @@ func TestEdits(t *testing.T) { func TestSend(t *testing.T) { f := newFake(t) c := connected(f.client()) - ids := c.Send(feature.Chat{GroupID: groupS}, "πŸŽ‰ **big** news, see [docs](https://x.example) and @Alice", nil, map[string]string{"alice": "1111111"}, 0, nil) + ids := c.Send(feature.Chat{GroupID: groupS}, "πŸŽ‰ **big** news, see [docs](https://x.example) and @Alice", nil, map[string]string{"alice": "1111111"}, 0, nil, feature.Markup{}) if !reflect.DeepEqual(ids, []int64{500}) { t.Fatalf("ids %v", ids) } @@ -309,7 +309,7 @@ func TestSend(t *testing.T) { if string(got) != want { t.Fatalf("entities\n got %s\n want %s", got, want) } - c.Send(feature.Chat{User: "1111111"}, strings.Repeat("word ", 1700), nil, nil, 0, nil) + c.Send(feature.Chat{User: "1111111"}, strings.Repeat("word ", 1700), nil, nil, 0, nil, feature.Markup{}) if n := len(f.callsTo("sendMessage")); n != 3 { // 8500 chars, capped at 8000: two messages t.Fatalf("a long reply in %d messages", n-1) } @@ -320,7 +320,7 @@ func TestSend(t *testing.T) { } // Entities Telegram refuses: the text alone. f.errs["sendMessage"] = `{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities"}` - if ids := c.Send(feature.Chat{User: "1111111"}, "**x**", nil, nil, 0, nil); len(ids) != 1 { + if ids := c.Send(feature.Chat{User: "1111111"}, "**x**", nil, nil, 0, nil, feature.Markup{}); len(ids) != 1 { t.Fatalf("fallback ids %v", ids) } if last := f.callsTo("sendMessage"); last[len(last)-1].Params["entities"] != nil || last[len(last)-1].Params["text"] != "x" { @@ -336,14 +336,14 @@ func TestSendPictures(t *testing.T) { f.results["sendMediaGroup"] = `[{"message_id":602},{"message_id":603}]` c := connected(f.client()) png := []byte("\x89PNG\r\n\x1a\nxx") - if ids := c.Send(feature.Chat{User: "1111111"}, "NVDA β–Ό 15.2%", []feature.Picture{{Data: png}}, nil, 0, nil); !reflect.DeepEqual(ids, []int64{601}) { + if ids := c.Send(feature.Chat{User: "1111111"}, "NVDA β–Ό 15.2%", []feature.Picture{{Data: png}}, nil, 0, nil, feature.Markup{}); !reflect.DeepEqual(ids, []int64{601}) { t.Fatalf("ids %v", ids) } ph := f.callsTo("sendPhoto")[0] if ph.Params["caption"] != "NVDA β–Ό 15.2%" || string(ph.Files["p0"]) != string(png) || len(f.callsTo("sendMessage")) != 0 { t.Fatalf("photo %v", ph.Params) } - if ids := c.Send(feature.Chat{GroupID: groupS}, "", []feature.Picture{{Data: png}, {Data: png}}, nil, 0, nil); !reflect.DeepEqual(ids, []int64{602, 603}) { + if ids := c.Send(feature.Chat{GroupID: groupS}, "", []feature.Picture{{Data: png}, {Data: png}}, nil, 0, nil, feature.Markup{}); !reflect.DeepEqual(ids, []int64{602, 603}) { t.Fatalf("album ids %v", ids) } if mg := f.callsTo("sendMediaGroup")[0]; len(mg.Files) != 2 || !strings.Contains(mg.Params["media"].(string), `"attach://p1"`) { @@ -358,7 +358,7 @@ func TestSendReply(t *testing.T) { f := newFake(t) f.results["sendPhoto"] = `{"message_id":601}` c := connected(f.client()) - c.Send(feature.Chat{GroupID: groupS}, strings.Repeat("word ", 1700), nil, nil, 42, nil) + c.Send(feature.Chat{GroupID: groupS}, strings.Repeat("word ", 1700), nil, nil, 42, nil, feature.Markup{}) msgs := f.callsTo("sendMessage") if len(msgs) != 2 { t.Fatalf("%d messages", len(msgs)) @@ -370,14 +370,14 @@ func TestSendReply(t *testing.T) { t.Errorf("second part replies too: %v", msgs[1].Params["reply_parameters"]) } png := []byte("\x89PNG\r\n\x1a\nxx") - c.Send(feature.Chat{User: "1111111"}, strings.Repeat("x", maxCaption+1), []feature.Picture{{Data: png}}, nil, 43, nil) + c.Send(feature.Chat{User: "1111111"}, strings.Repeat("x", maxCaption+1), []feature.Picture{{Data: png}}, nil, 43, nil, feature.Markup{}) if ph := f.callsTo("sendPhoto")[0]; ph.Params["reply_parameters"] != `{"allow_sending_without_reply":true,"message_id":43}` { t.Errorf("photo's reply_parameters %v", ph.Params["reply_parameters"]) } if msgs := f.callsTo("sendMessage"); len(msgs) != 3 || msgs[2].Params["reply_parameters"] != nil { t.Errorf("the text after the photo replies too: %v", msgs[len(msgs)-1].Params) } - c.Send(feature.Chat{User: "1111111"}, "plain", nil, nil, 0, nil) + c.Send(feature.Chat{User: "1111111"}, "plain", nil, nil, 0, nil, feature.Markup{}) if msgs := f.callsTo("sendMessage"); msgs[len(msgs)-1].Params["reply_parameters"] != nil { t.Errorf("a plain send replies: %v", msgs[len(msgs)-1].Params) } @@ -474,7 +474,7 @@ func TestTokenNeverLogged(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() c.Run(ctx, func(bot.Received) {}) - c.Send(feature.Chat{User: "1"}, "hi", nil, nil, 0, nil) + c.Send(feature.Chat{User: "1"}, "hi", nil, nil, 0, nil, feature.Markup{}) out := logs.String() if !strings.Contains(out, "getMe failed") || !strings.Contains(out, "send failed") || strings.Contains(out, "SECRET") { t.Fatalf("logs %q", out) @@ -565,8 +565,8 @@ func TestEvents(t *testing.T) { t.Fatal("an event with no hook") } c.Watch(bot.Watch{Events: true}) - c.groupAllowed(context.Background(), groupS) // Alice is in it - c.Send(feature.Chat{GroupID: groupS}, "hello", nil, nil, 0, nil) // message 500, the bot's + c.groupAllowed(context.Background(), groupS) // Alice is in it + c.Send(feature.Chat{GroupID: groupS}, "hello", nil, nil, 0, nil, feature.Markup{}) // message 500, the bot's r, _ := c.event(parse(t, `{"update_id":2,"message_reaction":{`+inGroup+`,"message_id":500,"user":{"id":1111111,"first_name":"Alice"},"old_reaction":[{"type":"emoji","emoji":"πŸ‘"}],"new_reaction":[]}}`)) e := r.(bot.Happened).Event if e.Reaction == nil || e.Reaction.Emoji != "πŸ‘" || !e.Reaction.Removed || !e.Reaction.Bot || e.By.ID != "1111111" || e.Reaction.Sent != 500 { @@ -646,14 +646,14 @@ func TestSendPicturesFail(t *testing.T) { c := connected(f.client()) png := []byte("\x89PNG\r\n\x1a\nxx") f.errs["sendPhoto"] = `{"ok":false,"error_code":400,"description":"Bad Request: PHOTO_INVALID_DIMENSIONS"}` - if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0, nil); !reflect.DeepEqual(ids, []int64{500}) { + if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0, nil, feature.Markup{}); !reflect.DeepEqual(ids, []int64{500}) { t.Fatalf("ids %v", ids) } if s := f.callsTo("sendMessage"); len(s) != 1 || s[0].Params["text"] != "the caption" { t.Fatalf("text %v", s) } f.errs["sendPhoto"] = `{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities"}` - if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0, nil); !reflect.DeepEqual(ids, []int64{601}) { + if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0, nil, feature.Markup{}); !reflect.DeepEqual(ids, []int64{601}) { t.Fatalf("ids %v", ids) } ph := f.callsTo("sendPhoto") @@ -670,12 +670,12 @@ func TestSendRetries(t *testing.T) { c := connected(f.client()) f.errs["sendMessage"] = `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}` start := time.Now() - if ids := c.Send(feature.Chat{GroupID: groupS}, "hi", nil, nil, 0, nil); !reflect.DeepEqual(ids, []int64{500}) || time.Since(start) < time.Second { + if ids := c.Send(feature.Chat{GroupID: groupS}, "hi", nil, nil, 0, nil, feature.Markup{}); !reflect.DeepEqual(ids, []int64{500}) || time.Since(start) < time.Second { t.Fatalf("ids %v after %s", ids, time.Since(start)) } f.errs["sendMessage"] = `{"ok":false,"error_code":400,"description":"Bad Request: group chat was upgraded to a supergroup chat","parameters":{"migrate_to_chat_id":-1009999999999}}` - c.Send(feature.Chat{GroupID: "-4444444"}, "one", nil, nil, 0, nil) - c.Send(feature.Chat{GroupID: "-4444444"}, "two", nil, nil, 0, nil) + c.Send(feature.Chat{GroupID: "-4444444"}, "one", nil, nil, 0, nil, feature.Markup{}) + c.Send(feature.Chat{GroupID: "-4444444"}, "two", nil, nil, 0, nil, feature.Markup{}) var to []any for _, s := range f.callsTo("sendMessage")[2:] { to = append(to, s.Params["chat_id"]) @@ -715,7 +715,7 @@ func TestTopics(t *testing.T) { if m.Quote != nil || m.Text != "hi" { t.Fatalf("message %+v", m) } - c.Send(in.Chat, "hello", nil, nil, 0, nil) + c.Send(in.Chat, "hello", nil, nil, 0, nil, feature.Markup{}) if s := f.callsTo("sendMessage")[0].Params; s["chat_id"] != groupS || s["message_thread_id"] != float64(7) { t.Fatalf("sent %v", s) } @@ -745,7 +745,7 @@ func TestMigration(t *testing.T) { if gs, _ := c.Groups(context.Background(), "1111111"); len(gs) != 1 || gs[0].ID != "-1009999999999" { t.Fatalf("groups %v", gs) } - c.Send(feature.Chat{GroupID: "-4444444"}, "scheduled", nil, nil, 0, nil) + c.Send(feature.Chat{GroupID: "-4444444"}, "scheduled", nil, nil, 0, nil, feature.Markup{}) if s := f.callsTo("sendMessage")[0].Params; s["chat_id"] != "-1009999999999" { t.Fatalf("sent to %v", s["chat_id"]) } @@ -831,7 +831,7 @@ func TestSendVoice(t *testing.T) { f := newFake(t) f.results["sendVoice"] = `{"message_id":701}` c := connected(f.client()) - ids := c.Send(feature.Chat{GroupID: groupS}, "🎡 Song 1", nil, nil, 42, []byte("ID3 clip")) + ids := c.Send(feature.Chat{GroupID: groupS}, "🎡 Song 1", nil, nil, 42, []byte("ID3 clip"), feature.Markup{}) v := f.callsTo("sendVoice") if len(v) != 1 || v[0].Params["reply_parameters"] != `{"allow_sending_without_reply":true,"message_id":42}` { t.Fatalf("sendVoice %+v", v) From 324f806f7a534129b6318fb2e75409ae23713e16 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:20:45 +0000 Subject: [PATCH 5/5] Charts: points may have a time of day A line chart's point date may now be YYYY-MM-DD HH:MM (or with seconds, a T, or an offset), so the model can chart hourly or intraday data. Times are the wall-clock times written, whatever their offset. - Under 2 days of timed points, the time axis has hour ticks (a step of 1, 2, 3, 6 or 12 for at most 8), each midnight labelled with its date. - The high, low and last-value labels give the date and time, or the time alone when the chart is one day. - Charts of dates alone are unchanged, image for image. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- README.md | 2 +- internal/features/charts/chart.go | 81 +++++++++++++++++++++---- internal/features/charts/chart_test.go | 82 +++++++++++++++++++++++++- 3 files changed, 149 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 2baa6db..3411b39 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ A small, [privacy-conscious](PRIVACY.md) chat bot for Signal, through a running ## Features - Responds to @mentions, replies to its messages, and DMs from whitelisted contacts -- Tools: web search, line and pie charts, [pictures](docs/FILES_LINKS_TOOLS_MCP.md#images) (drawings, art, diagrams) with GPT Image 2, and your own [MCP connectors](docs/FILES_LINKS_TOOLS_MCP.md#mcp-connectors) +- Tools: web search, line charts (by day, or by the hour within a day) and pie charts, [pictures](docs/FILES_LINKS_TOOLS_MCP.md#images) (drawings, art, diagrams) with GPT Image 2, and your own [MCP connectors](docs/FILES_LINKS_TOOLS_MCP.md#mcp-connectors) - [`/schedule`](docs/SCHEDULING.md) a reminder or command, once or repeating - [Custom MCP servers](docs/FILES_LINKS_TOOLS_MCP.md#addons) such as [GeoGuess](https://github.com/robdevops/GeoGuess), [TriviaQuiz](https://github.com/robdevops/TriviaQuiz), [SongGuess](https://github.com/robdevops/SongGuess), or roll your own - Understands [files](docs/FILES_LINKS_TOOLS_MCP.md#files) (PDFs, text and code, Word, Excel and PowerPoint) and the [pages you link to](docs/FILES_LINKS_TOOLS_MCP.md#links), and if the model supports it, images, stickers, voice notes and other audio diff --git a/internal/features/charts/chart.go b/internal/features/charts/chart.go index 012bd1c..8baf3ec 100644 --- a/internal/features/charts/chart.go +++ b/internal/features/charts/chart.go @@ -52,7 +52,7 @@ var dualAxisToolSchema = json.RawMessage(`{ "axis": {"type": "string", "enum": ["left", "right"], "description": "Which Y axis the series uses (default left)"}, "points": {"type": "array", "minItems": 2, "maxItems": 1000, "items": { "type": "object", "required": ["date", "value"], - "properties": {"date": {"type": "string", "description": "YYYY-MM-DD"}, "value": {"type": "number"}} + "properties": {"date": {"type": "string", "description": "YYYY-MM-DD, or with a time of day for data within a day: YYYY-MM-DD HH:MM (24-hour, the data's local time)"}, "value": {"type": "number"}} }} } }} @@ -91,7 +91,7 @@ func oneAxis(dual json.RawMessage) json.RawMessage { } const ( - chartBody = "Use it when a chart of numbers would help, e.g. to show a trend or compare series; not for a diagram such as a flowchart, org chart or mind map. Pass the raw values: an axis shows them as given unless its mode is change, which computes the % change for you. " + + chartBody = "Use it when a chart of numbers would help, e.g. to show a trend or compare series; not for a diagram such as a flowchart, org chart or mind map. Give times for hourly or intraday data. Pass the raw values: an axis shows them as given unless its mode is change, which computes the % change for you. " + "The chart is sent alone with its title as the caption, so write no other text: it would be discarded." chartToolDescription = "Draw a line chart of one or more series over time, on one Y axis, and attach it to your reply as an image. " + "Choose the axis mode by what the chart is meant to show, for one series as much as several: change, which draws each series as % change from its first point, " + @@ -143,6 +143,8 @@ type chartSpec struct { Series []chartSeries `json:"series"` left, right *chartAxis + timed bool // some point has a time of day, not just a date + from, to time.Time // the time axis's span, once drawn } // axisShorthand is arguments with an axis given as just its title taken as @@ -267,11 +269,11 @@ func parseChart(tool string, dual bool, arguments string) (*chartSpec, error) { } for j := range sr.Points { p := &sr.Points[j] - t, err := time.Parse("2006-01-02", p.Date) - if err != nil { - return nil, fmt.Errorf("series %s: date %q is not YYYY-MM-DD", sr.Name, txt.Clamp(p.Date, 20)) + t, timed, ok := when(p.Date) + if !ok { + return nil, fmt.Errorf("series %s: date %q is not YYYY-MM-DD or YYYY-MM-DD HH:MM", sr.Name, txt.Clamp(p.Date, 30)) } - p.t = t + p.t, s.timed = t, s.timed || timed } sort.SliceStable(sr.Points, func(a, b int) bool { return sr.Points[a].t.Before(sr.Points[b].t) }) if s.axisOf(*sr).Mode == "change" { @@ -287,6 +289,38 @@ func parseChart(tool string, dual bool, arguments string) (*chartSpec, error) { return &s, nil } +// whenLayouts are the forms a point's date may take: a date, or a date +// and time of day, with or without seconds and an offset. +var whenLayouts = []string{"2006-01-02 15:04", "2006-01-02T15:04", "2006-01-02 15:04:05", "2006-01-02T15:04:05", time.RFC3339} + +// when is a point's date as a time, and whether it has a time of day. The +// time is the wall-clock time written, in UTC, whatever offset it had, so +// a chart shows the data's own local times. +func when(date string) (t time.Time, timed, ok bool) { + date = strings.TrimSpace(date) + if d, err := time.Parse("2006-01-02", date); err == nil { + return d, false, true + } + for _, layout := range whenLayouts { + if t, err := time.Parse(layout, date); err == nil { + return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.UTC), true, true + } + } + return time.Time{}, false, false +} + +// stamp is t as a label beside a value: its date for a chart of dates, its +// date and time for one with times, its time alone when all is one day. +func (s *chartSpec) stamp(t time.Time) string { + switch { + case !s.timed: + return t.Format("2 Jan 2006") + case s.from.YearDay() == s.to.YearDay() && s.from.Year() == s.to.Year(): + return t.Format("15:04") + } + return t.Format("2 Jan 15:04") +} + // format writes a value as the axis labels it. func (a *chartAxis) format(v float64, decimals int) string { if a.Mode == "change" { @@ -439,10 +473,12 @@ type dateTick struct { label string } -// dateTicks picks tick dates for the span: days for up to 10 days, the 1st -// and 15th for up to two months, months up to two years, then years. They are -// thinned to at most 8. -func dateTicks(from, to time.Time) []dateTick { +// dateTicks picks tick dates for the span: for points with times (timed) +// under 2 days, hours, a step of 1, 2, 3, 6 or 12 for at most 8, each +// midnight labelled with its date; else days for up to 10 days, the 1st +// and 15th for up to two months, months up to two years, then years. They +// are thinned to at most 8. +func dateTicks(from, to time.Time, timed bool) []dateTick { days := to.Sub(from).Hours() / 24 var ticks []dateTick add := func(t time.Time, label string) { @@ -451,6 +487,24 @@ func dateTicks(from, to time.Time) []dateTick { } } switch { + case timed && days < 2: + step := 12 + for _, h := range []int{1, 2, 3, 6, 12} { + if to.Sub(from).Hours()/float64(h) <= 7 { + step = h + break + } + } + for t := from.Truncate(time.Hour); !t.After(to); t = t.Add(time.Hour) { + if t.Hour()%step != 0 { + continue + } + label := t.Format("15:04") + if t.Hour() == 0 { + label = t.Format("2 Jan") + } + add(t, label) + } case days <= 10: for t := from; !t.After(to); t = t.AddDate(0, 0, 1) { add(t, t.Format("2 Jan")) @@ -838,6 +892,7 @@ func drawChart(s *chartSpec, th *theme) *canvas { values[a] = append(values[a], p.Value) } } + s.from, s.to = from, to s.left.layout(values[s.left], top, bottom) if two { s.right.layout(values[s.right], top, bottom) @@ -873,7 +928,7 @@ func drawChart(s *chartSpec, th *theme) *canvas { if two { cv.text(axisTitleFace, th.muted, labelX-10, top-14, 1, s.right.Title) } - for _, tk := range dateTicks(from, to) { + for _, tk := range dateTicks(from, to, s.timed) { x := px(tk.t) cv.line(th.muted, 1.5, x, bottom+14, x, bottom+24) cv.text(axisFace, th.muted, x, bottom+60, 0.5, tk.label) @@ -952,7 +1007,7 @@ func drawArea(cv *canvas, s *chartSpec, px func(time.Time) float64, bottom, left }{{hi, "High", !a.Invert}, {lo, "Low", a.Invert}} { p := pts[m.i] x, y := px(p.t), a.y(p.Value) - lines := [2]string{m.word + " " + a.format(p.Value, decimals), p.t.Format("2 Jan 2006")} + lines := [2]string{m.word + " " + a.format(p.Value, decimals), s.stamp(p.t)} cv.fill(th.title, circle(x, y, 6.5)) cv.fill(th.bg, circle(x, y, 4.5)) // Above the high and below the low (swapped on an inverted axis), @@ -999,7 +1054,7 @@ func drawArea(cv *canvas, s *chartSpec, px func(time.Time) float64, bottom, left if change != "" { cv.text(valueFace, c, x+14, y+22, 0, change) } - cv.text(markFace, th.muted, x+14, y+20+below, 0, last.t.Format("2 Jan 2006")) + cv.text(markFace, th.muted, x+14, y+20+below, 0, s.stamp(last.t)) } // textWidth is how wide s is in pixels in face f. diff --git a/internal/features/charts/chart_test.go b/internal/features/charts/chart_test.go index 0668582..6f08ae1 100644 --- a/internal/features/charts/chart_test.go +++ b/internal/features/charts/chart_test.go @@ -156,11 +156,11 @@ func TestDateTicks(t *testing.T) { {"2026-11-15", "2027-03-01", "Dec,Jan 2027,Feb,Mar"}, {"2020-06-01", "2023-06-01", "2021,2022,2023"}, } { - if got := labels(dateTicks(d(tc.from), d(tc.to))); got != tc.want { + if got := labels(dateTicks(d(tc.from), d(tc.to), false)); got != tc.want { t.Errorf("%s..%s: %q, want %q", tc.from, tc.to, got, tc.want) } } - if n := len(dateTicks(d("2000-01-01"), d("2026-01-01"))); n > 8 { + if n := len(dateTicks(d("2000-01-01"), d("2026-01-01"), false)); n > 8 { t.Errorf("%d year ticks, want at most 8", n) } } @@ -716,3 +716,81 @@ func TestAxisAsJSONString(t *testing.T) { t.Fatalf("a plain title: %+v", s.left) } } + +// A point's date may have a time of day, kept as the wall-clock time +// written, whatever its offset; anything else is refused. +func TestWhen(t *testing.T) { + for _, tc := range []struct { + in string + want string + timed bool + }{ + {"2026-11-24", "2026-11-24 00:00", false}, + {"2026-11-24 15:30", "2026-11-24 15:30", true}, + {"2026-11-24T15:30", "2026-11-24 15:30", true}, + {"2026-11-24 15:30:45", "2026-11-24 15:30", true}, + {"2026-11-24T15:30:00+11:00", "2026-11-24 15:30", true}, + {"2026-11-24T00:00:00Z", "2026-11-24 00:00", true}, + } { + got, timed, ok := when(tc.in) + if !ok || got.Format("2006-01-02 15:04") != tc.want || timed != tc.timed { + t.Errorf("%q: %v %v %v", tc.in, got, timed, ok) + } + } + for _, bad := range []string{"24/11/2026", "2026-11-24 25:00", "2026-11-24 3pm", ""} { + if _, _, ok := when(bad); ok { + t.Errorf("%q accepted", bad) + } + } + if _, err := parseChart(chartTool, false, `{"title":"T","series":[{"name":"A","points":[{"date":"2026-11-24 09:00","value":1},{"date":"2026-11-24 9am","value":2}]}]}`); err == nil || !strings.Contains(err.Error(), "YYYY-MM-DD HH:MM") { + t.Errorf("a bad time: %v", err) + } + s, err := parseChart(chartTool, false, `{"title":"T","series":[{"name":"A","points":[{"date":"2026-11-24","value":1},{"date":"2026-11-24 12:00","value":2}]}]}`) + if err != nil || !s.timed { + t.Errorf("dates and times mixed: %+v %v", s, err) + } +} + +// Under 2 days of timed points, ticks are hours, at most 8, midnight +// labelled with its date; dates alone keep their day ticks. +func TestHourTicks(t *testing.T) { + at := func(s string) time.Time { tm, _, _ := when(s); return tm } + labels := func(ts []dateTick) string { + var b []string + for _, tk := range ts { + b = append(b, tk.label) + } + return strings.Join(b, ",") + } + for _, tc := range []struct{ from, to, want string }{ + {"2026-11-24 09:00", "2026-11-24 15:00", "09:00,10:00,11:00,12:00,13:00,14:00,15:00"}, + {"2026-11-24 00:00", "2026-11-24 23:00", "24 Nov,06:00,12:00,18:00"}, + {"2026-11-23 12:00", "2026-11-25 00:00", "12:00,18:00,24 Nov,06:00,12:00,18:00,25 Nov"}, + } { + ticks := dateTicks(at(tc.from), at(tc.to), true) + if got := labels(ticks); got != tc.want || len(ticks) > 8 { + t.Errorf("%s to %s: %s", tc.from, tc.to, got) + } + } + if got := labels(dateTicks(at("2026-11-24"), at("2026-11-25"), false)); got != "24 Nov,25 Nov" { + t.Errorf("dates alone: %s", got) + } +} + +// A value's label is its date for dates, its date and time with times, +// its time alone within one day. +func TestStamp(t *testing.T) { + at := func(s string) time.Time { tm, _, _ := when(s); return tm } + s := &chartSpec{from: at("2026-11-24"), to: at("2026-11-30")} + if got := s.stamp(at("2026-11-25")); got != "25 Nov 2026" { + t.Errorf("dates: %q", got) + } + s.timed = true + if got := s.stamp(at("2026-11-25 14:00")); got != "25 Nov 14:00" { + t.Errorf("times over days: %q", got) + } + s.from, s.to = at("2026-11-24 00:00"), at("2026-11-24 23:00") + if got := s.stamp(at("2026-11-24 14:00")); got != "14:00" { + t.Errorf("one day: %q", got) + } +}