diff --git a/internal/server/chat.go b/internal/server/chat.go index eccbcfe8..b320f108 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -176,12 +176,8 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker // External chat admission and readback must follow durable turn/queue // restoration: even readback can reconcile hub state. Internal recovery // does not dispatch requests here. The cold registry scan runs afterward. - if hub != nil && hub.recoveryReady != nil && strings.HasPrefix(string(request.Type), "chat_") { - select { - case <-hub.recoveryReady: - case <-ctx.Done(): - return true - } + if strings.HasPrefix(string(request.Type), "chat_") && !hub.awaitRecovery(ctx) { + return true } switch request.Type { case protocol.ChatPrompt: diff --git a/internal/server/chat_auto_continue_test.go b/internal/server/chat_auto_continue_test.go index 1f8765f4..ec5e3c67 100644 --- a/internal/server/chat_auto_continue_test.go +++ b/internal/server/chat_auto_continue_test.go @@ -2,6 +2,7 @@ package server import ( "context" + "path/filepath" "slices" "strings" "testing" @@ -161,3 +162,52 @@ func TestRestartedServerDoesNotScheduleTheRefusalTwice(t *testing.T) { t.Fatalf("queued after the restart = %v", ops) } } + +// A refusal reported while start-up recovery is still restoring the durable +// queue waits for it. Acted on earlier, recovery could read the queued +// auto-continue and put it back after the server's switch had removed it, so +// the switch's continue prompt waited behind it for the hour. +func TestUsageRefusalWaitsForStartupRecovery(t *testing.T) { + store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db")) + if err := store.RecordOperatorSession(context.Background(), "ses_1", "/work", "Fix ses_1", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + broker := &refusingChat{channelChat: newChannelChat(), quiet: true} + broker.switch_ = func(claude.UsageRefusal) (claude.AutoSwitch, error) { + return claude.AutoSwitch{}, claude.ErrNoAccountLeft + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + hub := newChatHub() + hub.baseCtx = ctx + hub.registry = store + hub.settings = store + hub.queueStore = store + hub.liveStore = store + ready := make(chan struct{}) + hub.recoveryReady = ready + hub.watchUsageRefusals(broker) + + handled := make(chan struct{}) + go func() { + defer close(handled) + broker.refuse(claude.UsageRefusal{SessionID: "ses_1", TurnID: "claude-1", MessageID: "refusal-1", ResetsAt: time.Now().Add(time.Hour)}) + }() + select { + case <-handled: + t.Fatal("the refusal was handled before start-up recovery finished") + case <-time.After(100 * time.Millisecond): + } + if ops := queuedOps(t, store); len(ops) != 0 { + t.Fatalf("queued during recovery = %v", ops) + } + close(ready) + select { + case <-handled: + case <-time.After(5 * time.Second): + t.Fatal("the refusal was not handled after recovery") + } + if ops := queuedOps(t, store); !slices.Equal(ops, []string{"auto-continue-refusal-1"}) { + t.Fatalf("queued = %v", ops) + } +} diff --git a/internal/server/chat_auto_switch.go b/internal/server/chat_auto_switch.go index fea5d75a..d9639697 100644 --- a/internal/server/chat_auto_switch.go +++ b/internal/server/chat_auto_switch.go @@ -115,6 +115,13 @@ func (h *chatHub) continueOnAnotherAccount(broker chatBroker, refusal claude.Usa if base == nil { base = context.Background() } + // A refusal arrives on its own goroutine, possibly while start-up + // recovery is still restoring the durable queue; acting on it then could + // have recovery put back the auto-continue this removes (see + // awaitRecovery). + if !h.awaitRecovery(base) { + return + } ctx, cancel := context.WithTimeout(base, time.Minute) defer cancel() title := "" diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index 25a35787..77164cda 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -182,6 +182,24 @@ func (h *chatHub) clock() time.Time { return time.Now() } +// awaitRecovery blocks until start-up recovery has restored the durable turn +// and queue state (resumeQueued), and reports false when ctx ends first. +// Everything that admits, removes or otherwise changes a session's queued +// prompts waits for it: resumeQueued reads the durable rows and then adds +// every one its room does not hold, so a prompt removed in between would be +// put back (and, as the queue head, hold everything behind it). +func (h *chatHub) awaitRecovery(ctx context.Context) bool { + if h == nil || h.recoveryReady == nil { + return true + } + select { + case <-h.recoveryReady: + return true + case <-ctx.Done(): + return false + } +} + // apply folds one pushed frame into the retained state. Text and reasoning // deltas append to their message's part; a tool frame upserts the part (merging // the fields it carries onto what is retained, and accounting for the whole diff --git a/internal/server/chat_shell_run_test.go b/internal/server/chat_shell_run_test.go index b82180b2..0a57f4d9 100644 --- a/internal/server/chat_shell_run_test.go +++ b/internal/server/chat_shell_run_test.go @@ -175,8 +175,17 @@ func TestChatShellShareQueuesAnOrdinaryPrompt(t *testing.T) { finishedShell(t, ctx, conns[0], run.ID) writeChat(t, ctx, conns[0], shellRequest(protocol.ChatShellShare, "share", run.ID, "")) // The composed prompt is echoed to the sender too: it has no local copy. - for _, conn := range conns { + // The turn runner writes the sender's reply straight to its connection + // while the echo goes through the sender's subscription writer, so the two + // arrive in either order; neither may be skipped while reading for the + // other. + var reply *protocol.Message + for i, conn := range conns { user := readShellFrame(t, ctx, conn, func(m protocol.Message) bool { + if i == 0 && m.ID == "share" { + reply = &m + return false + } return m.Type == protocol.ChatEvent && m.ChatEvent != nil && m.ChatEvent.Kind == protocol.ChatEventUser }).ChatEvent text := user.Part.Text @@ -184,7 +193,11 @@ func TestChatShellShareQueuesAnOrdinaryPrompt(t *testing.T) { t.Fatalf("shared prompt = %q", text) } } - if reply := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool { return m.ID == "share" }); reply.Type != protocol.ChatPrompt { + if reply == nil { + got := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool { return m.ID == "share" }) + reply = &got + } + if reply.Type != protocol.ChatPrompt { t.Fatalf("share reply = %+v", reply) } } diff --git a/internal/server/chat_tools_followup.go b/internal/server/chat_tools_followup.go index 0785c396..693aec6a 100644 --- a/internal/server/chat_tools_followup.go +++ b/internal/server/chat_tools_followup.go @@ -85,6 +85,9 @@ func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, me // queueFollowup queues an agent's follow-up prompt for sendAt: durably, under // the follow-up sender label, shown to every attached client as scheduled. func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error { + if !h.awaitRecovery(ctx) { + return ctx.Err() + } p := &chatQueuedPrompt{ text: text, operationID: operationID, diff --git a/internal/server/websocket.go b/internal/server/websocket.go index b44124b5..33732758 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -137,10 +137,6 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin settingsStore = stores[0] } hub.settings = settingsStore - if options.Chat != nil { - // A Claude chat refused for usage continues on another saved account. - hub.watchUsageRefusals(options.Chat) - } if len(stores) > 0 { // Prompts queued behind a running turn are durable and owned by their // session; resume delivering any a previous process left queued. @@ -641,6 +637,12 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin hub.retryReattachments(ctx, options.Chat) }() } + if options.Chat != nil { + // A Claude chat refused for usage continues on another saved account. + // Registered once the hub is fully wired (stores, recovery gate), since + // a refusal can arrive on its own goroutine at any moment after this. + hub.watchUsageRefusals(options.Chat) + } if runs != nil { // Continue the runs a previous process left in flight, now that the // runner's collaborators are wired and before any request is served.