Merge branch 'worktree-agent-a04a38e74fe1aef60'

This commit is contained in:
2026-12-02 19:56:31 +00:00
23 changed files with 1380 additions and 71 deletions
+3
View File
@@ -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
+215
View File
@@ -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}})
}
+163
View File
@@ -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)
}
}
+25 -12
View File
@@ -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,