Files
pipelines/internal/opencode/chat_test.go
T
alan 2307d45417 Release native chat runtimes on lifecycle changes
Ensure /new and chat close stop native foreground and background work before changing registry state. Preserve transcripts while surfacing release and recovery cleanup failures instead of reporting false success, with focused adapter and server regressions.
2026-11-11 17:11:40 +00:00

945 lines
42 KiB
Go

package opencode
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"reflect"
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestNormalizeChatEvent(t *testing.T) {
prior := &ChatStreamState{LastMessageID: "msg_prev"}
cases := []struct {
name string
payload string
state *ChatStreamState
wantOK bool
wantKind string
wantMsg string
wantDelta string
wantStatus string
wantStep string
wantUsage *protocol.ChatUsage
}{
{name: "text delta", payload: `{"type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0,"delta":"hel"}}`, wantOK: true, wantKind: protocol.ChatEventText, wantMsg: "msg_1", wantDelta: "hel"},
{name: "reasoning delta", payload: `{"type":"session.reasoning.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":1,"delta":"hmm"}}`, wantOK: true, wantKind: protocol.ChatEventReasoning, wantMsg: "msg_1", wantDelta: "hmm"},
{name: "step ended", payload: `{"type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","step":2}}`, wantOK: true, wantKind: protocol.ChatEventStep, wantStep: protocol.ChatStepEnded},
{name: "tool streaming", payload: `{"type":"session.tool.input.started","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","input":"{\"command\""}}`, wantOK: true, wantKind: protocol.ChatEventTool, wantStatus: protocol.ChatToolStreaming},
{name: "tool running", payload: `{"type":"session.tool.called","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","input":{"command":"ls"}}}`, wantOK: true, wantKind: protocol.ChatEventTool, wantStatus: protocol.ChatToolRunning},
{name: "tool completed", payload: `{"type":"session.tool.success","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","content":[{"type":"text","text":"ok"}]}}`, wantOK: true, wantKind: protocol.ChatEventTool, wantStatus: protocol.ChatToolCompleted},
{name: "tool failed", payload: `{"type":"session.tool.failed","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","error":{"type":"tool","message":"boom"}}}`, wantOK: true, wantKind: protocol.ChatEventTool, wantStatus: protocol.ChatToolError},
{name: "usage", payload: `{"type":"session.usage.updated","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","tokens":{"input":12,"output":34},"cost":0.001}}`, wantOK: true, wantKind: protocol.ChatEventUsage, wantUsage: &protocol.ChatUsage{InputTokens: 12, OutputTokens: 34, Cost: 0.001, Scope: "session", CostUSD: usageFloat(.001), Account: &protocol.ChatAccountUsage{Harness: "OpenCode", Unsupported: true}}},
{name: "message id fallback", payload: `{"type":"session.step.started","data":{"sessionID":"ses_1","index":1}}`, state: prior, wantOK: true, wantKind: protocol.ChatEventStep, wantMsg: "msg_prev", wantStep: protocol.ChatStepStarted},
{name: "foreign session skipped", payload: `{"type":"session.text.delta","data":{"sessionID":"ses_other","delta":"x"}}`, wantOK: false},
{name: "unknown type skipped", payload: `{"type":"session.created","data":{"sessionID":"ses_1"}}`, wantOK: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
frame, ok, err := NormalizeChatEvent([]byte(tc.payload), "ses_1", tc.state)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if ok != tc.wantOK {
t.Fatalf("ok = %v, want %v", ok, tc.wantOK)
}
if !ok {
return
}
if frame.SessionID != "ses_1" || frame.Kind != tc.wantKind {
t.Fatalf("frame = %+v", frame)
}
if tc.wantMsg != "" && frame.MessageID != tc.wantMsg {
t.Fatalf("messageID = %q, want %q", frame.MessageID, tc.wantMsg)
}
if tc.wantDelta != "" && frame.Delta != tc.wantDelta {
t.Fatalf("delta = %q, want %q", frame.Delta, tc.wantDelta)
}
if tc.wantStatus != "" && (frame.Part == nil || frame.Part.State == nil || frame.Part.State.Status != tc.wantStatus) {
t.Fatalf("tool state = %+v, want status %q", frame.Part, tc.wantStatus)
}
if tc.wantStep != "" && (frame.Step == nil || frame.Step.Status != tc.wantStep) {
t.Fatalf("step = %+v, want %q", frame.Step, tc.wantStep)
}
if tc.wantUsage != nil && !reflect.DeepEqual(frame.Usage, tc.wantUsage) {
t.Fatalf("usage = %+v, want %+v", frame.Usage, tc.wantUsage)
}
})
}
}
func TestNormalizeChatEventRejectsMalformedJSON(t *testing.T) {
if _, _, err := NormalizeChatEvent([]byte(`{"type":`), "ses_1", nil); err == nil {
t.Fatal("malformed event must return an error, not a frame")
}
}
func TestChatStreamFiltersFrames(t *testing.T) {
var prompts atomic.Int32
frames := []string{
`{"id":"evt_1","type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0,"delta":"hello "}}`,
`{"id":"evt_2","type":"session.text.delta","data":{"sessionID":"ses_other","assistantMessageID":"msg_x","ordinal":0,"delta":"ignore"}}`,
`{"id":"evt_3","type":"session.tool.called","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","input":{"command":"ls"}}}`,
`{"id":"evt_4","type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","step":1}}`,
}
srv := 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/session/ses_1/message":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[]}`))
case r.Method == http.MethodGet && r.URL.Path == "/api/session/ses_1":
w.WriteHeader(http.StatusNotFound) // older source flavor: events only
case r.Method == http.MethodGet && r.URL.Path == "/api/event":
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 srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var got []protocol.ChatEventFrame
err := chat.Stream(ctx, "ses_1", nil, func(frame protocol.ChatEventFrame) error {
got = append(got, frame)
return nil
})
if err != nil {
t.Fatalf("stream: %v", err)
}
if len(got) != 3 {
t.Fatalf("got %d frames, want 3 (foreign session filtered): %+v", len(got), got)
}
if got[0].Kind != protocol.ChatEventText || got[0].Delta != "hello " || got[0].MessageID != "msg_1" || got[0].Part == nil || got[0].Part.ID == "" {
t.Fatalf("text frame = %+v", got[0])
}
if got[1].Kind != protocol.ChatEventTool || got[1].Part == nil || got[1].Part.State == nil || got[1].Part.State.Status != protocol.ChatToolRunning {
t.Fatalf("tool frame = %+v", got[1])
}
if got[2].Kind != protocol.ChatEventStep || got[2].Step == nil || got[2].Step.Status != protocol.ChatStepEnded {
t.Fatalf("step frame = %+v", got[2])
}
for _, frame := range got {
if frame.SessionID != "ses_1" || frame.MessageID == "" {
t.Fatalf("frame missing stable ids: %+v", frame)
}
}
if err := chat.Prompt(ctx, "ses_1", "hello"); err != nil {
t.Fatalf("prompt: %v", err)
}
if prompts.Load() != 1 {
t.Fatalf("prompt posts = %d, want 1", prompts.Load())
}
}
func TestChatRejectsInvalidSessionWithoutCalling(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx := context.Background()
if err := chat.Prompt(ctx, "not-a-session", "hi"); err == nil {
t.Fatal("invalid session id must be rejected")
}
if err := chat.Stream(ctx, "", nil, func(protocol.ChatEventFrame) error { return nil }); err == nil {
t.Fatal("empty session id must be rejected")
}
if err := chat.Interrupt(ctx, "bad id"); err == nil {
t.Fatal("invalid interrupt session id must be rejected")
}
if _, err := chat.Messages(ctx, "bad id", 1, ""); err == nil {
t.Fatal("invalid history session id must be rejected")
}
if _, err := chat.Permissions(ctx, "not-a-session"); err == nil {
t.Fatal("invalid permission session id must be rejected")
}
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "not-a-session", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}); err == nil {
t.Fatal("invalid reply session id must be rejected")
}
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "", Decision: protocol.ChatDecisionOnce}); err == nil {
t.Fatal("empty reply request id must be rejected")
}
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: "maybe"}); err == nil {
t.Fatal("invalid reply decision must be rejected")
}
if calls.Load() != 0 {
t.Fatalf("invalid requests reached the service: %d", calls.Load())
}
}
// TestChatPermissionsListsAndFilters loads a pending-request fixture in the
// verified V2 session-owned envelope and asserts the adapter
// returns the requested session's request with its fields intact, filters out a
// foreign session's request, and reads the endpoint once.
func TestChatPermissionsListsAndFilters(t *testing.T) {
var reads atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/session/ses_1/permission" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
reads.Add(1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[
{"id":"per_1","sessionID":"ses_1","action":"bash","resources":["rm -rf /tmp"],"save":["bash:rm -rf /tmp"],"metadata":{"command":"rm -rf /tmp"},"source":{"type":"tool","messageID":"msg_1","id":"call_1"},"message":"wants to run a command"},
{"id":"per_2","sessionID":"ses_other","action":"edit","resources":["/etc/hosts"]}
]}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
frames, err := chat.Permissions(ctx, "ses_1")
if err != nil {
t.Fatalf("permissions: %v", err)
}
if reads.Load() != 1 {
t.Fatalf("permission endpoint read %d times, want 1", reads.Load())
}
if len(frames) != 1 {
t.Fatalf("frames = %+v, want the foreign request filtered", frames)
}
got := frames[0]
if got.SessionID != "ses_1" || got.RequestID != "per_1" || got.Action != "bash" {
t.Fatalf("frame = %+v", got)
}
if len(got.Resources) != 1 || got.Resources[0] != "rm -rf /tmp" || len(got.Save) != 1 || got.Message != "wants to run a command" {
t.Fatalf("frame detail = %+v", got)
}
if got.Metadata["command"] != "rm -rf /tmp" {
t.Fatalf("frame metadata = %+v", got.Metadata)
}
if got.Source == nil || got.Source.Type != "tool" || got.Source.MessageID != "msg_1" || got.Source.ID != "call_1" {
t.Fatalf("frame source = %+v", got.Source)
}
}
// TestChatPermissionsRejectsMalformedList pins that a response without the data
// array is an error, not an empty success.
func TestChatPermissionsRejectsMalformedList(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"location":{"directory":"/work"}}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if _, err := chat.Permissions(context.Background(), "ses_1"); err == nil {
t.Fatal("a malformed permission response must be an error, not empty success")
}
}
// TestChatPermissionReplyPostsReplyEndpoint pins the outbound approval reply: the
// adapter must POST exactly once to
// /api/session/{id}/permission/{requestID}/reply with the exact decision body,
// accept the documented 204 No Content success, and surface a non-2xx failure.
func TestChatPermissionReplyPostsReplyEndpoint(t *testing.T) {
for _, decision := range []string{protocol.ChatDecisionOnce, protocol.ChatDecisionAlways, protocol.ChatDecisionReject} {
t.Run(decision, func(t *testing.T) {
type request struct{ method, path, body string }
var mu sync.Mutex
var requests []request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := io.ReadAll(r.Body)
mu.Lock()
requests = append(requests, request{method: r.Method, path: r.URL.Path, body: string(data)})
mu.Unlock()
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: decision}); err != nil {
t.Fatalf("reply: %v", err)
}
mu.Lock()
got := append([]request(nil), requests...)
mu.Unlock()
if len(got) != 1 {
t.Fatalf("reply requests = %d, want 1: %+v", len(got), got)
}
if got[0].method != http.MethodPost || got[0].path != "/api/session/ses_1/permission/req_1/reply" {
t.Fatalf("reply request = %+v", got[0])
}
if got[0].body != `{"decision":"`+decision+`"}` {
t.Fatalf("reply body = %q, want decision %q", got[0].body, decision)
}
})
}
t.Run("failure", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if err := chat.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}); err == nil {
t.Fatal("a failing reply endpoint must return an error")
}
})
}
// TestChatPermissionV1TranslationGated pins the declared backend limitation: the
// permission list and reply are implemented against the V2 HTTP API, and the
// native serve translation rejects them explicitly (an actionable error, no
// guessed endpoint, no HTTP call) so the caller can see the limitation.
func TestChatPermissionV1TranslationGated(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v1", URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}})
ctx := context.Background()
if _, err := chat.Permissions(ctx, "ses_1"); !errors.Is(err, ErrPermissionUnsupported) {
t.Fatalf("v1 permission list must return the gate sentinel, got %v", err)
}
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}); !errors.Is(err, ErrPermissionUnsupported) {
t.Fatalf("v1 permission reply must return the gate sentinel, got %v", err)
}
if calls.Load() != 0 {
t.Fatalf("gated permission requests reached the service: %d", calls.Load())
}
}
// TestChatInterruptPostsInterruptEndpoint pins the outbound interrupt call: the
// adapter must POST an empty JSON body to /api/session/{id}/interrupt exactly
// once and return nil, and it must surface a non-nil error when the endpoint
// fails. One interrupter request, no probing beyond what the call needs.
func TestChatInterruptPostsInterruptEndpoint(t *testing.T) {
t.Run("success", func(t *testing.T) {
type request struct{ method, path, body string }
var mu sync.Mutex
var requests []request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := io.ReadAll(r.Body)
mu.Lock()
requests = append(requests, request{method: r.Method, path: r.URL.Path, body: string(data)})
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := chat.Interrupt(ctx, "ses_1"); err != nil {
t.Fatalf("interrupt: %v", err)
}
mu.Lock()
got := append([]request(nil), requests...)
mu.Unlock()
if len(got) != 1 {
t.Fatalf("interrupt requests = %d, want 1: %+v", len(got), got)
}
if got[0].method != http.MethodPost || got[0].path != "/api/session/ses_1/interrupt" {
t.Fatalf("interrupt request = %+v", got[0])
}
if got[0].body != "{}" {
t.Fatalf("interrupt body = %q, want {}", got[0].body)
}
})
t.Run("failure", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := chat.Interrupt(ctx, "ses_1"); err == nil {
t.Fatal("a failing interrupt endpoint must return an error")
}
})
}
func TestChatReleaseSessionStopsRunningShells(t *testing.T) {
var requests []string
var mu sync.Mutex
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
requests = append(requests, r.Method+" "+r.URL.Path)
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/session/ses_1/interrupt":
_, _ = w.Write([]byte(`{}`))
case "/api/shell":
_, _ = w.Write([]byte(`{"data":[{"id":"sh_running","status":"running","metadata":{"sessionID":"ses_1"}},{"id":"sh_done","status":"exited","metadata":{"sessionID":"ses_1"}}]}`))
case "/api/shell/sh_running":
_, _ = w.Write([]byte(`{}`))
default:
w.WriteHeader(http.StatusNotFound)
}
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if err := chat.ReleaseSession(context.Background(), "ses_1"); err != nil {
t.Fatal(err)
}
mu.Lock()
got := append([]string(nil), requests...)
mu.Unlock()
want := []string{"POST /api/session/ses_1/interrupt", "GET /api/shell", "DELETE /api/shell/sh_running"}
if !slices.Equal(got, want) {
t.Fatalf("release requests = %v, want %v", got, want)
}
}
// TestDecodeChatMessages loads a seeded user + assistant session in both
// response envelopes the two surfaces return and asserts the turns come back
// with role, id, part order, part ids and the completed tool's input, content
// and status intact. The V2 HTTP API (GET /api/session/{id}/message) wraps the
// messages in {"data":[...]} with the fields at the message top level and the
// parts under "content"; the native serve readback returns a bare array with the
// fields under "info" and the parts under "parts".
func TestDecodeChatMessages(t *testing.T) {
cases := []struct {
name string
raw string
wantUserPartID string
wantUserPartTxt string
wantTextPartID string
wantReasonPartID string
}{
{
name: "v2 data envelope",
raw: `{"data":[
{"id":"msg_user","time":{"created":10},"type":"user","text":"list the files"},
{"id":"msg_assistant","time":{"created":20,"streamed":25,"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"}],"metadata":{"exit":0}},"time":{"created":1,"ran":2,"completed":3}}
]}
],"cursor":{"next":null}}`,
wantUserPartID: "",
wantUserPartTxt: "list the files",
wantTextPartID: "",
wantReasonPartID: "",
},
{
name: "v1 bare array",
raw: `[
{"info":{"id":"msg_user","role":"user","created":10},"parts":[{"type":"text","id":"p0","text":"list the files"}]},
{"info":{"id":"msg_assistant","role":"assistant","modelID":"deepseek-v4.1-flash","agent":"build","created":20},"parts":[
{"type":"text","id":"p1","text":"here you go"},
{"type":"reasoning","id":"p2","text":"thinking"},
{"type":"tool","id":"call_1","name":"shell","executed":true,"state":{"status":"completed","input":{"command":"ls"},"content":[{"type":"text","text":"ok"}],"metadata":{"exit":0}},"time":{"created":1,"ran":2,"completed":3}}
]}
]`,
wantUserPartID: "p0",
wantUserPartTxt: "list the files",
wantTextPartID: "p1",
wantReasonPartID: "p2",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
messages, err := decodeChatMessages("ses_1", []byte(tc.raw))
if err != nil {
t.Fatalf("decode: %v", err)
}
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 || user.SessionID != "ses_1" {
t.Fatalf("user turn = %+v", user)
}
if len(user.Parts) != 1 || user.Parts[0].Type != protocol.ChatPartText || user.Parts[0].ID != tc.wantUserPartID || user.Parts[0].Text != tc.wantUserPartTxt {
t.Fatalf("user parts = %+v", user.Parts)
}
if assistant.ID != "msg_assistant" || assistant.Role != protocol.ChatRoleAssistant || assistant.SessionID != "ses_1" {
t.Fatalf("assistant turn = %+v", assistant)
}
if assistant.Model != "deepseek-v4.1-flash" || assistant.Agent != "build" {
t.Fatalf("assistant model/agent = %q/%q", assistant.Model, assistant.Agent)
}
if len(assistant.Parts) != 3 {
t.Fatalf("got %d assistant parts, want text+reasoning+tool: %+v", len(assistant.Parts), assistant.Parts)
}
if p := assistant.Parts[0]; p.Type != protocol.ChatPartText || p.ID != tc.wantTextPartID || p.Text != "here you go" {
t.Fatalf("text part = %+v", p)
}
if p := assistant.Parts[1]; p.Type != protocol.ChatPartReasoning || p.ID != tc.wantReasonPartID || p.Text != "thinking" {
t.Fatalf("reasoning part = %+v", p)
}
tool := assistant.Parts[2]
if tool.Type != protocol.ChatPartTool || tool.ID != "call_1" || tool.Name != "shell" || !tool.Executed {
t.Fatalf("tool part = %+v", tool)
}
if tool.State == nil || tool.State.Status != protocol.ChatToolCompleted {
t.Fatalf("tool state = %+v", tool.State)
}
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].Type != "text" || tool.State.Content[0].Text != "ok" {
t.Fatalf("tool content = %+v", tool.State.Content)
}
if tool.Time == nil || tool.Time.Completed != 3 {
t.Fatalf("tool time = %+v", tool.Time)
}
})
}
}
// TestDecodeChatMessagesSkipsUnknownPartsAndRoles pins that a non user/assistant
// turn and an unrecognised part type are skipped instead of failing the whole
// history, and that an unparseable body is an error rather than empty history.
func TestDecodeChatMessagesSkipsUnknownPartsAndRoles(t *testing.T) {
raw := `{"data":[
{"id":"msg_system","type":"system","content":[{"type":"text","text":"ignore me"}]},
{"id":"msg_user","time":{"created":1},"type":"user","text":"hi"},
{"id":"msg_assistant","time":{"created":2},"type":"assistant","content":[
{"type":"text","text":"ok"},
{"type":"file","text":"ignored"},
{"type":"step","text":"ignored"}
]}
]}`
messages, err := decodeChatMessages("ses_1", []byte(raw))
if err != nil {
t.Fatal(err)
}
if len(messages) != 2 {
t.Fatalf("got %d messages, want the system turn skipped: %+v", len(messages), messages)
}
if messages[0].Role != protocol.ChatRoleUser || len(messages[0].Parts) != 1 || messages[0].Parts[0].Text != "hi" {
t.Fatalf("user turn = %+v", messages[0])
}
if messages[1].Role != protocol.ChatRoleAssistant || len(messages[1].Parts) != 1 || messages[1].Parts[0].Text != "ok" {
t.Fatalf("assistant turn = %+v", messages[1])
}
if _, err := decodeChatMessages("ses_1", []byte("not json")); err == nil {
t.Fatal("an unparseable body must be an error, not empty history")
}
}
func TestDecodeChatMessagesMapsTopLevelUserFiles(t *testing.T) {
raw := `{"data":[{"id":"msg_user","time":{"created":1},"type":"user","text":"see attached","files":[
{"data":"aGVsbG8=","mime":"text/plain","source":{"type":"uri","uri":"file:///tmp/note.txt"},"name":"note.txt"}
]}]}`
messages, err := decodeChatMessages("ses_1", []byte(raw))
if err != nil {
t.Fatal(err)
}
if len(messages) != 1 || len(messages[0].Parts) != 2 {
t.Fatalf("messages = %+v", messages)
}
file := messages[0].Parts[1]
if file.Type != protocol.ChatPartFile || file.Name != "note.txt" || file.URI != "file:///tmp/note.txt" || file.Mime != "text/plain" {
t.Fatalf("file part = %+v", file)
}
if strings.Contains(file.URI, "aGVsbG8=") {
t.Fatal("history exposed inline file data")
}
}
func TestDecodeChatMessagesMapsUserFileParts(t *testing.T) {
raw := `{"data":[{"id":"msg_user","time":{"created":1},"type":"user","parts":[
{"type":"text","text":"see attached"},
{"type":"file","uri":"file:///tmp/note.txt","name":"note.txt","mime":"text/plain"}
]}]}`
messages, err := decodeChatMessages("ses_1", []byte(raw))
if err != nil {
t.Fatal(err)
}
if len(messages) != 1 || len(messages[0].Parts) != 2 {
t.Fatalf("messages = %+v", messages)
}
file := messages[0].Parts[1]
if file.Type != protocol.ChatPartFile || file.Name != "note.txt" || file.URI != "file:///tmp/note.txt" || file.Mime != "text/plain" {
t.Fatalf("file part = %+v", file)
}
}
func TestChatMessagesPagesLargeToolHistoryWithoutGlobalResponseLimit(t *testing.T) {
large := strings.Repeat("x", MaxResponse+1)
var paths []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.URL.String())
w.Header().Set("Content-Type", "application/json")
if r.URL.Query().Get("cursor") == "older-token" {
_, _ = io.WriteString(w, `{"data":[{"id":"old","type":"user","time":{"created":1},"text":"older"}],"cursor":{"next":null}}`)
return
}
_, _ = io.WriteString(w, `{"data":[{"id":"new","type":"assistant","time":{"created":2},"content":[{"type":"tool","id":"tool","state":{"status":"completed","content":[{"type":"text","text":"`+large+`"}]}},{"type":"text","text":"final answer"}]}],"cursor":{"next":"older-token"}}`)
}))
defer srv.Close()
conn := &Connection{Backend: "v2", URL: srv.URL}
chat := NewChat(conn)
page, err := chat.Messages(context.Background(), "ses_1", 1, "")
if err != nil {
t.Fatal(err)
}
if !page.HasMore || page.NextCursor != "older-token" || len(page.Messages) != 1 {
t.Fatalf("page = %+v", page)
}
parts := page.Messages[0].Parts
if len(parts) != 2 || parts[0].State == nil || !parts[0].State.Truncated || parts[1].Text != "final answer" {
t.Fatalf("parts = %+v", parts)
}
older, err := chat.Messages(context.Background(), "ses_1", 1, page.NextCursor)
if err != nil || older.HasMore || len(older.Messages) != 1 || older.Messages[0].ID != "old" {
t.Fatalf("older = %+v, %v", older, err)
}
if len(paths) != 2 || !strings.Contains(paths[1], "cursor=older-token") {
t.Fatalf("requests = %v", paths)
}
if _, err := conn.Call(context.Background(), "get", "/api/session/ses_1/message", nil); err == nil || !strings.Contains(err.Error(), "1 MiB") {
t.Fatalf("generic Call safeguard changed: %v", err)
}
}
// TestChatSessionsListsAndLiftsShape loads the verified V2 session list
// (GET /api/session: {"data":[{id,...,location.directory,time{created,updated},
// parentID}]}) and asserts the adapter reads it exactly once, lifts the nested
// directory/time onto protocol.ChatSession, orders newest-updated first, and does
// not scope the list to the connection's own directory (so operator sessions in
// other directories are returned for the caller to filter).
func TestChatSessionsListsAndLiftsShape(t *testing.T) {
var reads atomic.Int32
var scoped bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/session" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
reads.Add(1)
if r.URL.Query().Get("directory") != "" {
scoped = true
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[
{"id":"ses_old","title":"older","agent":"build","model":{"id":"m1"},"parentID":"ses_new","location":{"directory":"/proj"},"time":{"created":10,"updated":20}},
{"id":"ses_new","title":"newer","agent":"general","model":{"id":"m2"},"location":{"directory":"/proj"},"time":{"created":30,"updated":50}}
],"cursor":{"next":null}}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL, Directory: "/repo"})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
sessions, err := chat.Sessions(ctx)
if err != nil {
t.Fatalf("sessions: %v", err)
}
if reads.Load() != 1 {
t.Fatalf("session endpoint read %d times, want 1", reads.Load())
}
if scoped {
t.Fatal("session list was scoped to the connection directory; it must list every directory")
}
if len(sessions) != 2 {
t.Fatalf("sessions = %+v, want 2", sessions)
}
newer, older := sessions[0], sessions[1]
if newer.ID != "ses_new" || older.ID != "ses_old" {
t.Fatalf("not ordered newest-updated first: %+v", sessions)
}
if newer.Title != "newer" || newer.Agent != "general" || newer.Model != "m2" || newer.Directory != "/proj" || newer.CreatedAt != 30 || newer.UpdatedAt != 50 {
t.Fatalf("lifted fields wrong: %+v", newer)
}
if older.ParentID != "ses_new" || older.UpdatedAt != 20 || older.Title != "older" || older.Model != "m1" {
t.Fatalf("older session fields wrong: %+v", older)
}
}
// TestChatSessionsTolerantEnvelopes pins the decoder's edge cases: a bare array
// (the native serve readback) is accepted, records without a valid session id
// are dropped, and an unparseable body or a data:null envelope is an error, not
// a silent empty success.
func TestChatSessionsTolerantEnvelopes(t *testing.T) {
sessions, err := decodeChatSessions([]byte(`[
{"id":"ses_1","title":"kept","time":{"updated":5}},
{"id":"","title":"dropped empty"},
{"id":"msg_not_a_session","title":"dropped invalid"}
]`))
if err != nil {
t.Fatalf("bare array decode: %v", err)
}
if len(sessions) != 1 || sessions[0].ID != "ses_1" || sessions[0].Title != "kept" {
t.Fatalf("bare array mapping wrong: %+v", sessions)
}
if sessions, err := decodeChatSessions([]byte(`{"data":[]}`)); err != nil || len(sessions) != 0 {
t.Fatalf("empty data array must decode to no sessions: %+v %v", sessions, err)
}
for _, raw := range []string{`{"data":null}`, `not json`, `{"location":{"directory":"/work"}}`} {
if _, err := decodeChatSessions([]byte(raw)); err == nil {
t.Fatalf("body %q must be an error, not empty success", raw)
}
}
}
// TestChatSessionsV1Translation pins the native serve path: GET /api/session is
// translated to the native GET /session (a bare array), so chat_sessions works
// on the backend that currently enables brokered chat. The native list shape is
// not covered by the research; this asserts the translated endpoint and the
// shared tolerant decode, not an unverified service shape.
func TestChatSessionsV1Translation(t *testing.T) {
var sawList bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/session" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
sawList = true
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[{"id":"ses_1","title":"native","time":{"created":1,"updated":2}}]`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v1", URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
sessions, err := chat.Sessions(ctx)
if err != nil {
t.Fatalf("sessions: %v", err)
}
if !sawList {
t.Fatal("GET /api/session was not translated to the native GET /session")
}
if len(sessions) != 1 || sessions[0].ID != "ses_1" || sessions[0].Title != "native" || sessions[0].UpdatedAt != 2 {
t.Fatalf("native session list mapped wrong: %+v", sessions)
}
}
func TestChatStreamRejectsMalformedEvent(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: {\"type\":\"session.text.delta\",\"data\":{\"sessionID\":\"ses_1\"\n\n"))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
emitted := 0
err := chat.Stream(context.Background(), "ses_1", nil, func(protocol.ChatEventFrame) error {
emitted++
return nil
})
if err == nil {
t.Fatal("malformed event JSON must fail the stream")
}
if emitted != 0 {
t.Fatalf("malformed event produced %d frames", emitted)
}
}
func TestChatStreamRequiresEndpoint(t *testing.T) {
chat := NewChat(&Connection{Backend: "v2"})
err := chat.Stream(context.Background(), "ses_1", nil, func(protocol.ChatEventFrame) error { return nil })
if err == nil || !strings.Contains(err.Error(), "event-stream endpoint") {
t.Fatalf("expected endpoint error, got %v", err)
}
}
// TestChatCreatePostsSessionEndpoint pins the outbound create call: the adapter
// must POST exactly once to /api/session with the verified V2 body
// {"title":...,"location":{"directory":...}} (no invented mechanism, no model or
// permission override), read exactly that one path, and lift the nested
// location.directory from the {"data":{...}} response.
func TestChatCreatePostsSessionEndpoint(t *testing.T) {
type request struct{ method, path, body string }
var mu sync.Mutex
var requests []request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := io.ReadAll(r.Body)
mu.Lock()
requests = append(requests, request{method: r.Method, path: r.URL.Path, body: string(data)})
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":{"id":"ses_new","title":"demo","location":{"directory":"/work/proj"},"time":{"created":11,"updated":22}}}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
session, err := chat.Create(ctx, "demo", "/work/proj")
if err != nil {
t.Fatalf("create: %v", err)
}
mu.Lock()
got := append([]request(nil), requests...)
mu.Unlock()
if len(got) != 1 {
t.Fatalf("create requests = %d, want 1: %+v", len(got), got)
}
if got[0].method != http.MethodPost || got[0].path != "/api/session" {
t.Fatalf("create request = %+v", got[0])
}
if got[0].body != `{"title":"demo","location":{"directory":"/work/proj"}}` {
t.Fatalf("create body = %q", got[0].body)
}
if session.ID != "ses_new" || session.Title != "demo" || session.Directory != "/work/proj" || session.CreatedAt != 11 || session.UpdatedAt != 22 {
t.Fatalf("created session = %+v", session)
}
}
// TestChatCreateRejectsMalformedSession pins that a response without a valid
// session id is an error, not a silent empty success.
func TestChatCreateRejectsMalformedSession(t *testing.T) {
for _, raw := range []string{`{"data":{}}`, `{"data":{"id":""}}`, `{"data":{"id":"msg_not_a_session"}}`, `not json`} {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(raw))
}))
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if _, err := chat.Create(context.Background(), "demo", "/work"); err == nil {
t.Fatalf("response %q must be an error, not empty success", raw)
}
srv.Close()
}
}
func TestNormalizeChatEventWithoutMessageID(t *testing.T) {
for _, payload := range []string{
`{"type":"session.text.delta","data":{"sessionID":"ses_1","ordinal":0,"delta":"x"}}`,
`{"type":"session.tool.called","data":{"sessionID":"ses_1","id":"call_1","name":"shell","input":{"command":"ls"}}}`,
} {
if _, ok, err := NormalizeChatEvent([]byte(payload), "ses_1", nil); err != nil || ok {
t.Fatalf("event without a message id produced a frame: ok=%v err=%v", ok, err)
}
}
frame, ok, err := NormalizeChatEvent([]byte(`{"type":"session.usage.updated","data":{"sessionID":"ses_1","tokens":{"input":1,"output":2}}}`), "ses_1", nil)
if err != nil || !ok || frame.MessageID != "" || frame.Usage == nil || frame.Usage.Scope != "session" {
t.Fatalf("message-less session usage=%+v ok=%v err=%v", frame, ok, err)
}
}
// TestChatV1ConnectionDrivesThroughCall drives the adapter through a real
// (serve-shaped) Connection so the /api -> native translation and the owned
// endpoint are exercised, not a direct v2 URL shortcut.
func TestChatV1ConnectionDrivesThroughCall(t *testing.T) {
var sawPrompt, sawMessages bool
var promptBody string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && r.URL.Path == "/session/ses_1/message":
// Call must have translated /api/session/{id}/prompt to this path.
sawPrompt = true
body, _ := io.ReadAll(r.Body)
promptBody = string(body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ok":true}`))
case r.Method == http.MethodGet && r.URL.Path == "/session/ses_1/message":
sawMessages = true
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[{"info":{"id":"msg_1","role":"assistant","modelID":"m","agent":"build","created":10},"parts":[{"type":"text","id":"p1","text":"hi"}]}]`))
case r.Method == http.MethodGet && r.URL.Path == "/event":
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: {\"type\":\"session.text.delta\",\"data\":{\"sessionID\":\"ses_1\",\"assistantMessageID\":\"msg_1\",\"ordinal\":0,\"delta\":\"hi\"}}\n\n"))
default:
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
}
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v1", URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := chat.PromptWithMessageID(ctx, "ses_1", "hello", "msg_canonical"); err != nil {
t.Fatalf("prompt: %v", err)
}
if !sawPrompt {
t.Fatal("prompt was not translated to the native path")
}
// The translated body must carry the prompt text: the chat adapter sends the
// V2 `parts` shape and the v1 translation has to preserve it, or the native
// serve process receives an empty prompt.
var sent struct {
ID string `json:"id"`
Parts []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"parts"`
}
if err := json.Unmarshal([]byte(promptBody), &sent); err != nil {
t.Fatalf("prompt body: %v (%s)", err, promptBody)
}
if sent.ID != "msg_canonical" || len(sent.Parts) != 1 || sent.Parts[0].Type != protocol.ChatPartText || sent.Parts[0].Text != "hello" {
t.Fatalf("prompt text not carried through the v1 translation: %s", promptBody)
}
var got []protocol.ChatEventFrame
if err := chat.Stream(ctx, "ses_1", nil, func(frame protocol.ChatEventFrame) error {
got = append(got, frame)
return nil
}); err != nil {
t.Fatalf("stream: %v", err)
}
if len(got) != 1 || got[0].Kind != protocol.ChatEventText || got[0].MessageID != "msg_1" {
t.Fatalf("stream frames = %+v", got)
}
page, err := chat.Messages(ctx, "ses_1", 0, "")
if err != nil {
t.Fatalf("messages: %v", err)
}
if !sawMessages || len(page.Messages) != 1 || page.Messages[0].ID != "msg_1" {
t.Fatalf("messages = %+v", page.Messages)
}
}
// TestNormalizeChatEventForm proves the question tool's form lifecycle is
// surfaced: form.created carries the field structure and is remembered for the
// session, while the terminal events (which carry only an id) resolve the same
// form for that session and are ignored for another.
func TestNormalizeChatEventForm(t *testing.T) {
state := &ChatStreamState{}
created := []byte(`{"type":"form.created","data":{"form":{"id":"form_1","sessionID":"ses_1","title":"Choose a colour","metadata":{"kind":"question"},"fields":[{"key":"colour","title":"Which colour?","description":"Pick one","type":"string","required":true,"options":[{"value":"red","label":"Red","description":"Warm"},{"value":"blue","label":"Blue"}]}]}}}`)
frame, ok, err := NormalizeChatEvent(created, "ses_1", state)
if err != nil || !ok {
t.Fatalf("form.created: ok=%v err=%v", ok, err)
}
if frame.Kind != protocol.ChatEventForm || frame.Form == nil {
t.Fatalf("form.created frame = %+v", frame)
}
if frame.Form.ID != "form_1" || frame.Form.Kind != "question" || len(frame.Form.Fields) != 1 {
t.Fatalf("form.created form = %+v", frame.Form)
}
field := frame.Form.Fields[0]
if field.Key != "colour" || field.Title != "Which colour?" || !field.Required || len(field.Options) != 2 {
t.Fatalf("form.created field = %+v", field)
}
if field.Options[0].Value != "red" || field.Options[0].Label != "Red" || field.Options[0].Description != "Warm" {
t.Fatalf("form option = %+v", field.Options[0])
}
// Another session's terminal event is not this session's form.
if _, ok, err := NormalizeChatEvent([]byte(`{"type":"form.replied","data":{"id":"form_1"}}`), "ses_2", state); err != nil || ok {
t.Fatalf("foreign form.replied: ok=%v err=%v", ok, err)
}
resolved, ok, err := NormalizeChatEvent([]byte(`{"type":"form.replied","data":{"id":"form_1"}}`), "ses_1", state)
if err != nil || !ok || resolved.Form == nil || !resolved.Form.Resolved || resolved.Form.ID != "form_1" {
t.Fatalf("form.replied frame = %+v ok=%v err=%v", resolved, ok, err)
}
if _, ok, err := NormalizeChatEvent([]byte(`{"type":"form.cancelled","data":{"id":"form_1"}}`), "ses_1", state); err != nil || ok {
t.Fatalf("duplicate/unknown form.cancelled: ok=%v err=%v", ok, err)
}
}