2350 lines
94 KiB
Go
2350 lines
94 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"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/pipeline"
|
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
|
)
|
|
|
|
// newOperatorStore opens a scratch store for the operator-session registry, so
|
|
// the chat tests exercise the real SQL-backed registry (record, list, delete)
|
|
// rather than a second fake of it.
|
|
func newOperatorStore(t *testing.T) *pipeline.Store {
|
|
t.Helper()
|
|
store, err := pipeline.Open(filepath.Join(t.TempDir(), "operator.db"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { store.Close() })
|
|
return store
|
|
}
|
|
|
|
// 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
|
|
replyRequest protocol.ChatReplyRequest
|
|
replyErr error
|
|
messageCalls int
|
|
messageSessionID string
|
|
messageLimit int
|
|
messageCursor string
|
|
messages []protocol.ChatMessage
|
|
permissionCalls int
|
|
permissionSessionID string
|
|
permissions []protocol.ChatPermissionFrame
|
|
permissionErr error
|
|
shells []protocol.ChatShell
|
|
shellErr error
|
|
sessionCalls int
|
|
sessions []protocol.ChatSession
|
|
sessionErr error
|
|
permBlock bool
|
|
permDone chan struct{}
|
|
permOnce sync.Once
|
|
script []protocol.ChatEventFrame
|
|
started chan struct{}
|
|
done chan struct{}
|
|
startOnce sync.Once
|
|
streamCalls int
|
|
readyGate <-chan struct{}
|
|
block bool
|
|
subscribed bool
|
|
promptBeforeSubscribe bool
|
|
interruptErr error
|
|
createCalls int
|
|
createTitle string
|
|
createDirectory string
|
|
created protocol.ChatSession
|
|
createErr error
|
|
createGate <-chan struct{}
|
|
createStarted chan struct{}
|
|
createOnce sync.Once
|
|
activateCalls int
|
|
activateSessionID string
|
|
activateSkill string
|
|
activateErr error
|
|
sessionByIDCalls int
|
|
sessionByID string
|
|
sessionRecord protocol.ChatSession
|
|
sessionFound bool
|
|
sessionByIDErr error
|
|
}
|
|
|
|
func (f *fakeChat) BeginChatCreate(context.Context, string, string, string) (pipeline.ChatCreateBootstrap, error) {
|
|
return pipeline.ChatCreateBootstrap{State: "created"}, nil
|
|
}
|
|
func (f *fakeChat) SetChatCreateSession(context.Context, string, string) error { return nil }
|
|
func (f *fakeChat) AdvanceChatCreate(context.Context, string, string, string) error { return nil }
|
|
|
|
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.streamCalls++
|
|
readyGate := f.readyGate
|
|
f.mu.Unlock()
|
|
if f.started != nil {
|
|
f.startOnce.Do(func() { close(f.started) })
|
|
}
|
|
if readyGate != nil {
|
|
<-readyGate
|
|
}
|
|
if ready != nil {
|
|
ready()
|
|
}
|
|
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
|
|
}
|
|
|
|
// TestChatHubConcurrentObserversShareStream pins the start-up handoff: two
|
|
// clients that subscribe before the broker says ready still share one firehose.
|
|
func TestChatHubConcurrentObserversShareStream(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.block = true
|
|
broker.started = make(chan struct{})
|
|
gate := make(chan struct{})
|
|
broker.readyGate = gate
|
|
hub := newChatHub()
|
|
hub.mu.Lock()
|
|
room := hub.roomLocked("ses_1")
|
|
hub.mu.Unlock()
|
|
|
|
errs := make(chan error, 2)
|
|
go func() { errs <- hub.ensureObserving(room, broker) }()
|
|
select {
|
|
case <-broker.started:
|
|
case <-time.After(time.Second):
|
|
t.Fatal("first observer did not start the broker stream")
|
|
}
|
|
go func() { errs <- hub.ensureObserving(room, broker) }()
|
|
close(gate)
|
|
for range 2 {
|
|
if err := <-errs; err != nil {
|
|
t.Fatalf("ensureObserving: %v", err)
|
|
}
|
|
}
|
|
broker.mu.Lock()
|
|
calls := broker.streamCalls
|
|
broker.mu.Unlock()
|
|
if calls != 1 {
|
|
t.Fatalf("broker Stream calls = %d, want 1", calls)
|
|
}
|
|
room.cancel()
|
|
}
|
|
|
|
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, cursor string) (protocol.ChatHistoryPage, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.messageCalls++
|
|
f.messageSessionID = sessionID
|
|
f.messageLimit = limit
|
|
f.messageCursor = cursor
|
|
return protocol.ChatHistoryPage{Messages: 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, request protocol.ChatReplyRequest) error {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.replies++
|
|
f.replyRequest = request
|
|
return f.replyErr
|
|
}
|
|
|
|
// Permissions returns the seeded pending requests, or blocks until the caller's
|
|
// context is canceled when permBlock is set (used to prove the poller stops on
|
|
// disconnect). Every call is counted so a test can assert polling happened.
|
|
func (f *fakeChat) Shells(context.Context, string) ([]protocol.ChatShell, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return append([]protocol.ChatShell(nil), f.shells...), f.shellErr
|
|
}
|
|
|
|
func (f *fakeChat) Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error) {
|
|
f.mu.Lock()
|
|
f.permissionCalls++
|
|
f.permissionSessionID = sessionID
|
|
frames := append([]protocol.ChatPermissionFrame(nil), f.permissions...)
|
|
err := f.permissionErr
|
|
block := f.permBlock
|
|
done := f.permDone
|
|
f.mu.Unlock()
|
|
if block {
|
|
<-ctx.Done()
|
|
if done != nil {
|
|
f.permOnce.Do(func() { close(done) })
|
|
}
|
|
return nil, ctx.Err()
|
|
}
|
|
return frames, err
|
|
}
|
|
|
|
// permissionQuery reports the recorded permission poll count and session id.
|
|
func (f *fakeChat) permissionQuery() (int, string) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.permissionCalls, f.permissionSessionID
|
|
}
|
|
|
|
// Sessions returns the seeded session list and counts each call so a test can
|
|
// assert the list handler asks the broker at most once per request.
|
|
func (f *fakeChat) Sessions(context.Context) ([]protocol.ChatSession, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.sessionCalls++
|
|
return f.sessions, f.sessionErr
|
|
}
|
|
|
|
// sessionQuery reports the recorded chat_sessions call count.
|
|
func (f *fakeChat) sessionQuery() int {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.sessionCalls
|
|
}
|
|
|
|
// Create records the title and directory the handler forwarded and returns the
|
|
// seeded created session. A blank created id defaults to "ses_created" so a test
|
|
// only asserts what it cares about.
|
|
func (f *fakeChat) ActivateSkill(_ context.Context, sessionID, skill string) error {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.activateCalls++
|
|
f.activateSessionID, f.activateSkill = sessionID, skill
|
|
return f.activateErr
|
|
}
|
|
|
|
func (f *fakeChat) Create(_ context.Context, title, directory string) (protocol.ChatSession, error) {
|
|
f.mu.Lock()
|
|
f.createCalls++
|
|
f.createTitle = title
|
|
f.createDirectory = directory
|
|
gate, started := f.createGate, f.createStarted
|
|
f.mu.Unlock()
|
|
if started != nil {
|
|
f.createOnce.Do(func() { close(started) })
|
|
}
|
|
if gate != nil {
|
|
<-gate
|
|
}
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
if f.createErr != nil {
|
|
return protocol.ChatSession{}, f.createErr
|
|
}
|
|
session := f.created
|
|
if session.ID == "" {
|
|
session.ID = "ses_created"
|
|
}
|
|
return session, nil
|
|
}
|
|
|
|
// createQuery reports the recorded chat_create call count, title and directory.
|
|
func (f *fakeChat) createQuery() (int, string, string) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.createCalls, f.createTitle, f.createDirectory
|
|
}
|
|
|
|
// Session returns the seeded endpoint record of one session (or "not found")
|
|
// and counts each call, so the adopt handler can be asserted to read the
|
|
// endpoint exactly once and never invent a directory.
|
|
func (f *fakeChat) Session(_ context.Context, sessionID string) (protocol.ChatSession, bool, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.sessionByIDCalls++
|
|
f.sessionByID = sessionID
|
|
if f.sessionByIDErr != nil {
|
|
return protocol.ChatSession{}, false, f.sessionByIDErr
|
|
}
|
|
if !f.sessionFound {
|
|
return protocol.ChatSession{}, false, nil
|
|
}
|
|
session := f.sessionRecord
|
|
if session.ID == "" {
|
|
session.ID = sessionID
|
|
}
|
|
return session, true, nil
|
|
}
|
|
|
|
// sessionByIDQuery reports the recorded chat_adopt read count and last id.
|
|
func (f *fakeChat) sessionByIDQuery() (int, string) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.sessionByIDCalls, f.sessionByID
|
|
}
|
|
|
|
// replyQuery reports the recorded chat_reply count and the last forwarded
|
|
// request, so a test can assert the exact session/request/decision.
|
|
func (f *fakeChat) replyQuery() (int, protocol.ChatReplyRequest) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.replies, f.replyRequest
|
|
}
|
|
|
|
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: protocol.ChatDeltaPartID("msg_1", protocol.ChatPartText, 0)}, nil),
|
|
chatFrame(protocol.ChatEventText, "world", &protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID("msg_1", protocol.ChatPartText, 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()
|
|
return dialChatOptions(t, Options{Chat: broker})
|
|
}
|
|
|
|
func dialChatOptions(t *testing.T, options Options) (context.Context, context.CancelFunc, *websocket.Conn) {
|
|
t.Helper()
|
|
ctx, cancel, conns := dialChatConns(t, options, 1)
|
|
return ctx, cancel, conns[0]
|
|
}
|
|
|
|
// dialChatConns starts one server and dials n connections to the same hub, so a
|
|
// test can exercise two clients contending for one session.
|
|
func dialChatConns(t *testing.T, options Options, n int) (context.Context, context.CancelFunc, []*websocket.Conn) {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
srv := httptest.NewServer(HandlerWithOptions(ctx, options))
|
|
t.Cleanup(func() { srv.Close(); cancel() })
|
|
conns := make([]*websocket.Conn, 0, n)
|
|
for i := 0; i < n; i++ {
|
|
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { conn.CloseNow() })
|
|
conns = append(conns, conn)
|
|
}
|
|
return ctx, cancel, conns
|
|
}
|
|
|
|
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()
|
|
broker.messages = seededChatMessages()
|
|
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" || response.ChatHistory == nil {
|
|
t.Fatalf("resume response = %+v", response)
|
|
}
|
|
if calls, _, _ := broker.messageQuery(); calls != 1 {
|
|
t.Fatalf("authoritative history was not read: %d calls", calls)
|
|
}
|
|
assertSeededChatMessages(t, response.ChatMessages)
|
|
}
|
|
|
|
// 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_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}}
|
|
]},
|
|
{"id":"msg_user","time":{"created":10},"type":"user","text":"list the files"}
|
|
],"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/permission/request":
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[]}`))
|
|
case r.Method == http.MethodGet && r.URL.Path == "/api/shell":
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"data":[]}`))
|
|
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])
|
|
}
|
|
}
|
|
|
|
// OpenCode history exposes native message ids but no prompt operation id. The
|
|
// broker must therefore leave partial, reordered, older and overlapping pages
|
|
// untouched rather than inventing a positional identity mapping.
|
|
func TestChatHubHistoryDoesNotInventOperationIdentity(t *testing.T) {
|
|
hub := newChatHub()
|
|
page := []protocol.ChatMessage{
|
|
{ID: "history-y", Role: protocol.ChatRoleUser, OperationID: "provider-value"},
|
|
{ID: "history-x", Role: protocol.ChatRoleUser},
|
|
}
|
|
got := hub.reconcileHistory("ses_1", page)
|
|
if len(got) != len(page) || got[0].ID != "history-y" || got[0].OperationID != "provider-value" || got[1].OperationID != "" {
|
|
t.Fatalf("history changed without a canonical provider mapping: %+v", got)
|
|
}
|
|
}
|
|
|
|
func TestChatHubHistoryMapsOnlyCanonicalNativeIdentity(t *testing.T) {
|
|
hub := newChatHub()
|
|
hub.apply(protocol.ChatEventFrame{
|
|
SessionID: "ses_1", MessageID: "msg_x", Kind: protocol.ChatEventUser,
|
|
Client: "Phone", OperationID: "op_x",
|
|
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: "same"},
|
|
})
|
|
hub.apply(protocol.ChatEventFrame{
|
|
SessionID: "ses_1", MessageID: "msg_y", Kind: protocol.ChatEventUser,
|
|
Client: "Laptop", OperationID: "op_y",
|
|
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: "same"},
|
|
})
|
|
got := hub.reconcileHistory("ses_1", []protocol.ChatMessage{
|
|
{ID: "msg_y", Role: protocol.ChatRoleUser},
|
|
{ID: "unrelated", Role: protocol.ChatRoleUser, Parts: []protocol.ChatPart{{Text: "same"}}},
|
|
{ID: "msg_x", Role: protocol.ChatRoleUser},
|
|
})
|
|
if got[0].OperationID != "op_y" || got[2].OperationID != "op_x" || got[1].OperationID != "" {
|
|
t.Fatalf("history identity mapping = %+v", got)
|
|
}
|
|
}
|
|
|
|
// TestChatMessagesReconcilesProviderPagesThroughTheHandler exercises the normal
|
|
// history path, rather than calling reconcileHistory alone. The provider fixture
|
|
// deliberately returns partial, reordered, older and overlapping pages (including
|
|
// equal timestamps); only the explicit native ids may restore operation identity.
|
|
func TestChatMessagesReconcilesProviderPagesThroughTheHandler(t *testing.T) {
|
|
hub := newChatHub()
|
|
for _, turn := range []struct {
|
|
id, operation, client string
|
|
}{
|
|
{"msg_x", "op_x", "Phone"},
|
|
{"msg_y", "op_y", "Computer"},
|
|
} {
|
|
hub.apply(protocol.ChatEventFrame{
|
|
SessionID: "ses_1", MessageID: turn.id, Kind: protocol.ChatEventUser,
|
|
OperationID: turn.operation, Client: turn.client,
|
|
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: turn.operation},
|
|
})
|
|
}
|
|
|
|
pages := []struct {
|
|
name string
|
|
messages []protocol.ChatMessage
|
|
}{
|
|
{"partial-reordered", []protocol.ChatMessage{
|
|
{ID: "msg_y", Role: protocol.ChatRoleUser, CreatedAt: 10},
|
|
{ID: "msg_x", Role: protocol.ChatRoleUser, CreatedAt: 10},
|
|
}},
|
|
{"older", []protocol.ChatMessage{
|
|
{ID: "msg_x", Role: protocol.ChatRoleUser, CreatedAt: 10},
|
|
}},
|
|
{"overlap-reconnect", []protocol.ChatMessage{
|
|
{ID: "msg_y", Role: protocol.ChatRoleUser, CreatedAt: 10},
|
|
{ID: "unrelated", Role: protocol.ChatRoleUser, CreatedAt: 10},
|
|
}},
|
|
}
|
|
for _, page := range pages {
|
|
broker := scriptedChat()
|
|
broker.messages = page.messages
|
|
var response protocol.Message
|
|
handleChatMessages(context.Background(), protocol.Message{
|
|
Type: protocol.ChatMessages, ID: page.name,
|
|
ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"},
|
|
}, broker, hub, func(message protocol.Message) error {
|
|
response = message
|
|
return nil
|
|
})
|
|
if response.Type != protocol.ChatMessages || response.ChatHistory == nil {
|
|
t.Fatalf("%s response = %+v", page.name, response)
|
|
}
|
|
for _, message := range response.ChatHistory.Messages {
|
|
want := map[string]string{"msg_x": "op_x", "msg_y": "op_y"}[message.ID]
|
|
if want != "" && message.OperationID != want {
|
|
t.Fatalf("%s message %q operation = %q, want %q", page.name, message.ID, message.OperationID, want)
|
|
}
|
|
if message.ID == "unrelated" && message.OperationID != "" {
|
|
t.Fatalf("%s invented identity for unrelated message: %+v", page.name, message)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|
|
|
|
// TestChatHubRetainsToolNameAndInputAcrossLifecycle pins that a tool call keeps
|
|
// its name and its input for its whole lifecycle in the retained state a resume
|
|
// serves: the name arrives only in input.started, the arguments in input.ended's
|
|
// text or called's input, and then progress/success carry neither, so no later
|
|
// frame may blank a field the hub already learned.
|
|
func TestChatHubRetainsToolNameAndInputAcrossLifecycle(t *testing.T) {
|
|
hub := newChatHub()
|
|
apply := func(part *protocol.ChatPart) {
|
|
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventTool, Part: part})
|
|
}
|
|
// input.started: the name, no arguments yet.
|
|
apply(&protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", Name: "shell", State: &protocol.ChatToolState{Status: protocol.ChatToolStreaming}})
|
|
// input.ended/called: the arguments, no name.
|
|
apply(&protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", State: &protocol.ChatToolState{Status: protocol.ChatToolRunning, Input: json.RawMessage(`{"command":"ls"}`)}})
|
|
// progress: metadata only.
|
|
apply(&protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", State: &protocol.ChatToolState{Status: protocol.ChatToolRunning, Metadata: map[string]any{"exit": 0}}})
|
|
// success: the output, no name and no input.
|
|
apply(&protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", State: &protocol.ChatToolState{Status: protocol.ChatToolCompleted, Content: []protocol.ChatToolContent{{Type: "text", Text: "ok"}}}})
|
|
|
|
messages := hub.snapshot("ses_1")
|
|
if len(messages) != 1 || len(messages[0].Parts) != 1 {
|
|
t.Fatalf("snapshot = %+v", messages)
|
|
}
|
|
part := messages[0].Parts[0]
|
|
if part.Name != "shell" {
|
|
t.Fatalf("tool name was blanked by a later frame: %+v", part)
|
|
}
|
|
if part.State == nil || part.State.Status != protocol.ChatToolCompleted {
|
|
t.Fatalf("tool state = %+v", part.State)
|
|
}
|
|
var input struct {
|
|
Command string `json:"command"`
|
|
}
|
|
if err := json.Unmarshal(part.State.Input, &input); err != nil || input.Command != "ls" {
|
|
t.Fatalf("tool input was blanked by a later frame: %s (err %v)", part.State.Input, err)
|
|
}
|
|
if len(part.State.Content) != 1 || part.State.Content[0].Text != "ok" {
|
|
t.Fatalf("tool content = %+v", part.State.Content)
|
|
}
|
|
if part.State.Metadata["exit"] == nil {
|
|
t.Fatalf("tool metadata was blanked by a later frame: %+v", part.State.Metadata)
|
|
}
|
|
}
|
|
|
|
// TestChatHubRetainsShellOutlivingTurn pins the background-process state: a shell
|
|
// the agent started survives the turn that started it, so a client re-syncing the
|
|
// session still sees the process running, and its exit clears it. An exit for a
|
|
// shell the session never retained (another session's) clears nothing.
|
|
func TestChatHubRetainsShellOutlivingTurn(t *testing.T) {
|
|
hub := newChatHub()
|
|
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventShell, Shell: &protocol.ChatShell{ID: "sh_1", Status: protocol.ChatShellRunning, Command: "npm run dev"}})
|
|
// The turn that started the shell finishes while the shell keeps running.
|
|
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}})
|
|
shells := hub.shellSnapshot("ses_1")
|
|
if len(shells) != 1 || shells[0].ID != "sh_1" || shells[0].Command != "npm run dev" || shells[0].Status != protocol.ChatShellRunning {
|
|
t.Fatalf("running shell not retained past the turn: %+v", shells)
|
|
}
|
|
// An exit for a shell this session never started is not this session's.
|
|
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventShell, Shell: &protocol.ChatShell{ID: "sh_other", Status: protocol.ChatShellExited}})
|
|
if shells := hub.shellSnapshot("ses_1"); len(shells) != 1 {
|
|
t.Fatalf("foreign exit cleared the running shell: %+v", shells)
|
|
}
|
|
exit := 0
|
|
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventShell, Shell: &protocol.ChatShell{ID: "sh_1", Status: protocol.ChatShellExited, Exit: &exit}})
|
|
if shells := hub.shellSnapshot("ses_1"); shells != nil {
|
|
t.Fatalf("exited shell still retained: %+v", shells)
|
|
}
|
|
}
|
|
|
|
// TestChatPromptStreamsShellFrame pins that a shell frame reaches the watching
|
|
// client like every other frame kind, carrying its payload and no message id.
|
|
func TestChatPromptStreamsShellFrame(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.script = append([]protocol.ChatEventFrame{
|
|
{SessionID: "ses_1", Kind: protocol.ChatEventShell, Shell: &protocol.ChatShell{ID: "sh_1", Status: protocol.ChatShellRunning, Command: "sleep 120"}},
|
|
}, broker.script...)
|
|
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)
|
|
}
|
|
frames := readChatTurn(t, ctx, conn)
|
|
if len(frames) == 0 || frames[0].Kind != protocol.ChatEventShell {
|
|
t.Fatalf("first frame = %+v, want the shell frame", frames)
|
|
}
|
|
shell := frames[0]
|
|
if shell.MessageID != "" || shell.Shell == nil || shell.Shell.ID != "sh_1" || shell.Shell.Command != "sleep 120" || shell.Shell.Status != protocol.ChatShellRunning {
|
|
t.Fatalf("shell frame = %+v", shell)
|
|
}
|
|
}
|
|
|
|
// TestChatSubscribeReplaysRunningShell pins the shell half of the resume: a
|
|
// client attaching to a session's stream after a shell started is replayed the
|
|
// still-running shell, so a reconnect (or a chat opened from another device)
|
|
// shows the background process instead of nothing until it exits.
|
|
func TestChatSubscribeReplaysRunningShell(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.shells = []protocol.ChatShell{{ID: "sh_1", Status: protocol.ChatShellRunning, Command: "sleep 120"}}
|
|
broker.script = append([]protocol.ChatEventFrame{
|
|
{SessionID: "ses_1", Kind: protocol.ChatEventShell, Shell: &protocol.ChatShell{ID: "sh_1", Status: protocol.ChatShellRunning, Command: "sleep 120"}},
|
|
}, broker.script...)
|
|
ctx, _, conns := dialChatConns(t, Options{Chat: broker}, 2)
|
|
if err := wsjson.Write(ctx, conns[0], 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, conns[0], &ack); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
frames := readChatTurn(t, ctx, conns[0])
|
|
sawShell := false
|
|
for _, frame := range frames {
|
|
if frame.Kind == protocol.ChatEventShell && frame.Shell != nil && frame.Shell.ID == "sh_1" {
|
|
sawShell = true
|
|
}
|
|
}
|
|
if !sawShell {
|
|
t.Fatalf("shell frame not fanned out: %+v", frames)
|
|
}
|
|
// The second client attaches only now; the running shell must be replayed.
|
|
if err := wsjson.Write(ctx, conns[1], protocol.Message{Type: protocol.ChatSubscribe, ID: "sub1", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var subscription protocol.Message
|
|
if err := wsjson.Read(ctx, conns[1], &subscription); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if subscription.Type != protocol.ChatSubscribe || subscription.ID != "sub1" {
|
|
t.Fatalf("subscribe ack = %+v", subscription)
|
|
}
|
|
var replayed protocol.Message
|
|
if err := wsjson.Read(ctx, conns[1], &replayed); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if replayed.Type != protocol.ChatEvent || replayed.ChatEvent == nil || replayed.ChatEvent.Kind != protocol.ChatEventShell {
|
|
t.Fatalf("replay frame = %+v", replayed)
|
|
}
|
|
if replayed.ChatEvent.Shell == nil || replayed.ChatEvent.Shell.ID != "sh_1" || replayed.ChatEvent.Shell.Status != protocol.ChatShellRunning {
|
|
t.Fatalf("replayed shell = %+v", replayed.ChatEvent.Shell)
|
|
}
|
|
}
|
|
|
|
// TestChatSubscribeKeepsStreamWhenShellReadbackFails ensures a temporary
|
|
// authoritative readback failure does not make chat unavailable or replay a
|
|
// stale process as running. The subscriber receives an explicit limitation
|
|
// while its broker stream remains attached for future lifecycle events.
|
|
func TestChatSubscribeKeepsStreamWhenShellReadbackFails(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.block = true
|
|
broker.shellErr = errors.New("shell endpoint unavailable: https://user:secret@example.invalid private response body")
|
|
ctx, _, conn := dialChat(t, broker)
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub1", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}}); 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.ChatSubscribe || ack.ID != "sub1" {
|
|
t.Fatalf("subscribe ack = %+v", ack)
|
|
}
|
|
var limited protocol.Message
|
|
if err := wsjson.Read(ctx, conn, &limited); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if limited.Type != protocol.Error || limited.Error != "background shell visibility is limited" {
|
|
t.Fatalf("limited visibility notice = %+v", limited)
|
|
}
|
|
broker.mu.Lock()
|
|
calls := broker.streamCalls
|
|
broker.mu.Unlock()
|
|
if calls != 1 {
|
|
t.Fatalf("broker Stream calls = %d, want 1", calls)
|
|
}
|
|
}
|
|
|
|
// 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/permission/request":
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[]}`))
|
|
case r.Method == http.MethodGet && r.URL.Path == "/api/shell":
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"data":[]}`))
|
|
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)
|
|
}
|
|
}
|
|
|
|
// TestChatCreateRecordsOperatorSession is the chat_create acceptance test: the
|
|
// broker creates the session in the resolved directory, the handler records it in
|
|
// the operator registry with the operator tag, and the response carries the
|
|
// created session and the registry row (directory, tag). The registry can then
|
|
// list it.
|
|
func TestChatCreateRecordsOperatorSession(t *testing.T) {
|
|
store := newOperatorStore(t)
|
|
broker := scriptedChat()
|
|
broker.created = protocol.ChatSession{ID: "ses_new", Title: "demo"}
|
|
dir := t.TempDir()
|
|
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "c1", ChatCreate: &protocol.ChatCreateRequest{Title: "demo", Directory: dir}}); 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.ChatCreate || response.ID != "c1" || response.ChatSession == nil {
|
|
t.Fatalf("chat_create response = %+v", response)
|
|
}
|
|
if response.ChatSession.ID != "ses_new" || response.ChatSession.Directory != dir || response.ChatSession.Tag != protocol.ChatSessionTagOperator {
|
|
t.Fatalf("created session = %+v", response.ChatSession)
|
|
}
|
|
if len(response.ChatSessions) != 1 || response.ChatSessions[0].ID != "ses_new" || response.ChatSessions[0].Tag != protocol.ChatSessionTagOperator {
|
|
t.Fatalf("created session not echoed as a registry row: %+v", response.ChatSessions)
|
|
}
|
|
if calls, title, directory := broker.createQuery(); calls != 1 || title != "demo" || directory != dir {
|
|
t.Fatalf("broker.Create = %d/%q/%q, want 1/demo/%q", calls, title, directory, dir)
|
|
}
|
|
broker.mu.Lock()
|
|
activateCalls, activateSession, activateSkill := broker.activateCalls, broker.activateSessionID, broker.activateSkill
|
|
broker.mu.Unlock()
|
|
if activateCalls != 1 || activateSession != "ses_new" || activateSkill != "pipelines-manager" {
|
|
t.Fatalf("manager bootstrap = %d/%q/%q", activateCalls, activateSession, activateSkill)
|
|
}
|
|
recorded, err := store.OperatorSessions(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(recorded) != 1 || recorded[0].ID != "ses_new" || recorded[0].Directory != dir || recorded[0].Tag != protocol.ChatSessionTagOperator || recorded[0].Title != "demo" {
|
|
t.Fatalf("registry row = %+v", recorded)
|
|
}
|
|
}
|
|
|
|
func TestChatCreateReportsManagerBootstrapFailure(t *testing.T) {
|
|
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}, activateErr: errors.New("skill not found")}
|
|
store := newOperatorStore(t)
|
|
request := protocol.Message{ID: "create", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{}}
|
|
var response protocol.Message
|
|
handleChatCreate(context.Background(), request, broker, store, func(message protocol.Message) error {
|
|
response = message
|
|
return nil
|
|
})
|
|
if response.Type != protocol.Error || !strings.Contains(response.Error, "manager bootstrap failed") || !strings.Contains(response.Error, "skill not found") {
|
|
t.Fatalf("response = %#v", response)
|
|
}
|
|
if _, err := store.OperatorSessions(context.Background()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func TestChatCreateRetryReusesDurableBootstrap(t *testing.T) {
|
|
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_once"}}
|
|
store := newOperatorStore(t)
|
|
request := protocol.Message{ID: "create-once", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Title: "demo", OperationID: "operation-once"}}
|
|
for i := 0; i < 2; i++ {
|
|
var response protocol.Message
|
|
handleChatCreate(context.Background(), request, broker, store, func(message protocol.Message) error { response = message; return nil })
|
|
if response.Type != protocol.ChatCreate || response.ChatSession == nil || response.ChatSession.ID != "ses_once" {
|
|
t.Fatalf("retry %d response = %#v", i, response)
|
|
}
|
|
}
|
|
broker.mu.Lock()
|
|
creates, activations := broker.createCalls, broker.activateCalls
|
|
broker.mu.Unlock()
|
|
if creates != 1 || activations != 1 {
|
|
t.Fatalf("retry repeated external work: creates=%d activations=%d", creates, activations)
|
|
}
|
|
}
|
|
|
|
// TestChatCreateOperationSurvivesLostResponseAndStoreReopen verifies that the
|
|
// durable create identity, rather than the connection-local reply ID, resumes a
|
|
// completed create after a client lost its reply and the server reopened its DB.
|
|
func TestChatCreateOperationSurvivesLostResponseAndStoreReopen(t *testing.T) {
|
|
ctx := context.Background()
|
|
path := filepath.Join(t.TempDir(), "operator.db")
|
|
store, err := pipeline.Open(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_once"}}
|
|
handleChatCreate(ctx, protocol.Message{
|
|
ID: "cli-1", Type: protocol.ChatCreate,
|
|
ChatCreate: &protocol.ChatCreateRequest{Title: "demo", OperationID: "operation-once"},
|
|
}, broker, store, func(protocol.Message) error {
|
|
return nil // Simulate a reply lost after all durable checkpoints completed.
|
|
})
|
|
if err := store.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reopened, err := pipeline.Open(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer reopened.Close()
|
|
|
|
var response protocol.Message
|
|
handleChatCreate(ctx, protocol.Message{
|
|
ID: "cli-2", Type: protocol.ChatCreate,
|
|
ChatCreate: &protocol.ChatCreateRequest{Title: "demo", OperationID: "operation-once"},
|
|
}, broker, reopened, func(message protocol.Message) error {
|
|
response = message
|
|
return nil
|
|
})
|
|
if response.Type != protocol.ChatCreate || response.ID != "cli-2" || response.ChatSession == nil || response.ChatSession.ID != "ses_once" {
|
|
t.Fatalf("reopened retry response = %#v", response)
|
|
}
|
|
broker.mu.Lock()
|
|
creates, activations := broker.createCalls, broker.activateCalls
|
|
broker.mu.Unlock()
|
|
if creates != 1 || activations != 1 {
|
|
t.Fatalf("reopened retry repeated external work: creates=%d activations=%d", creates, activations)
|
|
}
|
|
}
|
|
|
|
// TestChatCreateDuplicateRequestReservesExternalWork proves the conditional
|
|
// durable transition, rather than timing or the race detector, elects exactly
|
|
// one request to call the external Create and ActivateSkill operations.
|
|
func TestChatCreateDuplicateRequestReservesExternalWork(t *testing.T) {
|
|
store := newOperatorStore(t)
|
|
createGate := make(chan struct{})
|
|
broker := &fakeChat{
|
|
created: protocol.ChatSession{ID: "ses_once"},
|
|
createGate: createGate,
|
|
createStarted: make(chan struct{}),
|
|
}
|
|
request := protocol.Message{ID: "same-request", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Title: "demo", OperationID: "operation-once"}}
|
|
responses := make(chan protocol.Message, 2)
|
|
run := func() {
|
|
handleChatCreate(context.Background(), request, broker, store, func(message protocol.Message) error {
|
|
responses <- message
|
|
return nil
|
|
})
|
|
}
|
|
go run()
|
|
select {
|
|
case <-broker.createStarted:
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("first request did not reserve Create")
|
|
}
|
|
go run()
|
|
select {
|
|
case response := <-responses:
|
|
if response.Type != protocol.Error || !strings.Contains(response.Error, "unfinished manager bootstrap") {
|
|
t.Fatalf("losing request response = %+v", response)
|
|
}
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("duplicate request did not finish at its durable reservation")
|
|
}
|
|
close(createGate)
|
|
select {
|
|
case response := <-responses:
|
|
if response.Type != protocol.ChatCreate || response.ChatSession == nil || response.ChatSession.ID != "ses_once" {
|
|
t.Fatalf("winning request response = %+v", response)
|
|
}
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("winning request did not finish")
|
|
}
|
|
broker.mu.Lock()
|
|
creates, activations := broker.createCalls, broker.activateCalls
|
|
broker.mu.Unlock()
|
|
if creates != 1 || activations != 1 {
|
|
t.Fatalf("duplicate request repeated external work: creates=%d activations=%d", creates, activations)
|
|
}
|
|
}
|
|
|
|
func TestChatCreateLegacyRequestWithoutOperationIDUsesFreshScope(t *testing.T) {
|
|
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}}
|
|
store := newOperatorStore(t)
|
|
for _, request := range []protocol.Message{
|
|
{ID: "cli-1", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Title: "first"}},
|
|
{ID: "cli-1", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Title: "second"}},
|
|
} {
|
|
var response protocol.Message
|
|
handleChatCreate(context.Background(), request, broker, store, func(message protocol.Message) error {
|
|
response = message
|
|
return nil
|
|
})
|
|
if response.Type != protocol.ChatCreate || response.ChatSession == nil {
|
|
t.Fatalf("legacy chat_create response = %+v", response)
|
|
}
|
|
}
|
|
broker.mu.Lock()
|
|
creates := broker.createCalls
|
|
broker.mu.Unlock()
|
|
if creates != 2 {
|
|
t.Fatalf("legacy creates = %d, want 2", creates)
|
|
}
|
|
}
|
|
|
|
func TestChatCreateOperationIDRejectsChangedInputBeforeExternalWork(t *testing.T) {
|
|
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}}
|
|
store := newOperatorStore(t)
|
|
first := protocol.Message{ID: "cli-1", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Title: "first", OperationID: "operation"}}
|
|
handleChatCreate(context.Background(), first, broker, store, func(protocol.Message) error { return nil })
|
|
var response protocol.Message
|
|
handleChatCreate(context.Background(), protocol.Message{ID: "cli-1", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Title: "second", OperationID: "operation"}}, broker, store, func(message protocol.Message) error {
|
|
response = message
|
|
return nil
|
|
})
|
|
if response.Type != protocol.Error || !strings.Contains(response.Error, "operation id was reused with different input") {
|
|
t.Fatalf("changed operation response = %+v", response)
|
|
}
|
|
broker.mu.Lock()
|
|
creates, activations := broker.createCalls, broker.activateCalls
|
|
broker.mu.Unlock()
|
|
if creates != 1 || activations != 1 {
|
|
t.Fatalf("changed operation repeated external work: creates=%d activations=%d", creates, activations)
|
|
}
|
|
}
|
|
|
|
func TestChatSessionsAllowsEmptyRequestID(t *testing.T) {
|
|
store := newOperatorStore(t)
|
|
if err := store.RecordOperatorSession(context.Background(), "ses_existing", "/work", "Existing", protocol.ChatSessionTagOperator); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
broker := &fakeChat{sessions: []protocol.ChatSession{{ID: "ses_existing"}}}
|
|
var response protocol.Message
|
|
handleChatSessions(context.Background(), protocol.Message{Type: protocol.ChatSessions}, broker, nil, store, func(message protocol.Message) error {
|
|
response = message
|
|
return nil
|
|
})
|
|
if response.Type != protocol.ChatSessions || len(response.ChatSessions) != 1 || response.ChatSessions[0].ID != "ses_existing" {
|
|
t.Fatalf("empty-ID chat_sessions response = %+v", response)
|
|
}
|
|
}
|
|
|
|
// TestChatCreateDirectoryResolution pins directory defaulting and rejection: an
|
|
// omitted/empty/"~"/"~/..." directory resolves to the operator's home (never the
|
|
// server's working directory), an explicit existing directory is recorded
|
|
// unchanged, and a relative or missing directory is rejected before any OpenCode
|
|
// call.
|
|
func TestChatCreateDirectoryResolution(t *testing.T) {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
explicit := t.TempDir()
|
|
cases := []struct {
|
|
name string
|
|
omitted bool
|
|
directory string
|
|
wantDirectory string
|
|
wantErr string
|
|
}{
|
|
{name: "omitted", omitted: true, wantDirectory: home},
|
|
{name: "empty", directory: "", wantDirectory: home},
|
|
{name: "tilde", directory: "~", wantDirectory: home},
|
|
{name: "tilde path", directory: "~/project", wantDirectory: home},
|
|
{name: "explicit", directory: explicit, wantDirectory: explicit},
|
|
{name: "relative", directory: "relative/dir", wantErr: "absolute"},
|
|
{name: "missing", directory: filepath.Join(t.TempDir(), "missing"), wantErr: "not available"},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
store := newOperatorStore(t)
|
|
broker := scriptedChat()
|
|
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
|
request := protocol.Message{Type: protocol.ChatCreate, ID: "c1"}
|
|
if !tc.omitted {
|
|
request.ChatCreate = &protocol.ChatCreateRequest{Title: "demo", Directory: tc.directory}
|
|
}
|
|
if err := wsjson.Write(ctx, conn, request); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var response protocol.Message
|
|
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if tc.wantErr != "" {
|
|
if response.Type != protocol.Error || !strings.Contains(response.Error, tc.wantErr) {
|
|
t.Fatalf("directory %q not rejected: %+v", tc.directory, response)
|
|
}
|
|
if calls, _, _ := broker.createQuery(); calls != 0 {
|
|
t.Fatalf("rejected directory still reached OpenCode: %d calls", calls)
|
|
}
|
|
if recorded, err := store.OperatorSessions(ctx); err != nil || len(recorded) != 0 {
|
|
t.Fatalf("rejected directory recorded a session: %+v %v", recorded, err)
|
|
}
|
|
return
|
|
}
|
|
if response.Type != protocol.ChatCreate || response.ChatSession == nil || response.ChatSession.Directory != tc.wantDirectory {
|
|
t.Fatalf("directory %q resolved wrong: %+v", tc.directory, response)
|
|
}
|
|
if calls, _, directory := broker.createQuery(); calls != 1 || directory != tc.wantDirectory {
|
|
t.Fatalf("broker.Create = %d/%q, want 1/%q", calls, directory, tc.wantDirectory)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestChatDirectoriesHomeThenBoundedRecents pins chat_directories: the operator's
|
|
// home first, then the directories of previous operator sessions
|
|
// most-recently-used first, deduplicated and capped at the fixed bound even with
|
|
// more directory history seeded than the cap.
|
|
func TestChatDirectoriesHomeThenBoundedRecents(t *testing.T) {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
store := newOperatorStore(t)
|
|
ctx, _, conn := dialChatOptions(t, Options{OperatorRegistry: store})
|
|
// Seed more directories than the bound, oldest first.
|
|
seeded := make([]string, 0, operatorDirectoryLimit+4)
|
|
for i := 0; i < operatorDirectoryLimit+4; i++ {
|
|
directory := filepath.Join(t.TempDir(), fmt.Sprintf("d%02d", i))
|
|
seeded = append(seeded, directory)
|
|
if err := store.RecordOperatorSession(ctx, fmt.Sprintf("ses_%02d", i), directory, "s", protocol.ChatSessionTagOperator); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
time.Sleep(2 * time.Millisecond)
|
|
}
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatDirectories, ID: "d1"}); 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.ChatDirectories || response.ID != "d1" {
|
|
t.Fatalf("chat_directories response = %+v", response)
|
|
}
|
|
if len(response.ChatDirectories) != operatorDirectoryLimit {
|
|
t.Fatalf("directories = %+v, want the bound of %d", response.ChatDirectories, operatorDirectoryLimit)
|
|
}
|
|
if response.ChatDirectories[0] != home {
|
|
t.Fatalf("home not first: %+v", response.ChatDirectories)
|
|
}
|
|
// The remainder are the most recently recorded directories, MRU first.
|
|
for i := 1; i < len(response.ChatDirectories); i++ {
|
|
want := seeded[len(seeded)-i]
|
|
if response.ChatDirectories[i] != want {
|
|
t.Fatalf("directory %d = %q, want %q (MRU order): %+v", i, response.ChatDirectories[i], want, response.ChatDirectories)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestChatSessionsListsOperatorSessionsOnly is the task evidence for the
|
|
// operator-session filter: the broker lists an operator-registered session, a
|
|
// genuine pipeline stage session recorded in run_steps/run_session_owners, and a
|
|
// foreign session; chat_sessions returns exactly the operator session, carrying
|
|
// its registry directory and operator tag, and asks the broker once. The stage
|
|
// session is proven to be genuinely recorded through store.OwnedSessions.
|
|
func TestChatSessionsListsOperatorSessionsOnly(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newOperatorStore(t)
|
|
if err := store.RecordOperatorSession(ctx, "ses_op", "/work/op", "Operator chat", protocol.ChatSessionTagOperator); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := store.Submit(ctx, "chatsrv", pipeline.Template([]string{"one"}, true)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
items, err := store.List(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
definition, err := store.Get(ctx, items[0].ID, 1)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
run, _, err := store.CreateRun(ctx, definition, "stage-run", "/work/stage", false, nil, map[string]any{"prompt": "task"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := store.BeginStep(ctx, run, 1, "one", map[string]any{"prompt": "task"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := store.RunSession(ctx, run, 1, "ses_stage", true, "v2", "/work/stage"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// Prove ses_stage is a real owned pipeline session, so its exclusion is the
|
|
// operator filter at work, not an unrecorded id.
|
|
owned, err := store.OwnedSessions(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sawStage := false
|
|
for _, owner := range owned {
|
|
if owner.ID == "ses_stage" {
|
|
sawStage = true
|
|
}
|
|
if owner.ID == "ses_op" {
|
|
t.Fatalf("operator session leaked into pipeline ownership: %+v", owner)
|
|
}
|
|
}
|
|
if !sawStage {
|
|
t.Fatalf("stage session was not recorded in run_steps: %+v", owned)
|
|
}
|
|
|
|
broker := scriptedChat()
|
|
broker.sessions = []protocol.ChatSession{
|
|
{ID: "ses_op", Title: "upstream", Directory: "/upstream"},
|
|
{ID: "ses_stage", Title: "pipeline internal", Directory: "/work/stage"},
|
|
{ID: "ses_foreign", Title: "someone else's", Directory: "/elsewhere"},
|
|
}
|
|
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); 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.ChatSessions || response.ID != "s1" {
|
|
t.Fatalf("chat_sessions response = %+v", response)
|
|
}
|
|
if len(response.ChatSessions) != 1 || response.ChatSessions[0].ID != "ses_op" {
|
|
t.Fatalf("non-operator session leaked into the list: %+v", response.ChatSessions)
|
|
}
|
|
got := response.ChatSessions[0]
|
|
if got.Directory != "/work/op" || got.Tag != protocol.ChatSessionTagOperator {
|
|
t.Fatalf("operator session shape = %+v", got)
|
|
}
|
|
if got.Busy {
|
|
t.Fatalf("inactive operator session marked busy: %+v", got)
|
|
}
|
|
if calls := broker.sessionQuery(); calls != 1 {
|
|
t.Fatalf("broker.Sessions called %d times, want 1", calls)
|
|
}
|
|
}
|
|
|
|
// TestChatSessionsNeverListsUntagged pins that a row with no recorded tag is not
|
|
// an operator session and is never listed, even when the broker still reports it.
|
|
func TestChatSessionsNeverListsUntagged(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newOperatorStore(t)
|
|
if err := store.RecordOperatorSession(ctx, "ses_untagged", "/work/untagged", "no tag", ""); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
broker := scriptedChat()
|
|
broker.sessions = []protocol.ChatSession{{ID: "ses_untagged"}}
|
|
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); 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.ChatSessions || len(response.ChatSessions) != 0 {
|
|
t.Fatalf("untagged session was listed: %+v", response)
|
|
}
|
|
}
|
|
|
|
// TestChatSessionsMostRecentlyUsedFirst pins the list order: sessions come back
|
|
// most-recently-used first by registry recency (later creation wins), with the
|
|
// directory and tag from the registry.
|
|
func TestChatSessionsMostRecentlyUsedFirst(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newOperatorStore(t)
|
|
if err := store.RecordOperatorSession(ctx, "ses_old", "/work/old", "old", protocol.ChatSessionTagOperator); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
time.Sleep(3 * time.Millisecond)
|
|
if err := store.RecordOperatorSession(ctx, "ses_new", "/work/new", "new", protocol.ChatSessionTagOperator); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
broker := scriptedChat()
|
|
// The broker lists them oldest-updated-first, so the handler's registry order
|
|
// is what decides the result.
|
|
broker.sessions = []protocol.ChatSession{
|
|
{ID: "ses_old", UpdatedAt: 100},
|
|
{ID: "ses_new", UpdatedAt: 50},
|
|
}
|
|
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var response protocol.Message
|
|
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(response.ChatSessions) != 2 {
|
|
t.Fatalf("chat_sessions = %+v, want 2", response.ChatSessions)
|
|
}
|
|
if response.ChatSessions[0].ID != "ses_new" || response.ChatSessions[1].ID != "ses_old" {
|
|
t.Fatalf("not most-recently-used first: %+v", response.ChatSessions)
|
|
}
|
|
if response.ChatSessions[0].Directory != "/work/new" || response.ChatSessions[0].Tag != protocol.ChatSessionTagOperator {
|
|
t.Fatalf("registry fields not applied: %+v", response.ChatSessions[0])
|
|
}
|
|
}
|
|
|
|
// TestChatSessionsFailsClosedWithoutOwnership pins the default when no operator
|
|
// registry (store or injection) is available: chat_sessions returns an empty list
|
|
// without consulting the broker, never the full OpenCode machine.
|
|
func TestChatSessionsFailsClosedWithoutOwnership(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.sessions = []protocol.ChatSession{{ID: "ses_1"}, {ID: "ses_2"}}
|
|
ctx, _, conn := dialChat(t, broker)
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); 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.ChatSessions || len(response.ChatSessions) != 0 {
|
|
t.Fatalf("unregistered sessions were exposed: %+v", response)
|
|
}
|
|
if calls := broker.sessionQuery(); calls != 0 {
|
|
t.Fatalf("fail-closed list consulted the broker %d times, want 0", calls)
|
|
}
|
|
}
|
|
|
|
// TestChatPromptPushesPermissionAndForwardsReply is the task evidence: with a
|
|
// blocking scripted stream keeping the subscription open, a seeded pending
|
|
// approval request is pushed as a chat_permission frame carrying the seeded
|
|
// session/request id after the prompt ack, and a chat_reply with Decision "once"
|
|
// is forwarded to the broker with the matching SessionID/RequestID/Decision.
|
|
//
|
|
// The live end-to-end approval flow against the real OpenCode service is NOT
|
|
// tested: this broker is the same interface seam the production handler uses, and
|
|
// the adapter's exact reply path/body are covered by the opencode package tests
|
|
// over an httptest fixture.
|
|
func TestChatPromptPushesPermissionAndForwardsReply(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.block = true
|
|
broker.started = make(chan struct{})
|
|
broker.permissions = []protocol.ChatPermissionFrame{{
|
|
SessionID: "ses_1", RequestID: "req_1", Action: "bash", Resources: []string{"rm -rf /tmp"},
|
|
}}
|
|
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: "run it"}}); 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)
|
|
}
|
|
var permission protocol.Message
|
|
if err := wsjson.Read(ctx, conn, &permission); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if permission.Type == protocol.Error {
|
|
t.Fatalf("unexpected error frame: %s", permission.Error)
|
|
}
|
|
if permission.Type != protocol.ChatPermission || permission.ChatPermission == nil {
|
|
t.Fatalf("expected a chat_permission frame, got %+v", permission)
|
|
}
|
|
if permission.ChatPermission.SessionID != "ses_1" || permission.ChatPermission.RequestID != "req_1" || permission.ChatPermission.Action != "bash" {
|
|
t.Fatalf("permission frame = %+v", permission.ChatPermission)
|
|
}
|
|
|
|
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)
|
|
}
|
|
var response protocol.Message
|
|
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)
|
|
}
|
|
count, forwarded := broker.replyQuery()
|
|
if count != 1 {
|
|
t.Fatalf("reply forwarded %d times, want 1", count)
|
|
}
|
|
if forwarded.SessionID != "ses_1" || forwarded.RequestID != "req_1" || forwarded.Decision != protocol.ChatDecisionOnce {
|
|
t.Fatalf("forwarded reply = %+v", forwarded)
|
|
}
|
|
}
|
|
|
|
// TestChatPermissionDedupesRepeatedPolls pins that the poller pushes each
|
|
// pending request at most once even though it re-reads the same list, and that a
|
|
// foreign session's request is never surfaced.
|
|
func TestChatPermissionDedupesRepeatedPolls(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.permissions = []protocol.ChatPermissionFrame{
|
|
{SessionID: "ses_1", RequestID: "req_1", Action: "bash"},
|
|
{SessionID: "ses_other", RequestID: "req_x", Action: "edit"},
|
|
}
|
|
hub := newChatHub()
|
|
var mu sync.Mutex
|
|
var pushed []protocol.Message
|
|
write := func(message protocol.Message) error {
|
|
mu.Lock()
|
|
pushed = append(pushed, message)
|
|
mu.Unlock()
|
|
return nil
|
|
}
|
|
if sub := hub.attach("ses_1", "c1", "phone", broker, write); sub == nil {
|
|
t.Fatal("attach returned nil")
|
|
}
|
|
for i := 0; i < 3; i++ {
|
|
if err := hub.pollPermissionsOnce(context.Background(), broker, "ses_1"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
deadline := time.Now().Add(2 * time.Second)
|
|
for {
|
|
mu.Lock()
|
|
count := len(pushed)
|
|
mu.Unlock()
|
|
if count > 0 {
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("no permission frame was pushed")
|
|
}
|
|
time.Sleep(5 * time.Millisecond)
|
|
}
|
|
// Give a duplicate a chance to arrive before asserting there is none.
|
|
time.Sleep(50 * time.Millisecond)
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
if len(pushed) != 1 {
|
|
t.Fatalf("pushed %d permission frames, want 1: %+v", len(pushed), pushed)
|
|
}
|
|
if pushed[0].Type != protocol.ChatPermission || pushed[0].ChatPermission == nil || pushed[0].ChatPermission.RequestID != "req_1" {
|
|
t.Fatalf("pushed frame = %+v", pushed[0])
|
|
}
|
|
if calls, sessionID := broker.permissionQuery(); calls != 3 || sessionID != "ses_1" {
|
|
t.Fatalf("permission polls = %d/%q, want 3/ses_1", calls, sessionID)
|
|
}
|
|
}
|
|
|
|
// TestChatDisconnectCancelsPermissionPoller pins that the permission poller is
|
|
// canceled on disconnect (reusing the stream's context), so it cannot leak a
|
|
// goroutine after the client goes away.
|
|
func TestChatDisconnectCancelsPermissionPoller(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.block = true
|
|
broker.started = make(chan struct{})
|
|
broker.done = make(chan struct{})
|
|
broker.permBlock = true
|
|
broker.permDone = 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")
|
|
}
|
|
select {
|
|
case <-broker.permDone:
|
|
t.Fatal("permission poller returned before disconnect")
|
|
default:
|
|
}
|
|
conn.CloseNow()
|
|
select {
|
|
case <-broker.permDone:
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("permission poller was not canceled on disconnect")
|
|
}
|
|
select {
|
|
case <-broker.done:
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("chat stream was not canceled on disconnect")
|
|
}
|
|
}
|
|
|
|
// TestChatPermissionPollErrorSurfaced pins that a malformed permission list is
|
|
// reported to the client as an error frame rather than silence.
|
|
func TestChatPermissionPollErrorSurfaced(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.block = true
|
|
broker.started = make(chan struct{})
|
|
broker.permissionErr = fmt.Errorf("invalid OpenCode permission response")
|
|
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)
|
|
}
|
|
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, "permission poll") {
|
|
t.Fatalf("malformed permission list not surfaced: %+v", response)
|
|
}
|
|
}
|
|
|
|
// TestChatReplyRejectsInvalidInput pins that a missing session id, an empty
|
|
// request id and an invalid decision are rejected with a protocol.Error before
|
|
// any broker call.
|
|
func TestChatReplyRejectsInvalidInput(t *testing.T) {
|
|
broker := scriptedChat()
|
|
ctx, _, conn := dialChat(t, broker)
|
|
cases := []*protocol.ChatReplyRequest{
|
|
nil,
|
|
{SessionID: "", RequestID: "req_1", Decision: protocol.ChatDecisionOnce},
|
|
{SessionID: "not-a-session", RequestID: "req_1", Decision: protocol.ChatDecisionOnce},
|
|
{SessionID: "ses_1", RequestID: "", Decision: protocol.ChatDecisionOnce},
|
|
{SessionID: "ses_1", RequestID: "req_1", Decision: ""},
|
|
{SessionID: "ses_1", RequestID: "req_1", Decision: "maybe"},
|
|
}
|
|
for _, reply := range cases {
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatReply, ID: "bad", ChatReply: reply}); 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("reply %+v not rejected: %+v", reply, response)
|
|
}
|
|
}
|
|
if count, _ := broker.replyQuery(); count != 0 {
|
|
t.Fatalf("invalid replies reached the broker: %d", count)
|
|
}
|
|
}
|
|
|
|
// TestChatReplyWithoutBroker pins that an unconfigured server answers chat_reply
|
|
// with the existing "not configured" error.
|
|
func TestChatReplyWithoutBroker(t *testing.T) {
|
|
ctx, _, conn := dialChat(t, nil)
|
|
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)
|
|
}
|
|
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 reply not rejected: %+v", response)
|
|
}
|
|
}
|
|
|
|
// TestChatPermissionUnsupportedBackendIsQuiet pins that a backend which does not
|
|
// expose the approval surface (the documented native v1 limitation, reported as
|
|
// opencode.ErrPermissionUnsupported) stops the poller without writing a
|
|
// per-prompt error frame, so a working prompt is not misread as a failure.
|
|
func TestChatPermissionUnsupportedBackendIsQuiet(t *testing.T) {
|
|
broker := scriptedChat()
|
|
broker.block = true
|
|
broker.started = make(chan struct{})
|
|
broker.permissionErr = opencode.ErrPermissionUnsupported
|
|
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("prompt ack = %+v", ack)
|
|
}
|
|
// No error frame may follow: a read with a short deadline must time out.
|
|
readCtx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
|
defer cancel()
|
|
var unexpected protocol.Message
|
|
if err := wsjson.Read(readCtx, conn, &unexpected); err == nil {
|
|
t.Fatalf("unsupported permission surface must not write a frame, got %+v", unexpected)
|
|
}
|
|
if calls, _ := broker.permissionQuery(); calls != 1 {
|
|
t.Fatalf("permission polls = %d, want 1 (the poller must stop on the documented limitation)", calls)
|
|
}
|
|
}
|
|
|
|
// TestChatAdoptRecordsEndpointSession is the chat_adopt acceptance test: the
|
|
// endpoint's own record supplies the directory and title, the handler records
|
|
// the row with the operator tag, and the response echoes the session and its
|
|
// registry row so the client can splice it into chat_sessions without a re-list.
|
|
func TestChatAdoptRecordsEndpointSession(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newOperatorStore(t)
|
|
broker := scriptedChat()
|
|
broker.sessionFound = true
|
|
broker.sessionRecord = protocol.ChatSession{ID: "ses_existing", Title: "my own work", Directory: "/work/existing"}
|
|
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_existing"}}); 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.ChatAdopt || response.ID != "a1" || response.ChatSession == nil {
|
|
t.Fatalf("chat_adopt response = %+v", response)
|
|
}
|
|
if response.ChatSession.ID != "ses_existing" || response.ChatSession.Directory != "/work/existing" || response.ChatSession.Tag != protocol.ChatSessionTagOperator {
|
|
t.Fatalf("adopted session = %+v", response.ChatSession)
|
|
}
|
|
if len(response.ChatSessions) != 1 || response.ChatSessions[0].ID != "ses_existing" || response.ChatSessions[0].Tag != protocol.ChatSessionTagOperator {
|
|
t.Fatalf("adopted session not echoed as a registry row: %+v", response.ChatSessions)
|
|
}
|
|
if calls, id := broker.sessionByIDQuery(); calls != 1 || id != "ses_existing" {
|
|
t.Fatalf("broker.Session = %d/%q, want 1/ses_existing", calls, id)
|
|
}
|
|
recorded, err := store.OperatorSessions(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(recorded) != 1 || recorded[0].ID != "ses_existing" || recorded[0].Directory != "/work/existing" || recorded[0].Title != "my own work" || recorded[0].Tag != protocol.ChatSessionTagOperator {
|
|
t.Fatalf("registry row = %+v", recorded)
|
|
}
|
|
// chat_sessions now lists the adopted session (the endpoint still reports it),
|
|
// carrying the registry directory and operator tag.
|
|
broker.mu.Lock()
|
|
broker.sessions = []protocol.ChatSession{{ID: "ses_existing", Title: "endpoint title", Directory: "/endpoint/elsewhere"}}
|
|
broker.mu.Unlock()
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var listed protocol.Message
|
|
if err := wsjson.Read(ctx, conn, &listed); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if listed.Type != protocol.ChatSessions || len(listed.ChatSessions) != 1 || listed.ChatSessions[0].ID != "ses_existing" || listed.ChatSessions[0].Directory != "/work/existing" || listed.ChatSessions[0].Tag != protocol.ChatSessionTagOperator {
|
|
t.Fatalf("chat_sessions did not list the adopted session with its registry directory: %+v", listed.ChatSessions)
|
|
}
|
|
// chat_prompt can continue the adopted session: TouchOperatorSession updates
|
|
// the recorded row, so it moves to the front of the list.
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "p1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_existing", Text: "continue"}}); 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 != "p1" {
|
|
t.Fatalf("adopted session prompt ack = %+v", ack)
|
|
}
|
|
}
|
|
|
|
// TestChatAdoptMissingIDRecordsNothing pins that an id the endpoint does not
|
|
// report is refused naming the id and leaves the registry unchanged.
|
|
func TestChatAdoptMissingIDRecordsNothing(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newOperatorStore(t)
|
|
// Seed one unrelated operator row so the "unchanged" claim compares the
|
|
// stored rows before and after, not merely an empty registry.
|
|
if err := store.RecordOperatorSession(ctx, "ses_other", "/work/other", "other", protocol.ChatSessionTagOperator); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
before, err := store.OperatorSessions(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
broker := scriptedChat()
|
|
broker.sessionFound = false
|
|
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_missing"}}); 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, "ses_missing") {
|
|
t.Fatalf("missing id not refused naming the id: %+v", response)
|
|
}
|
|
after, err := store.OperatorSessions(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(before) != 1 || len(after) != 1 || after[0].ID != before[0].ID {
|
|
t.Fatalf("missing id changed the registry: before %+v after %+v", before, after)
|
|
}
|
|
}
|
|
|
|
// TestChatAdoptRefusesEmptyDirectory pins the no-guessing rule: an endpoint
|
|
// record with an empty directory is refused and records nothing, never falling
|
|
// back to the server's working directory or the operator home.
|
|
func TestChatAdoptRefusesEmptyDirectory(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newOperatorStore(t)
|
|
broker := scriptedChat()
|
|
broker.sessionFound = true
|
|
broker.sessionRecord = protocol.ChatSession{ID: "ses_nodir"}
|
|
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
|
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_nodir"}}); 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, "directory") {
|
|
t.Fatalf("empty directory not refused: %+v", response)
|
|
}
|
|
if recorded, err := store.OperatorSessions(ctx); err != nil || len(recorded) != 0 {
|
|
t.Fatalf("empty directory recorded a session: %+v %v", recorded, err)
|
|
}
|
|
}
|
|
|
|
// TestChatAdoptRejectsInvalidInputBeforeBroker pins that a nil payload, a blank
|
|
// or foreign-shaped id, a nil registry and a nil broker are each refused before
|
|
// any endpoint call.
|
|
func TestChatAdoptRejectsInvalidInputBeforeBroker(t *testing.T) {
|
|
ctx := context.Background()
|
|
cases := []struct {
|
|
name string
|
|
request protocol.Message
|
|
options Options
|
|
wantCall int
|
|
}{
|
|
{name: "nil payload", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1"}, options: Options{Chat: scriptedChat(), OperatorRegistry: newOperatorStore(t)}, wantCall: 0},
|
|
{name: "blank id", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: " "}}, options: Options{Chat: scriptedChat(), OperatorRegistry: newOperatorStore(t)}, wantCall: 0},
|
|
{name: "foreign id", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "not-a-session"}}, options: Options{Chat: scriptedChat(), OperatorRegistry: newOperatorStore(t)}, wantCall: 0},
|
|
{name: "nil broker", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_1"}}, options: Options{OperatorRegistry: newOperatorStore(t)}, wantCall: 0},
|
|
{name: "nil registry", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_1"}}, options: Options{Chat: scriptedChat()}, wantCall: 0},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
broker, _ := tc.options.Chat.(*fakeChat)
|
|
_, _, conn := dialChatOptions(t, tc.options)
|
|
if err := wsjson.Write(ctx, conn, protocol.Message(tc.request)); 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 {
|
|
t.Fatalf("%s not refused: %+v", tc.name, response)
|
|
}
|
|
if broker != nil {
|
|
if calls, _ := broker.sessionByIDQuery(); calls != tc.wantCall {
|
|
t.Fatalf("%s reached the endpoint %d times, want %d", tc.name, calls, tc.wantCall)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|