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,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]) + "…"
|
||||
}
|
||||
Reference in New Issue
Block a user