fix(gateway): do not answer a redelivered message twice

Making the store idempotent stopped redelivery duplicating the inbound
record, but nothing consulted that result: respond() saved the message,
ignored the fact that nothing had changed, and called the model anyway.
The cost was a second billed turn, any tool side effects run a second
time, and a second assistant reply appended -- replies carry no upstream
reference, so they always get a fresh identity and always append. The
stated problem, "a re-delivered update appends a duplicate turn", was
only half fixed.

PriorReply answers "have I already replied to this?" from the history
the caller has already loaded, and the chat path replays that answer
instead of regenerating it. A message with nothing after it was never
answered -- the turn may have died partway -- so that still runs, since
the user is owed a reply.

CanonicalMessageID exposes the store's own derivation rather than
letting the caller reimplement it, since a lookup that silently never
matches is indistinguishable from a message never seen.

Refs archie-core-i6q
This commit is contained in:
sam committed 2026-08-04 22:23:17 +10:00
1 parent 0fd3398cf8
commit f64353f0b5
3 files changed
+213 -3

No files matched your search

+18 -3
View File
@@ -155,13 +155,28 @@ func makeTelegramLLMResponder(ctx context.Context, tg *telegram.Gateway, s teleg
if err != nil {
return "", fmt.Errorf("resolve chat session: %w", err)
}
if err := sessionStore.SaveMessage(ctx, sk, msg); err != nil {
return "", fmt.Errorf("save inbound chat message: %w", err)
}
history, err := sessionStore.RecentMessages(ctx, sk, 100)
if err != nil {
return "", fmt.Errorf("load chat history: %w", err)
}
// A redelivered update must not be answered twice. The store already
// refuses to store the message again, but that alone changed
// nothing here: the model still ran, costing a second billed turn,
// running any tool side effects again, and appending a second reply
// (replies carry no upstream reference, so they always append).
// Replaying the answer we already gave is both cheaper and correct.
if prior := gateway.PriorReply(history, sk, msg.SourceID, s.Cfg.BotUser); prior != "" {
s.Log.Info("replaying the reply to a redelivered message",
"session", sk, "source_id", msg.SourceID)
if onDelta != nil {
onDelta(prior)
}
return prior, nil
}
if err := sessionStore.SaveMessage(ctx, sk, msg); err != nil {
return "", fmt.Errorf("save inbound chat message: %w", err)
}
history = append(history, msg)
// Chat turns were entirely unlogged, so a report of lost context had
// no evidence to check against: session id, history depth and the
// resolved persona are the three things needed to tell "wrong