Files
archie/internal/channels/telegram/live.go
T
sam c29cdf6f79 feat(workflow): post line-anchored review comments with suggested fixes (#891)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.
2026-09-19 23:37:23 +10:00

835 lines
30 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package telegram
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
const (
// liveInterval is the minimum gap between live updates. Telegram rate
// limits per-chat writes, and an LLM emits tokens far faster than any
// human reads, so deltas are coalesced into one edit per tick rather
// than sent individually.
liveInterval = 1 * time.Second
// liveCursor marks the reply as still being written. It is appended at
// render time and never stored in the buffer, so every frame carries
// exactly one cursor and it is always at the current end.
liveCursor = "▌"
// fallbackMediaLinePrefix opens the line Media appends when it could
// 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 = 3900
// Keep tool activity to a minority of a live frame so the answer remains
// readable even when a turn makes many calls. The remainder is reserved
// for the answer (and the cursor).
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."
type liveReply struct {
g *Gateway
b *bot.Bot
chatID int64
messageThreadID int
showToolCalls bool
// interval throttles updates; zero renders every change.
interval time.Duration
// mediaWg lets tests (and a future bounded drain, mirroring
// abandonAllLive) wait for in-flight Media deliveries. Callers other
// than tests must not block on it: Media is fire-and-forget by
// contract, same as Delta and ToolCall.
mediaWg sync.WaitGroup
// 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
renderRequests chan chan 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 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
// mid-answer or clamped away.
toolLines []string
// failureLines and failureCounts let ToolCall replace a repeated failure
// in place with one counted entry instead of appending noisy retries.
failureLines map[string]int
failureCounts map[string]int
// rendered is the last body actually sent. Telegram rejects an edit
// that changes nothing, so an unchanged body is not sent at all.
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 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 sync.Once
}
// newLiveReply creates a renderer bound to one chat/thread. showToolCalls is
// copied into the reply so a config reload cannot change a turn mid-stream.
func (g *Gateway) newLiveReply(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, showToolCalls bool) *liveReply {
renderCtx, cancelRender := context.WithCancel(ctx)
live := &liveReply{
g: g,
b: b,
chatID: chatID,
messageThreadID: messageThreadID,
showToolCalls: showToolCalls,
interval: liveInterval,
newMediaSender: g.NewMediaSender,
cancelRender: cancelRender,
renderRequests: make(chan chan struct{}, 1),
renderDone: make(chan struct{}),
failureLines: make(map[string]int),
failureCounts: make(map[string]int),
}
go live.runRenderer(renderCtx)
g.registerLive(ctx, live)
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.
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.
func (g *Gateway) registerLive(ctx context.Context, l *liveReply) {
g.liveMu.Lock()
if g.liveStopped {
g.liveMu.Unlock()
go l.abandonRestarted(context.WithoutCancel(ctx))
return
}
if g.liveReplies == nil {
g.liveReplies = make(map[*liveReply]struct{})
}
g.liveReplies[l] = struct{}{}
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.
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.
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.
func (g *Gateway) abandonAllLive(ctx context.Context) {
g.liveMu.Lock()
g.liveStopped = true
live := make([]*liveReply, 0, len(g.liveReplies))
for l := range g.liveReplies {
live = append(live, l)
}
clear(g.liveReplies)
g.liveMu.Unlock()
if len(live) == 0 {
return
}
timeout := g.liveDrainTimeout
if timeout <= 0 {
timeout = abandonAllLiveTimeout
}
done := make(chan struct{})
go func() {
defer close(done)
var wg sync.WaitGroup
for _, l := range live {
wg.Go(func() { l.abandonRestarted(ctx) })
}
wg.Wait()
}()
select {
case <-done:
case <-time.After(timeout):
g.log.Warn("gateway stop: gave up waiting for in-flight replies to be marked as restarted",
"pending", len(live), "timeout", timeout)
}
}
func (l *liveReply) runRenderer(ctx context.Context) {
defer close(l.renderDone)
for {
select {
case <-ctx.Done():
return
case completed := <-l.renderRequests:
l.render(ctx)
if completed != nil {
close(completed)
}
}
}
}
func (l *liveReply) requestRender() {
select {
case l.renderRequests <- nil:
default:
}
}
func (l *liveReply) flushRendering() {
completed := make(chan struct{})
select {
case l.renderRequests <- completed:
case <-l.renderDone:
return
}
select {
case <-completed:
case <-l.renderDone:
}
}
func (l *liveReply) stopRendering() {
l.cancelRender()
<-l.renderDone
l.mu.Lock()
l.finalized = true
l.mu.Unlock()
}
// Delta appends the next fragment of assistant text. It satisfies
// gateway.TurnStream.
func (l *liveReply) Delta(text string) {
if text == "" {
return
}
l.mu.Lock()
l.answerBuf.WriteString(text)
throttled := time.Since(l.last) < l.interval
l.mu.Unlock()
if throttled {
return
}
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.
func (l *liveReply) ToolCall(event messaging.ToolCallEvent) {
if !l.showToolCalls || event.Name == "" {
return
}
// Render the completed result as a compact fenced block. Do not append the
// raw/JSON-shaped parameters: they are noisy, can expose secrets, and were
// the source of unreadable schema placeholders in Telegram.
line := messaging.RenderToolCall(event)
key := messaging.FailureKey(event)
l.mu.Lock()
if index, ok := l.failureLines[key]; key != "" && ok {
l.failureCounts[key]++
l.toolLines[index] = countedToolLine(line, l.failureCounts[key])
} else {
l.toolLines = append(l.toolLines, line)
if key != "" {
l.failureLines[key] = len(l.toolLines) - 1
l.failureCounts[key] = 1
}
}
l.mu.Unlock()
// A tool call is a discrete event rather than a token, and there are
// few of them: wake the renderer immediately so the user sees what ran
// while it is still relevant. The callback itself never waits on HTTP.
l.requestRender()
}
func countedToolLine(line string, count int) string {
if count <= 1 {
return line
}
if newline := strings.IndexByte(line, '\n'); newline >= 0 {
return line[:newline] + fmt.Sprintf(" ×%d", count) + line[newline:]
}
return line + fmt.Sprintf(" ×%d", count)
}
// 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.
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.
func (l *liveReply) Media(ctx context.Context, event messaging.MediaEvent) {
if event.Attachment.URL == "" && event.Attachment.Path == "" {
return
}
l.mediaWg.Go(func() {
sender := l.newMediaSender(l.b, l.chatID, l.messageThreadID)
// Checked before attempting delivery, not just on failure: that is
// the entire point of CapabilityReporter over attempt-then-catch
// -- a sender that already knows it cannot deliver a given media
// kind should never cost a doomed network round trip to find out.
if !messaging.CapabilitiesOf(sender).Media {
l.g.log.Debug("channel cannot deliver media inline, falling back to a link",
"tool", event.ToolName, "type", event.Attachment.Type)
l.appendFallbackLine(ctx, event.Attachment)
return
}
sendCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), mediaSendTimeout)
defer cancel()
_, err := sender.SendMedia(sendCtx, messaging.MessageEvent{
Media: []messaging.MediaAttachment{event.Attachment},
})
if err == nil {
return
}
l.g.log.Warn("media delivery failed, falling back to a link",
"tool", event.ToolName, "type", event.Attachment.Type, "error", err)
l.appendFallbackLine(ctx, event.Attachment)
})
}
// appendFallbackLine renders att as a visible link in the reply, for a
// MediaEvent that could not be (or was not attempted to be) delivered
// inline.
func (l *liveReply) appendFallbackLine(ctx context.Context, att messaging.MediaAttachment) {
// A local attachment has no URL to fall back to, and printing an empty
// one reads as a delivered file. Say plainly that it was not sent:
// the whole defect this path exists around is that non-delivery and
// success looked the same to everyone downstream, the agent included.
line := fallbackMediaLinePrefix + bot.EscapeMarkdown(att.Type) + ": " + att.URL
if att.URL == "" {
name := att.FileName
if name == "" {
name = att.Path
}
line = fallbackMediaLinePrefix + "could not send " + bot.EscapeMarkdown(name)
}
l.mu.Lock()
if l.finalized {
// The renderer that would have picked up toolLines is already
// gone -- requestRender below would be a silent no-op, and the
// live message it would have edited is done being edited. Send
// this as its own message instead of dropping it.
l.mu.Unlock()
sendCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), mediaSendTimeout)
defer cancel()
l.g.sendMessage(sendCtx, l.b, l.chatID, l.messageThreadID, line)
return
}
l.toolLines = append(l.toolLines, line)
l.mu.Unlock()
l.requestRender()
}
// waitMedia blocks until every Media delivery started so far has finished.
// Tests only: production callers never wait on Media's fire-and-forget
// goroutines.
func (l *liveReply) waitMedia() {
l.mediaWg.Wait()
}
// render writes the current buffer, cursor and all, to the live message.
func (l *liveReply) render(ctx context.Context) {
l.mu.Lock()
body := l.body()
if body == "" || body == l.rendered {
l.mu.Unlock()
return
}
messageID := l.messageID
l.mu.Unlock()
// Mid-stream text is frequently unbalanced Markdown (an unclosed ** or
// code fence); a rejected update is logged and skipped, and the next
// tick -- or finalize -- corrects it.
if messageID == 0 {
l.open(ctx, markdownToBlocks(body))
return
}
if err := l.edit(ctx, messageID, markdownToBlocks(body)); err == nil {
l.markRendered(body)
}
}
func (l *liveReply) markRendered(body string) {
l.mu.Lock()
l.rendered = body
l.last = time.Now()
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.
func (l *liveReply) finalize(ctx context.Context, reply string) {
ctx = context.WithoutCancel(ctx)
l.terminal.Do(func() { l.doFinalize(ctx, reply) })
}
func (l *liveReply) doFinalize(ctx context.Context, reply string) {
l.g.forgetLive(l)
// Finish any queued live frame before replacing it, then retire the
// worker so no stale edit can race the authoritative delivery.
l.flushRendering()
l.stopRendering()
l.mu.Lock()
content := l.finalText(reply)
messageID := l.messageID
l.mu.Unlock()
if content == "" {
l.abandonStopped(ctx)
return
}
if messageID == 0 {
l.g.sendMessage(ctx, l.b, l.chatID, l.messageThreadID, content)
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.
parts := splitBlocks(markdownToBlocks(content), messageMaxLen)
if len(parts) == 0 {
l.abandonStopped(ctx)
return
}
if err := l.edit(ctx, messageID, parts[0]); err != nil {
l.g.sendMessage(ctx, l.b, l.chatID, l.messageThreadID, content)
return
}
l.markRendered(strings.Join(blocksToPlainText(parts[0]), "\n\n"))
for _, part := range parts[1:] {
l.g.sendBlocks(ctx, l.b, l.chatID, l.messageThreadID, part, "send message part failed")
}
}
// abandonMarker is appended to a failed turn's partial text so it cannot be
// mistaken for a finished answer: without it, a truncated reply and a
// completed one are visually identical, and Telegram messages are
// 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.
func (l *liveReply) abandon(ctx context.Context) {
ctx = context.WithoutCancel(ctx)
l.terminal.Do(func() { l.doAbandon(ctx) })
}
func (l *liveReply) doAbandon(ctx context.Context) {
l.g.forgetLive(l)
l.stopRendering()
l.abandonStopped(ctx)
}
// abandonFailed leaves a failed turn readable and visibly marked as failed,
// unlike abandon: a provider error is not an acknowledged interruption, so
// the partial text alone would read as the finished answer and the user
// could act on incomplete information.
func (l *liveReply) abandonFailed(ctx context.Context) {
l.mu.Lock()
l.answerBuf.WriteString(abandonMarker)
l.mu.Unlock()
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.
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.
func (l *liveReply) abandonRestarted(ctx context.Context) {
l.mu.Lock()
l.answerBuf.WriteString(restartMarker)
l.mu.Unlock()
l.abandon(ctx)
}
func (l *liveReply) abandonStopped(ctx context.Context) {
l.mu.Lock()
answer := strings.TrimRight(l.answerBuf.String(), " \t\n")
// Bounded for the same reason a live frame is: this is still one edit
// of one message, and a stopped turn that had already streamed past
// the limit would keep its cursor if the edit were rejected.
text := l.framedText(answer)
messageID := l.messageID
if text == "" || text == l.rendered {
l.mu.Unlock()
return
}
l.mu.Unlock()
if messageID == 0 {
l.g.sendMessage(ctx, l.b, l.chatID, l.messageThreadID, text)
return
}
if err := l.edit(ctx, messageID, markdownToBlocks(text)); err == nil {
l.markRendered(text)
}
}
// body renders a mid-turn frame: tool activity so far, then the answer text
// streamed so far, then the cursor. The caller holds the lock.
func (l *liveReply) body() string {
answer := strings.TrimRight(l.answerBuf.String(), " \t\n")
if answer == "" && len(l.toolLines) == 0 {
return ""
}
return l.framedText(answer) + " " + liveCursor
}
// framedText composes tool activity ahead of the answer text and clamps the
// whole thing to fit one Telegram message. The caller holds the lock.
func (l *liveReply) framedText(answer string) string {
if len(l.toolLines) == 0 {
return l.clampAnswer(answer, liveBodyMaxRunes-2)
}
block := l.toolBlock()
if answer == "" {
return block
}
// Reserve the larger share of the frame for the answer. The two extra
// runes are the separator and the cursor appended by body.
budget := liveBodyMaxRunes - 2 - utf8.RuneCountInString(block) - 2
if budget <= 0 {
return block
}
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.
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.
func (l *liveReply) toolBlock() string {
if len(l.toolLines) == 0 {
return ""
}
best := -1
for start := range slices.Backward(l.toolLines) {
if utf8.RuneCountInString(l.toolBlockWith(start)) > liveToolMaxRunes {
break
}
best = start
}
if best >= 0 {
return l.toolBlockWith(best)
}
// Even the newest line alone overflows, so it is the only line retained
// and every older line must be reflected in the indicator.
omitted := len(l.toolLines) - 1
prefix := ""
if omitted > 0 {
prefix = fmt.Sprintf("+%d earlier\n\n", omitted)
}
available := liveToolMaxRunes - utf8.RuneCountInString(prefix)
if available <= 0 {
return clampToRunes(prefix, liveToolMaxRunes)
}
return prefix + clampToRunes(l.toolLines[len(l.toolLines)-1], available)
}
// toolBlockWith renders the activity from index start to the newest line,
// including the "+N earlier" indicator for whatever precedes start.
func (l *liveReply) toolBlockWith(start int) string {
prefix := ""
if omitted := start; omitted > 0 {
prefix = fmt.Sprintf("+%d earlier\n\n", omitted)
}
return prefix + strings.Join(l.toolLines[start:], "\n")
}
// clampToRunes cuts s to its last maxRunes runes, marking the cut with a
// leading ellipsis.
func clampToRunes(s string, maxRunes int) string {
runes := []rune(s)
if len(runes) <= maxRunes {
return s
}
if maxRunes <= 1 {
return "…"
}
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.
func (l *liveReply) finalText(reply string) string {
reply = strings.TrimSpace(reply)
if len(l.toolLines) == 0 {
return reply
}
block := strings.Join(l.toolLines, "\n")
if reply == "" {
return block + "\n\n_(no response)_"
}
return block + "\n\n" + reply
}
// open creates the live message and records its ID for later edits.
func (l *liveReply) open(ctx context.Context, blocks []models.InputRichBlock) {
params := &bot.SendRichMessageParams{
ChatID: l.chatID,
RichMessage: models.InputRichMessage{Blocks: blocks},
}
if l.messageThreadID != 0 {
params.MessageThreadID = l.messageThreadID
}
msg, err := l.b.SendRichMessage(ctx, params)
if err != nil {
l.g.log.Debug("live reply rich send failed, retrying unformatted", "error", err)
plain := &bot.SendMessageParams{ChatID: l.chatID, Text: strings.Join(blocksToPlainText(blocks), "\n\n")}
if l.messageThreadID != 0 {
plain.MessageThreadID = l.messageThreadID
}
msg, err = l.b.SendMessage(ctx, plain)
if err != nil {
l.g.log.Debug("live reply send failed", "error", err)
return
}
}
l.mu.Lock()
l.messageID = msg.ID
l.rendered = strings.Join(blocksToPlainText(blocks), "\n\n")
l.last = time.Now()
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.
func (l *liveReply) edit(ctx context.Context, messageID int, blocks []models.InputRichBlock) error {
_, richErr := l.b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: l.chatID,
MessageID: messageID,
RichMessage: &models.InputRichMessage{Blocks: blocks},
})
if richErr == nil {
return nil
}
l.g.log.Debug("live reply rich edit failed, retrying unformatted", "error", richErr)
if _, plainErr := l.b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: l.chatID,
MessageID: messageID,
Text: strings.Join(blocksToPlainText(blocks), "\n\n"),
}); plainErr != nil {
l.g.log.Debug("live reply edit failed", "error", plainErr)
return errors.Join(
fmt.Errorf("rich edit: %w", richErr),
fmt.Errorf("plain edit: %w", plainErr),
)
}
return nil
}