feat(messaging): retract ephemeral replies after their TTL

An EphemeralReply is a status notice a channel delivers and then removes
once its TTL elapses, so a transient placeholder does not linger in the
chat history after it is superseded. The TTL lives on the reply, the
Delete capability joins AdapterCapabilities alongside Media, and
channels.EphemeralSender does the send-then-retract with an injected
clock. A sender that cannot delete still delivers the reply and logs the
missed retraction instead of failing the turn.

Telegram implements MessageDeleter through deleteMessage and honours the
mechanism for the "Archie reloaded." status notice; the pre-restart
"Reloading…" message remains the durable acknowledgement.
This commit is contained in:
sam committed 2026-10-02 09:36:16 +10:00
1 parent d240f4979a
commit 962678113a
9 files changed
+795 -7

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
package channels
import (
"context"
"log/slog"
"sync"
"time"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// defaultEphemeralDeleteTimeout bounds one retraction. It is independent of
// the turn's own context, which may already be cancelled by the time the TTL
// elapses: the message was sent, so it still has to be removed.
const defaultEphemeralDeleteTimeout = 30 * time.Second
// SendFunc delivers one message and returns the platform's view of it, with
// at least the identifier a later retraction addresses. A sender whose
// platform cannot name a delivered message leaves ID empty, and a retraction
// of that message is then skipped rather than attempted blindly.
type SendFunc func(ctx context.Context, event messaging.MessageEvent) (messaging.MessageEvent, error)
// EphemeralSender delivers EphemeralReplies and retracts them after their TTL.
//
// The retraction runs on its own goroutine, so a TTL that has not elapsed
// never holds the turn that sent the reply. after is injected so the TTL
// fires in tests without sleeping; nil selects time.After, which is the
// production shape.
type EphemeralSender struct {
after func(time.Duration) <-chan time.Time
timeout time.Duration
log *slog.Logger
wg sync.WaitGroup
}
// NewEphemeralSender returns a sender whose retractions wait on after.
func NewEphemeralSender(log *slog.Logger, after func(time.Duration) <-chan time.Time) *EphemeralSender {
if after == nil {
after = time.After
}
if log == nil {
log = slog.Default()
}
return &EphemeralSender{
after: after,
timeout: defaultEphemeralDeleteTimeout,
log: log,
}
}
// Send delivers reply.Event through send. When sender reports the Delete
// capability, the delivered message is retracted once reply.TTL elapses;
// otherwise the reply is left in place and the fact is logged once, at debug
// level. A platform that cannot delete must never fail the turn, so the
// degrade returns the send's outcome rather than an error.
//
// A send error is returned unchanged and no retraction is scheduled: there
// is no message to remove. A non-positive TTL or a send that reported no
// message identifier also schedules nothing.
func (e *EphemeralSender) Send(ctx context.Context, sender any, reply messaging.EphemeralReply, send SendFunc) (messaging.MessageEvent, error) {
sent, err := send(ctx, reply.Event)
if err != nil {
return sent, err
}
// A reply with no lifetime, or a send the platform could not name, has
// nothing to schedule: there is either no deadline or no message to
// address.
if reply.TTL <= 0 || sent.ID == "" {
return sent, nil
}
deleter, ok := messaging.DeleterOf(sender)
if !ok {
e.log.Debug("channel cannot retract an ephemeral reply; leaving it in place",
"platform", reply.Event.Platform, "type", reply.Event.Type)
return sent, nil
}
e.wg.Go(func() {
<-e.after(reply.TTL)
// The turn's context may already be cancelled by the time the TTL
// elapses -- a delivered message is still retracted -- so the
// retraction carries its own bounded, uncancellable context.
delCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), e.timeout)
defer cancel()
if err := deleter.DeleteMessage(delCtx, sent); err != nil {
e.log.Warn("ephemeral reply retraction failed",
"platform", reply.Event.Platform, "error", err)
}
})
return sent, nil
}
// Wait blocks until every retraction started so far has finished. Tests only:
// production callers never wait on a retraction's own TTL.
func (e *EphemeralSender) Wait() {
e.wg.Wait()
}
+261
View File
@@ -0,0 +1,261 @@
package channels
import (
"bytes"
"context"
"errors"
"log/slog"
"strings"
"sync"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// recordingDeleter is a sender that can retract messages. report controls the
// Delete capability it advertises, so a test can prove the caller trusts the
// capability rather than the method set.
type recordingDeleter struct {
report bool
mu sync.Mutex
deleted []string
err error
}
func (d *recordingDeleter) DeleteMessage(_ context.Context, event messaging.MessageEvent) error {
d.mu.Lock()
defer d.mu.Unlock()
d.deleted = append(d.deleted, event.ID)
return d.err
}
func (d *recordingDeleter) Capabilities() messaging.AdapterCapabilities {
return messaging.AdapterCapabilities{Delete: d.report}
}
func (d *recordingDeleter) deletions() []string {
d.mu.Lock()
defer d.mu.Unlock()
return append([]string(nil), d.deleted...)
}
// plainSender is a launch-scoped sender that offers no optional delivery
// behavior at all -- the shape every adapter that cannot delete has.
type plainSender struct{}
// syncBuffer is a bytes.Buffer safe for a log record written on a retraction
// goroutine while the test reads it.
type syncBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *syncBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *syncBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
func newDebugLogger(buf *syncBuffer) *slog.Logger {
return slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
}
// sentEvent returns a send func that reports the platform's delivered event,
// carrying id, so a retraction has something to address.
func sentEvent(id string) SendFunc {
return func(_ context.Context, event messaging.MessageEvent) (messaging.MessageEvent, error) {
event.ID = id
return event, nil
}
}
// An ephemeral reply must be retracted once its TTL elapses, not before, and
// the retraction must address the message the send actually delivered. The
// clock is injected, so the test proves the TTL ordering without sleeping.
func TestEphemeralSenderRetractsAfterTTL(t *testing.T) {
deleter := &recordingDeleter{report: true}
fire := make(chan time.Time)
var gotTTL time.Duration
sender := NewEphemeralSender(slog.New(slog.DiscardHandler), func(d time.Duration) <-chan time.Time {
gotTTL = d
return fire
})
sent, err := sender.Send(t.Context(), deleter, messaging.EphemeralReply{
Event: messaging.MessageEvent{Type: messaging.MsgText, Text: "running tool X…"},
TTL: 5 * time.Second,
}, sentEvent("42"))
if err != nil {
t.Fatalf("Send: %v", err)
}
if sent.ID != "42" {
t.Fatalf("Send returned ID %q, want the delivered id", sent.ID)
}
if got := deleter.deletions(); len(got) != 0 {
t.Fatalf("retracted %v before the TTL elapsed, want nothing yet", got)
}
fire <- time.Now()
sender.Wait()
got := deleter.deletions()
if len(got) != 1 || got[0] != "42" {
t.Fatalf("retracted %v, want exactly the delivered message 42", got)
}
if gotTTL != 5*time.Second {
t.Fatalf("scheduled retraction after %v, want the reply's TTL 5s", gotTTL)
}
}
// A platform with no delete support must still deliver the reply: the
// message is sent, left in place, and the capability gap is logged, never
// returned as a turn error.
func TestEphemeralSenderDegradesWhenSenderCannotDelete(t *testing.T) {
var buf syncBuffer
sender := NewEphemeralSender(newDebugLogger(&buf), func(time.Duration) <-chan time.Time {
t.Error("scheduled a retraction for a sender with no delete support")
return closedTimeChan()
})
sendCalled := false
_, err := sender.Send(t.Context(), &plainSender{}, messaging.EphemeralReply{
Event: messaging.MessageEvent{Type: messaging.MsgText, Text: "thinking…"},
TTL: time.Second,
}, func(_ context.Context, event messaging.MessageEvent) (messaging.MessageEvent, error) {
sendCalled = true
event.ID = "7"
return event, nil
})
if err != nil {
t.Fatalf("Send returned an error for a sender that cannot delete: %v", err)
}
if !sendCalled {
t.Fatal("the reply was not sent; it must degrade to a normal send")
}
sender.Wait()
if !strings.Contains(buf.String(), "cannot retract") {
t.Fatalf("log = %q, want it to record the missed retraction", buf.String())
}
}
// The capability is the contract, not the method set: an adapter that
// implements DeleteMessage but reports Delete:false must not be retracted.
func TestEphemeralSenderTrustsCapabilityOverMethodSet(t *testing.T) {
deleter := &recordingDeleter{report: false}
fire := make(chan time.Time)
close(fire) // fire at once if anything schedules a retraction
sender := NewEphemeralSender(slog.New(slog.DiscardHandler), func(time.Duration) <-chan time.Time {
return fire
})
if _, err := sender.Send(t.Context(), deleter, messaging.EphemeralReply{
Event: messaging.MessageEvent{Type: messaging.MsgText, Text: "thinking…"},
TTL: time.Second,
}, sentEvent("9")); err != nil {
t.Fatalf("Send: %v", err)
}
sender.Wait()
if got := deleter.deletions(); len(got) != 0 {
t.Fatalf("retracted %v despite Capabilities().Delete == false", got)
}
}
// A failed send has no message to retract, and its error belongs to the
// caller: Send returns it unchanged and schedules nothing.
func TestEphemeralSenderPropagatesSendError(t *testing.T) {
wantErr := errors.New("send refused")
deleter := &recordingDeleter{report: true}
sender := NewEphemeralSender(slog.New(slog.DiscardHandler), func(time.Duration) <-chan time.Time {
t.Error("scheduled a retraction for a message that was never sent")
return closedTimeChan()
})
_, err := sender.Send(t.Context(), deleter, messaging.EphemeralReply{
Event: messaging.MessageEvent{Type: messaging.MsgText, Text: "thinking…"},
TTL: time.Second,
}, func(context.Context, messaging.MessageEvent) (messaging.MessageEvent, error) {
return messaging.MessageEvent{}, wantErr
})
if !errors.Is(err, wantErr) {
t.Fatalf("Send error = %v, want %v", err, wantErr)
}
sender.Wait()
if got := deleter.deletions(); len(got) != 0 {
t.Fatalf("retracted %v after a failed send", got)
}
}
// A reply with no lifetime and one whose send reported no message id both
// schedule nothing: there is either no deadline or no message to address.
func TestEphemeralSenderSchedulesNothingWithoutTTLOrMessageID(t *testing.T) {
closed := closedTimeChan()
tests := []struct {
name string
ttl time.Duration
id string
}{
{name: "zero TTL", ttl: 0, id: "11"},
{name: "negative TTL", ttl: -time.Second, id: "11"},
{name: "no message id", ttl: time.Second, id: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
deleter := &recordingDeleter{report: true}
sender := NewEphemeralSender(slog.New(slog.DiscardHandler), func(time.Duration) <-chan time.Time {
return closed
})
if _, err := sender.Send(t.Context(), deleter, messaging.EphemeralReply{
Event: messaging.MessageEvent{Type: messaging.MsgText, Text: "thinking…"},
TTL: tt.ttl,
}, sentEvent(tt.id)); err != nil {
t.Fatalf("Send: %v", err)
}
sender.Wait()
if got := deleter.deletions(); len(got) != 0 {
t.Fatalf("retracted %v, want nothing scheduled", got)
}
})
}
}
// A retraction failure is logged, not returned: the reply was delivered, and
// a platform hiccup removing it later must not surface as a turn error.
func TestEphemeralSenderLogsRetractionFailure(t *testing.T) {
var buf syncBuffer
deleter := &recordingDeleter{report: true, err: errors.New("message not found")}
fire := make(chan time.Time)
close(fire)
sender := NewEphemeralSender(newDebugLogger(&buf), func(time.Duration) <-chan time.Time {
return fire
})
if _, err := sender.Send(t.Context(), deleter, messaging.EphemeralReply{
Event: messaging.MessageEvent{Type: messaging.MsgText, Text: "thinking…"},
TTL: time.Second,
}, sentEvent("13")); err != nil {
t.Fatalf("Send: %v", err)
}
sender.Wait()
if !strings.Contains(buf.String(), "retraction failed") {
t.Fatalf("log = %q, want it to record the failed retraction", buf.String())
}
}
func closedTimeChan() <-chan time.Time {
ch := make(chan time.Time)
close(ch)
return ch
}
+60
View File
@@ -0,0 +1,60 @@
package telegram
import (
"context"
"fmt"
"strconv"
"github.com/go-telegram/bot"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// telegramMessageDeleter removes messages the launch that built it sent,
// through the Bot API's deleteMessage method.
//
// It captures the *bot.Bot at construction rather than reading a Gateway
// field, matching telegramMediaSender and telegramApprover: a deleter belongs
// to the launch that built it, so a /restart abandons in-flight retractions
// with the outgoing bot instance instead of silently directing them through
// the new one.
type telegramMessageDeleter struct {
bot *bot.Bot
chatID int64
}
var (
_ messaging.MessageDeleter = (*telegramMessageDeleter)(nil)
_ messaging.CapabilityReporter = (*telegramMessageDeleter)(nil)
)
// NewMessageDeleter returns a MessageDeleter bound to one chat and to the bot
// instance of the launch that created it. Construct it per launch, from the
// same b that handled the update.
func (g *Gateway) NewMessageDeleter(b *bot.Bot, chatID int64) messaging.MessageDeleter {
return &telegramMessageDeleter{bot: b, chatID: chatID}
}
// Capabilities reports Delete support. Telegram can remove any message the
// bot sent in a chat it administers, so this is unconditionally true.
func (d *telegramMessageDeleter) Capabilities() messaging.AdapterCapabilities {
return messaging.AdapterCapabilities{Delete: true}
}
// DeleteMessage removes the message event names. The event's ID is the
// Telegram message ID the send returned; a non-numeric one cannot address a
// platform message, so it is reported rather than sent to the API as a
// doomed request.
func (d *telegramMessageDeleter) DeleteMessage(ctx context.Context, event messaging.MessageEvent) error {
id, err := strconv.Atoi(event.ID)
if err != nil {
return fmt.Errorf("telegram delete: message id %q is not numeric: %w", event.ID, err)
}
if _, err := d.bot.DeleteMessage(ctx, &bot.DeleteMessageParams{
ChatID: d.chatID,
MessageID: id,
}); err != nil {
return fmt.Errorf("telegram delete message %d: %w", id, err)
}
return nil
}
@@ -0,0 +1,60 @@
package telegram
import (
"context"
"fmt"
"time"
"github.com/go-telegram/bot"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// statusNoticeTTL is how long a transient status notice stays in the chat
// before it is retracted: long enough to be read, short enough not to become
// history next to the conversation it reported on.
const statusNoticeTTL = 8 * time.Second
// sendEphemeral delivers text and retracts it after statusNoticeTTL.
//
// The retraction is best-effort by contract: a platform that cannot delete
// leaves the notice in place (channels.EphemeralSender logs the degrade), and
// a failed send is logged rather than returned, because a status notice must
// never take the operation it narrates down with it.
func (g *Gateway) sendEphemeral(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) {
sender := g.newEphemeralSender()
_, err := sender.Send(ctx, g.NewMessageDeleter(b, chatID), messaging.EphemeralReply{
Event: messaging.MessageEvent{
Type: messaging.MsgText,
Text: text,
ChannelID: fmt.Sprintf("%d", chatID),
Platform: "telegram",
},
TTL: statusNoticeTTL,
}, func(ctx context.Context, event messaging.MessageEvent) (messaging.MessageEvent, error) {
id := g.sendTextMessage(ctx, b, chatID, messageThreadID, event.Text)
if id == 0 {
// Nothing was delivered, so there is nothing to name or retract.
return messaging.MessageEvent{}, nil
}
event.ID = fmt.Sprintf("%d", id)
return event, nil
})
if err != nil {
g.log.Error("ephemeral notice send failed", "error", err)
}
}
// sendTextMessage delivers one message and returns its Bot API message ID.
//
// It returns 0 for text that must be split across messages: a retraction
// addresses exactly one message, so a reply that does not fit in one is left
// intact rather than half-deleted.
func (g *Gateway) sendTextMessage(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) int {
blocks := markdownToBlocks(text)
if blockTextLen(blocks) > messageMaxLen {
g.sendMessage(ctx, b, chatID, messageThreadID, text)
return 0
}
return g.sendBlocks(ctx, b, chatID, messageThreadID, blocks, "send ephemeral message failed")
}
@@ -0,0 +1,160 @@
package telegram
import (
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/go-telegram/bot"
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
func newTestDeleter(t *testing.T, serverURL string, chatID int64) messaging.MessageDeleter {
t.Helper()
b, err := bot.New("1:test", bot.WithServerURL(serverURL), bot.WithSkipGetMe())
if err != nil {
t.Fatalf("new test bot: %v", err)
}
return New("1:test", []int64{42}, slog.New(slog.DiscardHandler)).NewMessageDeleter(b, chatID)
}
// The delete capability must be reported, so an ephemeral reply's retraction
// path can be chosen without attempting a doomed call.
func TestMessageDeleterReportsDeleteCapability(t *testing.T) {
_, srv := newMediaAPI()
defer srv.Close()
deleter := newTestDeleter(t, srv.URL, 555)
if caps := messaging.CapabilitiesOf(deleter); !caps.Delete {
t.Error("telegram message deleter does not report the Delete capability")
}
}
// A retraction must reach the Bot API's deleteMessage method with the chat and
// the message the send returned.
func TestMessageDeleterCallsDeleteMessage(t *testing.T) {
api, srv := newMediaAPI()
api.body = `{"ok":true,"result":true}`
defer srv.Close()
deleter := newTestDeleter(t, srv.URL, 555)
if err := deleter.DeleteMessage(t.Context(), messaging.MessageEvent{ID: "77"}); err != nil {
t.Fatalf("DeleteMessage: %v", err)
}
method, form := api.called()
if method != "deleteMessage" {
t.Fatalf("Bot API method = %q, want deleteMessage", method)
}
if form["message_id"] != "77" {
t.Errorf("message_id = %q, want 77", form["message_id"])
}
if form["chat_id"] != "555" {
t.Errorf("chat_id = %q, want the bound chat 555", form["chat_id"])
}
}
// A message ID the platform never issued cannot address a message, so it is
// reported before any request rather than sent as a doomed one.
func TestMessageDeleterRejectsNonNumericID(t *testing.T) {
api, srv := newMediaAPI()
api.body = `{"ok":true,"result":true}`
defer srv.Close()
deleter := newTestDeleter(t, srv.URL, 555)
if err := deleter.DeleteMessage(t.Context(), messaging.MessageEvent{ID: "not-a-number"}); err == nil {
t.Fatal("DeleteMessage accepted a non-numeric message ID")
}
if method, _ := api.called(); method != "" {
t.Fatalf("Bot API method = %q, want no request for an undeliverable ID", method)
}
}
// An API failure must surface as an error so the caller can log it; a failed
// retraction is never silent.
func TestMessageDeleterReportsAPIError(t *testing.T) {
api, srv := newMediaAPI()
api.body = `{"ok":false,"error_code":400,"description":"message to delete not found"}`
defer srv.Close()
deleter := newTestDeleter(t, srv.URL, 555)
if err := deleter.DeleteMessage(t.Context(), messaging.MessageEvent{ID: "404"}); err == nil {
t.Fatal("DeleteMessage reported success for a rejected request")
}
}
// sendEphemeral is the transport honouring an ephemeral reply end to end: it
// sends the status notice, then retracts the message the send returned once
// the injected clock's TTL fires. The injected sender keeps the test off a
// real eight-second wait.
func TestSendEphemeralRetractsStatusNotice(t *testing.T) {
type call struct {
method string
form map[string]string
}
calls := make(chan call, 8)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
method := parts[len(parts)-1]
_ = r.ParseMultipartForm(1 << 20)
form := map[string]string{}
for k, v := range r.Form {
if len(v) > 0 {
form[k] = v[0]
}
}
calls <- call{method: method, form: form}
w.Header().Set("Content-Type", "application/json")
if method == "deleteMessage" {
_, _ = w.Write([]byte(`{"ok":true,"result":true}`))
return
}
_, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":321}}`))
}))
defer srv.Close()
b, err := bot.New("1:test", bot.WithServerURL(srv.URL), bot.WithSkipGetMe())
if err != nil {
t.Fatalf("new test bot: %v", err)
}
g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler))
g.newEphemeralSender = func() *channels.EphemeralSender {
return channels.NewEphemeralSender(g.log, func(time.Duration) <-chan time.Time {
ch := make(chan time.Time)
close(ch)
return ch
})
}
g.sendEphemeral(t.Context(), b, 555, 0, "✅ Archie reloaded.")
var sent, retracted *call
deadline := time.After(2 * time.Second)
for sent == nil || retracted == nil {
select {
case c := <-calls:
switch c.method {
case "sendRichMessage", "sendMessage":
sent = &c
case "deleteMessage":
retracted = &c
}
case <-deadline:
t.Fatalf("timed out; send=%v retraction=%v", sent, retracted)
}
}
if retracted.form["message_id"] != "321" {
t.Errorf("retracted message_id = %q, want the sent message 321", retracted.form["message_id"])
}
if retracted.form["chat_id"] != "555" {
t.Errorf("retraction chat_id = %q, want the chat the notice was sent to", retracted.form["chat_id"])
}
}
+25 -7
View File
@@ -142,6 +142,12 @@ type Gateway struct {
// where the library's default endpoint is used. It exists so launch's
// wiring can be tested without reaching api.telegram.org.
serverURL string
// newEphemeralSender builds the retracting sender sendEphemeral uses.
// Defaults to channels.NewEphemeralSender; tests override it to inject a
// clock so a status notice's retraction fires without waiting out its
// TTL, matching liveReply's newMediaSender seam.
newEphemeralSender func() *channels.EphemeralSender
}
type UpdateService interface {
@@ -161,7 +167,7 @@ type ReleaseAnnouncer interface {
// New returns an unstarted Gateway. Call Start to begin long-polling.
func New(token string, allowedUserIDs []int64, log *slog.Logger) *Gateway {
return &Gateway{
g := &Gateway{
Token: token,
AllowedUserIDs: allowedUserIDs,
restartCh: make(chan restartRequest, 1),
@@ -174,6 +180,10 @@ func New(token string, allowedUserIDs []int64, log *slog.Logger) *Gateway {
pendingApprovals: make(map[string]*pendingApproval),
log: log.With("component", "gateway-telegram"),
}
g.newEphemeralSender = func() *channels.EphemeralSender {
return channels.NewEphemeralSender(g.log, nil)
}
return g
}
func (g *Gateway) Name() string { return "telegram" }
@@ -221,8 +231,12 @@ func (g *Gateway) Start(ctx context.Context, client messaging.ChatContract, life
return err
}
// Confirm to whoever asked, now that the new instance can send.
// It is a status notice, not a record: it retracts itself after a
// short TTL so it does not sit in the chat as a stale "reloaded"
// line. The pre-restart "Reloading…" message from the outgoing
// instance stays as the durable acknowledgement.
if req := g.pendingRestart; req != nil && req.chatID != 0 {
g.sendMessage(runCtx, b, req.chatID, req.threadID, "✅ Archie reloaded.")
g.sendEphemeral(runCtx, b, req.chatID, req.threadID, "✅ Archie reloaded.")
}
if g.pendingRestart != nil {
g.pendingRestart = nil
@@ -865,12 +879,14 @@ func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, mes
}
// sendBlocks delivers one message as a Telegram rich message built from
// structured blocks.
// structured blocks and returns the Bot API message ID, or 0 when nothing was
// delivered. The ID is what an EphemeralReply's retraction addresses; callers
// that only send ignore it.
//
// Rich messages are a recent Bot API addition, so a rejection here is treated
// as "unsupported" rather than fatal: fall back to sending the blocks as plain
// text so the user still receives the reply, unformatted, instead of silence.
func (g *Gateway) sendBlocks(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, blocks []models.InputRichBlock, errMsg string) {
func (g *Gateway) sendBlocks(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, blocks []models.InputRichBlock, errMsg string) int {
rich := &bot.SendRichMessageParams{
ChatID: chatID,
RichMessage: models.InputRichMessage{Blocks: blocks},
@@ -878,9 +894,9 @@ func (g *Gateway) sendBlocks(ctx context.Context, b *bot.Bot, chatID int64, mess
if messageThreadID != 0 {
rich.MessageThreadID = messageThreadID
}
if _, err := b.SendRichMessage(ctx, rich); err == nil {
if msg, err := b.SendRichMessage(ctx, rich); err == nil {
g.log.Debug("telegram message sent", "renderer", telegramRenderVersion, "mode", "rich")
return
return msg.ID
} else {
g.log.Warn("rich send failed, retrying unformatted", "error", err)
}
@@ -889,10 +905,12 @@ func (g *Gateway) sendBlocks(ctx context.Context, b *bot.Bot, chatID int64, mess
if messageThreadID != 0 {
plain.MessageThreadID = messageThreadID
}
if _, err := b.SendMessage(ctx, plain); err != nil {
if msg, err := b.SendMessage(ctx, plain); err != nil {
g.log.Error(errMsg, "error", err)
return 0
} else {
g.log.Warn("telegram message sent via plain fallback", "renderer", telegramRenderVersion, "mode", "plain")
return msg.ID
}
}
+45
View File
@@ -0,0 +1,45 @@
package messaging
import (
"context"
"time"
)
// EphemeralReply is a reply the sender delivers and then retracts once its
// TTL elapses. It is for status and progress placeholders ("thinking…",
// "running tool X…") that are only meaningful while a turn is in flight and
// should not linger in the chat history after they are superseded.
//
// TTL is measured from the moment the send succeeds. A non-positive TTL
// means the reply is not retracted, which keeps a normal message and an
// ephemeral one with no lifetime on the same path.
type EphemeralReply struct {
Event MessageEvent
TTL time.Duration
}
// MessageDeleter is the optional interface a sender implements to remove a
// message it previously sent. It is the delete counterpart of MediaSender,
// discovered the same way: callers read Capabilities().Delete first so a
// platform without delete support is never probed with a doomed call.
//
// DeleteMessage is addressed by the MessageEvent the send returned, so its
// ID must be the platform identifier for the message to remove. A sender
// that cannot name that identifier must not report the Delete capability.
type MessageDeleter interface {
DeleteMessage(ctx context.Context, event MessageEvent) error
}
// DeleterOf returns sender's MessageDeleter only when sender reports the
// Delete capability. A sender that implements the interface but reports
// Delete:false is treated as unable to delete -- the capability is the
// contract, not the method set -- and one that reports Delete:true without
// implementing the interface is treated the same way, so a mis-reporting
// adapter degrades instead of panicking.
func DeleterOf(sender any) (MessageDeleter, bool) {
if !CapabilitiesOf(sender).Delete {
return nil, false
}
deleter, ok := sender.(MessageDeleter)
return deleter, ok
}
@@ -0,0 +1,80 @@
package messaging
import (
"context"
"testing"
)
// deletableSender implements the delete contract and reports it.
type deletableSender struct{}
func (deletableSender) DeleteMessage(context.Context, MessageEvent) error { return nil }
func (deletableSender) Capabilities() AdapterCapabilities {
return AdapterCapabilities{Delete: true}
}
// misreportingSender implements DeleteMessage but denies the capability, so
// the capability -- not the method set -- is what callers must trust.
type misreportingSender struct{ deletableSender }
func (misreportingSender) Capabilities() AdapterCapabilities {
return AdapterCapabilities{}
}
// A claimed capability must agree with the implemented interface: the Delete
// flag is the caller's way to know, ahead of a type assertion, whether a
// retraction is worth attempting, and a mismatch makes that signal lie.
func TestAdapterCapabilitiesDeleteMatchesImplementedInterface(t *testing.T) {
tests := []struct {
name string
sender any
want bool
implements bool
}{
{name: "sender with delete support", sender: deletableSender{}, want: true, implements: true},
{name: "sender without delete support", sender: struct{}{}, want: false, implements: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
caps := CapabilitiesOf(tt.sender)
if caps.Delete != tt.want {
t.Errorf("CapabilitiesOf(%s).Delete = %v, want %v", tt.name, caps.Delete, tt.want)
}
_, implements := tt.sender.(MessageDeleter)
if implements != tt.implements {
t.Errorf("%s: MessageDeleter implementation = %v, want %v", tt.name, implements, tt.implements)
}
if caps.Delete != implements {
t.Errorf("%s: reported Delete (%v) disagrees with MessageDeleter implementation (%v)", tt.name, caps.Delete, implements)
}
})
}
}
func TestDeleterOf(t *testing.T) {
tests := []struct {
name string
sender any
want bool
}{
{name: "capability and interface agree", sender: deletableSender{}, want: true},
{name: "interface without capability", sender: misreportingSender{}, want: false},
{name: "neither capability nor interface", sender: struct{}{}, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
deleter, ok := DeleterOf(tt.sender)
if ok != tt.want {
t.Fatalf("DeleterOf(%s) ok = %v, want %v", tt.name, ok, tt.want)
}
if ok && deleter == nil {
t.Fatalf("DeleterOf(%s) reported ok with a nil deleter", tt.name)
}
if !ok && deleter != nil {
t.Fatalf("DeleterOf(%s) reported !ok with a non-nil deleter", tt.name)
}
})
}
}
@@ -15,6 +15,12 @@ type SendResult struct {
// implements.
type AdapterCapabilities struct {
Media bool
// Delete reports whether the sender can remove a message it
// previously sent (MessageDeleter), which is what lets an
// EphemeralReply be retracted once its TTL elapses. A sender that
// cannot delete still delivers ephemeral replies, it just leaves them
// in place.
Delete bool
}
// MediaSender delivers a MessageEvent carrying MediaAttachments through a