package gateway import ( "context" "log/slog" "testing" "time" "github.com/samcharles93/archie-core/internal/domain/messaging" ) // A streamed turn outlives its caller: closing the stream must not cancel // the turn, and only Cancel stops it. func TestStreamedTurnSurvivesCallerDisconnect(t *testing.T) { for _, tc := range []struct { name string stop bool cancelled bool }{ {name: "caller disconnects", stop: false, cancelled: false}, {name: "caller disconnects then stops", stop: true, cancelled: true}, } { t.Run(tc.name, func(t *testing.T) { release := make(chan struct{}) finished := make(chan error, 1) router := &Router{LLMStream: func(ctx context.Context, _ Inbound, stream TurnStream) (string, error) { stream.Delta("working") select { case <-release: case <-ctx.Done(): } finished <- ctx.Err() return "reply", ctx.Err() }} turns := messaging.NewTurns(slog.New(slog.DiscardHandler)) adapter := &LocalChatAdapter{Router: router, Turns: turns} ctx, disconnect := context.WithCancel(context.Background()) in := Inbound{Message: messaging.Message{Text: "hello"}} done := make(chan struct{}) go func() { adapter.runStreamedTurn(ctx, in, "s1", make(chan ChatEvent, 32)) close(done) }() time.Sleep(10 * time.Millisecond) disconnect() <-done if tc.stop { turns.Stop("s1") } else { close(release) } select { case err := <-finished: if got := err != nil; got != tc.cancelled { t.Fatalf("turn cancelled = %v, want %v (err %v)", got, tc.cancelled, err) } case <-time.After(2 * time.Second): t.Fatal("turn never finished") } }) } }