18e0e565ca
The Claude account dialog shows 'Auto-switch account when usage runs out' (claude_account_auto_switch) when the server reports it. The usage-limit banner schedules no auto-continue while the server's auto-switch continue prompt is queued. A chat refused after another chat already switched the Claude home gets a fresh switch stamp, so its banner clears too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
286 lines
10 KiB
Go
286 lines
10 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. The app's own
|
|
// auto-continue-at-reset prompt for that refusal is taken back out. When no
|
|
// account has usage left nothing more happens, and auto-continue at the reset
|
|
// still applies.
|
|
|
|
const (
|
|
// chatAutoSwitchPrefix starts the operation id of the continue prompt.
|
|
chatAutoSwitchPrefix = "auto-switch-"
|
|
// chatAutoContinuePrefix starts the app's auto-continue-at-reset prompt
|
|
// ids ("auto-continue-<refusal message id>").
|
|
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()
|
|
}
|
|
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 {
|
|
return
|
|
}
|
|
result, err := switcher.AutoSwitchAccount(ctx, refusal)
|
|
if err != nil {
|
|
if !errors.Is(err, claude.ErrAutoSwitchOff) && !errors.Is(err, claude.ErrNoConfigDir) {
|
|
log.Printf("claude auto-switch session=%s: %v", refusal.SessionID, err)
|
|
}
|
|
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)); 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), and every
|
|
// attached client sees it under the server's own sender label.
|
|
func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sessionID, operationID, text string) error {
|
|
if duplicate, _, _ := h.duplicateOp(sessionID, operationID); duplicate {
|
|
return nil
|
|
}
|
|
p := &chatQueuedPrompt{
|
|
text: text,
|
|
operationID: operationID,
|
|
messageID: h.nextUserMessageID(),
|
|
client: chatAutoSwitchClient,
|
|
noSteer: true,
|
|
}
|
|
h.rememberOp(sessionID, operationID)
|
|
admission, err := h.admitPrompt(ctx, sessionID, broker, p)
|
|
if admission == chatAdmitRefused {
|
|
h.forgetOp(sessionID, operationID)
|
|
return err
|
|
}
|
|
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)
|
|
}
|
|
}
|