diff --git a/internal/channels/telegram/approval.go b/internal/channels/telegram/approval.go
index 2093d00ff..926e7d33e 100644
--- a/internal/channels/telegram/approval.go
+++ b/internal/channels/telegram/approval.go
@@ -17,14 +17,8 @@ import (
// from dangerousCmdPrefix so the two approval systems never collide.
const approvalCallbackPrefix = "approval:"
-// telegramApprover implements gateway.ApprovalRequester by rendering an
-// inline-button prompt in the chat it was built for and blocking until the
-// human decides, the context is cancelled, or the approval window elapses.
-//
-// It generalises the dangerous-command approval machinery: instead of
-// carrying an onApprove callback that executes a fixed command, a tool
-// approval carries a result channel that the callback handler signals, and
-// the blocked RequestApproval caller observes the decision.
+// telegramApprover implements gateway.ApprovalRequester with an inline-button
+// prompt, blocking until the human decides, ctx ends or the window elapses.
type telegramApprover struct {
gw *Gateway
bot *bot.Bot
@@ -59,11 +53,7 @@ var (
_ messaging.CapabilityReporter = (*telegramApprover)(nil)
)
-// Capabilities reports that this approver renders a native approval prompt.
-// It claims Approval only: clarify and picker have no native Telegram UI
-// wired yet, so claiming them would advertise an interaction this type
-// cannot carry. A caller that sees Clarify/Picker false uses the shared text
-// fallback instead of silently dropping the question.
+// Capabilities reports native approval only.
func (a *telegramApprover) Capabilities() messaging.AdapterCapabilities {
return messaging.AdapterCapabilities{Approval: true}
}
@@ -82,13 +72,8 @@ func (g *Gateway) NewApprover(b *bot.Bot, chatID int64, threadID int, recipient
}
}
-// RequestApproval asks the recipient to approve or deny action.
-//
-// A current permanent approval for the action short-circuits the prompt and
-// returns ApprovalPermanentlyApproved. Otherwise the recipient is shown the
-// three-button inline keyboard and the call blocks until the human decides,
-// the context is cancelled, or the 2-minute approval window
-// (messaging.ToolApprovalTimeout) elapses.
+// RequestApproval asks the recipient to approve action. A current permanent
+// approval returns ApprovalPermanentlyApproved without prompting.
func (a *telegramApprover) RequestApproval(ctx context.Context, action, description string) (messaging.ApprovalDecision, error) {
// Compose the lookup key so a permanent approval is scoped to
// the specific resource: "Approve Permanently" on "delete session
diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go
index 4bb5d1099..1c59963a8 100644
--- a/internal/channels/telegram/commands.go
+++ b/internal/channels/telegram/commands.go
@@ -28,11 +28,7 @@ var gatewayCommandSpecs = []commandSpec{
{Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name]
"},
{Command: "settings", Description: "Inspect or change runtime settings", Usage: "/settings [list|get |set = ...]"},
{Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] "},
- // /approve and /deny are Telegram's own dangerous-command approval surface:
- // dangerous.go lists the pending commands and the inline buttons decide.
- // The shared command specs use /approve for task approval instead, and
- // Telegram's exact-match handler shadows that path, so /help must describe
- // the Telegram meaning.
+ // On Telegram, /approve and /deny decide pending dangerous commands.
{Command: "approve", Description: "Show pending dangerous commands to approve", Usage: "/approve"},
{Command: "deny", Description: "Show pending dangerous commands to deny", Usage: "/deny"},
{Command: "start", Description: "Confirm that Archie is running", Usage: "/start"},
@@ -80,15 +76,8 @@ func gatewayHelpText() string {
return strings.TrimSpace(help.String())
}
-// commandScopes are the scopes the menu is published to.
-//
-// Telegram resolves a chat's menu by scope specificity, not recency: a
-// list set on all_private_chats wins over the default scope in every DM.
-// Publishing only to the default scope therefore leaves the bot showing
-// whatever a previous owner of the token registered against the narrower
-// scopes -- state that lives on Telegram's side and survives redeploys,
-// rewrites and migrations. Writing every scope we care about overwrites
-// those leftovers instead of being shadowed by them.
+// commandScopes are the scopes the command menu is published to. Publishing
+// to every scope overwrites menus left on narrower scopes.
var commandScopes = []models.BotCommandScope{
&models.BotCommandScopeDefault{},
&models.BotCommandScopeAllPrivateChats{},
diff --git a/internal/channels/telegram/dangerous.go b/internal/channels/telegram/dangerous.go
index 934aba2f2..234511711 100644
--- a/internal/channels/telegram/dangerous.go
+++ b/internal/channels/telegram/dangerous.go
@@ -274,11 +274,8 @@ func (g *Gateway) hasPermanentApproval(recipient int64, command string) bool {
return found
}
-// hasPermanentApprovalExact is the exact-match variant used by the tool
-// approval path. Prefix matching is appropriate for slash commands
-// (/rollback covers /rollback 3); it is not for tool-approval keys
-// composed of action + resource, where "delete session abc" must not
-// grant on "delete session abc2".
+// hasPermanentApprovalExact is the exact-match approval check for tool
+// approvals.
func (g *Gateway) hasPermanentApprovalExact(recipient int64, pattern string) bool {
g.dangerousMu.Lock()
defer g.dangerousMu.Unlock()
@@ -411,13 +408,8 @@ func rollbackApprovalText(num int) string {
// ── /stop handler ──────────────────────────────────────────────
-// stopCurrentTurn cancels whatever this conversation is currently doing.
-//
-// Cancellation propagates through the turn's context, so it reaches the
-// model stream and any tool running underneath it -- a shell command built
-// with exec.CommandContext is killed with the turn, which is the case that
-// matters. Whatever the reply had already streamed stays on screen: it is
-// the record of what Archie did before being stopped.
+// stopCurrentTurn cancels the conversation's running turn and any tool under
+// it. Streamed text stays.
func (g *Gateway) stopCurrentTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) {
var cancelled bool
var dropped int
@@ -440,11 +432,7 @@ func (g *Gateway) stopCurrentTurn(ctx context.Context, b *bot.Bot, msg *models.M
stopReport(cancelled, dropped, nil))
}
-// stopReport describes what a /stop actually stopped.
-//
-// It names the parts rather than saying "stopped" unconditionally.
-// Claiming success when nothing was running teaches the operator to
-// distrust the command at exactly the moment they need to believe it.
+// stopReport describes what a /stop stopped.
func stopReport(cancelled bool, dropped int, tasks []int64) string {
var parts []string
if cancelled {
@@ -479,15 +467,8 @@ func joinWithAnd(parts []string) string {
}
}
-// stopHandler serves /stop.
-//
-// Bare /stop is the emergency brake: it cancels the conversation's running
-// turn immediately, with no approval step. Approval exists to protect
-// against destructive commands, and stopping is the opposite -- gating it
-// behind a confirmation round-trip would defeat the entire point.
-//
-// /stop keeps the original behaviour of terminating a named
-// background process, which is destructive and still requires approval.
+// stopHandler serves /stop. Bare /stop cancels the running turn immediately;
+// /stop terminates a background process after approval.
func (g *Gateway) stopHandler(client messaging.ChatContract) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update)
@@ -580,11 +561,8 @@ func parseDangerousCallback(data string) (decision, token string) {
// ── /approve and /deny handlers ─────────────────────────────────
-// approveHandler serves /approve: list any pending dangerous commands,
-// or approve a specific one by token. When a pending command exists, the
-// user interacts via inline buttons rather than typing /approve directly;
-// this handler is for the edge case where a user types /approve without
-// a pending command context.
+// approveHandler serves /approve: lists pending dangerous commands or
+// approves one by token.
func (g *Gateway) approveHandler() bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update)
diff --git a/internal/channels/telegram/ephemeral.go b/internal/channels/telegram/ephemeral.go
index d94def032..32c6fabf5 100644
--- a/internal/channels/telegram/ephemeral.go
+++ b/internal/channels/telegram/ephemeral.go
@@ -10,14 +10,7 @@ import (
"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.
+// telegramMessageDeleter deletes messages through the bot it was built with.
type telegramMessageDeleter struct {
bot *bot.Bot
chatID int64
diff --git a/internal/channels/telegram/ephemeral_send.go b/internal/channels/telegram/ephemeral_send.go
index edcfb7356..885d8f71a 100644
--- a/internal/channels/telegram/ephemeral_send.go
+++ b/internal/channels/telegram/ephemeral_send.go
@@ -15,12 +15,8 @@ import (
// 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.
+// sendEphemeral sends text and deletes it after statusNoticeTTL. Failures are
+// logged.
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{
@@ -45,11 +41,8 @@ func (g *Gateway) sendEphemeral(ctx context.Context, b *bot.Bot, chatID int64, m
}
}
-// 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.
+// sendTextMessage sends one message and returns its ID, or 0 when the text
+// had to be split.
func (g *Gateway) sendTextMessage(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) int {
blocks := markdownToBlocks(text)
if blockTextLen(blocks) > messageMaxLen {
diff --git a/internal/channels/telegram/inboundmedia.go b/internal/channels/telegram/inboundmedia.go
index f6ab34661..dcada2fdb 100644
--- a/internal/channels/telegram/inboundmedia.go
+++ b/internal/channels/telegram/inboundmedia.go
@@ -111,11 +111,7 @@ func nilIfZero(v int64) *int64 {
return &v
}
-// maxInboundDownloadBytes is the Bot API download ceiling: bots cannot
-// fetch files larger than 20 MB through getFile, so a larger attachment
-// must be refused with a clear notice rather than met with a Bot API 400
-// nobody reads. It is the messaging contract's inbound attachment ceiling,
-// so the value the Gateway must be able to receive stays in one place.
+// maxInboundDownloadBytes is the Bot API download limit.
var maxInboundDownloadBytes int64 = messaging.MaxInboundAttachmentBytes
var errInboundMediaTooLarge = errors.New("file exceeds the bot download limit")
@@ -157,11 +153,8 @@ func (g *Gateway) downloadMedia(ctx context.Context, b *bot.Bot, att messaging.M
return data, nil
}
-// turnMessageText renders the text an inbound message's turn is built
-// from: plain text as received, or the attachment note plus caption when
-// the message carries a file. The note is what later turns read from
-// history, so a captioned photo whose caption alone would read as the
-// whole message ("what is this?") still names its attachment.
+// turnMessageText returns the message text, or the attachment note plus
+// caption for a message with a file.
func turnMessageText(msg *models.Message, media inboundMedia, hasMedia bool) string {
if !hasMedia {
return msg.Text
@@ -172,11 +165,8 @@ func turnMessageText(msg *models.Message, media inboundMedia, hasMedia bool) str
return media.note + "\n" + msg.Caption
}
-// unsupportedMediaNotice returns the refusal for content kinds Archie
-// cannot read, and "" for update content that is not a message to answer
-// at all -- a group member change or pin must stay silent, while a
-// sticker the sender meant Archie to react to must not disappear into the
-// void.
+// unsupportedMediaNotice returns the refusal for unreadable content, or ""
+// for updates that need no reply.
func unsupportedMediaNotice(msg *models.Message) string {
switch {
case msg.Sticker != nil:
diff --git a/internal/channels/telegram/interactive.go b/internal/channels/telegram/interactive.go
index e22956e4b..0fcc30b00 100644
--- a/internal/channels/telegram/interactive.go
+++ b/internal/channels/telegram/interactive.go
@@ -40,12 +40,8 @@ type replyResult struct {
err error
}
-// telegramInteractor carries clarify and picker interactions for one chat on
-// the channel's shared text fallback. Telegram renders no generic question or
-// single-choice widget in the agent-turn path, so both interactions appear as
-// text the human answers by replying; reporting the Clarify and Picker
-// capabilities is therefore honest, because the adapter can carry the
-// interaction even though it costs a typed answer.
+// telegramInteractor carries clarify and picker questions as plain text the
+// human replies to.
type telegramInteractor struct {
gw *Gateway
bot *bot.Bot
@@ -62,11 +58,7 @@ var (
_ messaging.CapabilityReporter = (*telegramInteractor)(nil)
)
-// Capabilities reports that this adapter can carry a clarify question and a
-// single-choice picker. Both go through the shared text fallback rather than a
-// native widget, and the capability is about carrying the interaction, not
-// about the widget, so claiming them is what keeps a question from being
-// silently dropped.
+// Capabilities reports clarify and picker support.
func (i *telegramInteractor) Capabilities() messaging.AdapterCapabilities {
return messaging.AdapterCapabilities{Clarify: true, Picker: true}
}
diff --git a/internal/channels/telegram/live.go b/internal/channels/telegram/live.go
index 304d84183..b286a7429 100644
--- a/internal/channels/telegram/live.go
+++ b/internal/channels/telegram/live.go
@@ -32,15 +32,8 @@ const (
// not deliver an attachment inline, so the user still gets the asset.
fallbackMediaLinePrefix = "📎 "
- // liveBodyMaxRunes bounds one mid-turn frame. Telegram rejects a
- // message over its character limit outright, so an unbounded frame
- // means every edit past that point fails and the live message freezes
- // at the last frame that fit -- for the rest of the turn, since the
- // buffer only grows. The bound is in runes rather than bytes because
- // the limit Telegram applies is a character count, not a byte count.
- //
- // Only the live frame is bounded. finalize sends the whole reply,
- // split across as many messages as it needs.
+ // liveBodyMaxRunes bounds one mid-turn frame below Telegram's message limit.
+ // finalize sends the full reply.
liveBodyMaxRunes = 3900
// Keep tool activity to a minority of a live frame so the answer remains
@@ -49,32 +42,8 @@ const (
liveToolMaxRunes = (liveBodyMaxRunes - 2) / 3
)
-// liveReply renders one chat turn into a single Telegram message as it is
-// generated, so the user watches the answer being written instead of waiting
-// on a silent "typing…" indicator.
-//
-// It keeps one canonical buffer and sends the whole of it on every update:
-// the first update creates the message, every later one edits that same
-// message. Editing has replace semantics, which is what makes a partial frame
-// impossible to append to the last one. (It previously streamed through
-// sendMessageDraft, whose drafts are ephemeral 30-second previews -- a tool
-// call longer than that outlived the preview, and successive frames were
-// observed concatenated, cursors and all.)
-//
-// Rendering is deliberately best-effort: it never blocks the generating
-// goroutine and never surfaces an error. The authoritative reply is the one
-// finalize writes when the turn completes -- if every live update failed,
-// the user simply sees the finished message appear the way it did before
-// streaming existed.
-//
-// A known, accepted trade-off of editing rather than sending: Telegram does
-// not change a message's date on edit, so the finished reply carries the
-// timestamp of the first streamed frame, not of finalize. A turn with a long
-// tool phase can therefore produce an answer timestamped before a user
-// message sent later, during that phase, and sort before the conversation
-// that produced it. Delete-and-resend on finalize would fix the ordering but
-// reintroduce the flicker/reorder streaming was built to avoid, so this is
-// left as-is rather than "fixed."
+// liveReply streams one chat turn into a single Telegram message, editing it
+// on each update. Rendering is best-effort; finalize writes the final reply.
type liveReply struct {
g *Gateway
b *bot.Bot
@@ -85,10 +54,6 @@ type liveReply struct {
interval time.Duration
// newMediaSender builds the MediaSender Media delivers through.
- // Defaults to g.NewMediaSender; tests override it to inject a sender
- // with fixed Capabilities(), which the real Telegram one can't
- // express (it always reports Media: true) but a future channel or a
- // capability-limited deployment might.
newMediaSender func(b *bot.Bot, chatID int64, threadID int) messaging.MediaSender
cancelRender context.CancelFunc
@@ -96,12 +61,7 @@ type liveReply struct {
renderDone chan struct{}
mu sync.Mutex
- // answerBuf is the assistant text streamed so far, in the order the
- // model produced it. Tool activity is not appended here: it is tracked
- // separately in toolLines so it can be kept whole and in front of the
- // answer at every rendering stage (mid-turn frame, abandon, finalize)
- // instead of scrolling out of the frame once the answer grows past the
- // live clamp.
+ // answerBuf is the streamed answer text; tool activity is kept in toolLines.
answerBuf strings.Builder
// toolLines holds the tool activity for this turn, in call order, so
// every rendering stage can lead with it rather than have it buried
@@ -116,27 +76,11 @@ type liveReply struct {
rendered string
messageID int
last time.Time
- // finalized is set once stopRendering returns, the single point every
- // finalize/abandon path funnels through to retire the renderer
- // goroutine. After that point requestRender is a silent no-op (a
- // non-blocking send into a channel nothing reads any more), so any
- // caller still trying to append to the live message after this point
- // -- Media's fire-and-forget delivery has its own 30s budget, far
- // longer than the turn's text usually takes -- must send its own
- // follow-up message instead of writing into a buffer nothing renders.
+ // finalized is set once rendering stops; later writers must send their own
+ // message.
finalized bool
- // terminal guards finalize and abandon so exactly one of them actually
- // runs its body. Without this, a turn finishing naturally (finalize)
- // and a concurrent Gateway.Stop (abandon, via abandonRestarted) can
- // both reach their own Telegram edit for the same message: both edits
- // go through, and whichever HTTP response Telegram processes last
- // decides what the user sees, nondeterministically -- including a
- // completed real answer getting silently overwritten by a restart
- // marker. The loser's call blocks until the winner's body returns
- // (sync.Once's own guarantee), then does nothing, so cleanup that must
- // happen exactly once (stopRendering, forgetLive) is never skipped or
- // duplicated regardless of which side wins.
+ // terminal ensures only one of finalize and abandon runs.
terminal sync.Once
}
@@ -163,22 +107,15 @@ func (g *Gateway) newLiveReply(ctx context.Context, b *bot.Bot, chatID int64, me
return live
}
-// resetLiveRegistry clears the previous launch's stopped mark. Called once
-// per launch, alongside rebuilding turns: a /restart's Stop marks the
-// registry stopped so nothing straggling from the outgoing bot instance
-// gets silently registered into it, but the incoming instance needs a live
-// registry of its own.
+// resetLiveRegistry clears the stopped mark at the start of a launch.
func (g *Gateway) resetLiveRegistry() {
g.liveMu.Lock()
g.liveStopped = false
g.liveMu.Unlock()
}
-// registerLive adds l to the set Stop drains on shutdown or restart. If a
-// drain already claimed the registry for this launch, l is abandoned
-// immediately instead of being registered: it arrived in the narrow window
-// between that claim and this call, and without this it would sit in no
-// registry, with nothing left to ever drain it.
+// registerLive adds l to the set Stop drains, or abandons it at once if the
+// registry is already stopped.
func (g *Gateway) registerLive(ctx context.Context, l *liveReply) {
g.liveMu.Lock()
if g.liveStopped {
@@ -193,36 +130,18 @@ func (g *Gateway) registerLive(ctx context.Context, l *liveReply) {
g.liveMu.Unlock()
}
-// forgetLive removes l from the registry. Called at the top of doFinalize
-// and doAbandon -- reached through l.terminal, so by the time this runs the
-// caller has already exclusively won the right to decide this reply's
-// outcome (see the terminal field doc) -- so a reply that completed on its
-// own is never picked up a second time by a later Stop, and a reply Stop
-// has already claimed is never double-processed.
+// forgetLive removes l from the registry.
func (g *Gateway) forgetLive(l *liveReply) {
g.liveMu.Lock()
defer g.liveMu.Unlock()
delete(g.liveReplies, l)
}
-// abandonAllLiveTimeout bounds how long Stop waits for in-flight replies to
-// be marked before giving up and returning anyway. A single stalled
-// Telegram API call must not hang gateway (and therefore daemon) shutdown
-// indefinitely; entries still in flight past this deadline keep running in
-// the background and finish (or die with the process) on their own.
+// abandonAllLiveTimeout bounds how long Stop waits for in-flight replies.
const abandonAllLiveTimeout = 5 * time.Second
-// abandonAllLive drops the cursor, marked as interrupted, on every turn
-// still streaming when the gateway stops or restarts. It exists because
-// nothing else guarantees this happens: cancelling turnCtx does not
-// guarantee the goroutine that owns a liveReply ever runs again to notice
-// and clean up after itself, and a full daemon process exit gives it no
-// chance to run at all, so this must not wait on that goroutine and must not
-// skip a reply just because its owning turn is still technically running.
-//
-// Marking liveStopped and draining the registry happen together, under the
-// same lock, so registerLive can never observe "stopped" without also
-// observing an empty-of-this-entry registry, or vice versa.
+// abandonAllLive marks every still-streaming reply as interrupted on stop or
+// restart, and stops the registry under the same lock.
func (g *Gateway) abandonAllLive(ctx context.Context) {
g.liveMu.Lock()
g.liveStopped = true
@@ -319,18 +238,7 @@ func (l *liveReply) Delta(text string) {
l.requestRender()
}
-// ToolCall appends one tool-activity line. It satisfies gateway.TurnStream.
-//
-// Tool activity is opt-in per deployment: without it the user cannot tell a
-// hallucinated action from a real one, but it also narrates every internal
-// step, which is noise in a conversation that is going fine.
-//
-// The name, parameters and summary all come from tool execution, not the
-// model's prose, and can carry raw Markdown metacharacters (a grep hit with
-// '*', a JSON parameter with '_' or backticks). They are escaped before
-// joining the line because the tool line and the model's reply share one
-// Markdown body (finalText): an unbalanced marker in the tool line breaks
-// parsing for the whole message, including the reply's own formatting.
+// ToolCall appends one escaped tool-activity line, when tool display is on.
func (l *liveReply) ToolCall(event messaging.ToolCallEvent) {
if !l.showToolCalls || event.Name == "" {
return
@@ -360,16 +268,7 @@ func (l *liveReply) ToolCall(event messaging.ToolCallEvent) {
l.requestRender()
}
-// countedToolLine marks a collapsed entry with how many calls it stands for.
-// The count belongs to the status, not to the preview, so it is inserted
-// before the preview separator rather than appended: "grep — done ×14 · 2
-// matches" counts calls, while "· 2 matches ×14" reads as counting matches.
-// toolLineSeparator joins tool lines. It ends each one with CommonMark's
-// hard-break marker rather than a blank line: a bare "\n" is a soft break,
-// which the block parser space-joins into one run-on paragraph, while a blank
-// line would insert a spacer block between every pair. A hard break gives
-// each line its own block AND suppresses the spacer, so a turn's activity
-// reads as consecutive lines instead of a double-spaced list.
+// toolLineSeparator ends each tool line with a Markdown hard break.
const toolLineSeparator = " \n"
func countedToolLine(line string, count int) string {
@@ -383,26 +282,11 @@ func countedToolLine(line string, count int) string {
return line + marker
}
-// mediaSendTimeout bounds one Media delivery. It is independent of the
-// render loop's own lifecycle (unlike answerBuf/toolLines, which a
-// /restart abandons via abandonAllLive): an upload in flight when the live
-// reply finalizes should still be allowed to land, since the asset is worth
-// delivering on its own even after the surrounding turn is done narrating.
+// mediaSendTimeout bounds one Media delivery, independent of the turn.
const mediaSendTimeout = 30 * time.Second
-// Media delivers the attachment through the media-specific Bot API, off the
-// generating goroutine: unlike Delta/ToolCall, this is a real network
-// upload, and TurnStream implementations must not block generation on one.
-// It satisfies gateway.TurnStream.
-//
-// An attachment carrying neither a URL to fetch nor a local Path to
-// upload is silently skipped: SendMedia would reject it as
-// invalid_message, there is nothing to fall back to, and Media has no
-// error return to report it through.
-//
-// This used to skip on a missing URL alone, which dropped every local
-// file before it reached the sender -- the guard, not just the sender,
-// was part of making a local path undeliverable.
+// Media uploads the attachment in the background. An attachment with no URL
+// or Path is skipped.
func (l *liveReply) Media(ctx context.Context, event messaging.MediaEvent) {
if event.Attachment.URL == "" && event.Attachment.Path == "" {
return
@@ -502,23 +386,9 @@ func (l *liveReply) markRendered(body string) {
l.mu.Unlock()
}
-// finalize replaces the live message with the turn's authoritative reply,
-// led by the tool activity that produced it, and drops the cursor. When
-// nothing was ever streamed -- a non-streaming provider, or a reply served
-// from the turn ledger -- it sends the reply as a new message instead.
-//
-// ctx is stripped of cancellation before anything is sent: the reply is
-// already decided and persisted by the time finalize runs, so a /stop
-// landing mid-finalize must not abort delivery the way it aborts the turn
-// itself -- that would strand the live message on a frame with the cursor
-// still attached, forever. Doing this inside finalize rather than trusting
-// each caller to pass a live context is what keeps this fix from silently
-// regressing the next time a caller is added.
-//
-// The actual work runs inside l.terminal so a concurrent abandon (a gateway
-// shutdown abandoning every in-flight reply while this turn is finishing
-// naturally, see Gateway.abandonAllLive) cannot send its own conflicting
-// edit for the same message -- see the terminal field doc.
+// finalize replaces the live message with the tool activity and the final
+// reply, or sends a new message if nothing streamed. It ignores ctx
+// cancellation and runs at most once.
func (l *liveReply) finalize(ctx context.Context, reply string) {
ctx = context.WithoutCancel(ctx)
l.terminal.Do(func() { l.doFinalize(ctx, reply) })
@@ -546,11 +416,8 @@ func (l *liveReply) doFinalize(ctx context.Context, reply string) {
return
}
- // The live message is one message, so an oversized reply keeps it as
- // the first part and sends the remainder after it. If the edit cannot
- // be delivered in either rich or plain form, send the complete reply
- // through the normal split path rather than losing the authoritative
- // answer behind a stale live frame.
+ // Edit the first part into the live message and send the rest; if the edit
+ // fails, send the whole reply.
parts := splitBlocks(markdownToBlocks(content), messageMaxLen)
if len(parts) == 0 {
l.abandonStopped(ctx)
@@ -572,17 +439,8 @@ func (l *liveReply) doFinalize(ctx context.Context, reply string) {
// immutable, so nothing can correct that impression after the fact.
const abandonMarker = "\n\n❌ _turn failed before finishing_"
-// abandon leaves a stopped turn readable: the partial text stays, but the
-// cursor goes, so the message does not claim to still be writing. A /stop is
-// a deliberate, acknowledged interruption, not a fault, so the partial is
-// left clean rather than marked as a failure.
-//
-// Like finalize, it strips ctx of cancellation before sending: abandon runs
-// precisely when a /stop has cancelled turnCtx, so honouring that
-// cancellation in the very edit meant to drop the cursor would leave the
-// cursor blinking on a message nothing will ever finish. And like finalize,
-// the actual work runs inside l.terminal -- see the terminal field doc and
-// finalize's.
+// abandon leaves a stopped turn's partial text without the cursor. It ignores
+// ctx cancellation and runs at most once.
func (l *liveReply) abandon(ctx context.Context) {
ctx = context.WithoutCancel(ctx)
l.terminal.Do(func() { l.doAbandon(ctx) })
@@ -605,18 +463,10 @@ func (l *liveReply) abandonFailed(ctx context.Context) {
l.abandon(ctx)
}
-// restartMarker distinguishes a gateway-restart abandon from both a clean
-// /stop (abandon) and a provider failure (abandonFailed): the turn was cut
-// off by an operational event rather than a fault in it or a deliberate
-// stop, and unlike either of those the user's message is still worth
-// resending once the gateway is back.
+// restartMarker marks a turn cut off by a gateway restart.
const restartMarker = "\n\n⚠️ _archie restarted before finishing -- send your message again_"
-// abandonRestarted leaves a turn interrupted by gateway shutdown or restart
-// readable and marked, for the same reason abandonFailed marks a provider
-// error: nothing will ever resume this turn, and an unmarked partial reads
-// as a finished answer either way. Called by Gateway.abandonAllLive, never
-// by the turn's own goroutine.
+// abandonRestarted marks a turn interrupted by a gateway stop or restart.
func (l *liveReply) abandonRestarted(ctx context.Context) {
l.mu.Lock()
l.answerBuf.WriteString(restartMarker)
@@ -676,27 +526,14 @@ func (l *liveReply) framedText(answer string) string {
return block + "\n\n" + l.clampAnswer(answer, budget)
}
-// clampAnswer cuts the answer to its budget, retaining the newest text and
-// marking the cut with a leading ellipsis.
-//
-// The marker matters on every frame, including the opening one. A turn that
-// streams a large first chunk, or that never opens a reply at all (so
-// messageID stays 0), would otherwise render text that appears to begin
-// mid-sentence with nothing to say a cut was made -- and Telegram messages are
-// immutable, so it can never be corrected afterwards.
+// clampAnswer keeps the newest budget runes of answer, prefixed with an
+// ellipsis when cut.
func (l *liveReply) clampAnswer(answer string, budget int) string {
return clampToRunes(answer, budget)
}
-// toolBlock returns the most recent activity that fits its deliberately
-// smaller frame budget, prefixed with a count of what was left out.
-//
-// The search runs from the newest line backwards, widening the window while
-// the result still fits, so EVERY line that fits is kept: returning as soon as
-// the newest line alone fits would discard history that was never over budget
-// and report a "+N earlier" that is simply untrue.
-//
-// The caller holds the lock.
+// toolBlock returns the newest tool lines that fit the budget, prefixed with
+// a count of the rest. The caller holds the lock.
func (l *liveReply) toolBlock() string {
if len(l.toolLines) == 0 {
return ""
@@ -748,19 +585,8 @@ func clampToRunes(s string, maxRunes int) string {
return "…" + string(runes[len(runes)-(maxRunes-1):])
}
-// finalText composes the finished message: the tool activity in the order it
-// happened, then the authoritative reply. The caller holds the lock.
-//
-// The reply is used rather than the streamed buffer because it is what the
-// turn actually returned and what was persisted to the conversation -- a
-// dropped or throttled frame cannot leave the visible message disagreeing
-// with the stored one.
-//
-// A turn that ran tools but produced no reply text still needs to say so:
-// the tool block alone reads as a completed answer that said nothing, and
-// Telegram messages are immutable, so nothing can correct it after the
-// fact. An empty reply with no tool activity either is left to the
-// content == "" path in finalize, which abandons instead of sending.
+// finalText returns the tool activity followed by reply, noting when tools
+// ran without a reply. The caller holds the lock.
func (l *liveReply) finalText(reply string) string {
reply = strings.TrimSpace(reply)
if len(l.toolLines) == 0 {
@@ -802,12 +628,8 @@ func (l *liveReply) open(ctx context.Context, blocks []models.InputRichBlock) {
l.mu.Unlock()
}
-// edit replaces the live message's content.
-//
-// Rich messages are a recent Bot API addition, and text is only optional on
-// an edit that carries one, so a server that rejects the rich body rejects
-// the whole edit. As with send, that is treated as "unsupported" rather than
-// fatal: retry unformatted so the user still gets the reply.
+// edit replaces the live message's content, retrying as plain text if the
+// rich body is rejected.
func (l *liveReply) edit(ctx context.Context, messageID int, blocks []models.InputRichBlock) error {
_, richErr := l.b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: l.chatID,
diff --git a/internal/channels/telegram/media.go b/internal/channels/telegram/media.go
index addc17387..3102d44ff 100644
--- a/internal/channels/telegram/media.go
+++ b/internal/channels/telegram/media.go
@@ -13,26 +13,9 @@ import (
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
-// telegramMediaSender delivers a MessageEvent's attachment through the
-// media-specific Bot API methods (sendVideo, sendPhoto, ...) rather than
-// sendMessage, which cannot carry a file at all.
-//
-// It captures the *bot.Bot at construction rather than reading the
-// Gateway's shared field, matching telegramApprover: a sender belongs to
-// the launch that built it, so a /restart abandons in-flight sends with
-// the outgoing bot instance instead of silently redirecting them through
-// the new one. That is the same lifetime rule the per-launch turns
-// registry documents.
-//
-// An attachment is delivered one of two ways, chosen by what it carries:
-// a URL is handed to Telegram to FETCH, while a Path is UPLOADED from this
-// host. Delivery used to be URL-only, which meant a locally produced file
-// was passed off as a URL Telegram could not fetch and the send did
-// nothing useful while reporting success.
-//
-// A MediaAttachment.FileID is still not accepted: it identifies a file on
-// the platform it was uploaded from and is meaningless as an outbound
-// handle here.
+// telegramMediaSender sends attachments through the media Bot API methods,
+// using the bot it was built with. A URL is fetched by Telegram; a Path is
+// uploaded. FileIDs are not accepted.
type telegramMediaSender struct {
bot *bot.Bot
chatID int64
@@ -118,19 +101,8 @@ var (
errTooLarge = errors.New("file exceeds the Telegram upload limit")
)
-// source builds the Bot API file value for att, and a function to release
-// whatever it holds open.
-//
-// A URL becomes an InputFileString, which tells Telegram to fetch it. A
-// local path becomes an InputFileUpload carrying an open *os.File, which
-// the library streams as multipart form data -- the only way bytes that
-// exist solely on this host can reach a chat.
-//
-// The size check happens here rather than being left to Telegram: over the
-// limit the API answers a bad request whose text nobody reads, and the
-// operator sees an attachment that never arrived. The returned error is
-// classified invalid_message by the caller, so it is not retried -- a
-// file does not get smaller on a second attempt.
+// source returns the Bot API file for att and a release function. It refuses
+// a local file over the size limit.
func (s *telegramMediaSender) source(att messaging.MediaAttachment) (models.InputFile, func(), error) {
noop := func() {}
if att.Path == "" {
@@ -222,15 +194,8 @@ func invalidMedia(err error) (messaging.SendResult, error) {
}, err
}
-// classifySendError maps a Bot API failure onto SendResult's error
-// vocabulary so a caller can decide on retry without inspecting
-// Telegram-specific errors.
-//
-// The library reports API failures as sentinel errors (bot.ErrorBadRequest
-// and friends), not as typed values, so these are errors.Is checks. A
-// failure matching no sentinel is a transport error or a 5xx, both of
-// which may yet succeed -- hence retryable, rather than defaulting to
-// permanent and silently dropping a deliverable asset.
+// classifySendError maps a Bot API error to a SendResult. Unrecognised errors
+// are retryable.
func classifySendError(err error) messaging.SendResult {
res := messaging.SendResult{Success: false, Error: err}
diff --git a/internal/channels/telegram/ratelimit.go b/internal/channels/telegram/ratelimit.go
index 4cb63aadd..bc1e61fe3 100644
--- a/internal/channels/telegram/ratelimit.go
+++ b/internal/channels/telegram/ratelimit.go
@@ -8,12 +8,6 @@ import (
)
// pipelineErrorHandler logs update-loop failures.
-//
-// go-telegram/bot v1.24.0 fixed getUpdates to honour retry_after on a 429
-// itself (https://github.com/go-telegram/bot/releases/tag/v1.24.0), instead
-// of retrying on its own 100ms-doubling-to-5s schedule regardless of what
-// Telegram asked for. This handler used to block for RetryAfter itself to
-// compensate; that workaround is gone now that the library does it.
func (g *Gateway) pipelineErrorHandler(_ context.Context) func(error) {
return func(err error) {
if tooMany, ok := errors.AsType[*bot.TooManyRequestsError](err); ok {
diff --git a/internal/channels/telegram/restart.go b/internal/channels/telegram/restart.go
index 8907ea9b7..963b28c81 100644
--- a/internal/channels/telegram/restart.go
+++ b/internal/channels/telegram/restart.go
@@ -14,13 +14,8 @@ type restartRequest struct {
threadID int
}
-// restartHandler serves /restart: an operator escape hatch for reloading
-// config (notably the sender allowlist) or recovering a wedged adapter
-// without shell access to the host.
-//
-// Authorisation is inherited: authorizedMessage rejects anyone outside
-// AllowedUserIDs before this runs, so reaching it already implies an
-// allowlisted sender.
+// restartHandler serves /restart, relaunching the bot to reload config. Only
+// allowlisted senders reach it.
func (g *Gateway) restartHandler() bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update)
@@ -28,11 +23,7 @@ func (g *Gateway) restartHandler() bot.HandlerFunc {
return
}
- // Restarting tears down this process, and the update installer runs
- // as its child -- a restart mid-install kills the install outright
- // (signal: terminated) rather than letting it finish or fail
- // cleanly, leaving the daemon on its old binary with no clear error
- // surfaced to the operator.
+ // Refuse to restart while an update is installing.
g.updateMu.Lock()
updating := g.updateInProgress
g.updateMu.Unlock()
diff --git a/internal/channels/telegram/richblocks.go b/internal/channels/telegram/richblocks.go
index bea711566..81e9eb3b4 100644
--- a/internal/channels/telegram/richblocks.go
+++ b/internal/channels/telegram/richblocks.go
@@ -9,11 +9,8 @@ import (
"github.com/go-telegram/bot/models"
)
-// Telegram's rich-message renderer has no ATX heading support and its
-// MarkdownV2 dialect needs escaping, so rather than translating Markdown into a
-// format it only partially implements we emit structured blocks the renderer
-// supports natively. Inline emphasis/code/links are reduced to plain text so no
-// Markdown marker can survive into the rendered message.
+// Markdown is rendered as Telegram rich blocks, with inline formatting
+// reduced to plain text.
var (
inlineLinkHTML = regexp.MustCompile(`\[([^\]]*)\]\(([^)]+)\)`)
@@ -114,11 +111,8 @@ func stripInlineMarkdown(s string) string {
return codeBlockMark.ReplaceAllString(s, "$1")
}
-// stripEmphasis removes paired emphasis delimiters and keeps their content.
-// Pairing follows CommonMark's flanking rules, so a delimiter that cannot open
-// or close is ordinary text and stays put.
-// *sql.Tx all used to lose characters to a non-greedy `_(.+?)_` that paired
-// any two markers on a line.
+// stripEmphasis removes paired emphasis delimiters, keeping their content,
+// using CommonMark's flanking rules.
func stripEmphasis(s, marker string) string {
var b strings.Builder
for i := 0; i < len(s); {
@@ -181,13 +175,8 @@ func flanksOf(s string, i, j int) delimiterFlanks {
}
// flanking reports whether the delimiter run s[i:j] may open or close
-// emphasis. The rules are CommonMark's, including the one that an underscore
-// may do neither inside a word.
-//
-// Single "*" carries one deliberate deviation: it may not open on
-// punctuation. CommonMark reads "*.go files in cmd/*" as emphasis, which in a
-// relay carrying shell globs and pointer types corrupts far more text than a
-// stray marker would. Emphasis opening on a word still works.
+// emphasis, per CommonMark, except that a single "*" may not open on
+// punctuation.
func flanking(s string, i, j int, marker string) (canOpen, canClose bool) {
f := flanksOf(s, i, j)
switch marker {
@@ -286,19 +275,8 @@ func (p *markdownBlockParser) handleLine(line string) {
case trimmed == "":
p.flush()
default:
- // A normal line ends a list or quote block and continues a
- // paragraph. Joined with a space, not "\n": this is a CommonMark
- // soft line break, and Telegram's rich-block paragraph text does
- // not render an embedded "\n" as a break at all -- it renders
- // nothing, jamming the two lines together with no separator
- // whatsoever. A space is the correct soft-break rendering anyway
- // and survives regardless of how the client treats a literal "\n".
- //
- // A line that ended in a hard break is the exception: the producer
- // said it is a line, so it closes its own block and the next one
- // hugs it. Line-oriented reports (/status, /tasks) depend on this;
- // without it every one of their lines soft-joined into one run-on
- // paragraph.
+ // A normal line ends a list or quote and continues the paragraph with a
+ // space. A line ending in a hard break closes its own block.
p.flushList()
p.flushQuote()
switch {
@@ -412,14 +390,8 @@ func (p *markdownBlockParser) flush() {
p.flushParagraph()
}
-// appendBlock adds block to the output. Telegram's rich-block renderer adds
-// no vertical gap between adjacent blocks on its own -- only a heading
-// carries its own margin -- so two blocks from source lines with no blank
-// line between them (an intro line immediately followed by a list, two
-// back-to-back paragraphs) render glued together with no visible break at
-// all. An empty paragraph spacer before any non-heading-following block
-// makes that gap explicit instead of relying on client-side spacing that
-// doesn't exist.
+// appendBlock adds block, preceded by an empty paragraph as a spacer unless
+// it follows a heading.
func (p *markdownBlockParser) appendBlock(block models.InputRichBlock) {
tight := p.tightNext
p.tightNext = false
diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go
index f1206fa2b..2272c8b02 100644
--- a/internal/channels/telegram/telegram.go
+++ b/internal/channels/telegram/telegram.go
@@ -28,11 +28,8 @@ import (
// Gateway is a Telegram gateway.Gateway backed by go-telegram/bot.
type Gateway struct {
Token string
- // AllowedUserIDs lists the Telegram user IDs allowed to use the bot,
- // matched against the sender rather than the chat so the bot cannot be
- // reached by adding it to a group. Empty denies everyone: a bot handle
- // is public, and chat tools run with the daemon's authority, so failing
- // open would expose those tools to any stranger who finds the bot.
+ // AllowedUserIDs lists the sender IDs allowed to use the bot. Empty denies
+ // everyone.
AllowedUserIDs []int64
// Reload re-reads configuration during /restart and applies it to g.
// Supplied by the composition root, which owns config paths. Nil
@@ -54,22 +51,12 @@ type Gateway struct {
// identity. Nil deliberately permits reads but makes writes fail closed.
ResolveActor func(int64) (string, bool)
- // UpdateReportPath is where the update watchdog (see
- // scripts/archie-update-watchdog) leaves the phase-2 outcome of an
- // update -- whether the restarted daemon came up healthy or was rolled
- // back. Checked and relayed on every gateway launch (process boot and
- // /restart alike), same as ReleaseAnnouncements. Empty disables it.
+ // UpdateReportPath is where the update watchdog leaves an update's outcome,
+ // relayed on each launch. Empty disables it.
UpdateReportPath string
- // RunningVersions reports, per component ID (see
- // releaseupdate.ComponentDaemon), the version that component reports for
- // itself rather than the version an installer claimed to install. It is
- // what turns a pending update report from a self-reported claim into a
- // checked one: the daemon's own compiled-in build version cannot be
- // talked out of being what is actually running. Only components that can
- // genuinely self-report belong here -- a guess would re-introduce
- // exactly the false success this check exists to catch. Nil leaves every
- // claim unverified.
+ // RunningVersions reports the version each component reports for itself, to
+ // verify update reports. Nil leaves claims unverified.
RunningVersions func() map[string]string
// Dangerous is the sandbox/process authority for /rollback and /stop.
@@ -121,24 +108,14 @@ type Gateway struct {
// liveMu guards liveReplies and liveStopped.
liveMu sync.Mutex
- // liveReplies tracks every liveReply currently mid-turn. Cancelling
- // turnCtx (a /restart, a daemon shutdown) does not guarantee the
- // goroutine that owns a liveReply ever runs again to notice and clean
- // up after itself -- a full process exit gives it no chance at all --
- // so Stop drains this registry directly rather than waiting on that
- // goroutine. See abandonAllLive. The map itself survives a /restart
- // (only turns above is rebuilt per launch); liveStopped is what scopes
- // draining to one launch's lifecycle.
+ // liveReplies tracks in-flight live replies so Stop can abandon them.
liveReplies map[*liveReply]struct{}
// liveDrainTimeout bounds abandonAllLive's wait for in-flight replies to
// be marked. Zero uses abandonAllLiveTimeout; tests shrink it so a
// deliberately-hung reply doesn't make the suite slow.
liveDrainTimeout time.Duration
- // liveStopped is set the instant abandonAllLive claims the registry, so
- // a newLiveReply that arrives in the narrow window between that claim
- // and its caller actually registering is abandoned immediately instead
- // of being added to a registry nothing will ever drain again. Reset to
- // false at the start of the next launch.
+ // liveStopped is set when abandonAllLive claims the registry, and reset at
+ // the next launch.
liveStopped bool
log *slog.Logger
@@ -218,12 +195,7 @@ func (g *Gateway) RequestRestart() error {
}
}
-// Start supervises the bot: it launches an instance and relaunches it
-// whenever a restart is requested, blocking until ctx is cancelled.
-//
-// Restarts are scoped to this gateway. The daemon keeps running, so
-// in-flight agent tasks are untouched -- the whole point of the escape
-// hatch is to recover chat without disturbing work in progress.
+// Start runs the bot and relaunches it on restart requests until ctx ends.
func (g *Gateway) Start(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) error {
if g.Token == "" {
return fmt.Errorf("telegram bot token is required")
@@ -238,11 +210,7 @@ func (g *Gateway) Start(ctx context.Context, client messaging.ChatContract, life
cancel()
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.
+ // Confirm the restart with a self-deleting notice.
if req := g.pendingRestart; req != nil && req.chatID != 0 {
g.sendEphemeral(runCtx, b, req.chatID, req.threadID, "✅ Archie reloaded.")
}
@@ -612,19 +580,8 @@ func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models
}
}
-// submitTurn hands the message to its session's turn lane and returns at
-// once, leaving the bot's single update worker free.
-//
-// The turn must not run on the caller's goroutine. go-telegram/bot serves
-// updates from one worker that invokes handlers synchronously, so a turn
-// running here would block delivery of every later update -- including the
-// /stop meant to cancel it, which would sit unread until the turn it was
-// aimed at had already finished.
-// turnInbound renders a Telegram message as the channel-neutral inbound a
-// chat turn is built from, with media attachments attached. ok is false
-// for messages with neither text nor media, which are not turns at all.
-// media/hasMedia are the caller's already-extracted attachment, so the
-// caller keeps the voice-note flag it needs without extracting twice.
+// turnInbound converts a Telegram message into an inbound turn. ok is false
+// for messages with no text or media.
func turnInbound(msg *models.Message, media inboundMedia, hasMedia bool) (messaging.Inbound, bool) {
if !hasMedia && msg.Text == "" {
return messaging.Inbound{}, false
@@ -632,11 +589,7 @@ func turnInbound(msg *models.Message, media inboundMedia, hasMedia bool) (messag
gm := messaging.Inbound{
Platform: "telegram",
Message: messaging.Message{
- // Telegram's message ID makes persistence idempotent: the store
- // derives a canonical ID from it, so a redelivered update is a
- // no-op rather than appending a duplicate or overwriting the
- // stored record, which must stay immutable. Date is the sender's
- // clock reading and is what history should be ordered by.
+ // The message ID makes redelivery idempotent.
SourceID: fmt.Sprintf("%d", msg.ID),
ConversationID: conversationID(msg),
Sender: msg.From.Username,
@@ -704,26 +657,9 @@ func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Messag
})
}
-// drainTurnEvents consumes a streamed turn, rendering deltas, tool calls
-// and media as they arrive, and returns the final reply.
-//
-// A cancelled turn is a /stop, not a fault. The stop handler has already
-// acknowledged it, and turnCtx is dead, so there is
-// nothing useful left to send from here -- but whatever was
-// already streamed stays, minus the cursor that would otherwise
-// claim the answer is still being written. abandon strips turnCtx's
-// own cancellation before it edits, so the cursor-drop is not itself
-// aborted by the /stop that triggered it.
-//
-// errors.Is(err, context.Canceled) reliably separates a /stop from a
-// fault; either way turnCtx is dead by the time we get here. A
-// genuine fault is marked as failed rather than left as a clean
-// partial: /stop is an acknowledged interruption, a provider error
-// is not, and an unmarked partial reads as a finished answer either
-// way.
-//
-// aborted means the turn was abandoned (as a stop or a failure) and its
-// reply must not be finalized.
+// drainTurnEvents renders a streamed turn's events and returns the final
+// reply. A cancelled turn is abandoned cleanly; a failed one is marked
+// failed. aborted means the reply must not be finalized.
func (g *Gateway) drainTurnEvents(
turnCtx context.Context, session string,
live *liveReply, stopTyping func(), events <-chan messaging.ChatEvent,
@@ -759,13 +695,8 @@ func (g *Gateway) drainTurnEvents(
return reply, false
}
-// fetchTurnMedia downloads the turn's inbound attachment onto the lane,
-// where waiting for the Telegram API belongs: the update worker stays free
-// to serve other messages and a /stop while this download progresses. A
-// failed download is reported as a failed attachment without starting the
-// turn, so the answer does not pretend the media was read -- a later
-// turn's history only knows the note, not the picture, and the model must
-// not reason from what it never saw.
+// fetchTurnMedia downloads the turn's attachment. A failed download is
+// reported and the turn does not start.
func (g *Gateway) fetchTurnMedia(ctx context.Context, b *bot.Bot, gm *messaging.Inbound, chatID int64, threadID int) bool {
if len(gm.Media) == 0 || gm.Media[0].Data != nil {
return true
@@ -893,14 +824,8 @@ 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 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.
+// sendBlocks sends one rich message and returns its ID, or 0. A rejected rich
+// message is resent as plain text.
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,
@@ -1040,24 +965,8 @@ func (g *Gateway) ValidateConfig(cfg map[string]any) error {
// Compile-time guard.
var _ channels.Channel = (*Gateway)(nil)
-// dropPendingUpdates clears Telegram's queue of undelivered updates before
-// long polling starts.
-//
-// Telegram holds updates for 24h and replays them on the first getUpdates,
-// so without this a daemon that was down overnight boots and answers every
-// message sent while it was gone -- one LLM turn each, in a burst. The
-// webhook path already passes DropPendingUpdates when it registers; polling
-// has no equivalent, so it has to be asked for explicitly. deleteWebhook is
-// the call that carries the flag, and it doubles as a guard against a stale
-// webhook registration, which would make getUpdates fail with 409.
-//
-// This also runs on /restart, so a message sent during the restart window is
-// discarded rather than answered late. That matches the webhook branch, which
-// passes the same flag on every launch.
-//
-// Best-effort: a failure here is logged, not fatal. Chat availability matters
-// more than a clean queue, and the deadline keeps an unreachable Telegram
-// from holding up gateway startup.
+// dropPendingUpdates discards queued updates before long polling starts,
+// via deleteWebhook. Best-effort.
func (g *Gateway) dropPendingUpdates(ctx context.Context, b *bot.Bot) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
diff --git a/internal/channels/telegram/update.go b/internal/channels/telegram/update.go
index 6cb9656f1..d18471932 100644
--- a/internal/channels/telegram/update.go
+++ b/internal/channels/telegram/update.go
@@ -147,12 +147,7 @@ func (g *Gateway) dispatchUpdateAction(ctx context.Context, b *bot.Bot, query *m
}
g.answerModelCallback(ctx, b, query.ID, "Starting update…", false)
g.editUpdateMessage(ctx, b, query, "Update approved. Starting now…")
- // The callback context belongs to Telegram's short-lived update
- // handler and is cancelled as soon as this handler returns. The
- // installer may build an image for several minutes, so detach only
- // the install operation from that request lifetime. Progress and
- // final-message edits still use ctx and may harmlessly fail when the
- // callback request is gone.
+ // Install outside the callback's short-lived context.
go g.installUpdate(ctx, b, query, fresh)
default:
g.answerModelCallback(ctx, b, query.ID, "That update action is no longer valid.", true)
@@ -169,14 +164,8 @@ func (g *Gateway) beginUpdate() bool {
return true
}
-// installUpdate runs the synchronous phase of an update (build/install) and
-// reports it live. It deliberately never claims the update itself
-// succeeded: the reference installer queues the daemon restart through a
-// detached unit precisely so restarting archied.service doesn't kill this
-// call before it can report a clean exit, which means the restart -- and
-// whether the new version actually comes up healthy -- happens after this
-// function returns. That outcome is reported separately, by whichever
-// archied process boots next, via SendPendingReport.
+// installUpdate runs and reports an update's install phase. The restart
+// outcome is reported by the next boot via SendPendingReport.
func (g *Gateway) installUpdate(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, snapshot releaseupdate.Snapshot) {
defer func() {
g.updateMu.Lock()
@@ -270,22 +259,8 @@ func formatVersionChanges(result releaseupdate.Result) string {
return strings.Join(parts, ", ")
}
-// formatPendingReport describes the phase-2 outcome. There are five distinct
-// cases, not two: the daemon came back up and confirms it is running what was
-// installed; it came back up but reports running something else; it came back
-// up and nothing could be checked either way; it didn't come up, and was
-// rolled back; or it didn't, and there was no backup to roll back to.
-//
-// Two of those are easy to collapse into a neighbour and must not be. A
-// no-backup failure worded like a rollback tells the operator to stand down
-// while the daemon may still be running the broken version, or not running
-// at all. An unverified success worded like a confirmed one re-asserts
-// exactly the claim that went unchecked in the incident this verification
-// was added for.
-//
-// running maps component ID to the version that component reports for
-// itself; see Report.Verify for why a passed health check is not on its own
-// evidence that the install took effect.
+// formatPendingReport describes an update's outcome: confirmed, version
+// drift, unverified, rolled back, or failed with no backup.
func formatPendingReport(report releaseupdate.Report, running map[string]string) string {
if !report.RolledBack && report.HealthCheck == "passed" {
return formatHealthyReport(report, report.Verify(running))
@@ -318,11 +293,7 @@ func formatHealthyReport(report releaseupdate.Report, verification releaseupdate
}
changes := formatVersionChanges(releaseupdate.Result{Previous: report.Previous, Installed: report.Installed})
if len(verification.Confirmed) == 0 {
- // Nothing self-reported a version we could check the claim against,
- // so a passed health probe is all we have -- and it only ever
- // proved that *something* answered. Calling this "Update complete"
- // would assert the exact thing that went unverified in the incident
- // this check was added for.
+ // No version could be checked.
text := "Update install finished"
if changes != "" {
text += " (" + changes + ")"
@@ -335,30 +306,14 @@ func formatHealthyReport(report releaseupdate.Report, verification releaseupdate
}
text += ". Health check passed — archie-core is healthy on the new version."
if len(verification.Unverified) > 0 {
- // Something WAS confirmed, so the headline is earned -- but the
- // version change printed above covers every component the
- // installer claimed, including ones nothing checked. Naming them
- // keeps the confirmed part from silently vouching for the rest.
- // This is the ordinary case, not an edge one: only the daemon can
- // self-report today, so the agent lands here on every successful
- // update.
+ // Name the components that were not checked.
text += " Not independently checked: " + strings.Join(verification.Unverified, ", ") + "."
}
return text
}
-// formatVersionDrift words the case where the installer reported success and
-// the health check passed, but a component reports it is running something
-// other than what was installed.
-//
-// "still the version this update meant to replace" is attached PER COMPONENT
-// rather than stated once for the whole message, because a single sentence
-// cannot be true of a mixed set: one component can be sitting on the version
-// the update meant to replace while another is on some third version the
-// report never mentions. Asserting one cause for both would invent a fact
-// about at least one of them -- the same defect as the false success this
-// whole check exists to catch. The trailing sentence is therefore worded to
-// hold either way, and says only what a passed probe actually establishes.
+// formatVersionDrift lists components running a version other than the one
+// installed.
func formatVersionDrift(drift []releaseupdate.VersionDrift) string {
parts := make([]string, 0, len(drift))
for _, d := range drift {
@@ -375,15 +330,8 @@ func formatVersionDrift(drift []releaseupdate.VersionDrift) string {
"Investigate before retrying — otherwise /update will report success again."
}
-// reportPendingUpdate checks for a phase-2 outcome left by the update
-// watchdog and relays it, exactly like announceRelease -- called on every
-// gateway launch so it fires whether this is a fresh process boot (the
-// common case after an update restart) or a later /restart. A report is
-// cleared as soon as it's handled -- relayed, or found unreadable -- so a
-// later launch never retries it. An unreadable report is discarded rather
-// than left in place: without clearing it, every future launch would fail
-// the same decode and the chat that approved the update would never learn
-// any outcome at all.
+// reportPendingUpdate relays and clears a pending update report on launch.
+// An unreadable report is discarded.
func (g *Gateway) reportPendingUpdate(ctx context.Context, b *bot.Bot) {
g.updateReportMu.Lock()
defer g.updateReportMu.Unlock()
@@ -407,23 +355,12 @@ func (g *Gateway) reportPendingUpdate(ctx context.Context, b *bot.Bot) {
}
}
-// SendPendingReport relays the phase-2 outcome of an update -- whether the
-// restarted daemon came up healthy, or was rolled back -- to the chat that
-// originally approved it. Called once, on startup, by whichever archied
-// process finds a pending report left by the previous boot's install; see
-// releaseupdate.ReadPendingReport.
+// SendPendingReport relays an update's outcome to the chat that approved it.
func (g *Gateway) SendPendingReport(ctx context.Context, b *bot.Bot, report releaseupdate.Report) {
g.sendMessage(ctx, b, report.ChatID, report.ThreadID, formatPendingReport(report, g.runningVersions()))
}
-// runningVersions returns the versions components report for themselves, or
-// nil when the composition root wired none.
-//
-// Nil is not a no-op: with nothing to check against, every claim is
-// Unverified, so the relayed message says the versions could not be
-// confirmed rather than repeating the pre-verification "healthy on the new
-// version". That is deliberate -- an unwired gateway should read as
-// unchecked, not as verified.
+// runningVersions returns self-reported component versions, or nil.
func (g *Gateway) runningVersions() map[string]string {
if g.RunningVersions == nil {
return nil