session export: write only session.html, retire the markdown export

A stage's session was exported twice, as session.md and session.html, and both
files were presented. It is now one html file; the markdown export is retired.

- internal/stage/session_export.go: ExportSession renders and writes exactly one
  file, session.html, via writeSessionFile; renderSessionMarkdown and its helpers
  are gone; SessionExportResult carries HTML/HTMLBytes only. The source read, the
  8 MiB source / 2 MiB rendered bounds, the truncation banner, the
  never-overwrite rule and the honest empty-session handling are unchanged.
- internal/protocol/runs.go: SessionExport drops markdown/markdown_bytes (a
  record written before the change still decodes; unknown fields are ignored),
  and adds LegacySessionMarkdownArtifact with RunStep.PresentedArtifacts(), the
  one Go rule that hides the retired session.md from every artifact listing.
- internal/server/runner.go: evidence.Markdown/MarkdownBytes are no longer copied.
- internal/tui: the artifacts panel, the recorded count and the per-visit summary
  derive from PresentedArtifacts(), so the terminal never lists session.md.
- web/src/app.js: the spike's renderArtifacts applies the same filter.
- android: the Session section is the html export alone in a WebView — SessionView,
  the Markdown/HTML toggle and the session markdown path are removed;
  presentedArtifacts(step) filters the retired session.md out of the per-visit
  gallery, the run gallery and its count, the verdict/selection lists and the
  timeline indicator; data/protocol SessionExport drops the markdown fields.
- Tests pin the single html file, prove no session.md is written and that a
  pre-existing one is neither overwritten nor presented, and prove a legacy
  export record still loads and its session.md is hidden.

The legacy session.md of an older run stays on disk (dated evidence); it is only
no longer produced and no longer presented.

Checks (macOS, Go 1.24, Android Gradle 8.11.1, 18 Oct 2026): gofmt -l . prints
nothing; go build ./... && go vet ./... clean; go test ./internal/... ./cmd/...
-> 19 packages ok, 0 failures; node --check web/src/app.js ok and node --test
web/test -> 20/20; gradle --offline --no-daemon :app:assembleDebug
:app:testDebugUnitTest -> BUILD SUCCESSFUL.

Packaged references checked: internal/author/skill/references/delivery.md and
operations.md both described the session.md+session.html pair, so both are
updated here to describe the single session.html export and the retired, hidden
session.md. README.md and internal/author/skill/SKILL.md carry no session.md
reference and install.go's managed inventory is unchanged (no reference added or
removed). docs/notes/session-html-only.md records the remaining stale shared
documentation (docs/stage-artifacts.md, docs/app-integration-verification.md) for
the docs-fold writer; shared docs are not edited by this item.
This commit is contained in:
2026-10-18 10:06:49 +01:00
parent 5a4cfc2e9c
commit 95362134aa
25 changed files with 666 additions and 571 deletions
+64 -222
View File
@@ -16,13 +16,18 @@ import (
)
// Session file export bounds. A stage's session is written under its own
// artifacts directory in markdown and html so the existing artifact listing and
// artifacts directory as one html file so the existing artifact listing and
// serving paths find it with no special casing. The source read is capped at
// SessionExportSourceLimit and each rendered file at SessionExportFileLimit, so
// the pair adds at most ~4 MiB per step, inside the artifact scan limits.
// SessionExportSourceLimit and the rendered file at SessionExportFileLimit, so
// the export adds at most ~2 MiB per step, inside the artifact scan limits.
const (
SessionMarkdownFile = "session.md"
SessionHTMLFile = "session.html"
// SessionHTMLFile is the one session export a stage writes.
SessionHTMLFile = "session.html"
// SessionMarkdownFile is the retired markdown session export name. Nothing
// writes it any more; a run recorded before the HTML-only change may still
// have it on disk, where it is dated evidence that is never presented. It is
// the protocol's one definition of the retired name, not a second copy.
SessionMarkdownFile = protocol.LegacySessionMarkdownArtifact
// SessionExportSourceLimit is the native session read cap; it is the one
// opencode.MaxSessionExport value, not a second copy.
SessionExportSourceLimit = opencode.MaxSessionExport
@@ -45,36 +50,32 @@ type SessionExportRequest struct {
Model string
}
// SessionExportResult is the outcome of one session export. Markdown/HTML are
// the written file names, their byte sizes, the decoded message count, the
// source, whether either file or the source was truncated and a sanitized
// diagnostic (for example a skipped overwrite).
// SessionExportResult is the outcome of one session export: the written html
// file name, its byte size, the decoded message count, the source, whether the
// source or the rendered file was truncated and a sanitized diagnostic (for
// example a skipped overwrite).
type SessionExportResult struct {
Markdown string
HTML string
MarkdownBytes int64
HTMLBytes int64
Messages int
Source string
Truncated bool
Diagnostic string
HTML string
HTMLBytes int64
Messages int
Source string
Truncated bool
Diagnostic string
}
const (
// sessionExportSource is the recorded source of a native-export readback.
sessionExportSource = "native_export"
// markdownTruncationBanner and htmlTruncationBanner are the visible labels a
// truncated export carries near its start and end so it is never mistaken for
// the whole session.
markdownTruncationBanner = "\n> **TRUNCATED**: this exported session is not the whole session; it was cut at the export size cap.\n"
htmlTruncationBanner = "<p style=\"padding:0.5rem;border:1px solid #b00;color:#900\"><strong>TRUNCATED</strong>: this exported session is not the whole session; it was cut at the export size cap.</p>\n"
// htmlTruncationBanner is the visible label a truncated export carries near
// its start and end so it is never mistaken for the whole session.
htmlTruncationBanner = "<p style=\"padding:0.5rem;border:1px solid #b00;color:#900\"><strong>TRUNCATED</strong>: this exported session is not the whole session; it was cut at the export size cap.</p>\n"
)
// ExportSession reads the stage's session read-only through the native export
// path, renders it to bounded markdown and html and writes both files
// atomically into the step's artifacts directory, refusing to overwrite an
// existing file. It returns a sanitized error and writes nothing when the read
// fails; it never mutates, resumes, interrupts or deletes the session.
// path, renders it to one bounded html file and writes it atomically into the
// step's artifacts directory, refusing to overwrite an existing file. It returns
// a sanitized error and writes nothing when the read fails; it never mutates,
// resumes, interrupts or deletes the session.
func ExportSession(ctx context.Context, request SessionExportRequest) (SessionExportResult, error) {
if !opencode.ValidSessionID(request.SessionID) {
return SessionExportResult{}, fmt.Errorf("session export: invalid session ID")
@@ -86,103 +87,62 @@ func ExportSession(ctx context.Context, request SessionExportRequest) (SessionEx
if err != nil {
return SessionExportResult{}, fmt.Errorf("session export: %s", RedactEvidence(err.Error()))
}
markdown, markdownTruncated := renderSessionMarkdown(session, request)
htmlDoc, htmlTruncated := renderSessionHTML(session, request)
result := SessionExportResult{
Markdown: SessionMarkdownFile,
HTML: SessionHTMLFile,
Messages: len(session.Messages),
Source: sessionExportSource,
Truncated: session.Truncated || markdownTruncated || htmlTruncated,
Diagnostic: "",
HTML: SessionHTMLFile,
Messages: len(session.Messages),
Source: sessionExportSource,
Truncated: session.Truncated || htmlTruncated,
}
written, diagnostic, err := writeSessionPair(request.ArtifactsDir, []sessionFile{
{name: SessionMarkdownFile, data: []byte(markdown)},
{name: SessionHTMLFile, data: []byte(htmlDoc)},
})
written, diagnostic, err := writeSessionFile(request.ArtifactsDir, SessionHTMLFile, []byte(htmlDoc))
if err != nil {
return SessionExportResult{}, fmt.Errorf("session export: %s", RedactEvidence(err.Error()))
}
if written[0] {
result.MarkdownBytes = int64(len(markdown))
}
if written[1] {
if written {
result.HTMLBytes = int64(len(htmlDoc))
}
result.Diagnostic = diagnostic
return result, nil
}
// sessionFile is one rendered file to write into the artifacts directory.
type sessionFile struct {
name string
data []byte
// writeSessionFile stages the rendered file to a temporary file, then renames it
// into place, so a failure before the rename leaves no partial session.html
// behind. An existing target is never overwritten: it is skipped and the reason
// is returned as a diagnostic.
func writeSessionFile(dir, name string, data []byte) (bool, string, error) {
target := filepath.Join(dir, name)
if _, err := os.Lstat(target); err == nil {
return false, "existing " + name + " was not overwritten", nil
} else if !os.IsNotExist(err) {
return false, "", err
}
tmp, err := os.CreateTemp(dir, "."+name+".tmp-*")
if err != nil {
return false, "", err
}
if _, err := tmp.Write(data); err != nil {
tmp.Close()
_ = os.Remove(tmp.Name())
return false, "", err
}
if err := tmp.Close(); err != nil {
_ = os.Remove(tmp.Name())
return false, "", err
}
if err := os.Rename(tmp.Name(), target); err != nil {
_ = os.Remove(tmp.Name())
return false, "", err
}
return true, "", nil
}
// writeSessionPair stages every rendered file to a temporary file, then renames
// each into place, so a failure before the renames leaves no partial session.md
// or session.html behind. An existing target is never overwritten: its file is
// skipped and the reason is returned as a diagnostic.
func writeSessionPair(dir string, files []sessionFile) ([]bool, string, error) {
written := make([]bool, len(files))
temps := make([]string, len(files))
cleanup := func() {
for _, tmp := range temps {
if tmp != "" {
_ = os.Remove(tmp)
}
}
}
var skipped []string
for i, file := range files {
target := filepath.Join(dir, file.name)
if _, err := os.Lstat(target); err == nil {
skipped = append(skipped, file.name)
continue
} else if !os.IsNotExist(err) {
cleanup()
return written, "", err
}
tmp, err := os.CreateTemp(dir, "."+file.name+".tmp-*")
if err != nil {
cleanup()
return written, "", err
}
temps[i] = tmp.Name()
if _, err := tmp.Write(file.data); err != nil {
tmp.Close()
cleanup()
return written, "", err
}
if err := tmp.Close(); err != nil {
cleanup()
return written, "", err
}
}
for i, file := range files {
if temps[i] == "" {
continue
}
if err := os.Rename(temps[i], filepath.Join(dir, file.name)); err != nil {
cleanup()
return written, "", err
}
written[i] = true
}
diagnostic := ""
if len(skipped) > 0 {
diagnostic = "existing " + strings.Join(skipped, ", ") + " was not overwritten"
}
return written, diagnostic, nil
}
// sessionMeta is one metadata row the rendered files carry.
// sessionMeta is one metadata row the rendered file carries.
type sessionMeta struct {
label string
value string
}
// sessionMetadata is the run/step/session identity both renderers show, so a
// sessionMetadata is the run/step/session identity the html renderer shows, so a
// file is self-describing without the run record.
func sessionMetadata(session opencode.ExportedSession, request SessionExportRequest) []sessionMeta {
meta := []sessionMeta{
@@ -205,114 +165,6 @@ func sessionMetadata(session opencode.ExportedSession, request SessionExportRequ
return meta
}
// renderSessionMarkdown renders the session as bounded markdown. The second
// result reports whether the rendered file itself was cut at the cap.
func renderSessionMarkdown(session opencode.ExportedSession, request SessionExportRequest) (string, bool) {
var header bytes.Buffer
header.WriteString("# Stage session export\n\n")
for _, meta := range sessionMetadata(session, request) {
fmt.Fprintf(&header, "- %s: %s\n", meta.label, meta.value)
}
header.WriteString("\n")
var body bytes.Buffer
if len(session.Messages) == 0 {
body.WriteString("_No messages were recorded for this session._\n\n")
}
for i, message := range session.Messages {
renderMarkdownMessage(&body, i+1, message)
}
return assembleSessionFile(header.String(), body.String(), session.Truncated, markdownTruncationBanner, markdownTruncationBanner)
}
// renderMarkdownMessage renders one turn with its role and parts.
func renderMarkdownMessage(out *bytes.Buffer, index int, message opencode.ExportedMessage) {
role := message.Role
if role == "" {
role = "unknown"
}
fmt.Fprintf(out, "## %d. %s\n\n", index, role)
var details bytes.Buffer
if message.ID != "" {
fmt.Fprintf(&details, "- id: %s\n", message.ID)
}
if message.Model != "" {
fmt.Fprintf(&details, "- model: %s\n", message.Model)
}
if message.Agent != "" {
fmt.Fprintf(&details, "- agent: %s\n", message.Agent)
}
if message.CreatedAt != 0 {
fmt.Fprintf(&details, "- created_at: %d\n", message.CreatedAt)
}
if details.Len() > 0 {
out.WriteString(details.String())
out.WriteString("\n")
}
for _, part := range message.Parts {
renderMarkdownPart(out, part)
}
}
// renderMarkdownPart renders one content element. Unknown types are rendered as
// their raw JSON rather than dropped.
func renderMarkdownPart(out *bytes.Buffer, part opencode.ExportedPart) {
switch part.Type {
case protocol.ChatPartText:
out.WriteString(part.Text)
out.WriteString("\n\n")
case protocol.ChatPartReasoning:
fmt.Fprintf(out, "_reasoning_\n\n%s\n\n", part.Text)
case protocol.ChatPartTool:
renderMarkdownTool(out, part)
default:
label := part.Type
if label == "" {
label = "unknown"
}
fmt.Fprintf(out, "### %s\n\n", label)
raw := part.Raw
if len(raw) == 0 {
raw = []byte("{}")
}
fence := dynamicFence(string(raw))
fmt.Fprintf(out, "%sjson\n%s\n%s\n\n", fence, strings.TrimSpace(string(raw)), fence)
}
}
// renderMarkdownTool renders a tool call with its name, status, input, result
// and error.
func renderMarkdownTool(out *bytes.Buffer, part opencode.ExportedPart) {
name := part.Name
if name == "" {
name = part.ID
}
status := ""
if part.State != nil {
status = part.State.Status
}
fmt.Fprintf(out, "### tool: %s (%s)\n\n", name, status)
if part.State == nil {
return
}
if len(part.State.Input) > 0 {
input := string(part.State.Input)
fence := dynamicFence(input)
fmt.Fprintf(out, "input:\n\n%sjson\n%s\n%s\n\n", fence, strings.TrimSpace(input), fence)
}
for _, content := range part.State.Content {
if content.Text != "" {
out.WriteString(content.Text)
out.WriteString("\n\n")
} else if content.URI != "" {
fmt.Fprintf(out, "- %s (%s)\n", content.URI, content.Mime)
}
}
if part.State.Error != nil {
fmt.Fprintf(out, "error: %s\n\n", part.State.Error.Message)
}
}
// renderSessionHTML renders the session as bounded html, escaping every session
// text value. The second result reports whether the rendered file was cut.
func renderSessionHTML(session opencode.ExportedSession, request SessionExportRequest) (string, bool) {
@@ -440,13 +292,3 @@ func assembleSessionFile(header, body string, sourceTruncated bool, leading, tra
}
return result, rendered
}
// dynamicFence returns a run of at least three backticks longer than any run in
// text, so markdown content that itself contains a fence cannot break out.
func dynamicFence(text string) string {
fence := "```"
for strings.Contains(text, fence) {
fence += "`"
}
return fence
}
+58 -43
View File
@@ -43,43 +43,36 @@ func sessionRequest(dir string) SessionExportRequest {
}
}
func TestExportSessionWritesBothFilesWithRealContent(t *testing.T) {
func TestExportSessionWritesTheHTMLFileWithRealContent(t *testing.T) {
dir := t.TempDir()
sessionCLI(t, "ses_ok", sessionBody())
result, err := ExportSession(context.Background(), sessionRequest(dir))
if err != nil {
t.Fatal(err)
}
if result.Markdown != "session.md" || result.HTML != "session.html" {
t.Fatalf("file names wrong: %+v", result)
if result.HTML != "session.html" {
t.Fatalf("file name wrong: %+v", result)
}
if result.Messages != 2 || result.Source != "native_export" || result.Truncated {
t.Fatalf("evidence wrong: %+v", result)
}
markdown, err := os.ReadFile(filepath.Join(dir, SessionMarkdownFile))
if err != nil {
t.Fatal(err)
// The retired markdown export is never written.
if _, err := os.Stat(filepath.Join(dir, SessionMarkdownFile)); !os.IsNotExist(err) {
t.Fatalf("session.md must not be produced: %v", err)
}
htmlDoc, err := os.ReadFile(filepath.Join(dir, SessionHTMLFile))
if err != nil {
t.Fatal(err)
}
if result.MarkdownBytes != int64(len(markdown)) || result.HTMLBytes != int64(len(htmlDoc)) {
t.Fatalf("sizes wrong: %+v", result)
if result.HTMLBytes != int64(len(htmlDoc)) {
t.Fatalf("size wrong: %+v", result)
}
for _, want := range []string{"hello <b>&\" world", "thinking hard", "tool: read (completed)", "tool output", `{"path":"a.go"}`, "please run"} {
if !strings.Contains(string(markdown), want) {
t.Fatalf("markdown missing %q", want)
}
}
if !strings.Contains(string(markdown), "file:///tmp/x") {
t.Fatal("markdown dropped the unknown 'file' part")
}
// HTML must escape session text and still carry the tool detail.
// HTML must escape session text and still carry the tool detail and the
// unknown 'file' part.
if strings.Contains(string(htmlDoc), "<b>") {
t.Fatal("html rendered unescaped session text")
}
for _, want := range []string{"&lt;b&gt;", "&amp;", "tool: read (completed)", "tool output"} {
for _, want := range []string{"&lt;b&gt;", "&amp;", "tool: read (completed)", "tool output", "file:///tmp/x"} {
if !strings.Contains(string(htmlDoc), want) {
t.Fatalf("html missing %q", want)
}
@@ -91,7 +84,7 @@ func TestExportSessionWritesBothFilesWithRealContent(t *testing.T) {
}
}
func TestExportSessionRenderedTruncationBannerInBothFiles(t *testing.T) {
func TestExportSessionRenderedTruncationBanner(t *testing.T) {
// A source under the read cap but whose rendering exceeds the file cap.
huge := strings.Repeat("line of text\n", SessionExportFileLimit/7)
session := opencode.ExportedSession{
@@ -102,18 +95,15 @@ func TestExportSessionRenderedTruncationBannerInBothFiles(t *testing.T) {
Parts: []opencode.ExportedPart{{Type: "text", Text: huge}},
}},
}
markdown, mdTruncated := renderSessionMarkdown(session, sessionRequest(t.TempDir()))
htmlDoc, htmlTruncated := renderSessionHTML(session, sessionRequest(t.TempDir()))
if !mdTruncated || !htmlTruncated {
t.Fatalf("rendered truncation not reported: md=%v html=%v", mdTruncated, htmlTruncated)
if !htmlTruncated {
t.Fatal("rendered truncation not reported")
}
for name, content := range map[string]string{"markdown": markdown, "html": htmlDoc} {
if len(content) > SessionExportFileLimit {
t.Fatalf("%s exceeds cap: %d", name, len(content))
}
if strings.Count(content, "TRUNCATED") < 2 {
t.Fatalf("%s lacks a leading and trailing truncation banner", name)
}
if len(htmlDoc) > SessionExportFileLimit {
t.Fatalf("html exceeds cap: %d", len(htmlDoc))
}
if strings.Count(htmlDoc, "TRUNCATED") < 2 {
t.Fatal("html lacks a leading and trailing truncation banner")
}
}
@@ -124,27 +114,52 @@ func TestExportSessionSourceTruncationIsLabelledNotWhole(t *testing.T) {
Truncated: true,
Messages: []opencode.ExportedMessage{{Role: "assistant", Parts: []opencode.ExportedPart{{Type: "text", Text: "partial"}}}},
}
markdown, _ := renderSessionMarkdown(session, sessionRequest(t.TempDir()))
if strings.Count(markdown, "TRUNCATED") < 2 {
t.Fatalf("source truncation must be labelled at both ends:\n%s", markdown)
htmlDoc, _ := renderSessionHTML(session, sessionRequest(t.TempDir()))
if strings.Count(htmlDoc, "TRUNCATED") < 2 {
t.Fatalf("source truncation must be labelled at both ends:\n%s", htmlDoc)
}
if !strings.Contains(markdown, "truncated: true") {
if !strings.Contains(htmlDoc, "<dt>truncated</dt><dd>true</dd>") {
t.Fatal("metadata must record truncation")
}
}
func TestExportSessionEmptySessionIsHonest(t *testing.T) {
session := opencode.ExportedSession{ID: "ses_ok", Backend: "v2"}
markdown, _ := renderSessionMarkdown(session, sessionRequest(t.TempDir()))
if !strings.Contains(markdown, "messages: 0") || !strings.Contains(markdown, "No messages were recorded") {
t.Fatalf("empty session must be honest, not fabricated:\n%s", markdown)
htmlDoc, _ := renderSessionHTML(session, sessionRequest(t.TempDir()))
if !strings.Contains(htmlDoc, "<dt>messages</dt><dd>0</dd>") || !strings.Contains(htmlDoc, "No messages were recorded") {
t.Fatalf("empty session must be honest, not fabricated:\n%s", htmlDoc)
}
}
func TestExportSessionRefusesOverwrite(t *testing.T) {
func TestExportSessionWritesNoMarkdownAndLeavesALegacyOneAlone(t *testing.T) {
dir := t.TempDir()
sessionCLI(t, "ses_ok", sessionBody())
existing := filepath.Join(dir, SessionMarkdownFile)
// A pre-existing session.md from an older run is dated evidence: the export
// neither rewrites nor removes it, and writes no new markdown.
legacy := filepath.Join(dir, SessionMarkdownFile)
if err := os.WriteFile(legacy, []byte("legacy dated evidence"), 0600); err != nil {
t.Fatal(err)
}
result, err := ExportSession(context.Background(), sessionRequest(dir))
if err != nil {
t.Fatal(err)
}
kept, err := os.ReadFile(legacy)
if err != nil || string(kept) != "legacy dated evidence" {
t.Fatalf("legacy session.md changed: %q %v", kept, err)
}
if result.HTML != SessionHTMLFile || result.HTMLBytes == 0 || result.Diagnostic != "" {
t.Fatalf("html export wrong: %+v", result)
}
if _, err := os.Stat(filepath.Join(dir, SessionHTMLFile)); err != nil {
t.Fatalf("html not written: %v", err)
}
}
func TestExportSessionRefusesToOverwriteTheHTMLFile(t *testing.T) {
dir := t.TempDir()
sessionCLI(t, "ses_ok", sessionBody())
existing := filepath.Join(dir, SessionHTMLFile)
if err := os.WriteFile(existing, []byte("keep me"), 0600); err != nil {
t.Fatal(err)
}
@@ -154,13 +169,13 @@ func TestExportSessionRefusesOverwrite(t *testing.T) {
}
kept, err := os.ReadFile(existing)
if err != nil || string(kept) != "keep me" {
t.Fatalf("existing session.md was overwritten: %q %v", kept, err)
t.Fatalf("existing session.html was overwritten: %q %v", kept, err)
}
if result.MarkdownBytes != 0 || !strings.Contains(result.Diagnostic, "not overwritten") {
if result.HTMLBytes != 0 || !strings.Contains(result.Diagnostic, "not overwritten") {
t.Fatalf("skip reason not recorded: %+v", result)
}
if _, err := os.Stat(filepath.Join(dir, SessionHTMLFile)); err != nil {
t.Fatalf("html should still be written: %v", err)
if _, err := os.Stat(filepath.Join(dir, SessionMarkdownFile)); !os.IsNotExist(err) {
t.Fatal("a skipped html export must not write a session.md")
}
}
@@ -199,7 +214,7 @@ func TestExportSessionRejectsInvalidIDAndMissingDirectory(t *testing.T) {
func TestAssembleSessionFileNeverExceedsLimit(t *testing.T) {
header := strings.Repeat("h", SessionExportFileLimit+10)
body := strings.Repeat("b", 100)
got, _ := assembleSessionFile(header, body, false, markdownTruncationBanner, markdownTruncationBanner)
got, _ := assembleSessionFile(header, body, false, htmlTruncationBanner, htmlTruncationBanner)
if len(got) > SessionExportFileLimit {
t.Fatalf("assembled file exceeds cap: %d", len(got))
}