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) } }