package claude import ( "context" "testing" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // A watcher whose buffer is full of streamed text may lose a delta, but never // the turn's end: a lost end left the chat "working" forever. func TestEmitDeliversTheTurnEndToAFullWatcher(t *testing.T) { c := newChat(context.Background()) t.Cleanup(c.cancel) s := c.sessionFor("ses_full", t.TempDir()) ch := s.subscribe() defer s.unsubscribe(ch) for len(ch) < cap(ch) { s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}}) } emitted := make(chan struct{}) go func() { defer close(emitted) s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}) }() // The watcher is slow, not gone: it drains only after the end was emitted. time.Sleep(100 * time.Millisecond) deadline := time.After(3 * time.Second) for { select { case frame := <-ch: if frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded { <-emitted return } case <-deadline: t.Fatal("the turn end never reached the full watcher") } } } // A watcher that never drains does not hold the CLI reader forever. func TestEmitGivesUpOnAStuckWatcher(t *testing.T) { prior := lifecycleDeliveryTimeout lifecycleDeliveryTimeout = 50 * time.Millisecond t.Cleanup(func() { lifecycleDeliveryTimeout = prior }) c := newChat(context.Background()) t.Cleanup(c.cancel) s := c.sessionFor("ses_stuck", t.TempDir()) ch := s.subscribe() defer s.unsubscribe(ch) for len(ch) < cap(ch) { s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}}) } start := time.Now() s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}) if waited := time.Since(start); waited > 2*time.Second { t.Fatalf("emit blocked %s on a stuck watcher", waited) } }