Chat info: Session section with native id, resume command and export
The chat information sheet gains a Session section: the harness's native session id (copy), harness, directory, a verified resume command (copy) and Export conversation (Markdown), Export JSON and, for Claude Code, Export native session (the JSONL transcript). Server: chat_sessions rows carry resume_command and native_export; new chat_export command builds Markdown/JSON from the same paged history chat_messages serves (bounded at 8 MiB), refuses non-operator sessions. App: exports go through the artifact file bridge (web download, share sheet on phones).
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// NativeExportLimit bounds the Claude Code session file chat_export returns.
|
||||
const NativeExportLimit = 8 << 20
|
||||
|
||||
// NativeExport returns Claude Code's own JSONL transcript for one session, the
|
||||
// file `claude --resume` reads. It is a plain read of the retained file; no CLI
|
||||
// process is started.
|
||||
func (c *Chat) NativeExport(ctx context.Context, id string) (protocol.ChatExportFile, error) {
|
||||
path := findTranscriptFile(id)
|
||||
if path == "" {
|
||||
return protocol.ChatExportFile{}, errors.New("Claude Code has not written a transcript for session " + id + " yet")
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
defer file.Close()
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return protocol.ChatExportFile{}, errors.New("the Claude Code transcript is not a regular file")
|
||||
}
|
||||
if info.Size() > NativeExportLimit {
|
||||
return protocol.ChatExportFile{}, fmt.Errorf("the Claude Code transcript is %d bytes, over the %d byte export limit; it is at %s on the server", info.Size(), NativeExportLimit, path)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(file, NativeExportLimit+1))
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
if len(data) > NativeExportLimit {
|
||||
return protocol.ChatExportFile{}, fmt.Errorf("the Claude Code transcript grew past the %d byte export limit", NativeExportLimit)
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
return protocol.ChatExportFile{}, errors.New("the Claude Code transcript is not valid UTF-8")
|
||||
}
|
||||
return protocol.ChatExportFile{
|
||||
SessionID: id,
|
||||
Format: protocol.ChatExportNative,
|
||||
Name: id + ".jsonl",
|
||||
Mime: "application/x-ndjson",
|
||||
Content: string(data),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestNativeExportReturnsTheSessionJSONL(t *testing.T) {
|
||||
config := t.TempDir()
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", config)
|
||||
id := "0b6f1c2e-1111-4222-8333-444455556666"
|
||||
project := filepath.Join(config, "projects", "-work-a")
|
||||
if err := os.MkdirAll(project, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := `{"type":"user","uuid":"u1"}` + "\n" + `{"type":"assistant","uuid":"a1"}` + "\n"
|
||||
if err := os.WriteFile(filepath.Join(project, id+".jsonl"), []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat := New(context.Background())
|
||||
defer chat.Close()
|
||||
file, err := chat.NativeExport(context.Background(), id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if file.Name != id+".jsonl" || file.Mime != "application/x-ndjson" || file.Content != body || file.Format != protocol.ChatExportNative {
|
||||
t.Fatalf("native export = %+v", file)
|
||||
}
|
||||
if _, err := chat.NativeExport(context.Background(), "0b6f1c2e-1111-4222-8333-000000000000"); err == nil || !strings.Contains(err.Error(), "has not written a transcript") {
|
||||
t.Fatalf("missing transcript error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,12 @@ const (
|
||||
// ChatRename records the operator's shared chat title on the server. Unlike
|
||||
// a local override, every browser and device then lists the same name.
|
||||
ChatRename = "chat_rename"
|
||||
// ChatExport returns one operator chat as a file the client saves or
|
||||
// shares. The body is ChatExportRequest and the reply carries
|
||||
// ChatExportFile: a Markdown or JSON transcript built from the same history
|
||||
// chat_messages serves, or the harness's own session file where one exists
|
||||
// (ChatSession.NativeExport).
|
||||
ChatExport = "chat_export"
|
||||
// ChatBackends lists the installed chat harnesses the server can create a
|
||||
// session on. The reply is a bounded array of backend names.
|
||||
ChatBackends = "chat_backends"
|
||||
@@ -280,6 +286,41 @@ type ChatSession struct {
|
||||
// epoch-millisecond time it was set, 0 while unstarred.
|
||||
Starred bool `json:"starred,omitempty"`
|
||||
StarredAt int64 `json:"starred_at,omitempty"`
|
||||
// ResumeCommand is the shell command that continues this session in a
|
||||
// terminal on the server machine with the harness's own CLI, run in the
|
||||
// session's directory. ID is the harness's native session id (Claude Code
|
||||
// session UUID, Codex thread id, OpenCode ses_ id). Empty when the harness
|
||||
// has no verified resume option.
|
||||
ResumeCommand string `json:"resume_command,omitempty"`
|
||||
// NativeExport says chat_export with format "native" can return the
|
||||
// harness's own session file (today: Claude Code's JSONL transcript).
|
||||
NativeExport bool `json:"native_export,omitempty"`
|
||||
}
|
||||
|
||||
// Chat export formats accepted by chat_export.
|
||||
const (
|
||||
ChatExportMarkdown = "markdown"
|
||||
ChatExportJSON = "json"
|
||||
ChatExportNative = "native"
|
||||
)
|
||||
|
||||
// ChatExportRequest is the chat_export body.
|
||||
type ChatExportRequest struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Format string `json:"format"`
|
||||
}
|
||||
|
||||
// ChatExportFile is the chat_export reply: one named, typed text file. Messages
|
||||
// counts the transcript messages included (0 for a native file). Truncated says
|
||||
// older history was left out to keep the file within the server's bound.
|
||||
type ChatExportFile struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Format string `json:"format"`
|
||||
Name string `json:"name"`
|
||||
Mime string `json:"mime"`
|
||||
Content string `json:"content"`
|
||||
Messages int `json:"messages,omitempty"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
}
|
||||
|
||||
// ChatCloseResult reports the outcome of a chat_close: the session id, the
|
||||
|
||||
@@ -203,6 +203,9 @@ type Message struct {
|
||||
ChatAnswer *ChatAnswerRequest `json:"chat_answer,omitempty"`
|
||||
// ChatRename is the chat_rename body; the reply echoes the updated session.
|
||||
ChatRename *ChatRenameRequest `json:"chat_rename,omitempty"`
|
||||
// ChatExport is the chat_export body and ChatExportFile its reply.
|
||||
ChatExport *ChatExportRequest `json:"chat_export,omitempty"`
|
||||
ChatExportFile *ChatExportFile `json:"chat_export_file,omitempty"`
|
||||
// ChatBackends is the chat_backends reply: the installed harnesses a new
|
||||
// chat can use.
|
||||
ChatBackends []string `json:"chat_backends,omitempty"`
|
||||
|
||||
@@ -206,6 +206,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatRename:
|
||||
handleChatRename(ctx, request, registry, write)
|
||||
return true
|
||||
case protocol.ChatExport:
|
||||
handleChatExport(ctx, request, broker, registry, write)
|
||||
return true
|
||||
case protocol.ChatBackends:
|
||||
handleChatBackends(request, broker, write)
|
||||
return true
|
||||
|
||||
@@ -148,5 +148,5 @@ func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSess
|
||||
out.Starred = true
|
||||
out.StarredAt = session.StarredAt
|
||||
}
|
||||
return out
|
||||
return withChatHandoff(out)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claude"
|
||||
"git.a-wan.net/alan/pipelines/internal/codex"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatExportLimit bounds an exported transcript. Older pages stop being read
|
||||
// once the newest history already fills it, and the file says so.
|
||||
const chatExportLimit = 8 << 20
|
||||
|
||||
// chatExportPageLimit bounds how many history pages one export reads.
|
||||
const chatExportPageLimit = 500
|
||||
|
||||
// chatNativeExporter is a harness that can hand back its own session file
|
||||
// cheaply (Claude Code's JSONL transcript).
|
||||
type chatNativeExporter interface {
|
||||
NativeExport(ctx context.Context, sessionID string) (protocol.ChatExportFile, error)
|
||||
}
|
||||
|
||||
// NativeExport routes to the session's harness; only harnesses with a cheap
|
||||
// native file implement it.
|
||||
func (m *chatManager) NativeExport(ctx context.Context, sessionID string) (protocol.ChatExportFile, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
exporter, ok := adapter.(chatNativeExporter)
|
||||
if !ok {
|
||||
return protocol.ChatExportFile{}, errors.New("this chat's harness has no native session export")
|
||||
}
|
||||
return exporter.NativeExport(ctx, sessionID)
|
||||
}
|
||||
|
||||
// chatBackendName is the harness's display name.
|
||||
func chatBackendName(backend string) string {
|
||||
switch backend {
|
||||
case claude.Backend:
|
||||
return "Claude Code"
|
||||
case codex.Backend:
|
||||
return "Codex"
|
||||
case "", "opencode":
|
||||
return "OpenCode"
|
||||
default:
|
||||
return backend
|
||||
}
|
||||
}
|
||||
|
||||
// chatResumeCommand is the terminal command that continues a session with the
|
||||
// harness's own CLI in its directory. Each form was checked against the CLI's
|
||||
// --help: `claude --resume <id>` (Claude Code 2.1), `codex resume <id>` (Codex
|
||||
// CLI 0.164) and `opencode --session <id>` (OpenCode 2.0).
|
||||
func chatResumeCommand(backend, sessionID, directory string) string {
|
||||
if !validChatSessionID(sessionID) {
|
||||
return ""
|
||||
}
|
||||
var command string
|
||||
switch backend {
|
||||
case claude.Backend:
|
||||
command = "claude --resume " + sessionID
|
||||
case codex.Backend:
|
||||
command = "codex resume " + sessionID
|
||||
case "", "opencode":
|
||||
command = "opencode --session " + sessionID
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
if strings.TrimSpace(directory) == "" {
|
||||
return command
|
||||
}
|
||||
return "cd " + shellQuote(directory) + " && " + command
|
||||
}
|
||||
|
||||
// chatNativeExportAvailable says chat_export format=native is offered.
|
||||
func chatNativeExportAvailable(backend string) bool { return backend == claude.Backend }
|
||||
|
||||
// withChatHandoff fills the session's resume command and native export flag.
|
||||
func withChatHandoff(session protocol.ChatSession) protocol.ChatSession {
|
||||
session.ResumeCommand = chatResumeCommand(session.Backend, session.ID, session.Directory)
|
||||
session.NativeExport = chatNativeExportAvailable(session.Backend)
|
||||
return session
|
||||
}
|
||||
|
||||
// shellQuote leaves a plain path as it is and single-quotes anything else.
|
||||
func shellQuote(value string) string {
|
||||
plain := value != ""
|
||||
for _, r := range value {
|
||||
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("/._-+,:@%=", r)) {
|
||||
plain = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if plain {
|
||||
return value
|
||||
}
|
||||
return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'"
|
||||
}
|
||||
|
||||
// handleChatExport answers chat_export for one recorded operator session.
|
||||
func handleChatExport(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
|
||||
fail := func(message string) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: message})
|
||||
}
|
||||
if broker == nil {
|
||||
fail("chat is not configured on this server")
|
||||
return
|
||||
}
|
||||
if registry == nil {
|
||||
fail("operator session registry is not configured on this server")
|
||||
return
|
||||
}
|
||||
body := request.ChatExport
|
||||
if body == nil || !validChatSessionID(body.SessionID) {
|
||||
fail("a valid chat session id is required")
|
||||
return
|
||||
}
|
||||
format := strings.TrimSpace(body.Format)
|
||||
if format == "" {
|
||||
format = protocol.ChatExportMarkdown
|
||||
}
|
||||
switch format {
|
||||
case protocol.ChatExportMarkdown, protocol.ChatExportJSON, protocol.ChatExportNative:
|
||||
default:
|
||||
fail("chat export format must be markdown, json or native")
|
||||
return
|
||||
}
|
||||
row, found, err := registry.OperatorSession(ctx, body.SessionID)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
fail("session " + body.SessionID + " is not an operator chat session")
|
||||
return
|
||||
}
|
||||
session := withChatHandoff(chatSessionFromOperator(row))
|
||||
var file protocol.ChatExportFile
|
||||
if format == protocol.ChatExportNative {
|
||||
if !session.NativeExport {
|
||||
fail(chatBackendName(session.Backend) + " has no native session export")
|
||||
return
|
||||
}
|
||||
exporter, ok := broker.(chatNativeExporter)
|
||||
if !ok {
|
||||
fail("native session export is not available on this server")
|
||||
return
|
||||
}
|
||||
file, err = exporter.NativeExport(ctx, body.SessionID)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
} else {
|
||||
messages, truncated, err := chatExportHistory(ctx, broker, body.SessionID)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
transcript := chatExportTranscript{Session: session, Messages: messages, Truncated: truncated, ExportedAt: time.Now().UTC()}
|
||||
file, err = transcript.file(format)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
file.SessionID = body.SessionID
|
||||
file.Format = format
|
||||
_ = write(protocol.Message{Type: protocol.ChatExport, ID: request.ID, ChatExportFile: &file})
|
||||
}
|
||||
|
||||
// chatExportHistory reads the session's whole history, newest page first as
|
||||
// chat_messages serves it, and returns it oldest first. It stops reading older
|
||||
// pages once the bound is reached and reports that older turns were left out.
|
||||
func chatExportHistory(ctx context.Context, broker chatBroker, sessionID string) ([]protocol.ChatMessage, bool, error) {
|
||||
var pages [][]protocol.ChatMessage
|
||||
seen := map[string]bool{}
|
||||
size := 0
|
||||
cursor := ""
|
||||
for page := 0; page < chatExportPageLimit; page++ {
|
||||
history, err := broker.Messages(ctx, sessionID, 100, cursor)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
kept := make([]protocol.ChatMessage, 0, len(history.Messages))
|
||||
for _, message := range history.Messages {
|
||||
if message.ID != "" && seen[message.ID] {
|
||||
continue
|
||||
}
|
||||
seen[message.ID] = true
|
||||
kept = append(kept, message)
|
||||
size += chatMessageSize(message)
|
||||
}
|
||||
pages = append(pages, kept)
|
||||
next := history.NextCursor
|
||||
if next == "" || next == cursor {
|
||||
return flattenChatPages(pages), false, nil
|
||||
}
|
||||
if size >= chatExportLimit {
|
||||
return flattenChatPages(pages), true, nil
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
return flattenChatPages(pages), true, nil
|
||||
}
|
||||
|
||||
func flattenChatPages(pages [][]protocol.ChatMessage) []protocol.ChatMessage {
|
||||
out := []protocol.ChatMessage{}
|
||||
for index := len(pages) - 1; index >= 0; index-- {
|
||||
out = append(out, pages[index]...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func chatMessageSize(message protocol.ChatMessage) int {
|
||||
size := 0
|
||||
for _, part := range message.Parts {
|
||||
size += len(part.Text) + len(part.Name) + 64
|
||||
}
|
||||
return size
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatExportTranscript is one session's history ready to be written as a file.
|
||||
type chatExportTranscript struct {
|
||||
Session protocol.ChatSession
|
||||
Messages []protocol.ChatMessage
|
||||
Truncated bool
|
||||
ExportedAt time.Time
|
||||
}
|
||||
|
||||
// chatExportEntry is one message as both formats describe it: the visible
|
||||
// text, attachments by name and each tool call summarised to one line.
|
||||
// Reasoning and full tool output are left out.
|
||||
type chatExportEntry struct {
|
||||
ID string `json:"id"`
|
||||
Role string `json:"role"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
CreatedAt string `json:"created_at,omitempty"`
|
||||
Client string `json:"client,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Attachments []string `json:"attachments,omitempty"`
|
||||
Tools []chatExportTool `json:"tools,omitempty"`
|
||||
}
|
||||
|
||||
type chatExportTool struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type chatExportSession struct {
|
||||
ID string `json:"id"`
|
||||
Backend string `json:"backend"`
|
||||
Harness string `json:"harness"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Directory string `json:"directory,omitempty"`
|
||||
ResumeCommand string `json:"resume_command,omitempty"`
|
||||
}
|
||||
|
||||
type chatExportDocument struct {
|
||||
Session chatExportSession `json:"session"`
|
||||
ExportedAt string `json:"exported_at"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
Messages []chatExportEntry `json:"messages"`
|
||||
}
|
||||
|
||||
func (t chatExportTranscript) entries() []chatExportEntry {
|
||||
out := make([]chatExportEntry, 0, len(t.Messages))
|
||||
for _, message := range t.Messages {
|
||||
entry := chatExportEntry{
|
||||
ID: message.ID, Role: message.Role, Kind: message.Kind,
|
||||
CreatedAt: chatExportTime(message.CreatedAt), Client: message.Client, Model: message.Model,
|
||||
}
|
||||
var text []string
|
||||
for _, part := range message.Parts {
|
||||
switch part.Type {
|
||||
case protocol.ChatPartText:
|
||||
if strings.TrimSpace(part.Text) != "" {
|
||||
text = append(text, strings.TrimRight(part.Text, "\n"))
|
||||
}
|
||||
case protocol.ChatPartFile:
|
||||
name := strings.TrimSpace(part.Name)
|
||||
if name == "" {
|
||||
name = "attachment"
|
||||
}
|
||||
entry.Attachments = append(entry.Attachments, name)
|
||||
case protocol.ChatPartTool:
|
||||
entry.Tools = append(entry.Tools, chatExportToolFor(part))
|
||||
}
|
||||
}
|
||||
entry.Text = strings.Join(text, "\n\n")
|
||||
if entry.Text == "" && len(entry.Attachments) == 0 && len(entry.Tools) == 0 {
|
||||
continue
|
||||
}
|
||||
out = append(out, entry)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (t chatExportTranscript) session() chatExportSession {
|
||||
backend := t.Session.Backend
|
||||
if backend == "" {
|
||||
backend = "opencode"
|
||||
}
|
||||
return chatExportSession{
|
||||
ID: t.Session.ID, Backend: backend, Harness: chatBackendName(backend),
|
||||
Title: t.Session.Title, Directory: t.Session.Directory, ResumeCommand: t.Session.ResumeCommand,
|
||||
}
|
||||
}
|
||||
|
||||
// file writes the transcript in one of the two transcript formats.
|
||||
func (t chatExportTranscript) file(format string) (protocol.ChatExportFile, error) {
|
||||
entries := t.entries()
|
||||
base := chatExportBaseName(t.Session)
|
||||
if format == protocol.ChatExportJSON {
|
||||
document := chatExportDocument{Session: t.session(), ExportedAt: t.ExportedAt.Format(time.RFC3339), Truncated: t.Truncated, Messages: entries}
|
||||
data, err := json.MarshalIndent(document, "", " ")
|
||||
if err != nil {
|
||||
return protocol.ChatExportFile{}, err
|
||||
}
|
||||
return protocol.ChatExportFile{Name: base + ".json", Mime: "application/json", Content: string(data) + "\n", Messages: len(entries), Truncated: t.Truncated}, nil
|
||||
}
|
||||
return protocol.ChatExportFile{Name: base + ".md", Mime: "text/markdown", Content: t.markdown(entries), Messages: len(entries), Truncated: t.Truncated}, nil
|
||||
}
|
||||
|
||||
func (t chatExportTranscript) markdown(entries []chatExportEntry) string {
|
||||
session := t.session()
|
||||
var b strings.Builder
|
||||
title := strings.TrimSpace(session.Title)
|
||||
if title == "" {
|
||||
title = "Chat"
|
||||
}
|
||||
fmt.Fprintf(&b, "# %s\n\n", exportOneLine(title))
|
||||
fmt.Fprintf(&b, "- Session ID: `%s`\n", session.ID)
|
||||
fmt.Fprintf(&b, "- Harness: %s\n", session.Harness)
|
||||
if session.Directory != "" {
|
||||
fmt.Fprintf(&b, "- Directory: `%s`\n", session.Directory)
|
||||
}
|
||||
if session.ResumeCommand != "" {
|
||||
fmt.Fprintf(&b, "- Resume: `%s`\n", session.ResumeCommand)
|
||||
}
|
||||
fmt.Fprintf(&b, "- Exported: %s\n", t.ExportedAt.Format("2006-01-02 15:04:05 UTC"))
|
||||
if t.Truncated {
|
||||
b.WriteString("\n> Older messages were left out to keep this export within the server's size limit.\n")
|
||||
}
|
||||
previous := ""
|
||||
for _, entry := range entries {
|
||||
heading := chatExportHeading(entry)
|
||||
group := heading + "\x00" + entry.Client
|
||||
if group != previous {
|
||||
b.WriteString("\n## " + heading)
|
||||
if entry.CreatedAt != "" {
|
||||
b.WriteString(" · " + strings.Replace(strings.TrimSuffix(entry.CreatedAt, "Z"), "T", " ", 1) + " UTC")
|
||||
}
|
||||
if entry.Client != "" {
|
||||
b.WriteString(" · " + exportOneLine(entry.Client))
|
||||
}
|
||||
b.WriteString("\n")
|
||||
previous = group
|
||||
}
|
||||
if entry.Text != "" {
|
||||
b.WriteString("\n" + entry.Text + "\n")
|
||||
}
|
||||
for _, name := range entry.Attachments {
|
||||
b.WriteString("\n- Attachment: " + exportOneLine(name) + "\n")
|
||||
}
|
||||
if len(entry.Tools) > 0 {
|
||||
b.WriteString("\n")
|
||||
for _, tool := range entry.Tools {
|
||||
b.WriteString(chatExportToolLine(tool) + "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func chatExportHeading(entry chatExportEntry) string {
|
||||
switch {
|
||||
case entry.Kind == protocol.ChatMessageKindAgentReport:
|
||||
return "Agent report"
|
||||
case entry.Kind == protocol.ChatMessageKindNotice:
|
||||
return "Notice"
|
||||
case entry.Role == protocol.ChatRoleUser:
|
||||
return "User"
|
||||
default:
|
||||
return "Assistant"
|
||||
}
|
||||
}
|
||||
|
||||
func chatExportToolLine(tool chatExportTool) string {
|
||||
line := "- Tool `" + tool.Name + "`"
|
||||
if tool.Status != "" {
|
||||
line += " (" + tool.Status + ")"
|
||||
}
|
||||
if tool.Summary != "" {
|
||||
line += ": " + tool.Summary
|
||||
}
|
||||
if tool.Error != "" {
|
||||
line += " — error: " + tool.Error
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
// chatExportToolSummaryKeys are the input fields that name what a tool call
|
||||
// did, in preference order.
|
||||
var chatExportToolSummaryKeys = []string{"description", "command", "file_path", "filePath", "path", "pattern", "query", "url", "subagent_type", "prompt"}
|
||||
|
||||
func chatExportToolFor(part protocol.ChatPart) chatExportTool {
|
||||
name := strings.TrimSpace(part.Name)
|
||||
if name == "" {
|
||||
name = "tool"
|
||||
}
|
||||
tool := chatExportTool{Name: exportOneLine(name)}
|
||||
if part.State == nil {
|
||||
return tool
|
||||
}
|
||||
tool.Status = part.State.Status
|
||||
if part.State.Error != nil {
|
||||
tool.Error = exportClip(exportOneLine(part.State.Error.Message), 200)
|
||||
}
|
||||
var input map[string]any
|
||||
if json.Unmarshal(part.State.Input, &input) == nil {
|
||||
for _, key := range chatExportToolSummaryKeys {
|
||||
if value, ok := input[key].(string); ok && strings.TrimSpace(value) != "" {
|
||||
tool.Summary = exportClip(exportOneLine(value), 160)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return tool
|
||||
}
|
||||
|
||||
func chatExportTime(ms int64) string {
|
||||
if ms <= 0 {
|
||||
return ""
|
||||
}
|
||||
return time.UnixMilli(ms).UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
var chatExportUnsafeName = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
|
||||
|
||||
// chatExportBaseName is a portable file name from the title and session id.
|
||||
func chatExportBaseName(session protocol.ChatSession) string {
|
||||
title := strings.Trim(chatExportUnsafeName.ReplaceAllString(strings.TrimSpace(session.Title), "-"), "-.")
|
||||
title = exportClip(title, 60)
|
||||
if title == "" {
|
||||
return "chat-" + session.ID
|
||||
}
|
||||
return title + "-" + session.ID
|
||||
}
|
||||
|
||||
var exportWhitespace = regexp.MustCompile(`\s+`)
|
||||
|
||||
func exportOneLine(value string) string {
|
||||
return strings.TrimSpace(exportWhitespace.ReplaceAllString(value, " "))
|
||||
}
|
||||
|
||||
func exportClip(value string, limit int) string {
|
||||
if utf8.RuneCountInString(value) <= limit {
|
||||
return value
|
||||
}
|
||||
runes := []rune(value)
|
||||
return string(runes[:limit-1]) + "…"
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"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 := wsjson.Read(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)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,7 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
|
||||
session.ClosedAt = operator.ClosedAt
|
||||
session.Starred = operator.StarredAt > 0
|
||||
session.StarredAt = operator.StarredAt
|
||||
session = withChatHandoff(session)
|
||||
response.ChatSessions = append(response.ChatSessions, session)
|
||||
}
|
||||
_ = write(response)
|
||||
|
||||
Reference in New Issue
Block a user