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:
2026-12-01 00:23:43 +00:00
parent 1995382e8c
commit ed9072b79a
30 changed files with 1362 additions and 21 deletions
+23 -10
View File
@@ -71,21 +71,34 @@ func (c *Chat) ClaudeAccounts(ctx context.Context, sessionID, directory, operati
case protocol.ClaudeAccountRemove:
return store.Remove(name)
case protocol.ClaudeAccountUse:
list, err := store.Use(name)
if err != nil {
return list, err
return c.useAccount(ctx, configDir, store, name)
case protocol.ClaudeAccountAutoSwitch:
switch name {
case "on", "off":
return store.SetAutoSwitch(name == "on")
}
email, org, plan, ok := store.Identity()
if ok {
account := accountIdentity{key: accountKeyFor(email, org), plan: plan, email: strings.TrimSpace(email), organization: strings.TrimSpace(org)}
list.Usage = c.switchAccount(ctx, configDir, account)
log.Printf("claude account: %s switched to a saved account", configDir)
}
return list, nil
return protocol.ClaudeAccountList{}, errors.New(`automatic switching is "on" or "off"`)
}
return protocol.ClaudeAccountList{}, errors.New("unknown Claude account operation " + operation)
}
// useAccount makes the saved account name configDir's login and moves every
// open chat on that Claude home to it (claude_account_use and the automatic
// switch share it).
func (c *Chat) useAccount(ctx context.Context, configDir string, store claudeaccounts.Store, name string) (protocol.ClaudeAccountList, error) {
list, err := store.Use(name)
if err != nil {
return list, err
}
email, org, plan, ok := store.Identity()
if ok {
account := accountIdentity{key: accountKeyFor(email, org), plan: plan, email: strings.TrimSpace(email), organization: strings.TrimSpace(org)}
list.Usage = c.switchAccount(ctx, configDir, account)
log.Printf("claude account: %s switched to a saved account", configDir)
}
return list, nil
}
// switchAccount records that configDir now signs in as account: its quota
// report is marked switched (an empty one when nothing is known yet), and
// every open session on that Claude home takes the new account and
+220
View File
@@ -0,0 +1,220 @@
package claude
import (
"context"
"errors"
"sort"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Automatic account switching: when a chat's turn is refused for a usage
// limit and its Claude home has another saved account with usage left, the
// home is switched to it (the claude_account_use path, under the same locks)
// so the server can continue the chat there. Switches of one home are
// serialized, so chats refused together switch once.
var (
// ErrAutoSwitchOff is returned when the Claude home's operator turned
// automatic switching off.
ErrAutoSwitchOff = errors.New("automatic Claude account switching is off for this Claude home")
// ErrNoAccountLeft is returned when no other saved account is known to
// have usage left.
ErrNoAccountLeft = errors.New("no other saved Claude account has usage left")
)
// refusalHold is how long a refused account is passed over when neither its
// quota nor the refusal said when its limit resets.
const refusalHold = time.Hour
// AutoSwitch is the outcome of AutoSwitchAccount.
type AutoSwitch struct {
// From is the account that was refused and To the one the home is
// signed in to now.
From, To string
// Switched is false when another refused chat on the same home had
// already switched it to To, which still has usage.
Switched bool
// Usage is To's latest known quota (marked switched when Switched).
Usage *protocol.ChatAccountUsage
}
// AutoSwitchAccount handles one usage-limit refusal: it marks the refused
// account as out of usage and, when the chat's Claude home allows automatic
// switching, signs the home in to the saved account with the lowest known
// usage that is not exhausted (an account with no known quota is still worth
// trying, after those known to have usage). It reports ErrAutoSwitchOff,
// ErrNoAccountLeft or ErrNoConfigDir when nothing is switched.
func (c *Chat) AutoSwitchAccount(ctx context.Context, refusal UsageRefusal) (AutoSwitch, error) {
directory := refusal.Directory
if strings.TrimSpace(directory) == "" {
if s := c.session(refusal.SessionID); s != nil {
s.mu.Lock()
directory = s.directory
s.mu.Unlock()
}
}
configDir, err := c.accountConfigDir(ctx, directory)
if err != nil {
return AutoSwitch{}, err
}
lock := c.autoLock(configDir)
lock.Lock()
defer lock.Unlock()
store := claudeaccounts.Store{ConfigDir: configDir}
if !store.AutoSwitch() {
return AutoSwitch{}, ErrAutoSwitchOff
}
list, err := store.List()
if err != nil {
return AutoSwitch{}, err
}
if list.Active == nil {
return AutoSwitch{}, ErrNoAccountLeft
}
now := time.Now()
from := strings.TrimSpace(refusal.Email)
if from == "" {
from = list.Active.Email
}
c.markRefused(from, organizationOf(list, from), now)
active := *list.Active
if !strings.EqualFold(active.Email, from) && c.usable(active, now) {
// Another chat's refusal already moved the home on.
identity := accountIdentity{key: accountKeyFor(active.Email, active.Organization), plan: active.Plan, email: active.Email, organization: active.Organization}
return AutoSwitch{From: from, To: active.Email, Usage: c.accountUsage(identity)}, nil
}
candidate, ok := c.pickAccount(list, from, now)
if !ok {
return AutoSwitch{}, ErrNoAccountLeft
}
switched, err := c.useAccount(ctx, configDir, store, candidate.Name)
if err != nil {
return AutoSwitch{}, err
}
to := candidate.Email
if switched.Active != nil {
to = switched.Active.Email
}
return AutoSwitch{From: from, To: to, Switched: true, Usage: switched.Usage}, nil
}
func (c *Chat) autoLock(configDir string) *sync.Mutex {
c.autoMu.Lock()
defer c.autoMu.Unlock()
if c.autoLocks == nil {
c.autoLocks = map[string]*sync.Mutex{}
}
lock := c.autoLocks[configDir]
if lock == nil {
lock = &sync.Mutex{}
c.autoLocks[configDir] = lock
}
return lock
}
func organizationOf(list protocol.ClaudeAccountList, email string) string {
if list.Active != nil && strings.EqualFold(list.Active.Email, email) {
return list.Active.Organization
}
for _, account := range list.Accounts {
if strings.EqualFold(account.Email, email) {
return account.Organization
}
}
return ""
}
// markRefused passes over email until its limit resets: the reset a
// rejected rate_limit_event named, else the latest reset of its exhausted
// windows, else refusalHold from now.
func (c *Chat) markRefused(email, organization string, now time.Time) {
if strings.TrimSpace(email) == "" {
return
}
c.quotaMu.Lock()
defer c.quotaMu.Unlock()
if c.rejectedUntil[strings.ToLower(strings.TrimSpace(email))].After(now) {
return
}
until := now.Add(refusalHold)
if quota := c.quotas[accountKeyFor(email, organization)]; quota != nil {
latest := int64(0)
for _, w := range quota.Windows {
if w.UsedPercent >= 100 && w.ResetsAt > now.UnixMilli() && w.ResetsAt > latest {
latest = w.ResetsAt
}
}
if latest > 0 {
until = time.UnixMilli(latest)
}
}
c.noteRejectedLocked(email, until)
}
// usable reports whether account is neither marked refused nor known to be
// out of usage.
func (c *Chat) usable(account protocol.ClaudeAccount, now time.Time) bool {
_, _, ok := c.usageLeft(account, now)
return ok
}
// usageLeft is account's highest current window use (known false when no
// quota is known) and whether it can take a turn now.
func (c *Chat) usageLeft(account protocol.ClaudeAccount, now time.Time) (percent float64, known, ok bool) {
c.quotaMu.Lock()
defer c.quotaMu.Unlock()
if c.rejectedUntil[strings.ToLower(strings.TrimSpace(account.Email))].After(now) {
return 0, false, false
}
quota := c.quotas[accountKeyFor(account.Email, account.Organization)]
if quota == nil || len(quota.Windows) == 0 {
return 0, false, true
}
for _, w := range quota.Windows {
if w.ResetsAt != 0 && w.ResetsAt <= now.UnixMilli() {
continue // reset since it was reported
}
if w.UsedPercent >= 100 {
return w.UsedPercent, true, false
}
if w.UsedPercent > percent {
percent = w.UsedPercent
}
}
return percent, true, true
}
// pickAccount chooses the saved account to switch to after from was refused.
func (c *Chat) pickAccount(list protocol.ClaudeAccountList, from string, now time.Time) (protocol.ClaudeAccount, bool) {
type option struct {
account protocol.ClaudeAccount
percent float64
known bool
}
var options []option
for _, account := range list.Accounts {
if account.Active || !account.Saved || strings.EqualFold(account.Email, from) {
continue
}
percent, known, ok := c.usageLeft(account, now)
if ok {
options = append(options, option{account, percent, known})
}
}
if len(options) == 0 {
return protocol.ClaudeAccount{}, false
}
sort.SliceStable(options, func(i, j int) bool {
a, b := options[i], options[j]
if a.known != b.known {
return a.known
}
return a.percent < b.percent
})
return options[0].account, true
}
+173
View File
@@ -0,0 +1,173 @@
package claude
import (
"context"
"errors"
"path/filepath"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestUsageLimitRefusalIsReportedOnceWithItsAccount(t *testing.T) {
chat := testChat(t)
refusals := make(chan UsageRefusal, 4)
chat.OnUsageRefused(func(refusal UsageRefusal) { refusals <- refusal })
created := newCreatedChat(t, chat)
frames := subscribe(t, chat, created.ID)
ended := func(what string) {
waitFrame(t, frames, what, func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded
})
}
if err := chat.Prompt(context.Background(), created.ID, "hello"); err != nil {
t.Fatal(err)
}
ended("an ordinary turn's end")
if err := chat.Prompt(context.Background(), created.ID, "usage-limit"); err != nil {
t.Fatal(err)
}
ended("the refused turn's end")
select {
case refusal := <-refusals:
if refusal.SessionID != created.ID || refusal.MessageID != "refusal-2" || refusal.Email != "fixture@example.invalid" ||
refusal.TurnID == "" || refusal.Directory != created.Directory {
t.Fatalf("refusal = %+v", refusal)
}
case <-time.After(5 * time.Second):
t.Fatal("the refusal was not reported")
}
select {
case extra := <-refusals:
t.Fatalf("a second refusal was reported: %+v", extra)
case <-time.After(200 * time.Millisecond):
}
// The rejected rate_limit_event says when the limit ends.
chat.quotaMu.Lock()
until := chat.rejectedUntil["fixture@example.invalid"]
chat.quotaMu.Unlock()
if !until.Equal(time.Unix(1900000000, 0)) {
t.Fatalf("rejected until %v", until)
}
}
func TestUsageRefusalNeedsTheLimitText(t *testing.T) {
s := &session{id: "s", turnID: "t1", account: accountIdentity{email: "a@example.invalid"}}
s.beginTurnLocked()
s.noteUsageRefusalLocked(lineEnvelope{}, messageBody{}, []contentBlock{{Type: "text", Text: "Done; nothing hit any limit."}}, "m1")
if _, refused := s.takeUsageRefusalLocked(lineEnvelope{IsError: true, Result: "Done"}); refused {
t.Fatal("an ordinary error result was taken for a usage refusal")
}
// The older CLI's text on the result alone is enough.
s.turnID = "t2"
refusal, refused := s.takeUsageRefusalLocked(lineEnvelope{IsError: true, Result: "Claude AI usage limit reached|1900000000"})
if !refused || refusal.Email != "a@example.invalid" || refusal.TurnID != "t2" {
t.Fatalf("refusal = %+v %v", refusal, refused)
}
}
// accountsHome is a chat directory whose Claude home has saved accounts a-e,
// signed in as a.
func accountsHome(t *testing.T, chat *Chat) string {
t.Helper()
profile := t.TempDir()
directory := t.TempDir()
writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n")
writeFile(t, filepath.Join(directory, ".envrc.allowed"), "")
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`"}`)
for _, name := range []string{"e", "d", "c", "b", "a"} {
writeLogin(t, profile, name+"@example.invalid", "uuid-"+name, name+"1")
if _, err := chat.ClaudeAccounts(context.Background(), "s", directory, protocol.ClaudeAccountSave, ""); err != nil {
t.Fatal(err)
}
}
return directory
}
func setQuota(chat *Chat, email string, percent float64, resetsAt int64) {
chat.quotaMu.Lock()
defer chat.quotaMu.Unlock()
if chat.quotas == nil {
chat.quotas = map[string]*protocol.ChatAccountUsage{}
}
chat.quotas[accountKeyFor(email, "Org")] = &protocol.ChatAccountUsage{Harness: quotaHarness,
Windows: []protocol.ChatQuotaWindow{{ID: "five_hour", Label: "5-hour", UsedPercent: percent, ResetsAt: resetsAt}}}
}
func TestAutoSwitchMovesToTheSavedAccountWithTheMostUsageLeft(t *testing.T) {
chat := directoryChat(t)
directory := accountsHome(t, chat)
ctx := context.Background()
future := time.Now().Add(3 * time.Hour).UnixMilli()
setQuota(chat, "a@example.invalid", 100, future)
setQuota(chat, "b@example.invalid", 80, future)
setQuota(chat, "c@example.invalid", 20, future)
setQuota(chat, "d@example.invalid", 100, future) // exhausted
// e has no known quota.
// Two chats refused on a at once: the home switches once, to c.
var wg sync.WaitGroup
results := make([]AutoSwitch, 2)
errs := make([]error, 2)
for i := range results {
wg.Add(1)
go func(i int) {
defer wg.Done()
results[i], errs[i] = chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: "a@example.invalid"})
}(i)
}
wg.Wait()
if errs[0] != nil || errs[1] != nil {
t.Fatalf("errs = %v", errs)
}
if results[0].Switched == results[1].Switched || results[0].To != "c@example.invalid" || results[1].To != "c@example.invalid" {
t.Fatalf("results = %+v", results)
}
for _, result := range results {
if result.From != "a@example.invalid" {
t.Fatalf("from = %+v", result)
}
if result.Switched && (result.Usage == nil || result.Usage.SwitchedAt == 0) {
t.Fatalf("the switch was not marked: %+v", result.Usage)
}
}
// c is refused too: the next best known account is b; then e, whose
// usage nobody knows; then nothing is left (a was refused, d is out).
for _, step := range []struct{ from, to string }{{"c@example.invalid", "b@example.invalid"}, {"b@example.invalid", "e@example.invalid"}} {
result, err := chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: step.from})
if err != nil || !result.Switched || result.To != step.to {
t.Fatalf("after %s: %+v %v", step.from, result, err)
}
}
if _, err := chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: "e@example.invalid"}); !errors.Is(err, ErrNoAccountLeft) {
t.Fatalf("all exhausted: %v", err)
}
list, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccounts, "")
if err != nil || list.Active == nil || list.Active.Email != "e@example.invalid" {
t.Fatalf("active = %+v %v", list.Active, err)
}
}
func TestAutoSwitchOffLeavesTheAccount(t *testing.T) {
chat := directoryChat(t)
directory := accountsHome(t, chat)
ctx := context.Background()
list, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountAutoSwitch, "off")
if err != nil || list.AutoSwitch {
t.Fatalf("auto off = %+v %v", list, err)
}
if _, err := chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: "a@example.invalid"}); !errors.Is(err, ErrAutoSwitchOff) {
t.Fatalf("err = %v", err)
}
list, _ = chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccounts, "")
if list.Active == nil || list.Active.Email != "a@example.invalid" {
t.Fatalf("switched while off: %+v", list.Active)
}
if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountAutoSwitch, "maybe"); err == nil {
t.Fatal("a bad choice was accepted")
}
}
+2
View File
@@ -188,6 +188,7 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
s.mu.Lock()
s.turnID = turn
s.running = true
s.beginTurnLocked()
s.steered = 0
s.awaitFollowUp = false
s.recordPromptLocked(messageID, text)
@@ -271,6 +272,7 @@ func (s *session) adoptFollowUpTurn() {
turn := fmt.Sprintf("claude-%d", time.Now().UnixNano())
s.turnID = turn
s.running = true
s.beginTurnLocked()
s.mu.Unlock()
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
}
+19 -2
View File
@@ -116,6 +116,17 @@ type Chat struct {
// quotas is the latest rate_limit_event quota per account (see quota.go).
quotaMu sync.Mutex
quotas map[string]*protocol.ChatAccountUsage
// rejectedUntil is when an account's usage-limit refusal ends, from a
// rejected rate_limit_event or a refusal (by lower-case email); guarded
// by quotaMu (auto_switch.go).
rejectedUntil map[string]time.Time
// onRefusal receives every live usage-limit refusal (refusal.go);
// autoLocks serializes automatic switches per Claude home.
refusalMu sync.Mutex
onRefusal func(UsageRefusal)
autoMu sync.Mutex
autoLocks map[string]*sync.Mutex
// catalog is the latest initialize model list of any session (efforts.go),
// so a listed row names its levels without starting a CLI.
@@ -370,8 +381,14 @@ type session struct {
automationProcess *process
// account is the signed-in account the live process reported.
account accountIdentity
prompts []promptRecord
models []protocol.ChatModel
// turnEmail is the account the running turn started on; limitMessageID
// and limitByError record a usage-limit refusal the turn received
// (refusal.go).
turnEmail string
limitMessageID string
limitByError bool
prompts []promptRecord
models []protocol.ChatModel
// commands are the slash commands the live CLI's initialize listed;
// terminalCommands are those its init line marks terminal-only (commands.go).
commands []protocol.ChatCommand
+1
View File
@@ -379,6 +379,7 @@ func (p *process) readHost(conn *claudehost.Conn, plan replayPlan) {
turn = fmt.Sprintf("claude-%d", time.Now().UnixNano())
s.turnID = turn
s.running = true
s.beginTurnLocked()
s.steered = 0
} else if !plan.busyAtAcked {
// Output that starts a turn after the reconnect (a follow-up of
+19
View File
@@ -200,6 +200,9 @@ func (s *session) handleRateLimit(raw json.RawMessage) {
}
c := s.chat
c.quotaMu.Lock()
if until, ok := rejectedUntil(raw); ok {
c.noteRejectedLocked(account.email, until)
}
next := mergeRateLimit(c.quotas[key], raw, account.plan, time.Now())
if next == nil {
c.quotaMu.Unlock()
@@ -229,6 +232,22 @@ func (s *session) handleRateLimit(raw json.RawMessage) {
}
}
// rejectedUntil reports when a rejected rate_limit_event's limit resets: a
// refusal the account cannot draw extra usage past.
func rejectedUntil(raw json.RawMessage) (time.Time, bool) {
var info rateLimitInfo
if len(raw) == 0 || json.Unmarshal(raw, &info) != nil || info.Status != "rejected" {
return time.Time{}, false
}
if extra := info.extraUsage(); extra != nil && extra.InUse {
return time.Time{}, false
}
if info.ResetsAt == nil || *info.ResetsAt <= 0 || math.IsInf(*info.ResetsAt, 0) {
return time.Time{}, false
}
return time.UnixMilli(int64(*info.ResetsAt * 1000)), true
}
func containsSession(list []*session, s *session) bool {
for _, other := range list {
if other == s {
+105
View File
@@ -0,0 +1,105 @@
package claude
import (
"regexp"
"strings"
"time"
)
// A turn Claude Code refuses for a usage limit ends with a synthetic
// assistant message carrying the API error ("rate_limit") and the CLI's own
// text, "You've hit your 5-hour limit · resets 5:20pm (Europe/London) · out of
// usage credits" (older CLIs: "Claude AI usage limit reached|<epoch>"), and a
// result line marked is_error that repeats it. The app recognises the same
// text (app domain/chat_usage_limit.dart).
var usageLimitText = regexp.MustCompile(`(?m)^\s*You['’]ve hit your [^·\n]*limit|usage limit reached\|\d{9,11}\b`)
// UsageRefusal is one live turn Claude Code refused because the account ran
// out of usage.
type UsageRefusal struct {
SessionID string
// Directory is the chat's working directory, which selects its Claude
// home (CLAUDE_CONFIG_DIR).
Directory string
TurnID string
// MessageID is the refusal message's id, as transcripts name it ("" when
// only the result reported it).
MessageID string
// Email is the account the refused turn started on ("" when unknown).
Email string
}
// OnUsageRefused registers the receiver of usage-limit refusals; each is
// delivered once, on its own goroutine, after the turn's end was published.
func (c *Chat) OnUsageRefused(handler func(UsageRefusal)) {
c.refusalMu.Lock()
c.onRefusal = handler
c.refusalMu.Unlock()
}
func (c *Chat) reportUsageRefusal(refusal UsageRefusal) {
c.refusalMu.Lock()
handler := c.onRefusal
c.refusalMu.Unlock()
if handler != nil {
go handler(refusal)
}
}
// beginTurnLocked records the account a new turn starts on and forgets any
// refusal of the previous turn. The caller holds s.mu.
func (s *session) beginTurnLocked() {
s.turnEmail = s.account.email
s.limitMessageID = ""
s.limitByError = false
}
// noteUsageRefusalLocked remembers an assistant message that is a
// usage-limit refusal. The caller holds s.mu.
func (s *session) noteUsageRefusalLocked(envelope lineEnvelope, body messageBody, blocks []contentBlock, messageID string) {
byError := envelope.Error == "rate_limit" || body.Error == "rate_limit"
byText := false
for _, block := range blocks {
if block.Type == "text" && usageLimitText.MatchString(block.Text) {
byText = true
break
}
}
if byError || byText {
s.limitMessageID = messageID
s.limitByError = s.limitByError || byError
}
}
// takeUsageRefusalLocked reports whether the turn a result line ends was
// refused for a usage limit, and clears the record. The caller holds s.mu.
func (s *session) takeUsageRefusalLocked(envelope lineEnvelope) (UsageRefusal, bool) {
refused := (s.limitMessageID != "" && (s.limitByError || envelope.IsError)) ||
(envelope.IsError && usageLimitText.MatchString(envelope.Result))
email := s.turnEmail
if email == "" {
email = s.account.email
}
refusal := UsageRefusal{SessionID: s.id, Directory: s.directory, TurnID: s.turnID, MessageID: s.limitMessageID, Email: email}
if refusal.TurnID == "" {
refusal.TurnID = "result-" + strings.TrimSpace(envelope.UUID)
}
s.limitMessageID = ""
s.limitByError = false
return refusal, refused
}
// noteRejectedLocked records when a rejected account's limit ends. The
// caller holds c.quotaMu.
func (c *Chat) noteRejectedLocked(email string, until time.Time) {
email = strings.ToLower(strings.TrimSpace(email))
if email == "" || until.IsZero() {
return
}
if c.rejectedUntil == nil {
c.rejectedUntil = map[string]time.Time{}
}
if until.After(c.rejectedUntil[email]) {
c.rejectedUntil[email] = until
}
}
+22
View File
@@ -79,6 +79,9 @@ def user_message(text):
if "background" in text:
background(message_id)
return
if "usage-limit" in text:
refused(message_id)
return
if "notify" in text:
send({"type": "system", "subtype": "task_notification", "task_id": "b1",
"tool_use_id": "toolu_bg_fake", "status": "completed", "summary": "Background command completed (exit code 0)"})
@@ -175,6 +178,25 @@ def background(message_id):
finish(message_id)
def refused(message_id):
"""A turn refused for a usage limit, as Claude Code 2.1 ends one: a rejected
rate_limit_event, a synthetic assistant API-error message and an is_error
result repeating its text."""
text = "You've hit your 5-hour limit · resets 5:20pm (Europe/London) · out of usage credits"
send({"type": "rate_limit_event", "uuid": "rate-%d" % state["turn"], "session_id": state["session"],
"rate_limit_info": {"status": "rejected", "resetsAt": 1900000000, "rateLimitType": "five_hour",
"isUsingOverage": False, "overageStatus": "rejected",
"overageDisabledReason": "out_of_credits"}})
refusal_id = "refusal-%d" % state["turn"]
message = {"id": refusal_id, "role": "assistant", "model": "<synthetic>",
"content": [{"type": "text", "text": text}]}
append({"type": "assistant", "uuid": refusal_id, "timestamp": stamp(), "error": "rate_limit",
"isApiErrorMessage": True, "message": message})
send({"type": "assistant", "uuid": refusal_id, "error": "rate_limit", "message": message})
send({"type": "result", "subtype": "success", "is_error": True, "result": text,
"session_id": state["session"]})
def finish(message_id):
# Shape of SDKRateLimitEvent in Claude Code 2.1.316 (synthetic numbers).
if os.environ.get("FAKE_CLAUDE_RATE_LIMIT"):
+10
View File
@@ -42,6 +42,9 @@ type lineEnvelope struct {
IsMeta bool `json:"isMeta"`
// RateLimitInfo is the payload of a rate_limit_event line (see quota.go).
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
// Error names an API error an assistant line reports ("rate_limit" for a
// usage-limit refusal; see refusal.go).
Error string `json:"error"`
// TerminalSlashCommands, on a system init line, names the commands that
// only work in the interactive terminal (see commands.go).
TerminalSlashCommands []string `json:"terminal_slash_commands"`
@@ -65,6 +68,7 @@ type contentBlock struct {
}
type messageBody struct {
Error string `json:"error"`
ID string `json:"id"`
Role string `json:"role"`
Model string `json:"model"`
@@ -419,6 +423,7 @@ func (s *session) handleAssistant(envelope lineEnvelope) {
}
blocks := decodeBlocks(body.Content)
s.mu.Lock()
s.noteUsageRefusalLocked(envelope, body, blocks, messageID)
if messageID != s.streamID {
// A message that was not streamed (or a new one): nothing streamed can
// be aligned with it. Later events of the same message keep this state.
@@ -625,8 +630,10 @@ func (s *session) handleResult(envelope lineEnvelope) {
turn := s.turnID
running := s.running
proc := s.proc
refusal, refused := s.takeUsageRefusalLocked(envelope)
if s.silent {
proc = nil // replayed: the live usage query is made once caught up
refused = false
}
s.running = false
s.turnID = ""
@@ -662,6 +669,9 @@ func (s *session) handleResult(envelope lineEnvelope) {
if proc != nil {
go s.refreshUsage(proc)
}
if refused {
s.chat.reportUsageRefusal(refusal)
}
}
func (s *session) handleSystem(envelope lineEnvelope) {
+1 -1
View File
@@ -40,7 +40,7 @@ func (s Store) List() (protocol.ClaudeAccountList, error) {
}
func (s Store) list() (protocol.ClaudeAccountList, error) {
out := protocol.ClaudeAccountList{ConfigDir: s.ConfigDir, Accounts: []protocol.ClaudeAccount{}}
out := protocol.ClaudeAccountList{ConfigDir: s.ConfigDir, Accounts: []protocol.ClaudeAccount{}, AutoSwitch: s.AutoSwitch()}
current, err := s.current()
if err != nil {
return out, err
+64
View File
@@ -0,0 +1,64 @@
package claudeaccounts
import (
"encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// settingsFile holds the Claude home's account-switching preferences, beside
// the saved slots (a file, so slots() never reads it as an account).
const settingsFile = "settings.json"
type settings struct {
// AutoSwitch is nil until the operator chooses; the default is on.
AutoSwitch *bool `json:"auto_switch,omitempty"`
}
func (s Store) readSettings() settings {
var out settings
data, err := os.ReadFile(filepath.Join(s.slotsDir(), settingsFile))
if err == nil {
_ = json.Unmarshal(data, &out)
}
return out
}
// AutoSwitch reports whether a chat on this Claude home that runs out of
// usage is switched to another saved account automatically (on by default).
func (s Store) AutoSwitch() bool {
if on := s.readSettings().AutoSwitch; on != nil {
return *on
}
return true
}
// SetAutoSwitch records the automatic-switch preference and returns the
// accounts list, which reports it.
func (s Store) SetAutoSwitch(on bool) (protocol.ClaudeAccountList, error) {
if err := s.check(); err != nil {
return protocol.ClaudeAccountList{}, err
}
dir := s.slotsDir()
if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, fs.ErrExist) {
return protocol.ClaudeAccountList{}, err
}
current := s.readSettings()
current.AutoSwitch = &on
data, err := marshal(current)
if err != nil {
return protocol.ClaudeAccountList{}, err
}
path := filepath.Join(dir, settingsFile)
if err := writeAtomic(path, data, 0o600); err != nil {
return protocol.ClaudeAccountList{}, err
}
if err := os.Chmod(path, 0o600); err != nil {
return protocol.ClaudeAccountList{}, err
}
return s.List()
}
+12 -2
View File
@@ -15,12 +15,15 @@ import (
"git.a-wan.net/alan/pipelines/internal/workenv"
)
const claudeAccountUsage = "usage: pipelines claude-account list | save [name] | use <name> | remove <name> [--dir DIR] [--json]"
const claudeAccountUsage = "usage: pipelines claude-account list | save [name] | use <name> | remove <name> | auto on|off [--dir DIR] [--json]"
// claudeAccount saves and switches the Claude login of the Claude home a
// directory selects (its CLAUDE_CONFIG_DIR after direnv/mise), locally and
// without a server. It changes the same files /login does, so running Claude
// Code processes there continue on the new account.
// Code processes there continue on the new account. `auto on|off` sets whether
// the server switches a chat that runs out of usage to another saved account
// and continues it (kept in the Claude home, so the server reads the same
// choice).
func (a App) claudeAccount(ctx context.Context, args []string) error {
f := flag.NewFlagSet("claude-account", flag.ContinueOnError)
f.SetOutput(a.Err)
@@ -63,6 +66,8 @@ func (a App) claudeAccount(ctx context.Context, args []string) error {
list, err = store.Use(pos[1])
case pos[0] == "remove" && len(pos) == 2:
list, err = store.Remove(pos[1])
case pos[0] == "auto" && len(pos) == 2 && (pos[1] == "on" || pos[1] == "off"):
list, err = store.SetAutoSwitch(pos[1] == "on")
default:
return errors.New(claudeAccountUsage)
}
@@ -89,6 +94,11 @@ func (a App) claudeAccount(ctx context.Context, args []string) error {
if list.Active == nil {
fmt.Fprintln(a.Out, "Signed out.")
}
auto := "off"
if list.AutoSwitch {
auto = "on"
}
fmt.Fprintf(a.Out, "Switch automatically when usage runs out: %s\n", auto)
if pos[0] == "use" && list.Active != nil {
fmt.Fprintf(a.Out, "Switched to %s. Running Claude Code sessions continue on it.\n", list.Active.Email)
}
+34
View File
@@ -76,3 +76,37 @@ func TestClaudeAccountCommandSavesAndSwitches(t *testing.T) {
t.Fatalf("no Claude home: %v", err)
}
}
func TestClaudeAccountAutoCommandTogglesAutomaticSwitching(t *testing.T) {
profile := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", profile)
t.Setenv(workenv.DisableEnvKey, "off")
dir := t.TempDir()
run := func(args ...string) (string, error) {
var out, errs bytes.Buffer
err := App{Out: &out, Err: &errs}.Run(context.Background(), append([]string{"claude-account"}, args...))
return out.String() + errs.String(), err
}
cliLogin(t, profile, "a@example.invalid", "uuid-a", "a1")
if out, err := run("list", "--dir", dir); err != nil || !strings.Contains(out, "Switch automatically when usage runs out: on") {
t.Fatalf("default: %v\n%s", err, out)
}
if out, err := run("auto", "off", "--dir", dir); err != nil || !strings.Contains(out, "Switch automatically when usage runs out: off") {
t.Fatalf("auto off: %v\n%s", err, out)
}
out, err := run("list", "--dir", dir, "--json")
var list protocol.ClaudeAccountList
if err != nil || json.Unmarshal([]byte(out), &list) != nil || list.AutoSwitch {
t.Fatalf("list json: %v\n%s", err, out)
}
info, err := os.Stat(filepath.Join(profile, "pipelines-accounts", "settings.json"))
if err != nil || info.Mode().Perm() != 0o600 {
t.Fatalf("settings file: %v %v", info, err)
}
if out, err := run("auto", "on", "--dir", dir); err != nil || !strings.Contains(out, "runs out: on") {
t.Fatalf("auto on: %v\n%s", err, out)
}
if _, err := run("auto", "maybe", "--dir", dir); err == nil {
t.Fatal("auto maybe was accepted")
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ var usage = map[string]string{
"stats": "stats [--json]",
"rpc": "rpc <request.json|->",
"retention": "retention report|apply [--older-than DURATION] [--keep N] [--db FILE] [--artifacts DIR] [--json] [--yes]",
"claude-account": "claude-account list | save [name] | use <name> | remove <name> [--dir DIR] [--json]",
"claude-account": "claude-account list | save [name] | use <name> | remove <name> | auto on|off [--dir DIR] [--json]",
"tui": "tui",
}
+1 -1
View File
@@ -56,7 +56,7 @@ SERVER / INTERFACE
harness setup <claude|codex|opencode|pi>
Install check, sign-in, models and verify for one harness
harness list Installed / signed-in / configured / default for all four
claude-account list|save|use|remove
claude-account list|save|use|remove|auto
Save and switch the Claude login of this directory's
CLAUDE_CONFIG_DIR (--dir DIR); running sessions follow
tui Open the dashboard (default with no command)
+10
View File
@@ -20,6 +20,10 @@ const (
// ClaudeAccountRemove deletes the saved account Name. The active login is
// unchanged.
ClaudeAccountRemove = "claude_account_remove"
// ClaudeAccountAutoSwitch sets whether a chat on this Claude home that
// runs out of usage is switched to another saved account with usage left
// and continued automatically (AutoSwitch; on by default).
ClaudeAccountAutoSwitch = "claude_account_auto_switch"
)
// ClaudeAccountRequest is the body of every claude_account* request.
@@ -28,6 +32,9 @@ type ClaudeAccountRequest struct {
// Name is the saved account (its name, slug or email); for a save, the
// name to save under ("" uses the email).
Name string `json:"name,omitempty"`
// AutoSwitch is the new automatic-switch choice of a
// claude_account_auto_switch request.
AutoSwitch *bool `json:"auto_switch,omitempty"`
}
// ClaudeAccount describes one Claude login without its credentials.
@@ -54,4 +61,7 @@ type ClaudeAccountList struct {
// Usage is the newly active account's latest known quota after a
// claude_account_use (see ChatAccountUsage.SwitchedAt).
Usage *ChatAccountUsage `json:"usage,omitempty"`
// AutoSwitch reports whether running out of usage switches the Claude
// home to another saved account and continues the chat automatically.
AutoSwitch bool `json:"auto_switch"`
}
+1 -1
View File
@@ -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:
+285
View File
@@ -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)
}
}
+256
View File
@@ -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)
}
}
+14 -2
View File
@@ -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
+3
View File
@@ -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
+6
View File
@@ -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 {
+1 -1
View File
@@ -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
+3
View File
@@ -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 {
+8
View File
@@ -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 {
+4
View File
@@ -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.
+18
View File
@@ -13,6 +13,7 @@ import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
@@ -90,6 +91,20 @@ func (NtfyStage) Run(ctx context.Context, def Definition, input Values) (Result,
return Result{Outcome: "success", Output: output}, nil
}
type ntfyPriorityKey struct{}
// WithNtfyPriority makes PublishNtfy calls under ctx send ntfy priority
// (1 min to 5 max); without it ntfy uses its default, 3.
func WithNtfyPriority(ctx context.Context, priority int) context.Context {
return context.WithValue(ctx, ntfyPriorityKey{}, priority)
}
// NtfyPriority is the priority WithNtfyPriority set on ctx, 0 when none.
func NtfyPriority(ctx context.Context) int {
priority, _ := ctx.Value(ntfyPriorityKey{}).(int)
return priority
}
// PublishNtfy is shared by native delivery stages and stage notification hooks.
// An empty filename publishes an event without an attachment. A non-empty click
// is an optional ntfy Click action (an absolute URL) so a tap on the notification
@@ -161,6 +176,9 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
if click != "" {
request.Header.Set("Click", click)
}
if priority, ok := ctx.Value(ntfyPriorityKey{}).(int); ok && priority >= 1 && priority <= 5 {
request.Header.Set("Priority", strconv.Itoa(priority))
}
if actions != "" {
request.Header.Set("Actions", actions)
}
+20
View File
@@ -169,6 +169,26 @@ func TestNtfyDoesNotRedirectOrRetryAndRedactsErrors(t *testing.T) {
}
}
func TestNtfyPriorityFromContext(t *testing.T) {
var priorities []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
priorities = append(priorities, r.Header.Get("Priority"))
_, _ = w.Write([]byte(`{"id":"msg","event":"message"}`))
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "")
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN_FILE", "")
for _, ctx := range []context.Context{context.Background(), WithNtfyPriority(context.Background(), 2), WithNtfyPriority(context.Background(), 9)} {
if _, err := PublishNtfy(ctx, "anime", "Title", "Summary", "", nil, ""); err != nil {
t.Fatal(err)
}
}
if strings.Join(priorities, ",") != ",2," {
t.Fatalf("priorities = %q", priorities)
}
}
func TestNtfyClickAndViewActions(t *testing.T) {
var click, actions []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {