diff --git a/internal/channels/telegram/live.go b/internal/channels/telegram/live.go index 84cf76fac..131a0bdff 100644 --- a/internal/channels/telegram/live.go +++ b/internal/channels/telegram/live.go @@ -165,15 +165,22 @@ func (l *liveReply) Delta(text string) { // 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 gateway.ToolCallEvent) { if !l.showToolCalls || event.Name == "" { return } - line := toolCallPrefix + event.Name + line := toolCallPrefix + bot.EscapeMarkdown(event.Name) if event.Parameters != "" { - line += " " + event.Parameters + line += " " + bot.EscapeMarkdown(event.Parameters) } - line += " — " + event.Summary() + line += " — " + bot.EscapeMarkdown(event.Summary()) l.mu.Lock() if l.buf.Len() > 0 && !strings.HasSuffix(l.buf.String(), "\n") { @@ -224,7 +231,17 @@ func (l *liveReply) markRendered(body string) { // 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. func (l *liveReply) finalize(ctx context.Context, reply string) { + ctx = context.WithoutCancel(ctx) + // Finish any queued live frame before replacing it, then retire the // worker so no stale edit can race the authoritative delivery. l.flushRendering() @@ -262,9 +279,14 @@ func (l *liveReply) finalize(ctx context.Context, reply string) { // abandon leaves a stopped or failed turn readable: the partial text stays, // but the cursor goes, so the message does not claim to still be writing. +// +// 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. func (l *liveReply) abandon(ctx context.Context) { l.stopRendering() - l.abandonStopped(ctx) + l.abandonStopped(context.WithoutCancel(ctx)) } func (l *liveReply) abandonStopped(ctx context.Context) { diff --git a/internal/channels/telegram/live_test.go b/internal/channels/telegram/live_test.go index 0d2a8d434..8fd3e639b 100644 --- a/internal/channels/telegram/live_test.go +++ b/internal/channels/telegram/live_test.go @@ -178,8 +178,34 @@ func TestLiveReplySnapshotsToolCallVisibility(t *testing.T) { live.finalize(context.Background(), "done") last := (*calls)[len(*calls)-1] - if !strings.Contains(last.markdown, `🔧 shell {"cmd":"true"} — exit 0`) { - t.Fatalf("final reply = %q, want the visibility captured when the reply started", last.markdown) + if !strings.Contains(last.markdown, `🔧 shell \{"cmd":"true"\} — exit 0`) { + t.Fatalf("final reply = %q, want the visibility captured when the reply started (with Markdown metacharacters escaped)", last.markdown) + } +} + +// The tool line and the model's reply share one Markdown body, so a stray +// metacharacter in tool output (a grep hit, a JSON parameter) must not +// unbalance the whole message and take the reply's own formatting down with +// it. +func TestLiveReplyToolCallEscapesMarkdownMetacharacters(t *testing.T) { + live, calls := newTestLiveReply(t, true) + + live.ToolCall(gateway.ToolCallEvent{ + Name: "grep", + Parameters: `{"pattern":"*_foo_*"}`, + Output: "found `*bold*` and _italic_ markers", + }) + live.finalize(context.Background(), "**the answer**") + + last := (*calls)[len(*calls)-1] + if strings.Contains(last.markdown, "found `*bold*` and _italic_ markers") { + t.Fatalf("tool summary rendered unescaped: %q", last.markdown) + } + if !strings.Contains(last.markdown, "**the answer**") { + t.Fatalf("model reply's own markdown was altered: %q", last.markdown) + } + if !strings.Contains(last.markdown, "found \\`\\*bold\\*\\` and \\_italic\\_ markers") { + t.Fatalf("tool summary not escaped as expected: %q", last.markdown) } } @@ -274,6 +300,25 @@ func TestLiveReplyAbandonDropsTheCursor(t *testing.T) { } } +// abandon runs precisely because turnCtx was cancelled by a /stop; the +// cursor-drop edit it performs must not itself be aborted by that same +// cancellation, or the message is stranded with its cursor forever. +func TestLiveReplyAbandonDropsTheCursorOnACancelledContext(t *testing.T) { + live, calls := newTestLiveReply(t, false) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + live.Delta("half an ans") + live.flushRendering() + live.abandon(ctx) + + last := (*calls)[len(*calls)-1] + if last.markdown != "half an ans" { + t.Fatalf("abandon on a cancelled context delivered %q, want the buffer without a cursor", last.markdown) + } +} + // Abandoning a turn that never rendered anything must stay silent rather than // posting an empty message. func TestLiveReplyAbandonWithoutAMessageIsSilent(t *testing.T) { @@ -528,3 +573,21 @@ func TestLiveReplyFinalizeSplitsAnOversizedReply(t *testing.T) { strings.Count(rendered.String(), "a"), strings.Count(long, "a")) } } + +// A /stop landing mid-finalize cancels turnCtx, but the reply is already +// decided by the time finalize runs -- every send it makes must go through +// regardless, or the live message is stranded with its cursor forever. +func TestLiveReplyFinalizeDeliversOnACancelledContext(t *testing.T) { + live, calls := newTestLiveReply(t, false) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + live.Delta("partial") + live.finalize(ctx, "the authoritative reply") + + last := (*calls)[len(*calls)-1] + if last.markdown != "the authoritative reply" { + t.Fatalf("finalize on a cancelled context delivered %q, want the authoritative reply", last.markdown) + } +} diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 29891a11d..48a617000 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -16,6 +16,7 @@ import ( "sync" "sync/atomic" "time" + "unicode/utf8" "github.com/go-telegram/bot" "github.com/go-telegram/bot/models" @@ -563,20 +564,19 @@ func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Messag // 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. + // 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, but turnCtx is dead either way, so the cursor-drop edits - // through context.WithoutCancel(turnCtx) -- a live context. A - // cancelled context would fail the edit and leave the cursor - // blinking on a message nothing will ever finish. + // errors.Is(err, context.Canceled) reliably separates a /stop from a + // fault; either way turnCtx is dead by the time we get here. if err != nil { if errors.Is(err, context.Canceled) { g.log.Info("chat turn stopped", "session", session) } else { g.log.Error("route failed", "error", err) } - live.abandon(context.WithoutCancel(turnCtx)) + live.abandon(turnCtx) return } live.finalize(turnCtx, reply) @@ -713,31 +713,43 @@ func (g *Gateway) send(ctx context.Context, b *bot.Bot, chatID int64, messageThr } } +// splitLongMessage divides text into parts of at most maxLen runes each, +// preferring to cut on newlines. Bounds are counted in runes, not bytes, +// and an oversized line is itself cut on rune boundaries -- slicing by byte +// offset instead would, for any line containing multi-byte UTF-8 (CJK, +// emoji, ...), land a cut inside a rune's continuation bytes and produce a +// part that is not valid UTF-8 on either side of the cut. func splitLongMessage(text string, maxLen int) []string { - if len(text) <= maxLen { + if utf8.RuneCountInString(text) <= maxLen { return []string{text} } var parts []string lines := strings.Split(text, "\n") var cur strings.Builder + curRunes := 0 for _, line := range lines { - if cur.Len()+len(line)+1 > maxLen { + lineRunes := utf8.RuneCountInString(line) + if curRunes+lineRunes+1 > maxLen { if cur.Len() > 0 { parts = append(parts, cur.String()) cur.Reset() + curRunes = 0 } - if len(line) > maxLen { - for i := 0; i < len(line); i += maxLen { - end := min(i+maxLen, len(line)) - parts = append(parts, line[i:end]) + if lineRunes > maxLen { + runes := []rune(line) + for i := 0; i < len(runes); i += maxLen { + end := min(i+maxLen, len(runes)) + parts = append(parts, string(runes[i:end])) } continue } } if cur.Len() > 0 { cur.WriteByte('\n') + curRunes++ } cur.WriteString(line) + curRunes += lineRunes } if cur.Len() > 0 { parts = append(parts, cur.String()) diff --git a/internal/channels/telegram/telegram_test.go b/internal/channels/telegram/telegram_test.go index f18303713..37331bca9 100644 --- a/internal/channels/telegram/telegram_test.go +++ b/internal/channels/telegram/telegram_test.go @@ -11,6 +11,7 @@ import ( "sync" "testing" "time" + "unicode/utf8" "github.com/go-telegram/bot" "github.com/go-telegram/bot/models" @@ -379,6 +380,39 @@ func TestSplitLongMessage(t *testing.T) { } } }) + + t.Run("multi-byte oversized line splits on rune boundaries", func(t *testing.T) { + // '界' is 3 bytes in UTF-8. 1334 of them is 4002 bytes but only 1334 + // runes, so a byte-based split at 4000 lands inside the last rune's + // continuation bytes while a rune-based split at 4000 does not. + longLine := strings.Repeat("界", 1334) + parts := splitLongMessage(longLine, 4000) + + var rebuilt strings.Builder + for _, p := range parts { + if !utf8.ValidString(p) { + t.Fatalf("part is not valid UTF-8: %q", p) + } + if n := utf8.RuneCountInString(p); n > 4000 { + t.Errorf("part has %d runes, want at most 4000", n) + } + rebuilt.WriteString(p) + } + if rebuilt.String() != longLine { + t.Fatalf("split lost or corrupted content: got %d runes, want %d", + utf8.RuneCountInString(rebuilt.String()), utf8.RuneCountInString(longLine)) + } + }) + + t.Run("multi-byte content respects the rune bound, not the byte length", func(t *testing.T) { + // 5 runes of '界' (15 bytes) must not be split at maxLen=10: 10 is a + // rune bound here, and 5 <= 10. + s := strings.Repeat("界", 5) + parts := splitLongMessage(s, 10) + if len(parts) != 1 || parts[0] != s { + t.Fatalf("expected the string kept whole, got %v", parts) + } + }) } func TestIsSenderAllowed(t *testing.T) {