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.
This commit is contained in:
@@ -37,6 +37,7 @@ type fakeChat struct {
|
||||
block bool
|
||||
subscribed bool
|
||||
promptBeforeSubscribe bool
|
||||
interruptErr error
|
||||
}
|
||||
|
||||
func (f *fakeChat) Prompt(context.Context, string, string) error {
|
||||
@@ -81,7 +82,7 @@ func (f *fakeChat) Interrupt(context.Context, string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.interrupts++
|
||||
return nil
|
||||
return f.interruptErr
|
||||
}
|
||||
|
||||
func (f *fakeChat) Messages(_ context.Context, sessionID string, limit int) ([]protocol.ChatMessage, error) {
|
||||
@@ -484,6 +485,183 @@ func TestChatInterruptAndReply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
|
||||
Reference in New Issue
Block a user