package server import ( "context" "encoding/json" "strings" "testing" "git.a-wan.net/alan/pipelines/internal/protocol" ) // pagedChat serves a fixed history in chat_messages pages, newest first like // every harness adapter, and a native file for the native-export path. type pagedChat struct { *fakeChat pages map[string]protocol.ChatHistoryPage // cursor -> page native protocol.ChatExportFile } func (p *pagedChat) Messages(_ context.Context, _ string, _ int, cursor string) (protocol.ChatHistoryPage, error) { return p.pages[cursor], nil } func (p *pagedChat) NativeExport(_ context.Context, sessionID string) (protocol.ChatExportFile, error) { file := p.native file.SessionID = sessionID return file, nil } const exportClaudeID = "0b6f1c2e-1111-4222-8333-444455556666" func exportFixture(t *testing.T, backend string) (*pagedChat, context.Context, func(protocol.Message) protocol.Message) { t.Helper() store := newOperatorStore(t) broker := &pagedChat{fakeChat: scriptedChat(), pages: map[string]protocol.ChatHistoryPage{ "": {HasMore: true, NextCursor: "older", Messages: []protocol.ChatMessage{ {ID: "m3", Role: protocol.ChatRoleAssistant, CreatedAt: 1_700_000_060_000, Parts: []protocol.ChatPart{ {Type: protocol.ChatPartReasoning, Text: "secret thinking"}, {Type: protocol.ChatPartTool, Name: "Bash", State: &protocol.ChatToolState{Status: protocol.ChatToolCompleted, Input: json.RawMessage(`{"command":"go test ./...","description":"Run the tests"}`), Content: []protocol.ChatToolContent{{Type: "text", Text: "huge tool output"}}}}, {Type: protocol.ChatPartText, Text: "All tests pass."}, }}, {ID: "m4", Role: protocol.ChatRoleUser, Kind: protocol.ChatMessageKindAgentReport, CreatedAt: 1_700_000_090_000, Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: "Subagent found two files."}}}, }}, "older": {Messages: []protocol.ChatMessage{ {ID: "m1", Role: protocol.ChatRoleUser, Client: "Pixel", CreatedAt: 1_700_000_000_000, Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: "Run the tests"}, {Type: protocol.ChatPartFile, Name: "notes.txt"}}}, {ID: "m2", Role: protocol.ChatRoleAssistant, CreatedAt: 1_700_000_030_000, Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: "Running them now."}}}, }}, }, native: protocol.ChatExportFile{Name: exportClaudeID + ".jsonl", Mime: "application/x-ndjson", Content: "{}\n"}} ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store}) if err := store.RecordOperatorSession(ctx, exportClaudeID, "/work/my repo", "Fix tests", protocol.ChatSessionTagOperator); err != nil { t.Fatal(err) } if err := store.SetOperatorSessionBackend(ctx, exportClaudeID, backend); err != nil { t.Fatal(err) } send := func(message protocol.Message) protocol.Message { writeChat(t, ctx, conn, message) for { var reply protocol.Message if err := readTestFrame(ctx, conn, &reply); err != nil { t.Fatalf("read reply to %s: %v", message.ID, err) } if reply.ID == message.ID { return reply } } } return broker, ctx, send } func TestChatExportMarkdownFromHistory(t *testing.T) { _, _, send := exportFixture(t, "claude") reply := send(protocol.Message{Type: protocol.ChatExport, ID: "x1", ChatExport: &protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "markdown"}}) if reply.Type != protocol.ChatExport || reply.ChatExportFile == nil { t.Fatalf("reply = %+v", reply) } file := reply.ChatExportFile if file.Name != "Fix-tests-"+exportClaudeID+".md" || file.Mime != "text/markdown" || file.Format != "markdown" || file.Messages != 4 || file.Truncated { t.Fatalf("file = %+v", file) } md := file.Content for _, want := range []string{ "# Fix tests\n", "- Session ID: `" + exportClaudeID + "`\n", "- Harness: Claude Code\n", "- Directory: `/work/my repo`\n", "- Resume: `cd '/work/my repo' && claude --resume " + exportClaudeID + "`\n", "## User · 2023-11-14 22:13:20 UTC · Pixel\n\nRun the tests\n", "- Attachment: notes.txt", "## Assistant · 2023-11-14 22:13:50 UTC\n\nRunning them now.\n\nAll tests pass.\n", "- Tool `Bash` (completed): Run the tests", "## Agent report · 2023-11-14 22:14:50 UTC\n\nSubagent found two files.\n", } { if !strings.Contains(md, want) { t.Fatalf("markdown lacks %q:\n%s", want, md) } } if strings.Index(md, "Run the tests\n") > strings.Index(md, "Running them now.") || strings.Index(md, "All tests pass.") > strings.Index(md, "Subagent found") { t.Fatalf("markdown is not oldest first:\n%s", md) } for _, absent := range []string{"secret thinking", "huge tool output"} { if strings.Contains(md, absent) { t.Fatalf("markdown includes %q", absent) } } } func TestChatExportJSONStructure(t *testing.T) { _, _, send := exportFixture(t, "codex") reply := send(protocol.Message{Type: protocol.ChatExport, ID: "x2", ChatExport: &protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "json"}}) if reply.ChatExportFile == nil || reply.ChatExportFile.Mime != "application/json" || !strings.HasSuffix(reply.ChatExportFile.Name, ".json") { t.Fatalf("reply = %+v", reply) } var document chatExportDocument if err := json.Unmarshal([]byte(reply.ChatExportFile.Content), &document); err != nil { t.Fatal(err) } if document.Session.ID != exportClaudeID || document.Session.Backend != "codex" || document.Session.Harness != "Codex" || document.Session.ResumeCommand != "cd '/work/my repo' && codex resume "+exportClaudeID { t.Fatalf("session = %+v", document.Session) } if document.ExportedAt == "" || len(document.Messages) != 4 { t.Fatalf("document = %+v", document) } ids := []string{} for _, message := range document.Messages { ids = append(ids, message.ID) } if strings.Join(ids, ",") != "m1,m2,m3,m4" { t.Fatalf("order = %v", ids) } tool := document.Messages[2].Tools if len(tool) != 1 || tool[0].Name != "Bash" || tool[0].Status != "completed" || tool[0].Summary != "Run the tests" { t.Fatalf("tools = %+v", tool) } if document.Messages[3].Kind != protocol.ChatMessageKindAgentReport || document.Messages[0].CreatedAt != "2023-11-14T22:13:20Z" || document.Messages[0].Attachments[0] != "notes.txt" { t.Fatalf("messages = %+v", document.Messages) } } func TestChatExportRefusals(t *testing.T) { _, _, send := exportFixture(t, "opencode") for _, c := range []struct { name string request protocol.ChatExportRequest want string }{ {"unknown session", protocol.ChatExportRequest{SessionID: "ses_unknown", Format: "markdown"}, "is not an operator chat session"}, {"invalid id", protocol.ChatExportRequest{SessionID: "../etc", Format: "markdown"}, "a valid chat session id is required"}, {"bad format", protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "pdf"}, "must be markdown, json or native"}, {"no native export", protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "native"}, "OpenCode has no native session export"}, } { request := c.request reply := send(protocol.Message{Type: protocol.ChatExport, ID: "r-" + c.name, ChatExport: &request}) if reply.Type != protocol.Error || !strings.Contains(reply.Error, c.want) { t.Fatalf("%s: reply = %+v", c.name, reply) } } } func TestChatExportNativeForClaude(t *testing.T) { _, _, send := exportFixture(t, "claude") reply := send(protocol.Message{Type: protocol.ChatExport, ID: "n1", ChatExport: &protocol.ChatExportRequest{SessionID: exportClaudeID, Format: "native"}}) file := reply.ChatExportFile if file == nil || file.Format != "native" || file.Name != exportClaudeID+".jsonl" || file.Content != "{}\n" || file.SessionID != exportClaudeID { t.Fatalf("reply = %+v", reply) } } func TestChatResumeCommandPerBackend(t *testing.T) { const uuid = "0b6f1c2e-1111-4222-8333-444455556666" for _, c := range []struct{ backend, id, dir, want string }{ {"claude", uuid, "/work/a", "cd /work/a && claude --resume " + uuid}, {"codex", uuid, "/work/a", "cd /work/a && codex resume " + uuid}, {"opencode", "ses_abc123", "/work/a", "cd /work/a && opencode --session ses_abc123"}, {"", "ses_abc123", "", "opencode --session ses_abc123"}, {"claude", uuid, "/work/it's here", `cd '/work/it'\''s here' && claude --resume ` + uuid}, {"pi", uuid, "/work/a", ""}, {"claude", "not an id; rm -rf /", "/work/a", ""}, } { if got := chatResumeCommand(c.backend, c.id, c.dir); got != c.want { t.Fatalf("%s %q: got %q want %q", c.backend, c.dir, got, c.want) } } } func TestChatSessionsCarryResumeCommand(t *testing.T) { store := newOperatorStore(t) broker := scriptedChat() broker.sessions = []protocol.ChatSession{{ID: exportClaudeID, Directory: "/work/a"}} ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store}) if err := store.RecordOperatorSession(ctx, exportClaudeID, "/work/a", "A", protocol.ChatSessionTagOperator); err != nil { t.Fatal(err) } if err := store.SetOperatorSessionBackend(ctx, exportClaudeID, "claude"); err != nil { t.Fatal(err) } writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "l1"}) reply := readUntil(t, ctx, conn, protocol.ChatSessions) if len(reply.ChatSessions) != 1 { t.Fatalf("sessions = %+v", reply.ChatSessions) } row := reply.ChatSessions[0] if row.ResumeCommand != "cd /work/a && claude --resume "+exportClaudeID || !row.NativeExport { t.Fatalf("row = %+v", row) } }