Chat: the server continues a usage-refused Claude chat at the reset
When Claude Code refuses an operator chat's turn for a usage limit and the server does not continue it on another account, the server now queues a durable prompt (auto-continue-<refusal id>, sent as Pipelines (automatic)) for a minute after the reset: the refused operator message when the turn did no work, else "continue". The reset comes from the refusal's text, else the rejected rate_limit_event. Refusals of turns Claude Code started itself are handled too, with no client attached; a restarted server or a device scheduling the same refusal adds nothing. The choice is kept per Claude home beside auto-switch (or by the server for chats without one), read and set with chat_auto_continue, on by default. The app's limit banner now finds the refusal as the latest turn, ignoring notices, agent reports and activity rows after it, reads and writes the server's choice, and only schedules its own prompt for older servers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
|
||||
)
|
||||
|
||||
// The operator's "Auto-continue when limits reset" choice is kept per Claude
|
||||
// home, beside the automatic-switch choice (claudeaccounts settings.json), so
|
||||
// every chat on that home and every device share it. A chat whose directory
|
||||
// selects no Claude home of its own reports ErrNoConfigDir; the server keeps
|
||||
// the choice for those itself.
|
||||
|
||||
// AutoContinue reports whether chats on the Claude home of sessionID's
|
||||
// directory ("" uses the open session's) continue automatically once a usage
|
||||
// limit resets.
|
||||
func (c *Chat) AutoContinue(ctx context.Context, sessionID, directory string) (bool, error) {
|
||||
store, err := c.homeStore(ctx, sessionID, directory)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return store.AutoContinue(), nil
|
||||
}
|
||||
|
||||
// SetAutoContinue records the auto-continue choice of that Claude home.
|
||||
func (c *Chat) SetAutoContinue(ctx context.Context, sessionID, directory string, on bool) error {
|
||||
store, err := c.homeStore(ctx, sessionID, directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return store.SetAutoContinue(on)
|
||||
}
|
||||
|
||||
func (c *Chat) homeStore(ctx context.Context, sessionID, directory string) (claudeaccounts.Store, error) {
|
||||
if strings.TrimSpace(directory) == "" {
|
||||
if s := c.session(sessionID); s != nil {
|
||||
s.mu.Lock()
|
||||
directory = s.directory
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
configDir, err := c.accountConfigDir(ctx, directory)
|
||||
if err != nil {
|
||||
return claudeaccounts.Store{}, err
|
||||
}
|
||||
return claudeaccounts.Store{ConfigDir: configDir}, nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// The auto-continue choice is kept per Claude home beside, and apart from,
|
||||
// the automatic-switch choice; it is on by default.
|
||||
func TestAutoContinueIsAClaudeHomeChoice(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
chat := directoryChat(t)
|
||||
directory := accountsHome(t, chat)
|
||||
if on, err := chat.AutoContinue(ctx, "s", directory); err != nil || !on {
|
||||
t.Fatalf("default = %v %v", on, err)
|
||||
}
|
||||
if err := chat.SetAutoContinue(ctx, "s", directory, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if on, err := chat.AutoContinue(ctx, "s", directory); err != nil || on {
|
||||
t.Fatalf("after off = %v %v", on, err)
|
||||
}
|
||||
list, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccounts, "")
|
||||
if err != nil || !list.AutoSwitch {
|
||||
t.Fatalf("auto-switch changed: %+v %v", list, err)
|
||||
}
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", "")
|
||||
if _, err := chat.AutoContinue(ctx, "s", t.TempDir()); !errors.Is(err, ErrNoConfigDir) {
|
||||
t.Fatalf("a directory without a Claude home: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -189,6 +189,7 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
|
||||
s.turnID = turn
|
||||
s.running = true
|
||||
s.beginTurnLocked()
|
||||
s.turnPrompt = strings.TrimSpace(text)
|
||||
s.steered = 0
|
||||
s.awaitFollowUp = false
|
||||
s.recordPromptLocked(messageID, text)
|
||||
@@ -254,6 +255,9 @@ func (c *Chat) SteerPrompt(ctx context.Context, id, text, messageID string, file
|
||||
s.mu.Lock()
|
||||
s.steered++
|
||||
s.lastUsed = time.Now()
|
||||
// A refused turn that took more than one message continues, rather
|
||||
// than resending its first.
|
||||
s.turnPrompt = ""
|
||||
s.recordPromptLocked(messageID, text)
|
||||
s.mu.Unlock()
|
||||
return true, nil
|
||||
|
||||
@@ -387,8 +387,18 @@ type session struct {
|
||||
turnEmail string
|
||||
limitMessageID string
|
||||
limitByError bool
|
||||
prompts []promptRecord
|
||||
models []protocol.ChatModel
|
||||
// limitText and limitAt are the refusal's own text and when it was
|
||||
// written; limitReset is when a rejected rate_limit_event of the turn
|
||||
// said the limit resets. turnPrompt is the operator's prompt that
|
||||
// started the running turn ("" for a turn Claude Code started itself)
|
||||
// and turnWorked is set once the turn produced anything but a refusal.
|
||||
limitText string
|
||||
limitAt time.Time
|
||||
limitReset time.Time
|
||||
turnPrompt string
|
||||
turnWorked 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
|
||||
|
||||
@@ -199,8 +199,14 @@ func (s *session) handleRateLimit(raw json.RawMessage) {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
c := s.chat
|
||||
until, rejected := rejectedUntil(raw)
|
||||
if rejected {
|
||||
s.mu.Lock()
|
||||
s.noteRejectedResetLocked(until)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
c.quotaMu.Lock()
|
||||
if until, ok := rejectedUntil(raw); ok {
|
||||
if rejected {
|
||||
c.noteRejectedLocked(account.email, until)
|
||||
}
|
||||
next := mergeRateLimit(c.quotas[key], raw, account.plan, time.Now())
|
||||
|
||||
+126
-5
@@ -2,6 +2,7 @@ package claude
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -27,6 +28,15 @@ type UsageRefusal struct {
|
||||
MessageID string
|
||||
// Email is the account the refused turn started on ("" when unknown).
|
||||
Email string
|
||||
// ResetsAt is when the limit resets: the time the refusal's own text
|
||||
// names, else the reset of the turn's rejected rate_limit_event; zero
|
||||
// when neither said.
|
||||
ResetsAt time.Time
|
||||
// Prompt is the operator's message the refusal answered when the
|
||||
// refused turn was started by it and did no work before the refusal;
|
||||
// "" for a turn that worked, or one Claude Code started itself (a
|
||||
// background-task notification).
|
||||
Prompt string
|
||||
}
|
||||
|
||||
// OnUsageRefused registers the receiver of usage-limit refusals; each is
|
||||
@@ -50,8 +60,19 @@ func (c *Chat) reportUsageRefusal(refusal UsageRefusal) {
|
||||
// refusal of the previous turn. The caller holds s.mu.
|
||||
func (s *session) beginTurnLocked() {
|
||||
s.turnEmail = s.account.email
|
||||
s.clearRefusalLocked()
|
||||
}
|
||||
|
||||
// clearRefusalLocked forgets the running turn's refusal record and prompt.
|
||||
// The caller holds s.mu.
|
||||
func (s *session) clearRefusalLocked() {
|
||||
s.limitMessageID = ""
|
||||
s.limitByError = false
|
||||
s.limitText = ""
|
||||
s.limitAt = time.Time{}
|
||||
s.limitReset = time.Time{}
|
||||
s.turnPrompt = ""
|
||||
s.turnWorked = false
|
||||
}
|
||||
|
||||
// noteUsageRefusalLocked remembers an assistant message that is a
|
||||
@@ -65,9 +86,23 @@ func (s *session) noteUsageRefusalLocked(envelope lineEnvelope, body messageBody
|
||||
break
|
||||
}
|
||||
}
|
||||
if byError || byText {
|
||||
s.limitMessageID = messageID
|
||||
s.limitByError = s.limitByError || byError
|
||||
if !byError && !byText {
|
||||
if messageID != s.limitMessageID {
|
||||
s.turnWorked = true
|
||||
}
|
||||
return
|
||||
}
|
||||
s.limitMessageID = messageID
|
||||
s.limitByError = s.limitByError || byError
|
||||
s.limitText = ""
|
||||
for _, block := range blocks {
|
||||
if block.Type == "text" {
|
||||
s.limitText += block.Text + "\n"
|
||||
}
|
||||
}
|
||||
s.limitAt = time.Now()
|
||||
if at, err := time.Parse(time.RFC3339Nano, envelope.Timestamp); err == nil {
|
||||
s.limitAt = at
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,11 +119,97 @@ func (s *session) takeUsageRefusalLocked(envelope lineEnvelope) (UsageRefusal, b
|
||||
if refusal.TurnID == "" {
|
||||
refusal.TurnID = "result-" + strings.TrimSpace(envelope.UUID)
|
||||
}
|
||||
s.limitMessageID = ""
|
||||
s.limitByError = false
|
||||
at := s.limitAt
|
||||
if at.IsZero() {
|
||||
at = time.Now()
|
||||
}
|
||||
if reset, ok := usageLimitReset(s.limitText+envelope.Result, at); ok {
|
||||
refusal.ResetsAt = reset
|
||||
} else if !s.limitReset.IsZero() {
|
||||
refusal.ResetsAt = s.limitReset
|
||||
}
|
||||
if !s.turnWorked {
|
||||
refusal.Prompt = s.turnPrompt
|
||||
}
|
||||
s.clearRefusalLocked()
|
||||
return refusal, refused
|
||||
}
|
||||
|
||||
// noteRejectedResetLocked records when a rejected rate_limit_event the
|
||||
// running turn received says the limit resets. The caller holds s.mu.
|
||||
func (s *session) noteRejectedResetLocked(until time.Time) {
|
||||
if until.After(s.limitReset) {
|
||||
s.limitReset = until
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
// usageLimitEpoch is the older CLI's "usage limit reached|<epoch>".
|
||||
usageLimitEpoch = regexp.MustCompile(`usage limit reached\|(\d{9,11})\b`)
|
||||
// usageLimitResets is the current CLI's "resets 5:20pm (Europe/London)",
|
||||
// or with a date for a longer window, "resets Dec 9, 5pm (Europe/London)".
|
||||
usageLimitResets = regexp.MustCompile(`(?i)\bresets\s+(?:([a-z]{3})[a-z]*\.?\s+(\d{1,2})(?:,|\s+at)?\s+)?(\d{1,2})(?::(\d{2}))?\s*([ap]m)\s*\(([^)\s]+)\)`)
|
||||
)
|
||||
|
||||
// usageLimitReset is the reset a refusal's text names, the first such time
|
||||
// after at (when the refusal was written).
|
||||
func usageLimitReset(text string, at time.Time) (time.Time, bool) {
|
||||
if match := usageLimitEpoch.FindStringSubmatch(text); match != nil {
|
||||
seconds, err := strconv.ParseInt(match[1], 10, 64)
|
||||
if err != nil || seconds <= 0 {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return time.Unix(seconds, 0), true
|
||||
}
|
||||
match := usageLimitResets.FindStringSubmatch(text)
|
||||
if match == nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
location, err := time.LoadLocation(match[6])
|
||||
if err != nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
hour, _ := strconv.Atoi(match[3])
|
||||
minute := 0
|
||||
if match[4] != "" {
|
||||
minute, _ = strconv.Atoi(match[4])
|
||||
}
|
||||
if hour < 1 || hour > 12 || minute > 59 {
|
||||
return time.Time{}, false
|
||||
}
|
||||
hour %= 12
|
||||
if strings.EqualFold(match[5], "pm") {
|
||||
hour += 12
|
||||
}
|
||||
local := at.In(location)
|
||||
if match[1] != "" {
|
||||
month, ok := monthOf(match[1])
|
||||
day, _ := strconv.Atoi(match[2])
|
||||
if !ok || day < 1 || day > 31 {
|
||||
return time.Time{}, false
|
||||
}
|
||||
reset := time.Date(local.Year(), month, day, hour, minute, 0, 0, location)
|
||||
if reset.Before(at.Add(-time.Minute)) {
|
||||
reset = time.Date(local.Year()+1, month, day, hour, minute, 0, 0, location)
|
||||
}
|
||||
return reset, true
|
||||
}
|
||||
reset := time.Date(local.Year(), local.Month(), local.Day(), hour, minute, 0, 0, location)
|
||||
if reset.Before(at.Add(-time.Minute)) {
|
||||
reset = time.Date(local.Year(), local.Month(), local.Day()+1, hour, minute, 0, 0, location)
|
||||
}
|
||||
return reset, true
|
||||
}
|
||||
|
||||
func monthOf(name string) (time.Month, bool) {
|
||||
for month := time.January; month <= time.December; month++ {
|
||||
if strings.EqualFold(month.String()[:3], name) {
|
||||
return month, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// noteRejectedLocked records when a rejected account's limit ends. The
|
||||
// caller holds c.quotaMu.
|
||||
func (c *Chat) noteRejectedLocked(email string, until time.Time) {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestUsageLimitResetIsReadFromTheRefusal(t *testing.T) {
|
||||
london, err := time.LoadLocation("Europe/London")
|
||||
if err != nil {
|
||||
t.Skip("no time zone data:", err)
|
||||
}
|
||||
at := time.Date(2026, 12, 2, 17, 21, 0, 0, london)
|
||||
for _, tc := range []struct {
|
||||
text string
|
||||
want time.Time
|
||||
}{
|
||||
{"You've hit your 5-hour limit · resets 7:20pm (Europe/London) · out of usage credits", time.Date(2026, 12, 2, 19, 20, 0, 0, london)},
|
||||
{"You've hit your limit · resets 5pm (Europe/London)", time.Date(2026, 12, 3, 17, 0, 0, 0, london)},
|
||||
{"You've hit your 5-hour limit · resets 12:30am (Europe/London)", time.Date(2026, 12, 3, 0, 30, 0, 0, london)},
|
||||
{"You've hit your weekly limit · resets Dec 9, 5pm (Europe/London)", time.Date(2026, 12, 9, 17, 0, 0, 0, london)},
|
||||
{"You've hit your weekly limit · resets Jan 2 at 9am (Europe/London)", time.Date(2027, 1, 2, 9, 0, 0, 0, london)},
|
||||
{"Claude AI usage limit reached|1900000000", time.Unix(1900000000, 0)},
|
||||
} {
|
||||
got, ok := usageLimitReset(tc.text, at)
|
||||
if !ok || !got.Equal(tc.want) {
|
||||
t.Errorf("%q: %v %v, want %v", tc.text, got, ok, tc.want)
|
||||
}
|
||||
}
|
||||
for _, text := range []string{"You've hit your limit", "resets 7:20pm (Nowhere/Land)", "resets 13pm (Europe/London)"} {
|
||||
if got, ok := usageLimitReset(text, at); ok {
|
||||
t.Errorf("%q read as %v", text, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The refused turn's operator message is sent again only when the turn did
|
||||
// nothing else; the reset falls back to the rejected rate_limit_event.
|
||||
func TestUsageRefusalCarriesItsPromptAndReset(t *testing.T) {
|
||||
limit := []contentBlock{{Type: "text", Text: "You've hit your limit"}}
|
||||
until := time.Now().Add(time.Hour)
|
||||
s := &session{id: "s", turnID: "t1"}
|
||||
s.beginTurnLocked()
|
||||
s.turnPrompt = "Fix the build"
|
||||
s.noteRejectedResetLocked(until)
|
||||
s.noteUsageRefusalLocked(lineEnvelope{Error: "rate_limit"}, messageBody{}, limit, "r1")
|
||||
refusal, refused := s.takeUsageRefusalLocked(lineEnvelope{IsError: true})
|
||||
if !refused || refusal.Prompt != "Fix the build" || !refusal.ResetsAt.Equal(until) {
|
||||
t.Fatalf("refusal = %+v %v", refusal, refused)
|
||||
}
|
||||
|
||||
s.turnID = "t2"
|
||||
s.beginTurnLocked()
|
||||
s.turnPrompt = "Fix the build"
|
||||
s.noteUsageRefusalLocked(lineEnvelope{}, messageBody{}, []contentBlock{{Type: "text", Text: "Looking at it"}}, "m2")
|
||||
s.noteUsageRefusalLocked(lineEnvelope{Error: "rate_limit"}, messageBody{}, limit, "r2")
|
||||
refusal, refused = s.takeUsageRefusalLocked(lineEnvelope{IsError: true})
|
||||
if !refused || refusal.Prompt != "" || !refusal.ResetsAt.IsZero() {
|
||||
t.Fatalf("worked refusal = %+v %v", refusal, refused)
|
||||
}
|
||||
}
|
||||
|
||||
func receiveRefusal(t *testing.T, refusals <-chan UsageRefusal) UsageRefusal {
|
||||
t.Helper()
|
||||
select {
|
||||
case refusal := <-refusals:
|
||||
return refusal
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the refusal was not reported")
|
||||
}
|
||||
return UsageRefusal{}
|
||||
}
|
||||
|
||||
// A live refusal of an operator prompt carries the prompt and the reset its
|
||||
// text names.
|
||||
func TestLiveUsageRefusalNamesItsResetAndPrompt(t *testing.T) {
|
||||
london, err := time.LoadLocation("Europe/London")
|
||||
if err != nil {
|
||||
t.Skip("no time zone data:", err)
|
||||
}
|
||||
chat := testChat(t)
|
||||
refusals := make(chan UsageRefusal, 4)
|
||||
chat.OnUsageRefused(func(refusal UsageRefusal) { refusals <- refusal })
|
||||
created := newCreatedChat(t, chat)
|
||||
before := time.Now()
|
||||
if err := chat.Prompt(context.Background(), created.ID, "usage-limit please"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refusal := receiveRefusal(t, refusals)
|
||||
local := before.In(london)
|
||||
want := time.Date(local.Year(), local.Month(), local.Day(), 17, 20, 0, 0, london)
|
||||
if want.Before(before.Add(-time.Minute)) {
|
||||
want = time.Date(local.Year(), local.Month(), local.Day()+1, 17, 20, 0, 0, london)
|
||||
}
|
||||
if refusal.Prompt != "usage-limit please" || !refusal.ResetsAt.Equal(want) {
|
||||
t.Fatalf("refusal = %+v, want reset %v", refusal, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A turn Claude Code started on its own (a background task's notification)
|
||||
// that the limit refuses is reported too, with nothing to send again.
|
||||
func TestRefusalOfATurnClaudeCodeStartedIsReported(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)
|
||||
if err := chat.Prompt(context.Background(), created.ID, "cli-refusal"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFrame(t, frames, "the operator turn's end", func(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded
|
||||
})
|
||||
refusal := receiveRefusal(t, refusals)
|
||||
if refusal.SessionID != created.ID || refusal.MessageID != "refusal-2" || refusal.Prompt != "" || refusal.ResetsAt.IsZero() {
|
||||
t.Fatalf("refusal = %+v", refusal)
|
||||
}
|
||||
}
|
||||
+13
@@ -82,6 +82,19 @@ def user_message(text):
|
||||
if "usage-limit" in text:
|
||||
refused(message_id)
|
||||
return
|
||||
if "cli-refusal" in text:
|
||||
# The turn works and ends; then a background task's notification
|
||||
# starts a turn of Claude Code's own, which the limit refuses.
|
||||
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test",
|
||||
"content": [{"type": "text", "text": "Started it"}]}})
|
||||
finish(message_id)
|
||||
state["turn"] += 1
|
||||
send({"type": "user", "origin": {"kind": "task-notification"},
|
||||
"message": {"role": "user", "content": [{"type": "text", "text":
|
||||
"<task-notification><task-id>b1</task-id><status>completed</status>"
|
||||
"<summary>Background command completed</summary></task-notification>"}]}})
|
||||
refused("msg_fake_%d" % state["turn"])
|
||||
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)"})
|
||||
|
||||
Reference in New Issue
Block a user