Files
pipelines/internal/server/chat_auto_continue_test.go
T
alan 026942b9b7 Chat queue: handle usage refusals only after start-up recovery; fix shell share test ordering
TestAutoSwitchReplacesTheAutoContinue flaked because a usage refusal (delivered
on its own goroutine) was acted on while start-up recovery was still running.
resumeQueued read the durable auto-continue row, the server's account switch
then removed it, and resumeQueued put it back into the room; as the queue head
scheduled an hour out it held the switch's continue prompt behind it. The
refusal handler (and the schedule_followup tool) now wait for the same
recovery gate chat_* requests already wait for, and the refusal watcher is
registered only once the hub is fully wired.

TestChatShellShareQueuesAnOrdinaryPrompt flaked because the turn runner writes
the sender's reply straight to its connection while the echoed user turn goes
through the subscription writer, so the reply can arrive first and the test
discarded it while reading for the echo. The test now accepts either order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:24:22 +00:00

214 lines
8.6 KiB
Go

package server
import (
"context"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// autoContinueServer is an operator chat whose refusals find no account to
// switch to.
func autoContinueServer(t *testing.T) (*refusingChat, *queueServer, *pipeline.Store) {
t.Helper()
capturePublications(t)
broker, server, store := autoSwitchServer(t, "ses_1")
broker.quiet = true
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) {
return claude.AutoSwitch{}, claude.ErrNoAccountLeft
}
return broker, server, store
}
func queuedRows(t *testing.T, store *pipeline.Store) []pipeline.ChatQueuedPrompt {
t.Helper()
rows, err := store.ChatQueuedPrompts(context.Background(), "ses_1")
if err != nil {
t.Fatal(err)
}
return rows
}
// A refusal the server could not switch away from schedules one automatic
// prompt a minute after the reset: "continue" after a turn that worked, the
// refused message itself after one that did not. Seeing it again (a second
// report, a device scheduling the same refusal) adds nothing.
func TestUsageRefusalSchedulesAutoContinueAtTheReset(t *testing.T) {
for _, tc := range []struct{ name, prompt, want string }{
{"worked", "", "continue"},
{"refused prompt", "Fix the build", "Fix the build"},
} {
t.Run(tc.name, func(t *testing.T) {
broker, server, store := autoContinueServer(t)
reset := time.Now().Add(2 * time.Hour).Truncate(time.Second)
refusal := claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", Email: "a@example.invalid", ResetsAt: reset, Prompt: tc.prompt}
broker.refuse(refusal)
broker.refuse(refusal)
conn := dialChatConn(t, server.ctx, server.srv)
if ack := sendScheduled(t, server.ctx, conn, "p1", "continue", "auto-continue-refusal-1", reset.Add(time.Minute)); !ack.ChatQueued {
t.Fatalf("device's copy ack = %+v", ack)
}
rows := queuedRows(t, store)
if len(rows) != 1 {
t.Fatalf("queued = %+v", rows)
}
row := rows[0]
if row.OperationID != "auto-continue-refusal-1" || row.Text != tc.want || row.Client != chatAutoSwitchClient ||
!row.SendAt.Equal(reset.Add(time.Minute)) {
t.Fatalf("row = %+v", row)
}
if n := broker.promptCount(); n != 0 {
t.Fatalf("prompts sent before the reset: %d", n)
}
})
}
}
// A refusal without a reset time is not continued, and neither is any
// refusal while the operator turned auto-continue off (a server-kept choice
// for a chat without a Claude home of its own).
func TestUsageRefusalAutoContinueNeedsAResetAndTheSetting(t *testing.T) {
broker, server, store := autoContinueServer(t)
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1"})
if ops := queuedOps(t, store); len(ops) != 0 {
t.Fatalf("queued without a reset: %v", ops)
}
conn := dialChatConn(t, server.ctx, server.srv)
read := func(id string, on *bool) *protocol.ChatAutoContinue {
t.Helper()
writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatAutoContinueType, ID: id, ChatAutoContinue: &protocol.ChatAutoContinue{SessionID: "ses_1", AutoContinue: on}})
reply := readUntil(t, server.ctx, conn, protocol.ChatAutoContinueType)
if reply.ChatAutoContinue == nil || reply.ChatAutoContinue.AutoContinue == nil {
t.Fatalf("reply = %+v", reply)
}
return reply.ChatAutoContinue
}
if got := read("r1", nil); !*got.AutoContinue || got.Scope != protocol.ChatAutoContinueServer {
t.Fatalf("default = %+v", got)
}
off := false
if got := read("r2", &off); *got.AutoContinue {
t.Fatalf("set off = %+v", got)
}
if got := read("r3", nil); *got.AutoContinue {
t.Fatalf("read back = %+v", got)
}
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-2", MessageID: "refusal-2", ResetsAt: time.Now().Add(time.Hour)})
if ops := queuedOps(t, store); len(ops) != 0 {
t.Fatalf("queued with auto-continue off: %v", ops)
}
}
// When the server continues a refusal on another account, no auto-continue
// is scheduled for it, and one still waiting from an earlier refusal is
// removed.
func TestAutoSwitchReplacesTheAutoContinue(t *testing.T) {
broker, _, store := autoContinueServer(t)
reset := time.Now().Add(time.Hour)
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: reset})
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-1"}) {
t.Fatalf("queued = %v", ops)
}
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) {
return claude.AutoSwitch{From: "a@example.invalid", To: "b@example.invalid", Switched: true}, nil
}
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-2", MessageID: "refusal-2", ResetsAt: reset})
// The idle chat takes the switch's continue prompt at once.
waitFor(t, "the continue prompt", func() bool { return broker.promptCount() == 1 })
if text := broker.promptTexts()[0]; !strings.HasPrefix(text, "[Sent automatically by Pipelines]") {
t.Fatalf("sent %q", text)
}
if ops := queuedOps(t, store); len(ops) != 0 {
t.Fatalf("queued after the switch = %v", ops)
}
}
// A later refusal (a background-task turn Claude Code started itself, say)
// leaves the waiting auto-continue as it is: it continues the chat, and
// keeps the operator's refused message.
func TestLaterRefusalKeepsTheWaitingAutoContinue(t *testing.T) {
broker, _, store := autoContinueServer(t)
reset := time.Now().Add(time.Hour)
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: reset, Prompt: "Fix the build"})
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "result-x", MessageID: "refusal-2", ResetsAt: reset})
rows := queuedRows(t, store)
if len(rows) != 1 || rows[0].OperationID != "auto-continue-refusal-1" || rows[0].Text != "Fix the build" {
t.Fatalf("queued = %+v", rows)
}
}
// A refusal reported again by a restarted server (its output replayed) finds
// the durable prompt and queues no second one.
func TestRestartedServerDoesNotScheduleTheRefusalTwice(t *testing.T) {
broker, server, store := autoContinueServer(t)
refusal := claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: time.Now().Add(time.Hour)}
broker.refuse(refusal)
server.stop()
restarted := &refusingChat{channelChat: newChannelChat(), quiet: true}
restarted.switch_ = broker.switch_
again := startQueueServer(t, restarted, store)
conn := dialChatConn(t, again.ctx, again.srv)
writeChat(t, again.ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}})
restarted.refuse(refusal)
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-1"}) {
t.Fatalf("queued after the restart = %v", ops)
}
}
// A refusal reported while start-up recovery is still restoring the durable
// queue waits for it. Acted on earlier, recovery could read the queued
// auto-continue and put it back after the server's switch had removed it, so
// the switch's continue prompt waited behind it for the hour.
func TestUsageRefusalWaitsForStartupRecovery(t *testing.T) {
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
if err := store.RecordOperatorSession(context.Background(), "ses_1", "/work", "Fix ses_1", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
broker := &refusingChat{channelChat: newChannelChat(), quiet: true}
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) {
return claude.AutoSwitch{}, claude.ErrNoAccountLeft
}
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
hub := newChatHub()
hub.baseCtx = ctx
hub.registry = store
hub.settings = store
hub.queueStore = store
hub.liveStore = store
ready := make(chan struct{})
hub.recoveryReady = ready
hub.watchUsageRefusals(broker)
handled := make(chan struct{})
go func() {
defer close(handled)
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: time.Now().Add(time.Hour)})
}()
select {
case <-handled:
t.Fatal("the refusal was handled before start-up recovery finished")
case <-time.After(100 * time.Millisecond):
}
if ops := queuedOps(t, store); len(ops) != 0 {
t.Fatalf("queued during recovery = %v", ops)
}
close(ready)
select {
case <-handled:
case <-time.After(5 * time.Second):
t.Fatal("the refusal was not handled after recovery")
}
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-1"}) {
t.Fatalf("queued = %v", ops)
}
}