Files
archie/internal/gateway/turn_stream_test.go
T
sam 0d73f2fa5a feat(chat): show tool calls inline and stream replies into one message
Chat returned only the final answer, so a wrong tool choice, a
hallucinated action, or a footgun like `systemctl stop` against
`restart` was invisible from the conversation. Only text deltas were
threaded through the turn, and tool calls executed inside Generate with
nowhere to report.

Replace the delta callback with gateway.TurnStream, which carries text
fragments and completed tool calls on one ordered path from the model
loop to the channel. The sequence is the point: a tool line that
overtakes the sentence it interrupted describes a turn that never
happened. Text-only callers use gateway.DeltaFunc and are unaffected.

A tool is reported on its result, never on its call  --  the call part
carries no outcome yet, so reporting both would list every tool twice,
once with nothing to say.

Telegram renders it behind [chat.telegram] show_tool_calls, off by
default: this is debugging visibility, and it narrates every internal
step to provide it. The dashboard always shows it, being the operator's
own observability surface; its tool lines are live-only and are not
persisted with the conversation.

The Telegram live reply changes mechanism, and with it what a frame
MEANS. It used to stream through sendMessageDraft: drafts are ephemeral
30-second previews, so a tool call longer than that outlived the
preview, and successive frames were observed concatenated with their
cursors intact. It now sends one real message and edits it. An update
used to be "the next preview of the answer"; it is now "the whole
answer as it currently stands, replacing what is there". The cursor is
appended at render time and never stored, so exactly one exists and
always at the end, and a frame too long for one message is cut to its
tail rather than rejected outright.

A stopped or failed turn now edits the cursor away instead of leaving
it blinking on a message nothing will finish. That cleanup runs on a
live context because turnCtx is already dead, and it runs on both
failure branches: ai-sdk raises an aborted stream as ErrAborted with
ctx.Err() formatted in rather than wrapped, so errors.Is cannot be
trusted to tell a /stop from a fault.

Closes #467
2026-08-14 02:36:12 +10:00

117 lines
3.7 KiB
Go

package gateway
import (
"context"
"log/slog"
"testing"
)
// recordingStream captures everything a turn reports, in arrival order, so a
// test can assert that text and tool activity stay interleaved as produced.
type recordingStream struct {
events []string
}
func (s *recordingStream) Delta(text string) {
s.events = append(s.events, "text:"+text)
}
func (s *recordingStream) ToolCall(event ToolCallEvent) {
s.events = append(s.events, "tool:"+event.Name+":"+event.Summary())
}
func newStreamTestRunner(t *testing.T, prepared *turnTestPreparedModel) *TurnRunner {
t.Helper()
store := NewSessionStoreMemory()
router := NewRouter(nil, nil, "telegram")
router.Identity = "archie"
router.InitSessions(store)
return NewTurnRunner(TurnRunnerConfig{
Router: router,
Sessions: store,
Models: &fakeModelManager{models: []string{"test/model"}, activeModel: "test/model"},
Personas: NewPersonaRegistry(DefaultPersonas()),
Model: &turnTestModel{prepared: prepared},
BotUser: "archie",
Channel: "telegram",
Log: slog.New(slog.DiscardHandler),
})
}
// A channel that renders tool activity has to receive it in the order the
// model produced it, not as a batch after the answer.
func TestTurnRunnerForwardsToolCallsInOrderWithText(t *testing.T) {
prepared := &turnTestPreparedModel{reply: "done"}
prepared.generateStream = func(stream TurnStream) (string, error) {
stream.Delta("looking")
stream.ToolCall(ToolCallEvent{Name: "shell", Output: "exit 0"})
stream.Delta(" and answering")
return "looking and answering", nil
}
runner := newStreamTestRunner(t, prepared)
sink := &recordingStream{}
reply, err := runner.Run(context.Background(), Message{
From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello",
}, sink)
if err != nil {
t.Fatalf("Run() error = %v", err)
}
if reply != "looking and answering" {
t.Fatalf("reply = %q", reply)
}
want := []string{"text:looking", "tool:shell:exit 0", "text: and answering"}
if len(sink.events) != len(want) {
t.Fatalf("stream events = %v, want %v", sink.events, want)
}
for i := range want {
if sink.events[i] != want[i] {
t.Fatalf("stream events = %v, want %v", sink.events, want)
}
}
}
// A redelivered message replays its stored reply without calling the model,
// so the channel gets the whole answer as one fragment and no tool activity.
func TestTurnRunnerReplayStreamsStoredReplyOnce(t *testing.T) {
prepared := &turnTestPreparedModel{reply: "the answer"}
runner := newStreamTestRunner(t, prepared)
msg := Message{From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello"}
if _, err := runner.Run(context.Background(), msg, DeltaFunc(nil)); err != nil {
t.Fatalf("first Run() error = %v", err)
}
sink := &recordingStream{}
reply, err := runner.Run(context.Background(), msg, sink)
if err != nil {
t.Fatalf("replay Run() error = %v", err)
}
if reply != "the answer" {
t.Fatalf("replayed reply = %q", reply)
}
if len(sink.events) != 1 || sink.events[0] != "text:the answer" {
t.Fatalf("replay stream events = %v, want one full-text delta", sink.events)
}
if prepared.generateN != 1 {
t.Fatalf("Generate calls = %d, want 1 -- a replay must not call the model", prepared.generateN)
}
}
// A nil sink means "not streaming": the turn still runs and returns its reply.
func TestTurnRunnerAcceptsNoStream(t *testing.T) {
prepared := &turnTestPreparedModel{reply: "quiet answer"}
runner := newStreamTestRunner(t, prepared)
reply, err := runner.Run(context.Background(), Message{
From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello",
}, nil)
if err != nil {
t.Fatalf("Run() error = %v", err)
}
if reply != "quiet answer" {
t.Fatalf("reply = %q", reply)
}
}