package server import ( "context" "path/filepath" "slices" "testing" "time" "github.com/coder/websocket" "git.a-wan.net/alan/pipelines/internal/protocol" ) // fastStaleTurnSettle shortens the queue's stale observed-turn settle period. func fastStaleTurnSettle(t *testing.T) { t.Helper() settle := chatQueueStaleTurnSettle chatQueueStaleTurnSettle = 150 * time.Millisecond t.Cleanup(func() { chatQueueStaleTurnSettle = settle }) } func (c *observedChat) setProbe(running bool) { c.smu.Lock() c.probe["ses_1"] = running c.smu.Unlock() } // waitStepFrame reads conn until the stream delivers the step frame for turn. func waitStepFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, status, turn string) { t.Helper() for { message := readChatMessage(t, ctx, conn) if message.Type == protocol.ChatEvent && message.ChatEvent != nil && message.ChatEvent.Step != nil && message.ChatEvent.Step.Status == status && message.ChatEvent.Step.TurnID == turn { return } } } // The live incident: a chat's last turn before a restart was refused for a // usage limit, so the app scheduled its auto-continue prompt for the limit's // reset, an hour away. After the restart the operator switched accounts and // sent "continue", which queued behind that scheduled head; then the // scheduled prompt was removed. The runner was asleep until the removed // prompt's send_at, so "continue" (due now, harness idle) sat in the queue // until the next restart. Removing the head must wake the runner. func TestChatPromptBehindAnUnqueuedScheduledHeadRunsAfterRestart(t *testing.T) { fastReattach(t) path := restartChatDB(t) first := newRestartChat() server := startChatRestartServer(t, first, path) conn := dialChatConn(t, server.ctx, server.srv) sendPrompt(t, server.ctx, conn, "p1", "keep going", "op-1") waitFor(t, "first prompt", func() bool { return first.promptCount() == 1 }) // The turn is refused for a usage limit: it ends at once. first.push(stepFrameFor(protocol.ChatStepStarted, "turn_refused")) first.push(stepFrameFor(protocol.ChatStepEnded, "turn_refused")) waitStepFrame(t, server.ctx, conn, protocol.ChatStepEnded, "turn_refused") reset := time.Now().Add(time.Hour) writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "auto", ChatPrompt: &protocol.ChatPromptRequest{ SessionID: "ses_1", Text: "keep going", OperationID: "auto-continue-refusal-1", Client: "Phone", SendAt: reset.UnixMilli()}}) if ack := readUntil(t, server.ctx, conn, protocol.ChatPrompt); !ack.ChatQueued { t.Fatalf("auto-continue was not scheduled: %+v", ack) } server.shutdown() second := newRestartChat() server = startChatRestartServer(t, second, path) conn = dialChatConn(t, server.ctx, server.srv) if ack := sendPrompt(t, server.ctx, conn, "p2", "continue", "op-continue"); !ack.ChatQueued { t.Fatalf("continue was not queued behind the scheduled head: %+v", ack) } writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatUnqueue, ID: "rm", ChatUnqueue: &protocol.ChatUnqueueRequest{SessionID: "ses_1", OperationID: "auto-continue-refusal-1"}}) if removed := readUntil(t, server.ctx, conn, protocol.ChatUnqueue); removed.ChatQueue == nil || removed.ChatQueue.Removed != "auto-continue-refusal-1" { t.Fatalf("unqueue reply = %+v", removed.ChatQueue) } waitFor(t, "continue delivered once the scheduled head is gone", func() bool { return second.promptCount() == 1 }) if texts := second.promptTexts(); !slices.Equal(texts, []string{"continue"}) { t.Fatalf("delivered = %v", texts) } } // A turn the room only observed (the harness started it on its own) whose // end event is lost must not hold a due prompt forever: once the harness // reports itself idle for the settle period, the stale turn is ended and the // prompt delivered. While the harness reports the turn running, it waits. func TestChatQueueEndsAStaleObservedTurnOnceTheHarnessIsIdle(t *testing.T) { fastUnattended(t) fastStaleTurnSettle(t) t.Setenv("PIPELINES_NTFY_URL", "") store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db")) broker := newObservedChat() server := startQueueServer(t, broker, store) conn := dialChatConn(t, server.ctx, server.srv) sendPrompt(t, server.ctx, conn, "p1", "build it", "op-1") waitFor(t, "first prompt", func() bool { return broker.promptCount() == 1 }) broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_1")) broker.push(stepFrameFor(protocol.ChatStepEnded, "turn_1")) // The harness starts a turn of its own (a background task finished); // its end never reaches the room. broker.setProbe(true) broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_cli")) waitStepFrame(t, server.ctx, conn, protocol.ChatStepStarted, "turn_cli") if ack := sendPrompt(t, server.ctx, conn, "p2", "continue", "op-2"); !ack.ChatQueued { t.Fatalf("prompt behind the harness's own turn was not queued: %+v", ack) } time.Sleep(4 * chatQueueStaleTurnSettle) if n := broker.promptCount(); n != 1 { t.Fatalf("prompt delivered while the harness reports its turn running: %v", broker.promptTexts()) } broker.setProbe(false) waitFor(t, "prompt delivered after the harness went idle", func() bool { return broker.promptCount() == 2 }) if texts := broker.promptTexts(); texts[1] != "continue" { t.Fatalf("delivered = %v", texts) } } // A reattached turn whose watcher gave up (its turn limit passed while the // harness still reported it running) left the room's observed turn set: once // the harness is idle, the queued prompt must still be delivered. func TestChatQueuedPromptRunsAfterAReattachedTurnWatcherGaveUp(t *testing.T) { fastReattach(t) fastStaleTurnSettle(t) limit := chatUnattendedTurnLimit chatUnattendedTurnLimit = 100 * time.Millisecond t.Cleanup(func() { chatUnattendedTurnLimit = limit }) path := restartChatDB(t) startTurnThenRestart(t, path, true) second := newRestartChat() second.setProbe(true) startChatRestartServer(t, second, path) waitFor(t, "reattached stream", func() bool { active, _ := second.streams(); return active >= 1 }) time.Sleep(3 * chatUnattendedTurnLimit) // the reattach watcher gives up if second.promptCount() != 0 { t.Fatalf("queued prompt delivered into a turn still running: %v", second.promptTexts()) } second.setProbe(false) waitFor(t, "queued prompt delivered", func() bool { return second.promptCount() == 1 }) if texts := second.promptTexts(); texts[0] != "then ship it" { t.Fatalf("wrong prompt delivered after restart: %v", texts) } }