Expose OpenCode conversation history in chat_messages

decodeChatMessages only understood the native-serve {info,parts} envelope,
so records from the V2 HTTP API (GET /api/session/{id}/message) decoded
with an empty role and were silently dropped, leaving chat_messages with
empty history. Teach nativeChatMessage to read the V2 top-level shape
(id/type/agent/model/time, parts under "content", user prompt as a bare
string) while keeping the native {info,parts} path via role/id/model/agent/
created accessors and a contentParts fallback.

Add seeded-session evidence: a decoder table test covering both envelopes
(user + assistant with text, reasoning and a completed tool part carrying
input, content and status) plus handler tests that drive chat_messages
through the broker fallthrough and through the real adapter.
This commit is contained in:
2026-10-16 05:24:00 +01:00
parent 315788b3cb
commit 915016df0b
3 changed files with 374 additions and 25 deletions
+156 -1
View File
@@ -26,6 +26,9 @@ type fakeChat struct {
promptCalls int
interrupts int
replies int
messageCalls int
messageSessionID string
messageLimit int
messages []protocol.ChatMessage
script []protocol.ChatEventFrame
started chan struct{}
@@ -81,10 +84,23 @@ func (f *fakeChat) Interrupt(context.Context, string) error {
return nil
}
func (f *fakeChat) Messages(context.Context, string, int) ([]protocol.ChatMessage, error) {
func (f *fakeChat) Messages(_ context.Context, sessionID string, limit int) ([]protocol.ChatMessage, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.messageCalls++
f.messageSessionID = sessionID
f.messageLimit = limit
return f.messages, nil
}
// messageQuery reports the recorded chat_messages call count, session id and
// limit so a test can assert the handler forwarded the query.
func (f *fakeChat) messageQuery() (int, string, int) {
f.mu.Lock()
defer f.mu.Unlock()
return f.messageCalls, f.messageSessionID, f.messageLimit
}
func (f *fakeChat) Reply(context.Context, protocol.ChatReplyRequest) error {
f.mu.Lock()
defer f.mu.Unlock()
@@ -271,6 +287,145 @@ func TestChatMessagesResumesRetainedState(t *testing.T) {
}
}
// seededChatMessages is the stored user + assistant + tool session the
// chat_messages evidence tests assert on, mirroring the OpenCode V2 shape of an
// assistant turn's completed tool part (input object, text content, status).
func seededChatMessages() []protocol.ChatMessage {
return []protocol.ChatMessage{
{ID: "msg_user", SessionID: "ses_1", Role: protocol.ChatRoleUser,
Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: "list the files"}}},
{ID: "msg_assistant", SessionID: "ses_1", Role: protocol.ChatRoleAssistant, Model: "deepseek-v4.1-flash", Agent: "build",
Parts: []protocol.ChatPart{
{Type: protocol.ChatPartText, ID: "p1", Text: "here you go"},
{Type: protocol.ChatPartReasoning, ID: "p2", Text: "thinking"},
{Type: protocol.ChatPartTool, ID: "call_1", Name: "shell", Executed: true,
State: &protocol.ChatToolState{Status: protocol.ChatToolCompleted, Input: json.RawMessage(`{"command":"ls"}`), Content: []protocol.ChatToolContent{{Type: "text", Text: "ok"}}},
Time: &protocol.ChatTime{Created: 1, Ran: 2, Completed: 3}},
}},
}
}
// assertSeededChatMessages fails unless the user + assistant + tool session came
// back with both roles and the completed tool part's input, content and status.
func assertSeededChatMessages(t *testing.T, messages []protocol.ChatMessage) {
t.Helper()
if len(messages) != 2 {
t.Fatalf("got %d messages, want user+assistant: %+v", len(messages), messages)
}
user, assistant := messages[0], messages[1]
if user.ID != "msg_user" || user.Role != protocol.ChatRoleUser || len(user.Parts) != 1 || user.Parts[0].Type != protocol.ChatPartText || user.Parts[0].Text != "list the files" {
t.Fatalf("user turn = %+v", user)
}
if assistant.ID != "msg_assistant" || assistant.Role != protocol.ChatRoleAssistant || len(assistant.Parts) != 3 {
t.Fatalf("assistant turn = %+v", assistant)
}
if p := assistant.Parts[0]; p.Type != protocol.ChatPartText || p.Text != "here you go" {
t.Fatalf("assistant text part = %+v", p)
}
tool := assistant.Parts[2]
if tool.Type != protocol.ChatPartTool || tool.ID != "call_1" || tool.Name != "shell" || tool.State == nil || tool.State.Status != protocol.ChatToolCompleted {
t.Fatalf("assistant tool part = %+v", tool)
}
var input struct {
Command string `json:"command"`
}
if err := json.Unmarshal(tool.State.Input, &input); err != nil || input.Command != "ls" {
t.Fatalf("tool input = %s (err %v)", tool.State.Input, err)
}
if len(tool.State.Content) != 1 || tool.State.Content[0].Text != "ok" {
t.Fatalf("tool content = %+v", tool.State.Content)
}
}
// TestChatMessagesReturnsBrokerHistory drives chat_messages through the handler
// with an empty hub, so it must fall through to broker.Messages and return the
// seeded user + assistant + tool session, forwarding the query limit unchanged.
func TestChatMessagesReturnsBrokerHistory(t *testing.T) {
broker := scriptedChat()
broker.messages = seededChatMessages()
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "r2", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1", Limit: 7}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || response.ID != "r2" {
t.Fatalf("response = %+v", response)
}
assertSeededChatMessages(t, response.ChatMessages)
if calls, sessionID, limit := broker.messageQuery(); calls != 1 || sessionID != "ses_1" || limit != 7 {
t.Fatalf("broker query = %d/%q/%d, want 1/ses_1/7", calls, sessionID, limit)
}
}
// TestChatMessagesThroughRealAdapter loads a seeded session through the real
// opencode.Chat broker: the chat_messages handler reads the V2
// GET /api/session/{id}/message fixture once and returns the user + assistant +
// tool turns decoded from it, exercising the full handler -> adapter -> decode
// path with no scripted broker.
func TestChatMessagesThroughRealAdapter(t *testing.T) {
var messageReads atomic.Int32
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/session/ses_1/message" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
messageReads.Add(1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[
{"id":"msg_user","time":{"created":10},"type":"user","text":"list the files"},
{"id":"msg_assistant","time":{"created":20,"completed":30},"type":"assistant","agent":"build","model":{"id":"deepseek-v4.1-flash","providerID":"opencode-go"},"content":[
{"type":"text","text":"here you go"},
{"type":"reasoning","text":"thinking"},
{"type":"tool","id":"call_1","name":"shell","executed":true,"state":{"status":"completed","input":{"command":"ls"},"content":[{"type":"text","text":"ok"}]},"time":{"created":1,"ran":2,"completed":3}}
]}
],"cursor":{"next":null}}`))
}))
defer fixture.Close()
broker := opencode.NewChat(&opencode.Connection{Backend: "v2", URL: fixture.URL})
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "r2", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || response.ID != "r2" {
t.Fatalf("response = %+v", response)
}
assertSeededChatMessages(t, response.ChatMessages)
if messageReads.Load() != 1 {
t.Fatalf("message endpoint read %d times, want 1", messageReads.Load())
}
}
// TestChatMessagesRejectsInvalidSession pins that a missing or malformed session
// id is rejected before any broker call.
func TestChatMessagesRejectsInvalidSession(t *testing.T) {
broker := scriptedChat()
broker.messages = seededChatMessages()
ctx, _, conn := dialChat(t, broker)
for _, query := range []*protocol.ChatQuery{nil, {SessionID: ""}, {SessionID: "not-a-session"}} {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "bad", ChatQuery: query}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
t.Fatalf("query %+v not rejected: %+v", query, response)
}
}
if calls, _, _ := broker.messageQuery(); calls != 0 {
t.Fatalf("invalid chat_messages reached the broker: %d", calls)
}
}
func TestChatDisconnectCancelsStream(t *testing.T) {
broker := scriptedChat()
broker.block = true