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)"})
|
||||
|
||||
@@ -17,6 +17,8 @@ const settingsFile = "settings.json"
|
||||
type settings struct {
|
||||
// AutoSwitch is nil until the operator chooses; the default is on.
|
||||
AutoSwitch *bool `json:"auto_switch,omitempty"`
|
||||
// AutoContinue is nil until the operator chooses; the default is on.
|
||||
AutoContinue *bool `json:"auto_continue,omitempty"`
|
||||
}
|
||||
|
||||
func (s Store) readSettings() settings {
|
||||
@@ -40,25 +42,43 @@ func (s Store) AutoSwitch() bool {
|
||||
// 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 {
|
||||
if err := s.updateSettings(func(current *settings) { current.AutoSwitch = &on }); err != nil {
|
||||
return protocol.ClaudeAccountList{}, err
|
||||
}
|
||||
return s.List()
|
||||
}
|
||||
|
||||
// AutoContinue reports whether a chat on this Claude home that a usage limit
|
||||
// refused is continued automatically once the limit resets (on by default).
|
||||
func (s Store) AutoContinue() bool {
|
||||
if on := s.readSettings().AutoContinue; on != nil {
|
||||
return *on
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// SetAutoContinue records the auto-continue-at-reset preference.
|
||||
func (s Store) SetAutoContinue(on bool) error {
|
||||
return s.updateSettings(func(current *settings) { current.AutoContinue = &on })
|
||||
}
|
||||
|
||||
func (s Store) updateSettings(change func(*settings)) error {
|
||||
if err := s.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
dir := s.slotsDir()
|
||||
if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, fs.ErrExist) {
|
||||
return err
|
||||
}
|
||||
current := s.readSettings()
|
||||
change(¤t)
|
||||
data, err := marshal(current)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := filepath.Join(dir, settingsFile)
|
||||
if err := writeAtomic(path, data, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chmod(path, 0o600)
|
||||
}
|
||||
|
||||
@@ -29,6 +29,26 @@ ON CONFLICT(key) DO UPDATE SET value=excluded.value`, openCodeEndpointSetting, u
|
||||
return err
|
||||
}
|
||||
|
||||
// ServerSetting reads one server_settings value; found is false when it was
|
||||
// never recorded.
|
||||
func (s *Store) ServerSetting(ctx context.Context, key string) (value string, found bool, err error) {
|
||||
err = s.db.QueryRowContext(ctx, `SELECT value FROM server_settings WHERE key=?`, key).Scan(&value)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return value, true, nil
|
||||
}
|
||||
|
||||
// SetServerSetting records one server_settings value.
|
||||
func (s *Store) SetServerSetting(ctx context.Context, key, value string) error {
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO server_settings(key,value) VALUES(?,?)
|
||||
ON CONFLICT(key) DO UPDATE SET value=excluded.value`, key, value)
|
||||
return err
|
||||
}
|
||||
|
||||
// OpenCodeEndpoint returns the recorded OpenCode endpoint, or an empty string
|
||||
// when none was ever recorded.
|
||||
func (s *Store) OpenCodeEndpoint(ctx context.Context) (string, error) {
|
||||
|
||||
@@ -65,3 +65,27 @@ type ClaudeAccountList struct {
|
||||
// home to another saved account and continues the chat automatically.
|
||||
AutoSwitch bool `json:"auto_switch"`
|
||||
}
|
||||
|
||||
// ChatAutoContinueType reads (AutoContinue nil) or sets the "Auto-continue
|
||||
// when limits reset" choice that applies to a chat: when a usage limit
|
||||
// refuses one of its turns, the server queues a prompt to send a minute after
|
||||
// the reset. The choice is kept per Claude home (beside auto_switch) for a
|
||||
// chat whose directory selects one, else by the server for every other chat;
|
||||
// it is on by default. The reply carries the current choice.
|
||||
const ChatAutoContinueType = "chat_auto_continue"
|
||||
|
||||
// Scopes of a ChatAutoContinue reply.
|
||||
const (
|
||||
ChatAutoContinueClaudeHome = "claude_home"
|
||||
ChatAutoContinueServer = "server"
|
||||
)
|
||||
|
||||
// ChatAutoContinue is the chat_auto_continue body and reply.
|
||||
type ChatAutoContinue struct {
|
||||
SessionID string `json:"session_id"`
|
||||
// AutoContinue is the new choice of a request (nil reads it) and the
|
||||
// current choice in the reply.
|
||||
AutoContinue *bool `json:"auto_continue,omitempty"`
|
||||
// Scope says where the choice is kept: claude_home or server (reply).
|
||||
Scope string `json:"scope,omitempty"`
|
||||
}
|
||||
|
||||
@@ -256,6 +256,8 @@ type Message struct {
|
||||
// ClaudeAccounts their reply (claude_accounts.go).
|
||||
ClaudeAccount *ClaudeAccountRequest `json:"claude_account,omitempty"`
|
||||
ClaudeAccounts *ClaudeAccountList `json:"claude_accounts,omitempty"`
|
||||
// ChatAutoContinue is the chat_auto_continue body and reply.
|
||||
ChatAutoContinue *ChatAutoContinue `json:"chat_auto_continue,omitempty"`
|
||||
// ModelRequest is the chat_model body and echoed selection.
|
||||
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
|
||||
// ChatModes is the chat_modes reply: the permission modes the session's
|
||||
|
||||
@@ -256,6 +256,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove, protocol.ClaudeAccountAutoSwitch:
|
||||
handleClaudeAccounts(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ChatAutoContinueType:
|
||||
handleChatAutoContinue(ctx, request, broker, hub, registry, write)
|
||||
return true
|
||||
case protocol.ChatModelSelect:
|
||||
handleChatModelSwitch(ctx, request, broker, write)
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claude"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// When Claude Code refuses an operator chat's turn for a usage limit and the
|
||||
// server did not continue it on another account (chat_auto_switch.go), the
|
||||
// server queues a durable prompt into the chat to send a minute after the
|
||||
// limit resets: the refused operator message again when the turn was that
|
||||
// message and did no work, else "continue". It is marked as sent
|
||||
// automatically and waits in the queue as "Scheduled", where the operator can
|
||||
// remove it. Its operation id, auto-continue-<refusal message id>, is the one
|
||||
// the app used when it scheduled the prompt itself, so a refusal is continued
|
||||
// once however many devices and servers saw it. It honours the operator's
|
||||
// "Auto-continue when limits reset" choice (on by default), kept per Claude
|
||||
// home, or by this server for a chat without one. A refusal that names no
|
||||
// reset is not continued.
|
||||
|
||||
const (
|
||||
// chatAutoContinueMargin is how long after the reset the prompt is sent,
|
||||
// so it does not race the quota coming back.
|
||||
chatAutoContinueMargin = time.Minute
|
||||
// chatAutoContinueText is sent when there is no refused message to send
|
||||
// again.
|
||||
chatAutoContinueText = "continue"
|
||||
// chatAutoContinueSetting is the server_settings key of the choice for
|
||||
// chats without a Claude home of their own.
|
||||
chatAutoContinueSetting = "chat.auto_continue"
|
||||
)
|
||||
|
||||
// chatAutoContinueHome keeps the choice per Claude home (*claude.Chat, and
|
||||
// chatManager routing to it). It reports claude.ErrNoConfigDir for a chat
|
||||
// whose directory selects no Claude home.
|
||||
type chatAutoContinueHome interface {
|
||||
AutoContinue(ctx context.Context, sessionID, directory string) (bool, error)
|
||||
SetAutoContinue(ctx context.Context, sessionID, directory string, on bool) error
|
||||
}
|
||||
|
||||
// chatServerSettings is the server's own settings table; *pipeline.Store
|
||||
// implements it.
|
||||
type chatServerSettings interface {
|
||||
ServerSetting(ctx context.Context, key string) (string, bool, error)
|
||||
SetServerSetting(ctx context.Context, key, value string) error
|
||||
}
|
||||
|
||||
// AutoContinue routes the Claude-home choice to the Claude harness.
|
||||
func (m *chatManager) AutoContinue(ctx context.Context, sessionID, directory string) (bool, error) {
|
||||
home, err := m.autoContinueHome(ctx, sessionID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return home.AutoContinue(ctx, sessionID, directory)
|
||||
}
|
||||
|
||||
// SetAutoContinue routes the Claude-home choice to the Claude harness.
|
||||
func (m *chatManager) SetAutoContinue(ctx context.Context, sessionID, directory string, on bool) error {
|
||||
home, err := m.autoContinueHome(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return home.SetAutoContinue(ctx, sessionID, directory, on)
|
||||
}
|
||||
|
||||
func (m *chatManager) autoContinueHome(ctx context.Context, sessionID string) (chatAutoContinueHome, error) {
|
||||
if m.backendFor(ctx, sessionID) != claude.Backend {
|
||||
return nil, errNotClaudeChat
|
||||
}
|
||||
home, ok := m.attached(claude.Backend).(chatAutoContinueHome)
|
||||
if !ok {
|
||||
return nil, errNotClaudeChat
|
||||
}
|
||||
return home, nil
|
||||
}
|
||||
|
||||
// serverSettings is the hub's settings table, or nil.
|
||||
func (h *chatHub) serverSettings() chatServerSettings {
|
||||
store, _ := h.settings.(chatServerSettings)
|
||||
return store
|
||||
}
|
||||
|
||||
// autoContinue reads the choice that applies to sessionID and where it is
|
||||
// kept.
|
||||
func (h *chatHub) autoContinue(ctx context.Context, broker chatBroker, sessionID, directory string) (bool, string, error) {
|
||||
if home, ok := broker.(chatAutoContinueHome); ok {
|
||||
on, err := home.AutoContinue(ctx, sessionID, directory)
|
||||
if err == nil {
|
||||
return on, protocol.ChatAutoContinueClaudeHome, nil
|
||||
}
|
||||
if !errors.Is(err, claude.ErrNoConfigDir) && !errors.Is(err, errNotClaudeChat) {
|
||||
return false, "", err
|
||||
}
|
||||
}
|
||||
store := h.serverSettings()
|
||||
if store == nil {
|
||||
return true, protocol.ChatAutoContinueServer, nil
|
||||
}
|
||||
value, found, err := store.ServerSetting(ctx, chatAutoContinueSetting)
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
on := true
|
||||
if found {
|
||||
on, _ = strconv.ParseBool(value)
|
||||
}
|
||||
return on, protocol.ChatAutoContinueServer, nil
|
||||
}
|
||||
|
||||
// setAutoContinue records the choice where autoContinue reads it.
|
||||
func (h *chatHub) setAutoContinue(ctx context.Context, broker chatBroker, sessionID, directory string, on bool) (string, error) {
|
||||
if home, ok := broker.(chatAutoContinueHome); ok {
|
||||
err := home.SetAutoContinue(ctx, sessionID, directory, on)
|
||||
if err == nil {
|
||||
return protocol.ChatAutoContinueClaudeHome, nil
|
||||
}
|
||||
if !errors.Is(err, claude.ErrNoConfigDir) && !errors.Is(err, errNotClaudeChat) {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
store := h.serverSettings()
|
||||
if store == nil {
|
||||
return "", errors.New("auto-continue cannot be changed: this server keeps no settings")
|
||||
}
|
||||
return protocol.ChatAutoContinueServer, store.SetServerSetting(ctx, chatAutoContinueSetting, strconv.FormatBool(on))
|
||||
}
|
||||
|
||||
// continueAtReset queues refusal's auto-continue prompt (see the file
|
||||
// comment). The caller already claimed the refusal.
|
||||
func (h *chatHub) continueAtReset(ctx context.Context, broker chatBroker, refusal claude.UsageRefusal) {
|
||||
if refusal.ResetsAt.IsZero() {
|
||||
return
|
||||
}
|
||||
on, _, err := h.autoContinue(ctx, broker, refusal.SessionID, refusal.Directory)
|
||||
if err != nil {
|
||||
log.Printf("claude auto-continue session=%s: read the setting: %v", refusal.SessionID, err)
|
||||
return
|
||||
}
|
||||
if !on {
|
||||
return
|
||||
}
|
||||
operationID := chatAutoContinuePrefix + refusalKey(refusal)
|
||||
if h.autoContinueSuperseded(refusal.SessionID, operationID) {
|
||||
return
|
||||
}
|
||||
// A prompt already waiting to continue the chat (an earlier refusal's,
|
||||
// perhaps resending the operator's message) continues it; were it
|
||||
// refused again, that refusal schedules the next.
|
||||
for _, prompt := range h.queueFrame(refusal.SessionID).Prompts {
|
||||
if strings.HasPrefix(prompt.OperationID, chatAutoContinuePrefix) && prompt.OperationID != operationID {
|
||||
return
|
||||
}
|
||||
}
|
||||
text := strings.TrimSpace(refusal.Prompt)
|
||||
if text == "" {
|
||||
text = chatAutoContinueText
|
||||
}
|
||||
sendAt := refusal.ResetsAt.Add(chatAutoContinueMargin)
|
||||
if err := h.queueServerPrompt(ctx, broker, refusal.SessionID, operationID, text, sendAt); err != nil {
|
||||
log.Printf("claude auto-continue session=%s: queue the prompt: %v", refusal.SessionID, err)
|
||||
return
|
||||
}
|
||||
log.Printf("claude auto-continue session=%s: scheduled %s for %s", refusal.SessionID, operationID, sendAt.Format(time.RFC3339))
|
||||
}
|
||||
|
||||
// holdsQueued reports whether the session's queue (live, else durable)
|
||||
// holds operationID.
|
||||
func (h *chatHub) holdsQueued(sessionID, operationID string) bool {
|
||||
for _, prompt := range h.queueFrame(sessionID).Prompts {
|
||||
if prompt.OperationID == operationID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// handleChatAutoContinue answers chat_auto_continue: it reads, or sets, the
|
||||
// auto-continue choice that applies to a chat.
|
||||
func handleChatAutoContinue(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, write func(protocol.Message) error) {
|
||||
body := request.ChatAutoContinue
|
||||
if body == nil || !validChatSessionID(body.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
|
||||
return
|
||||
}
|
||||
directory := ""
|
||||
if registry != nil {
|
||||
if row, found, err := registry.OperatorSession(ctx, body.SessionID); err == nil && found {
|
||||
directory = row.Directory
|
||||
}
|
||||
}
|
||||
var (
|
||||
on bool
|
||||
scope string
|
||||
err error
|
||||
)
|
||||
if body.AutoContinue != nil {
|
||||
on = *body.AutoContinue
|
||||
scope, err = hub.setAutoContinue(ctx, broker, body.SessionID, directory, on)
|
||||
} else {
|
||||
on, scope, err = hub.autoContinue(ctx, broker, body.SessionID, directory)
|
||||
}
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatAutoContinueType, ID: request.ID,
|
||||
ChatAutoContinue: &protocol.ChatAutoContinue{SessionID: body.SessionID, AutoContinue: &on, Scope: scope}})
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"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"
|
||||
)
|
||||
|
||||
// autoContinueServer is an operator chat whose refusals find no account to
|
||||
// switch to.
|
||||
func autoContinueServer(t *testing.T) (*refusingChat, *queueServer, *pipeline.Store) {
|
||||
t.Helper()
|
||||
capturePublications(t)
|
||||
broker, server, store := autoSwitchServer(t, "ses_1")
|
||||
broker.quiet = true
|
||||
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) {
|
||||
return claude.AutoSwitch{}, claude.ErrNoAccountLeft
|
||||
}
|
||||
return broker, server, store
|
||||
}
|
||||
|
||||
func queuedRows(t *testing.T, store *pipeline.Store) []pipeline.ChatQueuedPrompt {
|
||||
t.Helper()
|
||||
rows, err := store.ChatQueuedPrompts(context.Background(), "ses_1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// A refusal the server could not switch away from schedules one automatic
|
||||
// prompt a minute after the reset: "continue" after a turn that worked, the
|
||||
// refused message itself after one that did not. Seeing it again (a second
|
||||
// report, a device scheduling the same refusal) adds nothing.
|
||||
func TestUsageRefusalSchedulesAutoContinueAtTheReset(t *testing.T) {
|
||||
for _, tc := range []struct{ name, prompt, want string }{
|
||||
{"worked", "", "continue"},
|
||||
{"refused prompt", "Fix the build", "Fix the build"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
broker, server, store := autoContinueServer(t)
|
||||
reset := time.Now().Add(2 * time.Hour).Truncate(time.Second)
|
||||
refusal := claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", Email: "a@example.invalid", ResetsAt: reset, Prompt: tc.prompt}
|
||||
broker.refuse(refusal)
|
||||
broker.refuse(refusal)
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p1", "continue", "auto-continue-refusal-1", reset.Add(time.Minute)); !ack.ChatQueued {
|
||||
t.Fatalf("device's copy ack = %+v", ack)
|
||||
}
|
||||
rows := queuedRows(t, store)
|
||||
if len(rows) != 1 {
|
||||
t.Fatalf("queued = %+v", rows)
|
||||
}
|
||||
row := rows[0]
|
||||
if row.OperationID != "auto-continue-refusal-1" || row.Text != tc.want || row.Client != chatAutoSwitchClient ||
|
||||
!row.SendAt.Equal(reset.Add(time.Minute)) {
|
||||
t.Fatalf("row = %+v", row)
|
||||
}
|
||||
if n := broker.promptCount(); n != 0 {
|
||||
t.Fatalf("prompts sent before the reset: %d", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A refusal without a reset time is not continued, and neither is any
|
||||
// refusal while the operator turned auto-continue off (a server-kept choice
|
||||
// for a chat without a Claude home of its own).
|
||||
func TestUsageRefusalAutoContinueNeedsAResetAndTheSetting(t *testing.T) {
|
||||
broker, server, store := autoContinueServer(t)
|
||||
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1"})
|
||||
if ops := queuedOps(t, store); len(ops) != 0 {
|
||||
t.Fatalf("queued without a reset: %v", ops)
|
||||
}
|
||||
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
read := func(id string, on *bool) *protocol.ChatAutoContinue {
|
||||
t.Helper()
|
||||
writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatAutoContinueType, ID: id, ChatAutoContinue: &protocol.ChatAutoContinue{SessionID: "ses_1", AutoContinue: on}})
|
||||
reply := readUntil(t, server.ctx, conn, protocol.ChatAutoContinueType)
|
||||
if reply.ChatAutoContinue == nil || reply.ChatAutoContinue.AutoContinue == nil {
|
||||
t.Fatalf("reply = %+v", reply)
|
||||
}
|
||||
return reply.ChatAutoContinue
|
||||
}
|
||||
if got := read("r1", nil); !*got.AutoContinue || got.Scope != protocol.ChatAutoContinueServer {
|
||||
t.Fatalf("default = %+v", got)
|
||||
}
|
||||
off := false
|
||||
if got := read("r2", &off); *got.AutoContinue {
|
||||
t.Fatalf("set off = %+v", got)
|
||||
}
|
||||
if got := read("r3", nil); *got.AutoContinue {
|
||||
t.Fatalf("read back = %+v", got)
|
||||
}
|
||||
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-2", MessageID: "refusal-2", ResetsAt: time.Now().Add(time.Hour)})
|
||||
if ops := queuedOps(t, store); len(ops) != 0 {
|
||||
t.Fatalf("queued with auto-continue off: %v", ops)
|
||||
}
|
||||
}
|
||||
|
||||
// When the server continues a refusal on another account, no auto-continue
|
||||
// is scheduled for it, and one still waiting from an earlier refusal is
|
||||
// removed.
|
||||
func TestAutoSwitchReplacesTheAutoContinue(t *testing.T) {
|
||||
broker, _, store := autoContinueServer(t)
|
||||
reset := time.Now().Add(time.Hour)
|
||||
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: reset})
|
||||
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-1"}) {
|
||||
t.Fatalf("queued = %v", ops)
|
||||
}
|
||||
broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) {
|
||||
return claude.AutoSwitch{From: "a@example.invalid", To: "b@example.invalid", Switched: true}, nil
|
||||
}
|
||||
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-2", MessageID: "refusal-2", ResetsAt: reset})
|
||||
// The idle chat takes the switch's continue prompt at once.
|
||||
waitFor(t, "the continue prompt", func() bool { return broker.promptCount() == 1 })
|
||||
if text := broker.promptTexts()[0]; !strings.HasPrefix(text, "[Sent automatically by Pipelines]") {
|
||||
t.Fatalf("sent %q", text)
|
||||
}
|
||||
if ops := queuedOps(t, store); len(ops) != 0 {
|
||||
t.Fatalf("queued after the switch = %v", ops)
|
||||
}
|
||||
}
|
||||
|
||||
// A later refusal (a background-task turn Claude Code started itself, say)
|
||||
// leaves the waiting auto-continue as it is: it continues the chat, and
|
||||
// keeps the operator's refused message.
|
||||
func TestLaterRefusalKeepsTheWaitingAutoContinue(t *testing.T) {
|
||||
broker, _, store := autoContinueServer(t)
|
||||
reset := time.Now().Add(time.Hour)
|
||||
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: reset, Prompt: "Fix the build"})
|
||||
broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "result-x", MessageID: "refusal-2", ResetsAt: reset})
|
||||
rows := queuedRows(t, store)
|
||||
if len(rows) != 1 || rows[0].OperationID != "auto-continue-refusal-1" || rows[0].Text != "Fix the build" {
|
||||
t.Fatalf("queued = %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
// A refusal reported again by a restarted server (its output replayed) finds
|
||||
// the durable prompt and queues no second one.
|
||||
func TestRestartedServerDoesNotScheduleTheRefusalTwice(t *testing.T) {
|
||||
broker, server, store := autoContinueServer(t)
|
||||
refusal := claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: time.Now().Add(time.Hour)}
|
||||
broker.refuse(refusal)
|
||||
server.stop()
|
||||
|
||||
restarted := &refusingChat{channelChat: newChannelChat(), quiet: true}
|
||||
restarted.switch_ = broker.switch_
|
||||
again := startQueueServer(t, restarted, store)
|
||||
conn := dialChatConn(t, again.ctx, again.srv)
|
||||
writeChat(t, again.ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}})
|
||||
restarted.refuse(refusal)
|
||||
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-1"}) {
|
||||
t.Fatalf("queued after the restart = %v", ops)
|
||||
}
|
||||
}
|
||||
@@ -19,16 +19,17 @@ import (
|
||||
// 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.
|
||||
// continues. It works with no client attached. Any auto-continue-at-reset
|
||||
// prompt for that refusal is taken back out. When no account has usage left
|
||||
// (or switching is off), the chat continues at the reset instead
|
||||
// (chat_auto_continue.go).
|
||||
|
||||
const (
|
||||
// chatAutoSwitchPrefix starts the operation id of the continue prompt.
|
||||
chatAutoSwitchPrefix = "auto-switch-"
|
||||
// chatAutoContinuePrefix starts the app's auto-continue-at-reset prompt
|
||||
// ids ("auto-continue-<refusal message id>").
|
||||
// chatAutoContinuePrefix starts the auto-continue-at-reset prompt ids
|
||||
// ("auto-continue-<refusal message id>"), the server's and an older
|
||||
// app's alike.
|
||||
chatAutoContinuePrefix = "auto-continue-"
|
||||
// chatAutoSwitchClient is the sender label of the continue prompt.
|
||||
chatAutoSwitchClient = "Pipelines (automatic)"
|
||||
@@ -129,19 +130,22 @@ func (h *chatHub) continueOnAnotherAccount(broker chatBroker, refusal claude.Usa
|
||||
}
|
||||
switcher, ok := broker.(chatAutoSwitcher)
|
||||
if !ok {
|
||||
h.continueAtReset(ctx, broker, refusal)
|
||||
return
|
||||
}
|
||||
result, err := switcher.AutoSwitchAccount(ctx, refusal)
|
||||
if err != nil {
|
||||
if !errors.Is(err, claude.ErrAutoSwitchOff) && !errors.Is(err, claude.ErrNoConfigDir) {
|
||||
if !errors.Is(err, claude.ErrAutoSwitchOff) && !errors.Is(err, claude.ErrNoConfigDir) &&
|
||||
!errors.Is(err, claude.ErrNoAccountLeft) && !errors.Is(err, errNotClaudeChat) {
|
||||
log.Printf("claude auto-switch session=%s: %v", refusal.SessionID, err)
|
||||
}
|
||||
h.continueAtReset(ctx, broker, refusal)
|
||||
return
|
||||
}
|
||||
operationID := chatAutoSwitchPrefix + refusalKey(refusal)
|
||||
h.autoSwitch.supersede(refusal, operationID)
|
||||
h.dropAutoContinue(ctx, refusal.SessionID)
|
||||
if err := h.queueServerPrompt(ctx, broker, refusal.SessionID, operationID, chatAutoSwitchText(result.From, result.To)); err != nil {
|
||||
if err := h.queueServerPrompt(ctx, broker, refusal.SessionID, operationID, chatAutoSwitchText(result.From, result.To), time.Time{}); err != nil {
|
||||
log.Printf("claude auto-switch session=%s: queue the continue prompt: %v", refusal.SessionID, err)
|
||||
return
|
||||
}
|
||||
@@ -229,10 +233,13 @@ func (h *chatHub) dropAutoContinue(ctx context.Context, sessionID string) {
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// once the current turn has ended (queued durably behind it), or not before
|
||||
// sendAt when that is set, and every attached client sees it under the
|
||||
// server's own sender label (a scheduled one through the queue, as
|
||||
// "Scheduled", until it is sent). A prompt the session already holds under
|
||||
// operationID is not queued again.
|
||||
func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error {
|
||||
if duplicate, _, _ := h.duplicateOp(sessionID, operationID); duplicate || h.holdsQueued(sessionID, operationID) {
|
||||
return nil
|
||||
}
|
||||
p := &chatQueuedPrompt{
|
||||
@@ -242,12 +249,18 @@ func (h *chatHub) queueServerPrompt(ctx context.Context, broker chatBroker, sess
|
||||
client: chatAutoSwitchClient,
|
||||
noSteer: true,
|
||||
}
|
||||
if sendAt.After(h.clock()) {
|
||||
p.sendAt = sendAt
|
||||
}
|
||||
h.rememberOp(sessionID, operationID)
|
||||
admission, err := h.admitPrompt(ctx, sessionID, broker, p)
|
||||
if admission == chatAdmitRefused {
|
||||
h.forgetOp(sessionID, operationID)
|
||||
return err
|
||||
}
|
||||
if !p.sendAt.IsZero() {
|
||||
return nil
|
||||
}
|
||||
h.broadcastUser(protocol.ChatEventFrame{
|
||||
SessionID: sessionID,
|
||||
MessageID: p.messageID,
|
||||
|
||||
Reference in New Issue
Block a user