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>
This commit is contained in:
2026-12-03 00:24:22 +00:00
parent accb9970b6
commit 026942b9b7
7 changed files with 101 additions and 12 deletions
+2 -6
View File
@@ -176,12 +176,8 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
// External chat admission and readback must follow durable turn/queue
// restoration: even readback can reconcile hub state. Internal recovery
// does not dispatch requests here. The cold registry scan runs afterward.
if hub != nil && hub.recoveryReady != nil && strings.HasPrefix(string(request.Type), "chat_") {
select {
case <-hub.recoveryReady:
case <-ctx.Done():
return true
}
if strings.HasPrefix(string(request.Type), "chat_") && !hub.awaitRecovery(ctx) {
return true
}
switch request.Type {
case protocol.ChatPrompt:
@@ -2,6 +2,7 @@ package server
import (
"context"
"path/filepath"
"slices"
"strings"
"testing"
@@ -161,3 +162,52 @@ func TestRestartedServerDoesNotScheduleTheRefusalTwice(t *testing.T) {
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)
}
}
+7
View File
@@ -115,6 +115,13 @@ func (h *chatHub) continueOnAnotherAccount(broker chatBroker, refusal claude.Usa
if base == nil {
base = context.Background()
}
// A refusal arrives on its own goroutine, possibly while start-up
// recovery is still restoring the durable queue; acting on it then could
// have recovery put back the auto-continue this removes (see
// awaitRecovery).
if !h.awaitRecovery(base) {
return
}
ctx, cancel := context.WithTimeout(base, time.Minute)
defer cancel()
title := ""
+18
View File
@@ -182,6 +182,24 @@ func (h *chatHub) clock() time.Time {
return time.Now()
}
// awaitRecovery blocks until start-up recovery has restored the durable turn
// and queue state (resumeQueued), and reports false when ctx ends first.
// Everything that admits, removes or otherwise changes a session's queued
// prompts waits for it: resumeQueued reads the durable rows and then adds
// every one its room does not hold, so a prompt removed in between would be
// put back (and, as the queue head, hold everything behind it).
func (h *chatHub) awaitRecovery(ctx context.Context) bool {
if h == nil || h.recoveryReady == nil {
return true
}
select {
case <-h.recoveryReady:
return true
case <-ctx.Done():
return false
}
}
// apply folds one pushed frame into the retained state. Text and reasoning
// deltas append to their message's part; a tool frame upserts the part (merging
// the fields it carries onto what is retained, and accounting for the whole
+15 -2
View File
@@ -175,8 +175,17 @@ func TestChatShellShareQueuesAnOrdinaryPrompt(t *testing.T) {
finishedShell(t, ctx, conns[0], run.ID)
writeChat(t, ctx, conns[0], shellRequest(protocol.ChatShellShare, "share", run.ID, ""))
// The composed prompt is echoed to the sender too: it has no local copy.
for _, conn := range conns {
// The turn runner writes the sender's reply straight to its connection
// while the echo goes through the sender's subscription writer, so the two
// arrive in either order; neither may be skipped while reading for the
// other.
var reply *protocol.Message
for i, conn := range conns {
user := readShellFrame(t, ctx, conn, func(m protocol.Message) bool {
if i == 0 && m.ID == "share" {
reply = &m
return false
}
return m.Type == protocol.ChatEvent && m.ChatEvent != nil && m.ChatEvent.Kind == protocol.ChatEventUser
}).ChatEvent
text := user.Part.Text
@@ -184,7 +193,11 @@ func TestChatShellShareQueuesAnOrdinaryPrompt(t *testing.T) {
t.Fatalf("shared prompt = %q", text)
}
}
if reply := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool { return m.ID == "share" }); reply.Type != protocol.ChatPrompt {
if reply == nil {
got := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool { return m.ID == "share" })
reply = &got
}
if reply.Type != protocol.ChatPrompt {
t.Fatalf("share reply = %+v", reply)
}
}
+3
View File
@@ -85,6 +85,9 @@ func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, me
// queueFollowup queues an agent's follow-up prompt for sendAt: durably, under
// the follow-up sender label, shown to every attached client as scheduled.
func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error {
if !h.awaitRecovery(ctx) {
return ctx.Err()
}
p := &chatQueuedPrompt{
text: text,
operationID: operationID,
+6 -4
View File
@@ -137,10 +137,6 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
settingsStore = stores[0]
}
hub.settings = settingsStore
if options.Chat != nil {
// A Claude chat refused for usage continues on another saved account.
hub.watchUsageRefusals(options.Chat)
}
if len(stores) > 0 {
// Prompts queued behind a running turn are durable and owned by their
// session; resume delivering any a previous process left queued.
@@ -641,6 +637,12 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
hub.retryReattachments(ctx, options.Chat)
}()
}
if options.Chat != nil {
// A Claude chat refused for usage continues on another saved account.
// Registered once the hub is fully wired (stores, recovery gate), since
// a refusal can arrive on its own goroutine at any moment after this.
hub.watchUsageRefusals(options.Chat)
}
if runs != nil {
// Continue the runs a previous process left in flight, now that the
// runner's collaborators are wired and before any request is served.