Files
pipelines/internal/server/chat_test.go
T
alan b28f88be66 Add tests proving chat_interrupt stops a running chat turn
The chat_interrupt path was already wired end to end (protocol type,
server dispatch through handleChatSimple to broker.Interrupt, and the
adapter POST /api/session/{id}/interrupt), but nothing exercised it
against a live stream. Add the missing coverage:

- internal/opencode/chat_test.go: pin the adapter's outbound call
  exactly (POST /api/session/ses_1/interrupt, empty JSON body, one
  request, nil on 200) plus a non-nil error on HTTP 500.
- internal/server/chat_test.go: drive the real opencode.Chat adapter
  over an httptest SSE fixture that holds the turn open until the
  interrupt arrives, then assert the run ends, the interrupt is
  acknowledged, no error frame is sent, and the prompt/interrupt posts
  and interrupt path match. Also cover invalid-session rejection,
  the unconfigured-broker error, and broker-failure reporting, adding a
  spare interruptErr hook to the scripted fakeChat.

Production code is unchanged: verification found no gap in the existing
interrupt transport. Tests use httptest loopback fixtures only and do
not touch the live OpenCode service.
2026-10-16 06:43:02 +01:00

897 lines
35 KiB
Go

package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// fakeChat is a scripted chatBroker. It counts calls and either emits a fixed
// frame sequence or blocks until the caller's context is canceled.
type fakeChat struct {
mu sync.Mutex
promptCalls int
interrupts int
replies int
messageCalls int
messageSessionID string
messageLimit int
messages []protocol.ChatMessage
script []protocol.ChatEventFrame
started chan struct{}
done chan struct{}
startOnce sync.Once
block bool
subscribed bool
promptBeforeSubscribe bool
interruptErr error
}
func (f *fakeChat) Prompt(context.Context, string, string) error {
f.mu.Lock()
defer f.mu.Unlock()
f.promptCalls++
if !f.subscribed {
f.promptBeforeSubscribe = true
}
return nil
}
func (f *fakeChat) Stream(ctx context.Context, _ string, ready func(), emit func(protocol.ChatEventFrame) error) error {
f.mu.Lock()
f.subscribed = true
f.mu.Unlock()
if ready != nil {
ready()
}
if f.started != nil {
f.startOnce.Do(func() { close(f.started) })
}
if f.block {
<-ctx.Done()
if f.done != nil {
close(f.done)
}
return ctx.Err()
}
for _, frame := range f.script {
if err := ctx.Err(); err != nil {
return err
}
if err := emit(frame); err != nil {
return err
}
}
return nil
}
func (f *fakeChat) Interrupt(context.Context, string) error {
f.mu.Lock()
defer f.mu.Unlock()
f.interrupts++
return f.interruptErr
}
func (f *fakeChat) Messages(_ context.Context, sessionID string, limit int) ([]protocol.ChatMessage, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.messageCalls++
f.messageSessionID = sessionID
f.messageLimit = limit
return f.messages, nil
}
// messageQuery reports the recorded chat_messages call count, session id and
// limit so a test can assert the handler forwarded the query.
func (f *fakeChat) messageQuery() (int, string, int) {
f.mu.Lock()
defer f.mu.Unlock()
return f.messageCalls, f.messageSessionID, f.messageLimit
}
func (f *fakeChat) Reply(context.Context, protocol.ChatReplyRequest) error {
f.mu.Lock()
defer f.mu.Unlock()
f.replies++
return nil
}
func (f *fakeChat) counts() (int, int, int) {
f.mu.Lock()
defer f.mu.Unlock()
return f.promptCalls, f.interrupts, f.replies
}
func chatFrame(kind, delta string, part *protocol.ChatPart, step *protocol.ChatStep) protocol.ChatEventFrame {
return protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: kind, Delta: delta, Part: part, Step: step}
}
func scriptedChat() *fakeChat {
return &fakeChat{script: []protocol.ChatEventFrame{
chatFrame(protocol.ChatEventText, "hello ", &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1#0"}, nil),
chatFrame(protocol.ChatEventText, "world", &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1#0"}, nil),
chatFrame(protocol.ChatEventTool, "", &protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", Name: "shell", State: &protocol.ChatToolState{Status: protocol.ChatToolCompleted, Input: []byte(`{"command":"ls"}`)}}, nil),
chatFrame(protocol.ChatEventStep, "", nil, &protocol.ChatStep{Status: protocol.ChatStepEnded, Index: 1}),
}}
}
func dialChat(t *testing.T, broker chatBroker) (context.Context, context.CancelFunc, *websocket.Conn) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{Chat: broker}))
t.Cleanup(func() { srv.Close(); cancel() })
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.CloseNow() })
return ctx, cancel, conn
}
func readChatTurn(t *testing.T, ctx context.Context, conn *websocket.Conn) []protocol.ChatEventFrame {
t.Helper()
var frames []protocol.ChatEventFrame
for {
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
t.Fatal(err)
}
if message.Type == protocol.Error {
t.Fatalf("unexpected error frame: %s", message.Error)
}
if message.ChatEvent == nil {
continue
}
frames = append(frames, *message.ChatEvent)
if message.ChatEvent.Kind == protocol.ChatEventStep && message.ChatEvent.Step != nil && message.ChatEvent.Step.Status == protocol.ChatStepEnded {
return frames
}
}
}
func TestChatPromptStreamsEvents(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.ID != "r1" {
t.Fatalf("ack = %+v", ack)
}
frames := readChatTurn(t, ctx, conn)
if len(frames) != 4 {
t.Fatalf("got %d frames, want 4", len(frames))
}
sawText, sawStep := false, false
for _, frame := range frames {
if frame.SessionID != "ses_1" || frame.MessageID != "msg_1" {
t.Fatalf("frame missing stable ids: %+v", frame)
}
switch frame.Kind {
case protocol.ChatEventText:
sawText = true
case protocol.ChatEventStep:
sawStep = true
if frame.Step == nil || frame.Step.Status != protocol.ChatStepEnded {
t.Fatalf("step frame = %+v", frame)
}
}
}
if !sawText || !sawStep {
t.Fatalf("missing text or step frame: %+v", frames)
}
if prompts, _, _ := broker.counts(); prompts != 1 {
t.Fatalf("prompt forwarded %d times, want 1", prompts)
}
}
func TestChatPromptRejectsInvalidSession(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
for _, id := range []string{"", "not-a-session", "msg_1"} {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "bad", ChatPrompt: &protocol.ChatPromptRequest{SessionID: id, Text: "hi"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
t.Fatalf("session %q not rejected: %+v", id, response)
}
}
if prompts, _, _ := broker.counts(); prompts != 0 {
t.Fatalf("invalid sessions reached OpenCode: %d", prompts)
}
}
func TestChatPromptRejectsOversizedText(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
oversized := strings.Repeat("x", opencode.MaxRequest+1)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "big", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: oversized}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "64 KiB") {
t.Fatalf("oversized prompt not rejected: %+v", response)
}
if prompts, _, _ := broker.counts(); prompts != 0 {
t.Fatalf("oversized prompt reached OpenCode: %d", prompts)
}
}
func TestChatPromptWithoutBroker(t *testing.T) {
ctx, _, conn := dialChat(t, nil)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "not configured") {
t.Fatalf("unconfigured chat not rejected: %+v", response)
}
}
func TestChatMessagesResumesRetainedState(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
readChatTurn(t, ctx, conn)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "r2", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || response.ID != "r2" || len(response.ChatMessages) != 1 {
t.Fatalf("resume response = %+v", response)
}
message := response.ChatMessages[0]
if message.ID != "msg_1" || message.Role != protocol.ChatRoleAssistant || len(message.Parts) != 2 {
t.Fatalf("resumed message = %+v", message)
}
if message.Parts[0].Type != protocol.ChatPartText || message.Parts[0].ID != "msg_1#0" || message.Parts[0].Text != "hello world" {
t.Fatalf("resumed text part = %+v", message.Parts[0])
}
if message.Parts[1].Type != protocol.ChatPartTool || message.Parts[1].State == nil || message.Parts[1].State.Status != protocol.ChatToolCompleted {
t.Fatalf("resumed tool part = %+v", message.Parts[1])
}
}
// seededChatMessages is the stored user + assistant + tool session the
// chat_messages evidence tests assert on, mirroring the OpenCode V2 shape of an
// assistant turn's completed tool part (input object, text content, status).
func seededChatMessages() []protocol.ChatMessage {
return []protocol.ChatMessage{
{ID: "msg_user", SessionID: "ses_1", Role: protocol.ChatRoleUser,
Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: "list the files"}}},
{ID: "msg_assistant", SessionID: "ses_1", Role: protocol.ChatRoleAssistant, Model: "deepseek-v4.1-flash", Agent: "build",
Parts: []protocol.ChatPart{
{Type: protocol.ChatPartText, ID: "p1", Text: "here you go"},
{Type: protocol.ChatPartReasoning, ID: "p2", Text: "thinking"},
{Type: protocol.ChatPartTool, ID: "call_1", Name: "shell", Executed: true,
State: &protocol.ChatToolState{Status: protocol.ChatToolCompleted, Input: json.RawMessage(`{"command":"ls"}`), Content: []protocol.ChatToolContent{{Type: "text", Text: "ok"}}},
Time: &protocol.ChatTime{Created: 1, Ran: 2, Completed: 3}},
}},
}
}
// assertSeededChatMessages fails unless the user + assistant + tool session came
// back with both roles and the completed tool part's input, content and status.
func assertSeededChatMessages(t *testing.T, messages []protocol.ChatMessage) {
t.Helper()
if len(messages) != 2 {
t.Fatalf("got %d messages, want user+assistant: %+v", len(messages), messages)
}
user, assistant := messages[0], messages[1]
if user.ID != "msg_user" || user.Role != protocol.ChatRoleUser || len(user.Parts) != 1 || user.Parts[0].Type != protocol.ChatPartText || user.Parts[0].Text != "list the files" {
t.Fatalf("user turn = %+v", user)
}
if assistant.ID != "msg_assistant" || assistant.Role != protocol.ChatRoleAssistant || len(assistant.Parts) != 3 {
t.Fatalf("assistant turn = %+v", assistant)
}
if p := assistant.Parts[0]; p.Type != protocol.ChatPartText || p.Text != "here you go" {
t.Fatalf("assistant text part = %+v", p)
}
tool := assistant.Parts[2]
if tool.Type != protocol.ChatPartTool || tool.ID != "call_1" || tool.Name != "shell" || tool.State == nil || tool.State.Status != protocol.ChatToolCompleted {
t.Fatalf("assistant tool part = %+v", tool)
}
var input struct {
Command string `json:"command"`
}
if err := json.Unmarshal(tool.State.Input, &input); err != nil || input.Command != "ls" {
t.Fatalf("tool input = %s (err %v)", tool.State.Input, err)
}
if len(tool.State.Content) != 1 || tool.State.Content[0].Text != "ok" {
t.Fatalf("tool content = %+v", tool.State.Content)
}
}
// TestChatMessagesReturnsBrokerHistory drives chat_messages through the handler
// with an empty hub, so it must fall through to broker.Messages and return the
// seeded user + assistant + tool session, forwarding the query limit unchanged.
func TestChatMessagesReturnsBrokerHistory(t *testing.T) {
broker := scriptedChat()
broker.messages = seededChatMessages()
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "r2", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1", Limit: 7}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || response.ID != "r2" {
t.Fatalf("response = %+v", response)
}
assertSeededChatMessages(t, response.ChatMessages)
if calls, sessionID, limit := broker.messageQuery(); calls != 1 || sessionID != "ses_1" || limit != 7 {
t.Fatalf("broker query = %d/%q/%d, want 1/ses_1/7", calls, sessionID, limit)
}
}
// TestChatMessagesThroughRealAdapter loads a seeded session through the real
// opencode.Chat broker: the chat_messages handler reads the V2
// GET /api/session/{id}/message fixture once and returns the user + assistant +
// tool turns decoded from it, exercising the full handler -> adapter -> decode
// path with no scripted broker.
func TestChatMessagesThroughRealAdapter(t *testing.T) {
var messageReads atomic.Int32
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/session/ses_1/message" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
messageReads.Add(1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[
{"id":"msg_user","time":{"created":10},"type":"user","text":"list the files"},
{"id":"msg_assistant","time":{"created":20,"completed":30},"type":"assistant","agent":"build","model":{"id":"deepseek-v4.1-flash","providerID":"opencode-go"},"content":[
{"type":"text","text":"here you go"},
{"type":"reasoning","text":"thinking"},
{"type":"tool","id":"call_1","name":"shell","executed":true,"state":{"status":"completed","input":{"command":"ls"},"content":[{"type":"text","text":"ok"}]},"time":{"created":1,"ran":2,"completed":3}}
]}
],"cursor":{"next":null}}`))
}))
defer fixture.Close()
broker := opencode.NewChat(&opencode.Connection{Backend: "v2", URL: fixture.URL})
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "r2", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || response.ID != "r2" {
t.Fatalf("response = %+v", response)
}
assertSeededChatMessages(t, response.ChatMessages)
if messageReads.Load() != 1 {
t.Fatalf("message endpoint read %d times, want 1", messageReads.Load())
}
}
// TestChatMessagesRejectsInvalidSession pins that a missing or malformed session
// id is rejected before any broker call.
func TestChatMessagesRejectsInvalidSession(t *testing.T) {
broker := scriptedChat()
broker.messages = seededChatMessages()
ctx, _, conn := dialChat(t, broker)
for _, query := range []*protocol.ChatQuery{nil, {SessionID: ""}, {SessionID: "not-a-session"}} {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "bad", ChatQuery: query}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
t.Fatalf("query %+v not rejected: %+v", query, response)
}
}
if calls, _, _ := broker.messageQuery(); calls != 0 {
t.Fatalf("invalid chat_messages reached the broker: %d", calls)
}
}
func TestChatDisconnectCancelsStream(t *testing.T) {
broker := scriptedChat()
broker.block = true
broker.started = make(chan struct{})
broker.done = make(chan struct{})
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
select {
case <-broker.started:
case <-time.After(2 * time.Second):
t.Fatal("stream never started")
}
conn.CloseNow()
// The server's read loop returns on disconnect, canceling the connection
// context the subscription observes; no goroutine may keep running.
select {
case <-broker.done:
case <-time.After(3 * time.Second):
t.Fatal("chat stream was not canceled on disconnect")
}
if prompts, _, _ := broker.counts(); prompts != 1 {
t.Fatalf("prompt forwarded %d times, want 1", prompts)
}
}
func TestChatInterruptAndReply(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatInterrupt, ID: "i1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatInterrupt || response.ID != "i1" {
t.Fatalf("interrupt response = %+v", response)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatReply, ID: "p1", ChatReply: &protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatReply || response.ID != "p1" {
t.Fatalf("reply response = %+v", response)
}
if _, interrupts, replies := broker.counts(); interrupts != 1 || replies != 1 {
t.Fatalf("interrupts=%d replies=%d, want 1/1", interrupts, replies)
}
}
// TestChatInterruptEndsRunningPrompt is the task evidence: it starts a
// long-running turn through the real opencode.Chat adapter over an httptest SSE
// fixture, sends chat_interrupt, and asserts the run ends. The fixture records
// the actual POST /api/session/ses_1/interrupt and only closes the SSE
// subscription once that request arrives, so the run genuinely terminates rather
// than completing on its own.
func TestChatInterruptEndsRunningPrompt(t *testing.T) {
var (
mu sync.Mutex
prompts int
interrupts int
interruptPath string
)
interrupted := make(chan struct{})
var interruptOnce sync.Once
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && r.URL.Path == "/api/session/ses_1/prompt":
mu.Lock()
prompts++
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`))
case r.Method == http.MethodGet && r.URL.Path == "/api/event":
flusher, ok := w.(http.Flusher)
if !ok {
t.Errorf("event stream response is not flushable")
return
}
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: " + `{"id":"evt_1","type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0,"delta":"working"}}` + "\n\n"))
flusher.Flush()
// Hold the turn open until the interrupt arrives so the test exercises
// a running run, not a stream that already completed.
select {
case <-interrupted:
case <-r.Context().Done():
return
}
_, _ = w.Write([]byte("data: " + `{"id":"evt_2","type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","step":1}}` + "\n\n"))
flusher.Flush()
case r.Method == http.MethodPost && r.URL.Path == "/api/session/ses_1/interrupt":
mu.Lock()
interrupts++
interruptPath = r.URL.Path
mu.Unlock()
interruptOnce.Do(func() { close(interrupted) })
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{}`))
default:
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
}
}))
defer fixture.Close()
broker := opencode.NewChat(&opencode.Connection{Backend: "v2", URL: fixture.URL})
ctx, _, conn := dialChat(t, broker)
// Start a long-running turn.
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "start a long-running task"}}); err != nil {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.ID != "r1" {
t.Fatalf("prompt ack = %+v", ack)
}
// The first text delta proves the turn is live and the subscription attached.
var first protocol.Message
if err := wsjson.Read(ctx, conn, &first); err != nil {
t.Fatal(err)
}
if first.Type != protocol.ChatEvent || first.ChatEvent == nil || first.ChatEvent.Kind != protocol.ChatEventText || first.ChatEvent.Delta != "working" {
t.Fatalf("expected a live text delta, got %+v", first)
}
// Stop the running turn.
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatInterrupt, ID: "i1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
// Read until both the interrupt ack and the step.ended frame arrive, in
// whichever order the server emits them; any error frame fails the test.
var acked, ended bool
for !acked || !ended {
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
t.Fatal(err)
}
if message.Type == protocol.Error {
t.Fatalf("unexpected error frame: %s", message.Error)
}
if message.Type == protocol.ChatInterrupt {
if message.ID != "i1" {
t.Fatalf("interrupt ack id = %q, want i1", message.ID)
}
acked = true
}
if event := message.ChatEvent; event != nil && event.SessionID == "ses_1" && event.Kind == protocol.ChatEventStep && event.Step != nil && event.Step.Status == protocol.ChatStepEnded {
ended = true
}
}
mu.Lock()
gotPrompts, gotInterrupts, gotPath := prompts, interrupts, interruptPath
mu.Unlock()
if gotPrompts != 1 {
t.Fatalf("prompt posts = %d, want 1", gotPrompts)
}
if gotInterrupts != 1 {
t.Fatalf("interrupt posts = %d, want 1", gotInterrupts)
}
if gotPath != "/api/session/ses_1/interrupt" {
t.Fatalf("interrupt path = %q, want /api/session/ses_1/interrupt", gotPath)
}
}
// TestChatInterruptRejectsInvalidSession pins that a missing, empty or malformed
// session id is rejected with a protocol.Error before any broker call.
func TestChatInterruptRejectsInvalidSession(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
for _, query := range []*protocol.ChatQuery{nil, {}, {SessionID: "not-a-session"}} {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatInterrupt, ID: "bad", ChatQuery: query}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
t.Fatalf("query %+v not rejected: %+v", query, response)
}
}
if _, interrupts, _ := broker.counts(); interrupts != 0 {
t.Fatalf("invalid interrupts reached the broker: %d", interrupts)
}
}
// TestChatInterruptWithoutBroker pins that an unconfigured server answers
// chat_interrupt with the existing "not configured" error.
func TestChatInterruptWithoutBroker(t *testing.T) {
ctx, _, conn := dialChat(t, nil)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatInterrupt, ID: "i1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "not configured") {
t.Fatalf("unconfigured interrupt not rejected: %+v", response)
}
}
// TestChatInterruptErrorReported pins that a broker failure is surfaced to the
// client as a protocol.Error frame carrying the echoed request id.
func TestChatInterruptErrorReported(t *testing.T) {
broker := scriptedChat()
broker.interruptErr = fmt.Errorf("run is already finished")
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatInterrupt, ID: "i1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "i1" || !strings.Contains(response.Error, "already finished") {
t.Fatalf("interrupt failure not reported: %+v", response)
}
if _, interrupts, _ := broker.counts(); interrupts != 1 {
t.Fatalf("interrupts = %d, want 1", interrupts)
}
}
func TestChatHubAccumulatesAndEvicts(t *testing.T) {
tick := 0
hub := newChatHub()
hub.now = func() time.Time { tick++; return time.Unix(int64(tick), 0) }
for _, delta := range []string{"a", "b", "c"} {
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventText, Delta: delta, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1#0"}})
}
messages := hub.snapshot("ses_1")
if len(messages) != 1 || len(messages[0].Parts) != 1 || messages[0].Parts[0].Text != "abc" {
t.Fatalf("snapshot = %+v", messages)
}
for i := 0; i < chatMaxTurns+5; i++ {
id := fmt.Sprintf("ses_%d", i)
hub.apply(protocol.ChatEventFrame{SessionID: id, MessageID: "m", Kind: protocol.ChatEventText, Delta: "x", Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: id + "#0"}})
}
if len(hub.turns) != chatMaxTurns {
t.Fatalf("retained %d turns, want %d", len(hub.turns), chatMaxTurns)
}
}
// TestChatHubKeepsMessagesSeparate pins per-message retention: a second prompt
// in one session must not fold its parts onto the first turn's message id.
func TestChatHubKeepsMessagesSeparate(t *testing.T) {
hub := newChatHub()
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventText, Delta: "one", Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1#0"}})
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_2", Kind: protocol.ChatEventText, Delta: "two", Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_2#0"}})
messages := hub.snapshot("ses_1")
if len(messages) != 2 {
t.Fatalf("messages = %+v", messages)
}
if messages[0].ID != "msg_1" || messages[0].Parts[0].ID != "msg_1#0" || messages[0].Parts[0].Text != "one" {
t.Fatalf("first message = %+v", messages[0])
}
if messages[1].ID != "msg_2" || messages[1].Parts[0].ID != "msg_2#0" || messages[1].Parts[0].Text != "two" {
t.Fatalf("second message = %+v", messages[1])
}
}
// TestChatHubChargesToolStateBytes pins the retained-state cap: a tool part's
// input/content bytes count against it, and an upsert that would exceed the cap
// is dropped with the overflow diagnostic rather than growing memory.
func TestChatHubChargesToolStateBytes(t *testing.T) {
hub := newChatHub()
big := strings.Repeat("x", chatRetainedLimit/2)
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventTool, Part: &protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", Name: "shell", State: &protocol.ChatToolState{Status: protocol.ChatToolStreaming, Input: json.RawMessage(`"` + big + `"`)}}})
hub.mu.Lock()
size := hub.turns["ses_1"].size
hub.mu.Unlock()
if size < len(big) {
t.Fatalf("tool input not charged: size=%d want >= %d", size, len(big))
}
huge := strings.Repeat("y", chatRetainedLimit)
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventTool, Part: &protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", Name: "shell", State: &protocol.ChatToolState{Status: protocol.ChatToolCompleted, Input: json.RawMessage(`"` + huge + `"`)}}})
messages := hub.snapshot("ses_1")
if len(messages) != 1 || len(messages[0].Parts) != 1 || messages[0].Parts[0].State == nil || messages[0].Parts[0].State.Status != protocol.ChatToolStreaming {
t.Fatalf("overflowing tool state was retained: %+v", messages)
}
}
// TestChatPromptSubscribesBeforePrompt pins the subscribe-before-prompt order:
// the firehose has no replay cursor, so the subscription must be attached before
// the prompt is posted or deltas emitted in between are lost.
func TestChatPromptSubscribesBeforePrompt(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
readChatTurn(t, ctx, conn)
broker.mu.Lock()
before := broker.promptBeforeSubscribe
broker.mu.Unlock()
if before {
t.Fatal("prompt was posted before the event subscription was attached")
}
}
// realAdapterChat posts a chat_prompt through the real opencode.Chat broker and
// HandlerWithOptions against a v2 HTTP fixture that replays frames, so the
// acceptance path forwards to an actual OpenCode-shaped stream (not a scripted
// fake) and returns the chat_event frames the server pushed. It pins exactly one
// prompt POST and one event subscription per chat_prompt, then asserts the ack
// echoes the request id; callers assert the frames themselves.
func realAdapterChat(t *testing.T, frames []string) []protocol.ChatEventFrame {
t.Helper()
var prompts, streams atomic.Int32
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && r.URL.Path == "/api/session/ses_1/prompt":
prompts.Add(1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`))
case r.Method == http.MethodGet && r.URL.Path == "/api/event":
streams.Add(1)
w.Header().Set("Content-Type", "text/event-stream")
for _, frame := range frames {
_, _ = w.Write([]byte("data: " + frame + "\n\n"))
}
default:
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
}
}))
defer fixture.Close()
broker := opencode.NewChat(&opencode.Connection{Backend: "v2", URL: fixture.URL})
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "ping"}}); err != nil {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.ID != "r1" {
t.Fatalf("ack = %+v", ack)
}
framesIn := readChatTurn(t, ctx, conn)
if prompts.Load() != 1 || streams.Load() != 1 {
t.Fatalf("prompts=%d streams=%d, want 1/1", prompts.Load(), streams.Load())
}
return framesIn
}
// assertStableFrameIDs fails unless every frame carries the fixture's session
// and message ids: a client cannot attribute a frame without them.
func assertStableFrameIDs(t *testing.T, frames []protocol.ChatEventFrame) {
t.Helper()
for _, frame := range frames {
if frame.SessionID != "ses_1" || frame.MessageID != "msg_1" {
t.Fatalf("frame missing stable ids: %+v", frame)
}
}
}
// TestChatPromptThroughRealAdapter drives a text, tool and step turn end to end.
func TestChatPromptThroughRealAdapter(t *testing.T) {
framesIn := realAdapterChat(t, []string{
`{"id":"evt_1","type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0,"delta":"pong"}}`,
`{"id":"evt_2","type":"session.tool.called","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","input":{"command":"ls"}}}`,
`{"id":"evt_3","type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","step":1}}`,
})
assertStableFrameIDs(t, framesIn)
sawText, sawTool := false, false
for _, frame := range framesIn {
if frame.Kind == protocol.ChatEventText && frame.Delta == "pong" {
sawText = true
}
if frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.Name == "shell" {
sawTool = true
}
}
if !sawText || !sawTool {
t.Fatalf("missing text or tool frame: %+v", framesIn)
}
}
// TestChatPromptNoToolThroughRealAdapter is the task's evidence harness: it posts
// a trivial no-tool prompt to the real opencode.Chat adapter over a v2 SSE
// fixture that emits only a text delta and a step, and asserts both arrive as
// chat_event frames with stable session/message ids. It reuses dialChat,
// readChatTurn and realAdapterChat so it pins the same ack/stream contract as the
// other chat tests, and it pins exactly one prompt POST and one event subscription.
func TestChatPromptNoToolThroughRealAdapter(t *testing.T) {
framesIn := realAdapterChat(t, []string{
`{"id":"evt_1","type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0,"delta":"pong"}}`,
`{"id":"evt_2","type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","step":1}}`,
})
assertStableFrameIDs(t, framesIn)
sawText, sawStep, sawTool := false, false, false
for _, frame := range framesIn {
switch frame.Kind {
case protocol.ChatEventText:
sawText = frame.Delta == "pong"
case protocol.ChatEventStep:
sawStep = frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded
case protocol.ChatEventTool:
sawTool = true
}
}
if !sawText || !sawStep {
t.Fatalf("missing text or step frame: %+v", framesIn)
}
if sawTool {
t.Fatalf("a trivial no-tool prompt produced a tool frame: %+v", framesIn)
}
}
// TestChatPromptRejectsEmptyText pins the whitespace guard: an empty or
// whitespace-only prompt is rejected before any OpenCode call.
func TestChatPromptRejectsEmptyText(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
for _, text := range []string{"", " ", "\t\n"} {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "empty", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: text}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "empty" {
t.Fatalf("empty text %q not rejected: %+v", text, response)
}
}
if prompts, _, _ := broker.counts(); prompts != 0 {
t.Fatalf("empty prompts reached OpenCode: %d", prompts)
}
}
// TestChatSessionsAndCreateAnswerExplicitly pins the declared-but-unbrokered
// boundary: chat_sessions and chat_create are answered with a protocol error
// rather than falling through to the generic Pong.
func TestChatSessionsAndCreateAnswerExplicitly(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
for _, typ := range []string{protocol.ChatSessions, protocol.ChatCreate} {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: typ, ID: "c1"}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "c1" {
t.Fatalf("%s did not answer with an explicit error: %+v", typ, response)
}
}
}