Files
pipelines/internal/server/chat_auto_switch.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

306 lines
11 KiB
Go

package server
import (
"context"
"errors"
"log"
"strings"
"sync"
"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"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// When Claude Code refuses an operator chat's turn because the account ran
// out of usage, and the chat's Claude home has another saved account with
// usage left (and the operator left automatic switching on), the server
// switches the home to that account and queues a prompt, marked as sent
// automatically, that asks the agent to check it is still on track before it
// continues. It works with no client attached. Any auto-continue-at-reset
// prompt for that refusal is taken back out. When no account has usage left
// (or switching is off), the chat continues at the reset instead
// (chat_auto_continue.go).
const (
// chatAutoSwitchPrefix starts the operation id of the continue prompt.
chatAutoSwitchPrefix = "auto-switch-"
// chatAutoContinuePrefix starts the auto-continue-at-reset prompt ids
// ("auto-continue-<refusal message id>"), the server's and an older
// app's alike.
chatAutoContinuePrefix = "auto-continue-"
// chatAutoSwitchClient is the sender label of the continue prompt.
chatAutoSwitchClient = "Pipelines (automatic)"
// chatAutoSwitchPriority is ntfy's "low" priority.
chatAutoSwitchPriority = 2
// chatAutoSwitchRemembered bounds the refusals remembered as handled.
chatAutoSwitchRemembered = 256
)
// chatRefusalSource is a harness that reports usage-limit refusals
// (*claude.Chat).
type chatRefusalSource interface {
OnUsageRefused(func(claude.UsageRefusal))
}
// chatAutoSwitcher switches a refused chat's Claude home to another account.
type chatAutoSwitcher interface {
AutoSwitchAccount(ctx context.Context, refusal claude.UsageRefusal) (claude.AutoSwitch, error)
}
// chatAutoSwitchState is the hub's record of refusals it acted on.
type chatAutoSwitchState struct {
mu sync.Mutex
// handled holds session\x00turn of every refusal already considered, so
// one refusal switches at most once; order bounds it.
handled map[string]bool
order []string
// superseded holds session\x00auto-continue id of refusals the server
// continued; last is each session's latest continue prompt id.
superseded map[string]bool
last map[string]string
}
// OnUsageRefused hands Claude Code's usage-limit refusals to handler, now and
// for a Claude harness attached later.
func (m *chatManager) OnUsageRefused(handler func(claude.UsageRefusal)) {
m.mu.Lock()
m.onRefusal = handler
client := m.claude
m.mu.Unlock()
if source, ok := client.(chatRefusalSource); ok {
source.OnUsageRefused(handler)
}
}
// AutoSwitchAccount routes an automatic switch to the Claude harness.
func (m *chatManager) AutoSwitchAccount(ctx context.Context, refusal claude.UsageRefusal) (claude.AutoSwitch, error) {
if m.backendFor(ctx, refusal.SessionID) != claude.Backend {
return claude.AutoSwitch{}, errNotClaudeChat
}
switcher, ok := m.attached(claude.Backend).(chatAutoSwitcher)
if !ok {
return claude.AutoSwitch{}, errNotClaudeChat
}
return switcher.AutoSwitchAccount(ctx, refusal)
}
// watchUsageRefusals connects broker's refusals to the hub.
func (h *chatHub) watchUsageRefusals(broker chatBroker) {
if source, ok := broker.(chatRefusalSource); ok {
source.OnUsageRefused(func(refusal claude.UsageRefusal) {
h.continueOnAnotherAccount(broker, refusal)
})
}
}
// chatAutoSwitchText is the continue prompt.
func chatAutoSwitchText(from, to string) string {
if from == "" {
from = "the previous account"
}
return "[Sent automatically by Pipelines] Usage ran out on " + from + ", so Pipelines switched this chat to " + to + ". " +
"Before continuing: you already used up a full usage window on this task. Briefly check your progress against my original request and your plan, " +
"and make sure you are on track, not going in circles or off the rails. If something looks wrong, stop and ask me; otherwise continue where you left off."
}
// continueOnAnotherAccount handles one refusal (see the file comment).
func (h *chatHub) continueOnAnotherAccount(broker chatBroker, refusal claude.UsageRefusal) {
if !validChatSessionID(refusal.SessionID) || !h.autoSwitch.claim(refusal) {
return
}
base := h.baseCtx
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 := ""
if h.registry != nil {
row, found, err := h.registry.OperatorSession(ctx, refusal.SessionID)
if err != nil || !found || row.ClosedAt != 0 {
return // only the operator's open chats continue on their own
}
title = row.Title
if refusal.Directory == "" {
refusal.Directory = row.Directory
}
}
switcher, ok := broker.(chatAutoSwitcher)
if !ok {
h.continueAtReset(ctx, broker, refusal)
return
}
result, err := switcher.AutoSwitchAccount(ctx, refusal)
if err != nil {
if !errors.Is(err, claude.ErrAutoSwitchOff) && !errors.Is(err, claude.ErrNoConfigDir) &&
!errors.Is(err, claude.ErrNoAccountLeft) && !errors.Is(err, errNotClaudeChat) {
log.Printf("claude auto-switch session=%s: %v", refusal.SessionID, err)
}
h.continueAtReset(ctx, broker, refusal)
return
}
operationID := chatAutoSwitchPrefix + refusalKey(refusal)
h.autoSwitch.supersede(refusal, operationID)
h.dropAutoContinue(ctx, refusal.SessionID)
if err := h.queueServerPrompt(ctx, broker, refusal.SessionID, operationID, chatAutoSwitchText(result.From, result.To), time.Time{}); err != nil {
log.Printf("claude auto-switch session=%s: queue the continue prompt: %v", refusal.SessionID, err)
return
}
log.Printf("claude auto-switch session=%s: continued on another saved account (switched=%t)", refusal.SessionID, result.Switched)
h.publishAutoSwitchNotice(ctx, refusal, title, result.To)
}
func refusalKey(refusal claude.UsageRefusal) string {
if refusal.MessageID != "" {
return refusal.MessageID
}
return refusal.TurnID
}
// claim reports whether refusal is new, remembering it.
func (s *chatAutoSwitchState) claim(refusal claude.UsageRefusal) bool {
key := refusal.SessionID + "\x00" + refusal.TurnID + "\x00" + refusal.MessageID
s.mu.Lock()
defer s.mu.Unlock()
if s.handled[key] {
return false
}
if s.handled == nil {
s.handled = map[string]bool{}
}
s.handled[key] = true
s.order = append(s.order, key)
for len(s.order) > chatAutoSwitchRemembered {
delete(s.handled, s.order[0])
s.order = s.order[1:]
}
return true
}
// supersede records that refusal continues through operationID, so its
// auto-continue-at-reset prompt is refused from now on.
func (s *chatAutoSwitchState) supersede(refusal claude.UsageRefusal, operationID string) {
s.mu.Lock()
defer s.mu.Unlock()
if s.superseded == nil {
s.superseded = map[string]bool{}
s.last = map[string]string{}
}
if len(s.superseded) >= chatAutoSwitchRemembered {
s.superseded = map[string]bool{}
}
if refusal.MessageID != "" {
s.superseded[refusal.SessionID+"\x00"+chatAutoContinuePrefix+refusal.MessageID] = true
}
s.last[refusal.SessionID] = operationID
}
// autoContinueSuperseded reports whether an auto-continue prompt arriving
// for sessionID belongs to a refusal the server already continued: its
// refusal is one the server handled, or the server's continue prompt is
// still waiting to be sent (no later refusal can have happened yet).
func (h *chatHub) autoContinueSuperseded(sessionID, operationID string) bool {
if !strings.HasPrefix(operationID, chatAutoContinuePrefix) {
return false
}
s := &h.autoSwitch
s.mu.Lock()
superseded := s.superseded[sessionID+"\x00"+operationID]
last := s.last[sessionID]
s.mu.Unlock()
if superseded || last == "" {
return superseded
}
h.mu.Lock()
defer h.mu.Unlock()
room := h.rooms[sessionID]
return room != nil && room.holdsOp(last)
}
// dropAutoContinue takes every auto-continue-at-reset prompt out of the
// session's queue.
func (h *chatHub) dropAutoContinue(ctx context.Context, sessionID string) {
for _, prompt := range h.queueFrame(sessionID).Prompts {
if strings.HasPrefix(prompt.OperationID, chatAutoContinuePrefix) {
if _, err := h.unqueue(ctx, sessionID, prompt.OperationID); err != nil {
log.Printf("claude auto-switch session=%s: remove %s: %v", sessionID, prompt.OperationID, err)
}
}
}
}
// queueServerPrompt hands the session a prompt the server composed: it runs
// once the current turn has ended (queued durably behind it), or not before
// sendAt when that is set, and every attached client sees it under the
// server's own sender label (a scheduled one through the queue, as
// "Scheduled", until it is sent). A prompt the session already holds under
// operationID is not queued again.
func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error {
if duplicate, _, _ := h.duplicateOp(sessionID, operationID); duplicate || h.holdsQueued(sessionID, operationID) {
return nil
}
p := &chatQueuedPrompt{
text: text,
operationID: operationID,
messageID: h.nextUserMessageID(),
client: chatAutoSwitchClient,
noSteer: true,
}
if sendAt.After(h.clock()) {
p.sendAt = sendAt
}
h.rememberOp(sessionID, operationID)
admission, err := h.admitPrompt(ctx, sessionID, broker, p)
if admission == chatAdmitRefused {
h.forgetOp(sessionID, operationID)
return err
}
if !p.sendAt.IsZero() {
return nil
}
h.broadcastUser(protocol.ChatEventFrame{
SessionID: sessionID,
MessageID: p.messageID,
Kind: protocol.ChatEventUser,
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text},
Client: chatAutoSwitchClient,
OperationID: operationID,
}, "")
return nil
}
// publishAutoSwitchNotice tells the operator, at low priority, through the
// app notification stream and (when enabled) ntfy.
func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.UsageRefusal, name, email string) {
name = singleLine(name)
if name == "" {
name = "a chat"
}
title := truncateUTF8("Switched "+name+" to "+singleLine(email)+" and continued", 256)
message := "Claude usage ran out, so Pipelines switched the account and asked the agent to check it is on track before continuing."
click, views := chatAttentionLinks(refusal.SessionID)
if h.notes != nil {
h.notes.record(ctx, pipeline.AppNotificationRecord{
AppNotification: protocol.AppNotification{ID: "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal), Kind: protocol.NotificationChatReply,
Title: title, Message: message, Click: click, Priority: chatAutoSwitchPriority, Tags: []string{}, Group: "chat:" + refusal.SessionID},
SessionID: refusal.SessionID,
})
}
if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled {
return
}
if _, err := chatAttentionPublish(stage.WithNtfyPriority(ctx, chatAutoSwitchPriority), "system", title, message, "", nil, click, views...); err != nil {
log.Printf("claude auto-switch notification session=%s: %v", refusal.SessionID, err)
}
}