Claude accounts: switch a chat refused for usage to another saved account and continue it
When Claude Code refuses an operator chat's turn for a usage limit, the server marks the refused account until its reset and, if the chat's Claude home allows it (claude_account_auto_switch / `pipelines claude-account auto on|off`, on by default, kept in pipelines-accounts/settings.json), switches the home to the saved account with the most usage left through the claude_account_use path. Switches of one home are serialized, so chats refused together switch once. Each refused chat gets one queued prompt, marked as sent automatically, that asks the agent to check it is on track before continuing; the app's auto-continue-at-reset prompt for the refusal is removed (and refused if it arrives later), and the operator gets a low-priority notification. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -253,7 +253,7 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatCommands:
|
||||
handleChatCommands(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove:
|
||||
case protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove, protocol.ClaudeAccountAutoSwitch:
|
||||
handleClaudeAccounts(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ChatModelSelect:
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
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
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"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"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// refusingChat is a channelChat that reports usage refusals and switches
|
||||
// accounts as scripted.
|
||||
type refusingChat struct {
|
||||
*channelChat
|
||||
mu sync.Mutex
|
||||
handler func(claude.UsageRefusal)
|
||||
calls []claude.UsageRefusal
|
||||
switch_ func(claude.UsageRefusal) (claude.AutoSwitch, error)
|
||||
// quiet streams nothing for every session (channelChat has one stream).
|
||||
quiet bool
|
||||
}
|
||||
|
||||
func (c *refusingChat) Stream(ctx context.Context, id string, ready func(), emit func(protocol.ChatEventFrame) error) error {
|
||||
if !c.quiet {
|
||||
return c.channelChat.Stream(ctx, id, ready, emit)
|
||||
}
|
||||
if ready != nil {
|
||||
ready()
|
||||
}
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (c *refusingChat) OnUsageRefused(handler func(claude.UsageRefusal)) {
|
||||
c.mu.Lock()
|
||||
c.handler = handler
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *refusingChat) refuse(refusal claude.UsageRefusal) {
|
||||
c.mu.Lock()
|
||||
handler := c.handler
|
||||
c.mu.Unlock()
|
||||
handler(refusal)
|
||||
}
|
||||
|
||||
func (c *refusingChat) AutoSwitchAccount(_ context.Context, refusal claude.UsageRefusal) (claude.AutoSwitch, error) {
|
||||
c.mu.Lock()
|
||||
c.calls = append(c.calls, refusal)
|
||||
c.mu.Unlock()
|
||||
return c.switch_(refusal)
|
||||
}
|
||||
|
||||
func (c *refusingChat) callCount() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return len(c.calls)
|
||||
}
|
||||
|
||||
type publishedNotice struct {
|
||||
title string
|
||||
priority int
|
||||
}
|
||||
|
||||
func capturePublications(t *testing.T) func() []publishedNotice {
|
||||
t.Helper()
|
||||
t.Setenv("PIPELINES_NTFY_URL", "https://ntfy.invalid/pipelines")
|
||||
var mu sync.Mutex
|
||||
var got []publishedNotice
|
||||
previous := chatAttentionPublish
|
||||
chatAttentionPublish = func(ctx context.Context, _, title, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
|
||||
mu.Lock()
|
||||
got = append(got, publishedNotice{title, stage.NtfyPriority(ctx)})
|
||||
mu.Unlock()
|
||||
return stage.Values{}, nil
|
||||
}
|
||||
t.Cleanup(func() { chatAttentionPublish = previous })
|
||||
return func() []publishedNotice {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]publishedNotice(nil), got...)
|
||||
}
|
||||
}
|
||||
|
||||
func autoSwitchServer(t *testing.T, sessions ...string) (*refusingChat, *queueServer, *pipeline.Store) {
|
||||
t.Helper()
|
||||
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
|
||||
for _, id := range sessions {
|
||||
if err := store.RecordOperatorSession(context.Background(), id, "/work", "Fix "+id, protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
broker := &refusingChat{channelChat: newChannelChat()}
|
||||
broker.switch_ = func(refusal claude.UsageRefusal) (claude.AutoSwitch, error) {
|
||||
return claude.AutoSwitch{From: "a@example.invalid", To: "b@example.invalid", Switched: true}, nil
|
||||
}
|
||||
return broker, startQueueServer(t, broker, store), store
|
||||
}
|
||||
|
||||
// A refused turn switches once and queues one guarded, visibly automatic
|
||||
// continue prompt behind the turn; the app's auto-continue-at-reset prompt
|
||||
// for the refusal is taken out, and a late one is refused. The operator is
|
||||
// told at low priority.
|
||||
func TestUsageRefusalSwitchesAccountAndQueuesAGuardedContinue(t *testing.T) {
|
||||
published := capturePublications(t)
|
||||
broker, server, store := autoSwitchServer(t, "ses_1")
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
if ack := sendPrompt(t, server.ctx, conn, "p1", "work", "op-1"); ack.ChatQueued {
|
||||
t.Fatalf("first prompt queued: %+v", ack)
|
||||
}
|
||||
waitFor(t, "turn started", func() bool { return broker.promptCount() == 1 })
|
||||
// The app saw the refusal and scheduled auto-continue at the reset.
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p2", "continue", "auto-continue-refusal-1", time.Now().Add(time.Hour)); !ack.ChatQueued {
|
||||
t.Fatalf("auto-continue not queued: %+v", ack)
|
||||
}
|
||||
|
||||
refusal := claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", Email: "a@example.invalid"}
|
||||
broker.refuse(refusal)
|
||||
broker.refuse(refusal) // the same refusal again switches nothing more
|
||||
if n := broker.callCount(); n != 1 {
|
||||
t.Fatalf("switch attempts = %d", n)
|
||||
}
|
||||
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-switch-refusal-1"}) {
|
||||
t.Fatalf("queued = %v", ops)
|
||||
}
|
||||
// Another device scheduling the same refusal's auto-continue now is
|
||||
// acknowledged and taken straight back out.
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p3", "continue", "auto-continue-refusal-1", time.Now().Add(time.Hour)); !ack.ChatQueued {
|
||||
t.Fatalf("late auto-continue ack = %+v", ack)
|
||||
}
|
||||
// So is one for any refusal while the continue prompt is still waiting.
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p4", "continue", "auto-continue-other", time.Now().Add(time.Hour)); !ack.ChatQueued {
|
||||
t.Fatalf("other auto-continue ack = %+v", ack)
|
||||
}
|
||||
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-switch-refusal-1"}) {
|
||||
t.Fatalf("queued after late auto-continue = %v", ops)
|
||||
}
|
||||
|
||||
endTurn(broker.channelChat)
|
||||
waitFor(t, "continue prompt delivered", func() bool { return broker.promptCount() == 2 })
|
||||
text := broker.promptTexts()[1]
|
||||
for _, want := range []string{"[Sent automatically by Pipelines]", "a@example.invalid", "b@example.invalid", "off the rails", "stop and ask me"} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Fatalf("continue prompt lacks %q: %s", want, text)
|
||||
}
|
||||
}
|
||||
waitFor(t, "queue emptied", func() bool { return len(queuedOps(t, store)) == 0 })
|
||||
// Once it was sent, a later refusal's auto-continue is the app's again.
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p5", "continue", "auto-continue-refusal-9", time.Now().Add(time.Hour)); !ack.ChatQueued {
|
||||
t.Fatalf("later auto-continue ack = %+v", ack)
|
||||
}
|
||||
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-9"}) {
|
||||
t.Fatalf("later auto-continue not kept: %v", ops)
|
||||
}
|
||||
notices := published()
|
||||
if len(notices) != 1 || notices[0].title != "Switched Fix ses_1 to b@example.invalid and continued" || notices[0].priority != 2 {
|
||||
t.Fatalf("notices = %+v", notices)
|
||||
}
|
||||
}
|
||||
|
||||
// With nothing to switch to (every account exhausted, or switching turned
|
||||
// off), the refusal is left to auto-continue at the reset.
|
||||
func TestUsageRefusalWithoutASwitchLeavesTheChat(t *testing.T) {
|
||||
for _, failure := range []error{claude.ErrNoAccountLeft, claude.ErrAutoSwitchOff} {
|
||||
t.Run(failure.Error(), func(t *testing.T) {
|
||||
published := capturePublications(t)
|
||||
broker, server, store := autoSwitchServer(t, "ses_1")
|
||||
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) { return claude.AutoSwitch{}, failure }
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p1", "continue", "auto-continue-refusal-1", time.Now().Add(time.Hour)); !ack.ChatQueued {
|
||||
t.Fatalf("auto-continue not queued: %+v", ack)
|
||||
}
|
||||
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", Email: "a@example.invalid"})
|
||||
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-1"}) {
|
||||
t.Fatalf("queued = %v", ops)
|
||||
}
|
||||
if n := broker.promptCount(); n != 0 || len(published()) != 0 {
|
||||
t.Fatalf("prompts = %d notices = %v", n, published())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Chats refused together each get their own continue prompt; a chat that is
|
||||
// not the operator's is left alone.
|
||||
func TestConcurrentUsageRefusalsContinueEveryChat(t *testing.T) {
|
||||
capturePublications(t)
|
||||
broker, _, _ := autoSwitchServer(t, "ses_1", "ses_2")
|
||||
broker.quiet = true
|
||||
var once sync.Once
|
||||
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) {
|
||||
switched := false
|
||||
once.Do(func() { switched = true })
|
||||
return claude.AutoSwitch{From: "a@example.invalid", To: "b@example.invalid", Switched: switched}, nil
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for _, id := range []string{"ses_1", "ses_2", "ses_stage"} {
|
||||
wg.Add(1)
|
||||
go func(id string) {
|
||||
defer wg.Done()
|
||||
broker.refuse(claude.UsageRefusal{SessionID: id, TurnID: "claude-1", MessageID: "refusal-" + id, Email: "a@example.invalid"})
|
||||
}(id)
|
||||
}
|
||||
wg.Wait()
|
||||
if n := broker.callCount(); n != 2 {
|
||||
t.Fatalf("switch attempts = %d", n)
|
||||
}
|
||||
waitFor(t, "both chats continued", func() bool { return broker.promptCount() == 2 })
|
||||
for _, text := range broker.promptTexts() {
|
||||
if !strings.HasPrefix(text, "[Sent automatically by Pipelines]") {
|
||||
t.Fatalf("prompt = %q", text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeAccountAutoSwitchRequestRoutesTheChoice(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "chat.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
claudeID := "01900000-0000-7000-8000-000000000031"
|
||||
if err := store.RecordOperatorSession(ctx, claudeID, "/home/op/caplens", "chat", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetOperatorSessionBackend(ctx, claudeID, "claude"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claudeChat := &accountChat{fakeChat: scriptedChat()}
|
||||
manager := &chatManager{claude: claudeChat, registry: store, cache: map[string]string{}}
|
||||
var reply protocol.Message
|
||||
capture := func(msg protocol.Message) error { reply = msg; return nil }
|
||||
for _, on := range []bool{false, true} {
|
||||
value := on
|
||||
handleChat(ctx, protocol.Message{Type: protocol.ClaudeAccountAutoSwitch, ID: "r", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: claudeID, AutoSwitch: &value}}, manager, nil, store, "client", capture)
|
||||
if reply.Type != protocol.ClaudeAccountAutoSwitch || reply.ClaudeAccounts == nil {
|
||||
t.Fatalf("reply = %+v", reply)
|
||||
}
|
||||
}
|
||||
want := []string{claudeID + "|/home/op/caplens|claude_account_auto_switch|off", claudeID + "|/home/op/caplens|claude_account_auto_switch|on"}
|
||||
if !slices.Equal(claudeChat.calls, want) {
|
||||
t.Fatalf("calls = %v", claudeChat.calls)
|
||||
}
|
||||
handleChat(ctx, protocol.Message{Type: protocol.ClaudeAccountAutoSwitch, ID: "r", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: claudeID}}, manager, nil, store, "client", capture)
|
||||
if reply.Type != protocol.Error || !strings.Contains(reply.Error, "auto_switch") {
|
||||
t.Fatalf("missing choice reply = %+v", reply)
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,8 @@ func (m *chatManager) ClaudeAccounts(ctx context.Context, sessionID, operation,
|
||||
}
|
||||
|
||||
// handleClaudeAccounts answers claude_accounts, claude_account_save,
|
||||
// claude_account_use and claude_account_remove. Replies describe accounts
|
||||
// claude_account_use, claude_account_remove and claude_account_auto_switch
|
||||
// (whose choice reaches the adapter as the name "on" or "off"). Replies describe accounts
|
||||
// only; no token ever leaves the server.
|
||||
func handleClaudeAccounts(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
|
||||
body := request.ClaudeAccount
|
||||
@@ -53,6 +54,17 @@ func handleClaudeAccounts(ctx context.Context, request protocol.Message, broker
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a saved account name is required"})
|
||||
return
|
||||
}
|
||||
name := body.Name
|
||||
if request.Type == protocol.ClaudeAccountAutoSwitch {
|
||||
if body.AutoSwitch == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "auto_switch (true or false) is required"})
|
||||
return
|
||||
}
|
||||
name = "off"
|
||||
if *body.AutoSwitch {
|
||||
name = "on"
|
||||
}
|
||||
}
|
||||
switcher, ok := broker.(interface {
|
||||
ClaudeAccounts(ctx context.Context, sessionID, operation, name string) (protocol.ClaudeAccountList, error)
|
||||
})
|
||||
@@ -60,7 +72,7 @@ func handleClaudeAccounts(ctx context.Context, request protocol.Message, broker
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: errNotClaudeChat.Error()})
|
||||
return
|
||||
}
|
||||
list, err := switcher.ClaudeAccounts(ctx, body.SessionID, request.Type, body.Name)
|
||||
list, err := switcher.ClaudeAccounts(ctx, body.SessionID, request.Type, name)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
|
||||
@@ -89,6 +89,9 @@ type chatHub struct {
|
||||
// shown holds the items chats showed through the Pipelines tools; the
|
||||
// subscribe reply carries a chat's retained list. nil records none.
|
||||
shown chatShownStore
|
||||
// autoSwitch records the usage-limit refusals the server already
|
||||
// continued on another Claude account (chat_auto_switch.go).
|
||||
autoSwitch chatAutoSwitchState
|
||||
}
|
||||
|
||||
// chatPart is the retained form of one part. Text and reasoning deltas append to
|
||||
|
||||
@@ -42,6 +42,9 @@ type chatManager struct {
|
||||
closed bool
|
||||
cache map[string]string // session id -> backend
|
||||
hinted map[string]bool // sessions whose directory was given to a chatDirectoryHinter
|
||||
// onRefusal receives Claude Code's usage-limit refusals
|
||||
// (chat_auto_switch.go); guarded by mu.
|
||||
onRefusal func(claude.UsageRefusal)
|
||||
}
|
||||
|
||||
// harnessProbeInterval bounds how often a missing harness is probed again, so
|
||||
@@ -158,6 +161,9 @@ func (m *chatManager) harness(backend string) chatBroker {
|
||||
m.codex = client
|
||||
} else {
|
||||
m.claude = client
|
||||
if source, ok := client.(chatRefusalSource); ok && m.onRefusal != nil {
|
||||
source.OnUsageRefused(m.onRefusal)
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if m.started {
|
||||
|
||||
@@ -101,7 +101,7 @@ func (h *chatHub) admitPrompt(ctx context.Context, sessionID string, broker chat
|
||||
h.mu.Unlock()
|
||||
return chatAdmitRun, nil
|
||||
}
|
||||
if steerer, ok := broker.(chatMidTurn); ok && !queuedAhead {
|
||||
if steerer, ok := broker.(chatMidTurn); ok && !queuedAhead && !p.noSteer {
|
||||
delivered, err := steerer.SteerPrompt(ctx, sessionID, p.text, p.nativeID, p.files)
|
||||
if err != nil {
|
||||
return chatAdmitRefused, err
|
||||
|
||||
@@ -123,6 +123,9 @@ type chatQueuedPrompt struct {
|
||||
// sendAt schedules the prompt: the runner holds it (and, FIFO, everything
|
||||
// queued behind it) until this time. Zero means deliver when free.
|
||||
sendAt time.Time
|
||||
// noSteer queues a prompt behind a running turn instead of handing it to
|
||||
// that turn (a prompt the server composed to follow the turn's end).
|
||||
noSteer bool
|
||||
}
|
||||
|
||||
type chatObservation struct {
|
||||
|
||||
@@ -77,6 +77,14 @@ func admitChatPrompt(ctx context.Context, request protocol.Message, broker chatB
|
||||
hub.attach(prompt.SessionID, clientID, sanitizeChatClientLabel(prompt.Client), broker, write)
|
||||
_ = write(protocol.Message{Type: protocol.ChatPrompt, ID: request.ID, ChatQueued: queued, ChatSteered: steered})
|
||||
return
|
||||
} else if hub.autoContinueSuperseded(prompt.SessionID, operationID) {
|
||||
// The server already continued this refusal on another Claude account:
|
||||
// acknowledge the auto-continue and take it straight back out, as if
|
||||
// another device had unchecked it.
|
||||
hub.attach(prompt.SessionID, clientID, sanitizeChatClientLabel(prompt.Client), broker, write)
|
||||
_ = write(protocol.Message{Type: protocol.ChatPrompt, ID: request.ID, ChatQueued: true})
|
||||
hub.fanoutQueue(prompt.SessionID, protocol.ChatQueueFrame{Removed: operationID})
|
||||
return
|
||||
}
|
||||
attachmentFiles, attachmentParts, err := prepareChatAttachments(prompt.SessionID, prompt.Attachments)
|
||||
if err != nil {
|
||||
|
||||
@@ -137,6 +137,10 @@ 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.
|
||||
|
||||
Reference in New Issue
Block a user