package opencode import ( "context" "encoding/json" "io" "net/http" "net/http/httptest" "strings" "sync/atomic" "testing" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) func TestNormalizeChatEvent(t *testing.T) { last := "msg_prev" cases := []struct { name string payload string last *string 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}}, {name: "message id fallback", payload: `{"type":"session.step.started","data":{"sessionID":"ses_1","index":1}}`, last: &last, 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) { lastID := tc.last frame, ok, err := NormalizeChatEvent([]byte(tc.payload), "ses_1", lastID) 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 && (frame.Usage == nil || *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/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 calls.Load() != 0 { t.Fatalf("invalid requests reached the service: %d", calls.Load()) } } func TestDecodeChatMessages(t *testing.T) { raw := []byte(`{"data":[{"info":{"id":"msg_1","role":"assistant","modelID":"m","agent":"build","created":10},"parts":[{"type":"text","id":"p1","text":"hi"},{"type":"reasoning","id":"p2","text":"hmm"},{"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}}]}]}`) messages, err := decodeChatMessages("ses_1", raw) if err != nil { t.Fatal(err) } if len(messages) != 1 || messages[0].Role != protocol.ChatRoleAssistant || len(messages[0].Parts) != 3 { t.Fatalf("messages = %+v", messages) } tool := messages[0].Parts[2] if tool.Type != protocol.ChatPartTool || tool.Name != "shell" || tool.State == nil || tool.State.Status != protocol.ChatToolCompleted || tool.Time == nil { t.Fatalf("tool part = %+v", tool) } } 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) } } 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"}}}`, `{"type":"session.usage.updated","data":{"sessionID":"ses_1","tokens":{"input":1,"output":2}}}`, } { 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) } } } // 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.Prompt(ctx, "ses_1", "hello"); 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 { 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 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) } messages, err := chat.Messages(ctx, "ses_1", 0) if err != nil { t.Fatalf("messages: %v", err) } if !sawMessages || len(messages) != 1 || messages[0].ID != "msg_1" { t.Fatalf("messages = %+v", messages) } }