WIP preserve large chat history recovery

This commit is contained in:
2026-10-18 15:03:18 +01:00
parent f91145001a
commit 998da0e7af
21 changed files with 1088 additions and 75 deletions
+1 -1
View File
@@ -19,7 +19,7 @@ type chatBroker interface {
// can order the prompt after the subscription.
Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error
Interrupt(ctx context.Context, sessionID string) error
Messages(ctx context.Context, sessionID string, limit int) ([]protocol.ChatMessage, error)
Messages(ctx context.Context, sessionID string, limit int, cursor string) (protocol.ChatHistoryPage, error)
// Sessions lists the endpoint's OpenCode sessions so the handler can
// restrict them to the operator's own recorded sessions.
Sessions(ctx context.Context) ([]protocol.ChatSession, error)
+5 -9
View File
@@ -15,23 +15,19 @@ func handleChatMessages(ctx context.Context, request protocol.Message, broker ch
return
}
response := protocol.Message{Type: protocol.ChatMessages, ID: request.ID}
// Resume from retained server state first: a reconnecting client gets the
// accumulated turns with the same stable ids without re-reading OpenCode.
if messages := hub.snapshot(query.SessionID); len(messages) > 0 {
response.ChatMessages = messages
_ = write(response)
return
}
// A hub snapshot is only the live tail. It is never authoritative history:
// serving it here used to make older turns unreachable after a reconnect.
if broker == nil {
_ = write(response)
return
}
messages, err := broker.Messages(ctx, query.SessionID, query.Limit)
page, err := broker.Messages(ctx, query.SessionID, query.Limit, query.Cursor)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
response.ChatMessages = messages
response.ChatMessages = page.Messages // legacy peers keep working.
response.ChatHistory = &page
_ = write(response)
}
+107
View File
@@ -0,0 +1,107 @@
package server
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Scratch HTTP + real /connect websocket fixture, NOT a live-model/production
// claim. Covers both >1 MiB total (many tools) and one >1 MiB tool string.
func TestChatHistoryLargeFixtureWebsocketTraversalAndReconnect(t *testing.T) {
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/session/ses_1/message" || r.URL.Query().Get("limit") != "2" {
t.Errorf("unexpected history query %s", r.URL)
}
w.Header().Set("Content-Type", "application/json")
page := 0
switch r.URL.Query().Get("cursor") {
case "":
case "older+/=&":
page = 1
case "last":
page = 2
default:
t.Errorf("cursor not passed opaquely: %s", r.URL)
}
io.WriteString(w, `{"data":[`)
for i := 0; i < 2; i++ {
if i != 0 {
io.WriteString(w, ",")
}
id := 6 - page*2 - i
// Equal timestamps deliberately: order comes from the verified V2
// descending sequence, not a guessed timestamp comparison.
fmt.Fprintf(w, `{"id":"msg_%d","type":"assistant","time":{"created":1},"content":[`, id)
if page == 0 && i == 0 {
io.WriteString(w, `{"type":"tool","id":"huge","state":{"content":[{"type":"text","text":"`)
chunk := strings.Repeat("x", 32<<10)
for n := 0; n < 65; n++ {
io.WriteString(w, chunk)
}
io.WriteString(w, `"}]}},`)
}
if page == 1 && i == 0 {
for n := 0; n < 25; n++ {
fmt.Fprintf(w, `{"type":"tool","id":"tool_%d","state":{"status":"completed","content":[{"type":"text","text":%q}]}},`, n, strings.Repeat("y", 48<<10))
}
}
fmt.Fprintf(w, `{"type":"text","text":"answer %d"}]}`, id)
}
next := []any{"older+/=&", "last", nil}[page]
encoded, _ := json.Marshal(next)
fmt.Fprintf(w, `],"cursor":{"next":%s}}`, encoded)
}))
defer fixture.Close()
broker := opencode.NewChat(&opencode.Connection{Backend: "v2", URL: fixture.URL})
ctx, _, srv, conns := dialChatServer(t, Options{Chat: broker}, 1)
conn := conns[0]
conn.SetReadLimit(8 << 20)
cursor := ""
var ids []string
seen := map[string]bool{}
for page := 0; page < 3; page++ {
writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "history", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1", Limit: 2, Cursor: cursor}})
response := readUntil(t, ctx, conn, protocol.ChatMessages)
if response.ChatHistory == nil || len(response.ChatHistory.Messages) != 2 {
t.Fatalf("missing page: %+v", response)
}
history := response.ChatHistory
if !reflect.DeepEqual(response.ChatMessages, history.Messages) {
t.Fatal("legacy/page views differ")
}
for _, message := range history.Messages {
if seen[message.ID] {
t.Fatalf("duplicate %s", message.ID)
}
seen[message.ID] = true
}
pageIDs := []string{history.Messages[0].ID, history.Messages[1].ID}
ids = append(pageIDs, ids...)
if page == 0 {
newest := history.Messages[1]
if newest.Parts[len(newest.Parts)-1].Text != "answer 6" || !newest.Parts[0].State.Truncated {
t.Fatal("huge tool prevented newest answer")
}
}
cursor = history.NextCursor
if history.HasMore != (page < 2) {
t.Fatal("incorrect continuation")
}
// Reconnect between pages: continuation is server-owned, not a hub tail.
conn.CloseNow()
conn = dialChatConn(t, ctx, srv)
conn.SetReadLimit(8 << 20)
}
if cursor != "" || !reflect.DeepEqual(ids, []string{"msg_1", "msg_2", "msg_3", "msg_4", "msg_5", "msg_6"}) {
t.Fatalf("incomplete traversal: %v cursor=%q", ids, cursor)
}
}
+12 -14
View File
@@ -68,8 +68,8 @@ func (c *channelChat) Stream(ctx context.Context, _ string, ready func(), emit f
func (c *channelChat) Interrupt(context.Context, string) error { return nil }
func (c *channelChat) Messages(context.Context, string, int) ([]protocol.ChatMessage, error) {
return nil, nil
func (c *channelChat) Messages(context.Context, string, int, string) (protocol.ChatHistoryPage, error) {
return protocol.ChatHistoryPage{}, nil
}
func (c *channelChat) Sessions(context.Context) ([]protocol.ChatSession, error) { return nil, nil }
@@ -440,10 +440,11 @@ func TestChatPendingApprovalsAllReplayed(t *testing.T) {
}
// TestChatResyncAfterReconnect is the resync acceptance test: a client that drops
// and reconnects re-syncs the whole conversation from retained state, including
// the user turn and who sent it.
// and reconnects reads authoritative history rather than mistaking a retained
// live tail for the whole conversation.
func TestChatResyncAfterReconnect(t *testing.T) {
broker := scriptedChat()
broker.messages = seededChatMessages()
ctx, _, srv, conns := dialChatServer(t, Options{Chat: broker}, 1)
phone := conns[0]
@@ -454,19 +455,16 @@ func TestChatResyncAfterReconnect(t *testing.T) {
// The phone's socket drops.
phone.CloseNow()
// A fresh connection re-syncs from retained state.
// A fresh connection reads the authoritative history rather than treating the
// retained live tail as a complete transcript.
reconnected := dialChatConn(t, ctx, srv)
writeChat(t, ctx, reconnected, protocol.Message{Type: protocol.ChatMessages, ID: "m1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}})
response := readUntil(t, ctx, reconnected, protocol.ChatMessages)
if len(response.ChatMessages) != 2 {
t.Fatalf("resync returned %d messages, want user+assistant: %+v", len(response.ChatMessages), response.ChatMessages)
if response.ChatHistory == nil {
t.Fatalf("resync did not return a history page: %+v", response)
}
user := response.ChatMessages[0]
if user.Role != protocol.ChatRoleUser || user.Client != "Pixel 9" || len(user.Parts) != 1 || user.Parts[0].Text != "hi" {
t.Fatalf("resynced user turn = %+v", user)
}
assistant := response.ChatMessages[1]
if assistant.Role != protocol.ChatRoleAssistant || assistant.ID != "msg_1" {
t.Fatalf("resynced assistant turn = %+v", assistant)
assertSeededChatMessages(t, response.ChatHistory.Messages)
if calls, _, _ := broker.messageQuery(); calls != 1 {
t.Fatalf("reconnect skipped authoritative history: %d calls", calls)
}
}
+11 -22
View File
@@ -47,6 +47,7 @@ type fakeChat struct {
messageCalls int
messageSessionID string
messageLimit int
messageCursor string
messages []protocol.ChatMessage
permissionCalls int
permissionSessionID string
@@ -123,13 +124,14 @@ func (f *fakeChat) Interrupt(context.Context, string) error {
return f.interruptErr
}
func (f *fakeChat) Messages(_ context.Context, sessionID string, limit int) ([]protocol.ChatMessage, error) {
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
return f.messages, nil
f.messageCursor = cursor
return protocol.ChatHistoryPage{Messages: f.messages}, nil
}
// messageQuery reports the recorded chat_messages call count, session id and
@@ -420,6 +422,7 @@ func TestChatPromptWithoutBroker(t *testing.T) {
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)
@@ -436,27 +439,13 @@ func TestChatMessagesResumesRetainedState(t *testing.T) {
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || response.ID != "r2" || len(response.ChatMessages) != 2 {
if response.Type != protocol.ChatMessages || response.ID != "r2" || response.ChatHistory == nil {
t.Fatalf("resume response = %+v", response)
}
// The prompt is retained as a user turn and the assistant reply beside it, so
// a reconnecting client re-syncs a conversation that still says who sent
// what. The user turn carries the sending client's label (the generic
// fallback when the prompt did not name one).
user := response.ChatMessages[0]
if user.Role != protocol.ChatRoleUser || len(user.Parts) != 1 || user.Parts[0].Type != protocol.ChatPartText || user.Parts[0].Text != "hi" || user.Client != chatClientLabelFallback {
t.Fatalf("resumed user turn = %+v", user)
}
message := response.ChatMessages[1]
if message.ID != "msg_1" || message.Role != protocol.ChatRoleAssistant || len(message.Parts) != 2 {
t.Fatalf("resumed message = %+v", message)
}
if message.Parts[0].Type != protocol.ChatPartText || message.Parts[0].ID != protocol.ChatDeltaPartID("msg_1", protocol.ChatPartText, 0) || message.Parts[0].Text != "hello world" {
t.Fatalf("resumed text part = %+v", message.Parts[0])
}
if message.Parts[1].Type != protocol.ChatPartTool || message.Parts[1].State == nil || message.Parts[1].State.Status != protocol.ChatToolCompleted {
t.Fatalf("resumed tool part = %+v", message.Parts[1])
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
@@ -547,12 +536,12 @@ func TestChatMessagesThroughRealAdapter(t *testing.T) {
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}}
]}
]},
{"id":"msg_user","time":{"created":10},"type":"user","text":"list the files"}
],"cursor":{"next":null}}`))
}))
defer fixture.Close()