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
+6 -4
View File
@@ -17,11 +17,13 @@ with its own rules.
oversized file records nothing and never changes the verdict. Never invent an
artifact or claim a stage produced one — the server observes the directory after the
stage.
- An OpenCode-harness stage also gets its real session exported as `session.md` and
`session.html` in the same directory: bounded (8 MiB source, 2 MiB per file), with
- An OpenCode-harness stage also gets its real session exported as one file,
`session.html`, in the same directory: bounded (8 MiB source, 2 MiB rendered), with
a visible truncation banner and `session_export.truncated` when cut; the step's
`session_export` records the files. Export failures and Pi (no native export path)
record a diagnostic and never fail the run or change the stage result.
`session_export` records the file. The `session.md` export is retired — never
written, never presented (a run recorded before the change still lists it and every
listing hides it). Export failures and Pi (no native export path) record a
diagnostic and never fail the run or change the stage result.
## Publish a build to the LAN
+13 -7
View File
@@ -236,16 +236,22 @@ traversal, absolute paths, symlink escapes and unknown runs/steps.
- When an OpenCode-harness model stage finishes, the server exports its real
session read-only (v1 `opencode export <id>`, v2 `opencode session export <id>`)
and writes `session.md` and `session.html` into the same `<run>/<step>` artifacts
directory; they list and serve like any other artifact.
- The source read is capped at 8 MiB and each file at 2 MiB; a cut source or a cut
rendered file carries a visible truncation banner at both ends and
and writes exactly one file, `session.html`, into the same `<run>/<step>` artifacts
directory; it lists and serves like any other artifact.
- The `session.md` export is retired: nothing writes it any more and it is never
presented. A run recorded before the HTML-only change still lists `session.md`
among its stored artifacts (dated evidence kept on disk, not deleted); every
listing — app, TUI, web spike — hides it rather than showing it beside the html.
- The source read is capped at 8 MiB and the rendered file at 2 MiB; a cut source or
a cut rendered file carries a visible truncation banner at both ends and
`session_export.truncated: true`, and a truncated export is never called whole.
- The step records `session_export` (`session_id`, `backend`, `source`, file names,
sizes, `messages`, `truncated`, `diagnostic`) in `inspect RUN_ID --json`.
- The step records `session_export` (`session_id`, `backend`, `source`, the html
file name, `html_bytes`, `messages`, `truncated`, `diagnostic`) in
`inspect RUN_ID --json`. A record written before the change still carried
`markdown` and `markdown_bytes`; readers ignore those fields.
- A failed export, or a Pi stage with no native export path, records a diagnostic
(Pi: `source: "unavailable"`) and never fails the run or changes the stage result.
An existing `session.md`/`session.html` is never overwritten.
An existing `session.html` is never overwritten.
### Operator-only retention
+37 -2
View File
@@ -477,8 +477,7 @@ func TestSessionExportRoundTripAndAbsentEvidence(t *testing.T) {
}
want := &protocol.SessionExport{
SessionID: "ses_recorded", Backend: "v2", Source: "native_export",
Markdown: "session.md", HTML: "session.html",
MarkdownBytes: 1234, HTMLBytes: 2345, Messages: 9, Truncated: true,
HTML: "session.html", HTMLBytes: 2345, Messages: 9, Truncated: true,
Diagnostic: "kept",
}
if err := store.FinishStep(ctx, withExport, protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Output: map[string]any{}, Transcript: strings.Repeat("x", 40<<10), SessionExport: want}); err != nil {
@@ -506,3 +505,39 @@ func TestSessionExportRoundTripAndAbsentEvidence(t *testing.T) {
t.Fatalf("absent export evidence was fabricated: %+v", plain.Steps[0].SessionExport)
}
}
// TestSessionExportIgnoresLegacyMarkdownFields proves a record written before
// the HTML-only change still loads: the retired markdown fields are ignored and
// the html evidence is read, so an older database opens cleanly.
func TestSessionExportIgnoresLegacyMarkdownFields(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "legacy-session-exports.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "legacy-exports", Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
definition, _ := store.Get(ctx, items[0].ID, 1)
runID, _, err := store.CreateRun(ctx, definition, "legacy", "workspace", false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, runID, 1, "one", map[string]any{"prompt": "task"}); err != nil {
t.Fatal(err)
}
legacy := `{"session_id":"ses_old","backend":"v2","source":"native_export","markdown":"session.md","html":"session.html","markdown_bytes":111,"html_bytes":222,"messages":3}`
if _, err := store.db.ExecContext(ctx, "INSERT INTO step_session_exports(run_id,sequence,export_json) VALUES(?,?,?)", runID, 1, legacy); err != nil {
t.Fatal(err)
}
detail, err := store.GetRun(ctx, runID)
if err != nil {
t.Fatalf("an older database must still open: %v", err)
}
got := detail.Steps[0].SessionExport
if got == nil || got.HTML != "session.html" || got.HTMLBytes != 222 || got.Messages != 3 || got.SessionID != "ses_old" {
t.Fatalf("legacy export record did not load: %+v", got)
}
}
+45 -13
View File
@@ -101,20 +101,20 @@ type SessionEvidence struct {
}
// SessionExport is the recorded evidence of one stage's session file export:
// the file names written under the step's artifacts directory, their byte sizes,
// the decoded message count, the source, whether the export was truncated and a
// sanitized diagnostic. It is observed server-side evidence, not a model claim.
// the html file name written under the step's artifacts directory, its byte
// size, the decoded message count, the source, whether the export was truncated
// and a sanitized diagnostic. It is observed server-side evidence, not a model
// claim. A record written before the HTML-only change also carried markdown and
// markdown_bytes; readers ignore those fields.
type SessionExport struct {
SessionID string `json:"session_id,omitempty"`
Backend string `json:"backend,omitempty"`
Source string `json:"source,omitempty"`
Markdown string `json:"markdown,omitempty"`
HTML string `json:"html,omitempty"`
MarkdownBytes int64 `json:"markdown_bytes,omitempty"`
HTMLBytes int64 `json:"html_bytes,omitempty"`
Messages int `json:"messages"`
Truncated bool `json:"truncated,omitempty"`
Diagnostic string `json:"diagnostic,omitempty"`
SessionID string `json:"session_id,omitempty"`
Backend string `json:"backend,omitempty"`
Source string `json:"source,omitempty"`
HTML string `json:"html,omitempty"`
HTMLBytes int64 `json:"html_bytes,omitempty"`
Messages int `json:"messages"`
Truncated bool `json:"truncated,omitempty"`
Diagnostic string `json:"diagnostic,omitempty"`
}
type RunSummary struct {
@@ -197,6 +197,38 @@ type StageArtifact struct {
URL string `json:"url"`
}
// LegacySessionMarkdownArtifact is the retired markdown session export file name.
// Nothing writes it any more, but a run recorded before the HTML-only change
// still lists session.md among its stored artifacts: it is dated evidence that is
// never presented, so every listing hides it rather than showing it beside the
// session html. This is the one definition of the retired name, shared by the
// stage export and the clients.
const LegacySessionMarkdownArtifact = "session.md"
// PresentedArtifacts is one step's recorded artifacts as they are presented: the
// files with the retired markdown session export filtered out. It is the single
// rule every Go artifact listing derives from, so a stage's artifacts never show
// a session markdown beside the session html and a recorded count can never
// disagree with the tiles. It never mutates the step and returns nil when nothing
// is presented; the stored record still carries the legacy file. Pure,
// O(artifacts) per step.
func (s RunStep) PresentedArtifacts() []StageArtifact {
if len(s.Artifacts) == 0 {
return nil
}
presented := make([]StageArtifact, 0, len(s.Artifacts))
for _, artifact := range s.Artifacts {
if artifact.Name == LegacySessionMarkdownArtifact {
continue
}
presented = append(presented, artifact)
}
if len(presented) == 0 {
return nil
}
return presented
}
// StageUsage is the usage one model stage actually reported, carried from the
// stage's already-measured budget accounting rather than a second measurement or
// a transcript parse. TokensTotal/TokensKnown are the reported total; TokensIn
+22
View File
@@ -51,3 +51,25 @@ func TestRunStepOmitsAbsentArtifacts(t *testing.T) {
t.Fatalf("absent field must decode empty: %+v", decoded)
}
}
func TestPresentedArtifactsHidesRetiredSessionMarkdown(t *testing.T) {
step := RunStep{Artifacts: []StageArtifact{
{Name: "session.md", URL: "/artifacts/344/1/session.md"},
{Name: "session.html", URL: "/artifacts/344/1/session.html"},
{Name: "shot.png", URL: "/artifacts/344/1/shot.png"},
}}
presented := step.PresentedArtifacts()
if len(presented) != 2 || presented[0].Name != "session.html" || presented[1].Name != "shot.png" {
t.Fatalf("presented = %+v", presented)
}
if len(step.Artifacts) != 3 {
t.Fatalf("PresentedArtifacts mutated the stored record: %+v", step.Artifacts)
}
if got := (RunStep{}).PresentedArtifacts(); got != nil {
t.Fatalf("empty step presented %+v, want nil", got)
}
onlyLegacy := RunStep{Artifacts: []StageArtifact{{Name: LegacySessionMarkdownArtifact}}}
if got := onlyLegacy.PresentedArtifacts(); got != nil {
t.Fatalf("legacy-only step presented %+v, want nil", got)
}
}
-2
View File
@@ -1225,9 +1225,7 @@ func (r *runner) exportStageSession(ctx context.Context, owner pipeline.SessionO
return evidence
}
evidence.Source = result.Source
evidence.Markdown = result.Markdown
evidence.HTML = result.HTML
evidence.MarkdownBytes = result.MarkdownBytes
evidence.HTMLBytes = result.HTMLBytes
evidence.Messages = result.Messages
evidence.Truncated = result.Truncated
+24 -17
View File
@@ -30,8 +30,8 @@ func sessionExportLiveSource(provider, model string) string {
// TestSessionExportLive is an opt-in live check: it runs one real OpenCode stage
// on a temporary store and artifacts root using the configured host harness,
// then proves the real session.md/session.html are written, listed and served
// 200. It is gated so the default suite never spends inference.
// then proves the real session.html is written, listed and served 200. It is
// gated so the default suite never spends inference.
func TestSessionExportLive(t *testing.T) {
if os.Getenv("PIPELINES_SESSION_EXPORT_LIVE") != "1" {
t.Skip("set PIPELINES_SESSION_EXPORT_LIVE=1 and PIPELINES_SESSION_EXPORT_MODEL to run chargeable session-export inference")
@@ -89,15 +89,18 @@ func TestSessionExportLive(t *testing.T) {
t.Fatalf("live run did not succeed: %+v", detail)
}
step := detail.Steps[0]
if step.SessionExport == nil || step.SessionExport.Source != "native_export" || step.SessionExport.MarkdownBytes == 0 || step.SessionExport.HTMLBytes == 0 {
if step.SessionExport == nil || step.SessionExport.Source != "native_export" || step.SessionExport.HTML != "session.html" || step.SessionExport.HTMLBytes == 0 {
t.Fatalf("live session export evidence missing: %+v", step.SessionExport)
}
if step.SessionExport.Messages == 0 || step.SessionExport.Truncated {
t.Fatalf("live session export was empty or truncated: %+v", step.SessionExport)
}
if _, ok := artifactNamed(step.Artifacts, stage.SessionMarkdownFile); ok {
t.Fatalf("live run produced a legacy session.md: %+v", step.Artifacts)
}
srv := httptest.NewServer(handler)
defer srv.Close()
for _, name := range []string{"session.md", "session.html"} {
for _, name := range []string{stage.SessionHTMLFile} {
artifact, ok := artifactNamed(step.Artifacts, name)
if !ok {
t.Fatalf("%s not in live artifact listing: %+v", name, step.Artifacts)
@@ -150,19 +153,23 @@ func TestSessionExportRecorded(t *testing.T) {
if err != nil {
t.Fatalf("recorded session export failed: %v", err)
}
for _, name := range []string{stage.SessionMarkdownFile, stage.SessionHTMLFile} {
info, err := os.Stat(filepath.Join(dir, name))
if err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(dir, name))
first := string(data)
if idx := strings.IndexByte(first, '\n'); idx >= 0 {
first = first[:idx]
}
t.Logf("recorded export (NOT a fresh runner stage) %s: path=%s size=%d first_line=%q", name, filepath.Join(dir, name), info.Size(), first)
if result.HTML != stage.SessionHTMLFile || result.HTMLBytes == 0 {
t.Fatalf("recorded export wrote no html: %+v", result)
}
if result.MarkdownBytes == 0 || result.HTMLBytes == 0 {
t.Fatalf("recorded export wrote no files: %+v", result)
htmlPath := filepath.Join(dir, stage.SessionHTMLFile)
info, err := os.Stat(htmlPath)
if err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(htmlPath)
first := string(data)
if idx := strings.IndexByte(first, '\n'); idx >= 0 {
first = first[:idx]
}
t.Logf("recorded export (NOT a fresh runner stage) %s: path=%s size=%d first_line=%q", stage.SessionHTMLFile, htmlPath, info.Size(), first)
if _, err := os.Stat(filepath.Join(dir, stage.SessionMarkdownFile)); err == nil {
// A pre-existing session.md from an older run may sit here; the export
// must not have produced or rewritten it.
t.Logf("pre-existing %s left in place; the export writes no markdown", stage.SessionMarkdownFile)
}
}
+30 -38
View File
@@ -86,11 +86,11 @@ func sessionExportRunner(t *testing.T, backend string, seam func(stage.SessionEx
return handler, store, run.ID
}
// TestRunnerExportsSessionFilesIntoArtifactsAndServesThem proves the real export
// path writes both files into the step's artifacts directory, lists them with
// artifact URLs and serves them 200, without changing the step's status, outcome
// or target.
func TestRunnerExportsSessionFilesIntoArtifactsAndServesThem(t *testing.T) {
// TestRunnerExportsTheHTMLSessionIntoArtifactsAndServesIt proves the real export
// path writes the one html session file into the step's artifacts directory,
// lists it with an artifact URL and serves it 200, without changing the step's
// status, outcome or target, and produces no legacy session.md.
func TestRunnerExportsTheHTMLSessionIntoArtifactsAndServesIt(t *testing.T) {
sessionExportCLI(t)
handler, store, runID := sessionExportRunner(t, "v2", nil)
detail, err := store.GetRun(context.Background(), runID)
@@ -110,45 +110,37 @@ func TestRunnerExportsSessionFilesIntoArtifactsAndServesThem(t *testing.T) {
if step.SessionExport == nil || step.SessionExport.SessionID != "ses_run" || step.SessionExport.Source != "native_export" {
t.Fatalf("export evidence missing: %+v", step.SessionExport)
}
if step.SessionExport.Messages != 2 || step.SessionExport.MarkdownBytes == 0 || step.SessionExport.HTMLBytes == 0 {
if step.SessionExport.HTML != "session.html" || step.SessionExport.Messages != 2 || step.SessionExport.HTMLBytes == 0 {
t.Fatalf("export evidence wrong: %+v", step.SessionExport)
}
for _, name := range []string{"session.md", "session.html"} {
artifact, ok := artifactNamed(step.Artifacts, name)
if !ok {
t.Fatalf("%s not in the artifact listing: %+v", name, step.Artifacts)
}
wantURL := fmt.Sprintf("/artifacts/%d/1/%s", runID, name)
if artifact.URL != wantURL || artifact.SizeBytes == 0 {
t.Fatalf("%s listing wrong: %+v", name, artifact)
}
if _, ok := artifactNamed(step.Artifacts, stage.SessionMarkdownFile); ok {
t.Fatalf("legacy session.md must not be produced: %+v", step.Artifacts)
}
artifact, ok := artifactNamed(step.Artifacts, "session.html")
if !ok {
t.Fatalf("session.html not in the artifact listing: %+v", step.Artifacts)
}
wantURL := fmt.Sprintf("/artifacts/%d/1/session.html", runID)
if artifact.URL != wantURL || artifact.SizeBytes == 0 {
t.Fatalf("session.html listing wrong: %+v", artifact)
}
srv := httptest.NewServer(handler)
defer srv.Close()
for _, name := range []string{"session.md", "session.html"} {
resp, err := http.Get(srv.URL + fmt.Sprintf("/artifacts/%d/1/%s", runID, name))
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK || len(body) == 0 {
t.Fatalf("%s served %d (%d bytes)", name, resp.StatusCode, len(body))
}
contentType := resp.Header.Get("Content-Type")
if name == "session.md" && !strings.HasPrefix(contentType, "text/markdown") && !strings.HasPrefix(contentType, "text/plain") {
t.Fatalf("session.md content type = %q", contentType)
}
if name == "session.html" && !strings.HasPrefix(contentType, "text/html") {
t.Fatalf("session.html content type = %q", contentType)
}
if name == "session.md" && !strings.Contains(string(body), "do the task") {
t.Fatalf("served markdown missing session text")
}
if name == "session.html" && !strings.Contains(string(body), "output here") {
t.Fatalf("served html missing tool output")
}
resp, err := http.Get(srv.URL + wantURL)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK || len(body) == 0 {
t.Fatalf("session.html served %d (%d bytes)", resp.StatusCode, len(body))
}
if contentType := resp.Header.Get("Content-Type"); !strings.HasPrefix(contentType, "text/html") {
t.Fatalf("session.html content type = %q", contentType)
}
if !strings.Contains(string(body), "output here") {
t.Fatal("served html missing tool output")
}
}
+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))
}
+6 -3
View File
@@ -29,8 +29,11 @@ type artifactVisit struct {
// order the run produced them: stages in first-appearance order and each
// stage's visits by sequence. The display visit number is the recorded control
// visit when present, else the position within the stage (mirroring the app's
// runTimeline/runArtifactGroups). Pure, O(n), and it never dedupes steps, so a
// repeated stage's visits stay distinct.
// runTimeline/runArtifactGroups). A visit carries the step's presented
// artifacts (protocol.RunStep.PresentedArtifacts), so the retired session
// markdown is never listed beside the session html, exactly as the app hides it.
// Pure, O(n), and it never dedupes steps, so a repeated stage's visits stay
// distinct.
func runArtifactVisits(steps []protocol.RunStep) []artifactVisit {
order := make([]string, 0)
index := map[string]int{}
@@ -54,7 +57,7 @@ func runArtifactVisits(steps []protocol.RunStep) []artifactVisit {
if step.Control != nil && step.Control.Visit > 0 {
visit = step.Control.Visit
}
visits = append(visits, artifactVisit{stage: stage, visit: visit, step: step, artifacts: step.Artifacts})
visits = append(visits, artifactVisit{stage: stage, visit: visit, step: step, artifacts: step.PresentedArtifacts()})
}
}
return visits
+47
View File
@@ -155,6 +155,53 @@ func TestArtifactsViewEmptyRun(t *testing.T) {
}
}
// A run recorded before the HTML-only change still lists session.md among its
// stored artifacts. It is dated evidence that must never be presented beside the
// session html, so the panel, its recorded count and its summary all hide it,
// exactly as the app does.
func TestArtifactsViewHidesLegacySessionMarkdown(t *testing.T) {
m := New(context.Background(), "ws://127.0.0.1:8080/connect")
m.width, m.height = 120, 24
m.runDetail = &protocol.RunDetail{
RunSummary: protocol.RunSummary{ID: 344, Status: "succeeded"},
Steps: []protocol.RunStep{{Sequence: 1, Stage: "committer", Status: "completed",
Artifacts: []protocol.StageArtifact{
{Name: "session.md", SizeBytes: 62370, ContentType: "text/markdown", URL: "/artifacts/344/1/session.md"},
{Name: "session.html", SizeBytes: 68813, ContentType: "text/html", URL: "/artifacts/344/1/session.html"},
}}},
}
view := ansi.Strip(m.artifactsView(20))
if strings.Contains(view, "session.md") {
t.Fatalf("legacy session markdown presented beside the html:\n%s", view)
}
for _, want := range []string{"session.html", "Artifacts · run #344 · 1 recorded · 1 visits"} {
if !strings.Contains(view, want) {
t.Fatalf("artifacts view missing %q:\n%s", want, view)
}
}
// The step's own stored record is untouched: only the presentation filters.
if len(m.runDetail.Steps[0].Artifacts) != 2 {
t.Fatalf("presentation mutated the stored artifact record: %d", len(m.runDetail.Steps[0].Artifacts))
}
}
func TestArtifactsSummaryAndNotesHideLegacySessionMarkdown(t *testing.T) {
legacy := protocol.RunStep{Status: "completed", ArtifactsSkipped: 1,
Artifacts: []protocol.StageArtifact{{Name: "session.md", URL: "/artifacts/344/1/session.md"}}}
if got, want := artifactsSummary(legacy), "Artifacts · not recorded for this visit"; got != want {
t.Fatalf("summary = %q, want %q", got, want)
}
if notes := artifactCaptureNotes(legacy); len(notes) != 0 {
t.Fatalf("legacy-only visit still produced capture notes: %v", notes)
}
presented := protocol.RunStep{Status: "completed", Artifacts: []protocol.StageArtifact{
{Name: "session.md"}, {Name: "session.html"},
}}
if got, want := artifactsSummary(presented), "Artifacts · 1 recorded"; got != want {
t.Fatalf("summary = %q, want %q", got, want)
}
}
func artifactsScrollFixture() (Model, []string) {
m := New(context.Background(), "ws://127.0.0.1:8080/connect")
m.width, m.height = 80, 14
+4 -3
View File
@@ -31,13 +31,14 @@ func fileChangesSummary(step protocol.RunStep) string {
}
func artifactsSummary(step protocol.RunStep) string {
if len(step.Artifacts) == 0 {
artifacts := step.PresentedArtifacts()
if len(artifacts) == 0 {
if step.Status == "running" {
return "Artifacts · capture pending"
}
return "Artifacts · not recorded for this visit"
}
label := fmt.Sprintf("Artifacts · %d recorded", len(step.Artifacts))
label := fmt.Sprintf("Artifacts · %d recorded", len(artifacts))
if step.ArtifactsSkipped > 0 || step.ArtifactsTruncated > 0 {
label += " · partial capture"
}
@@ -64,7 +65,7 @@ func HumanBytes(size int64) string {
// complete. A visit with no recorded artifacts yields no notes, mirroring the
// app's artifactCaptureNotes, so notes never accompany an empty-state summary.
func artifactCaptureNotes(step protocol.RunStep) []string {
if len(step.Artifacts) == 0 {
if len(step.PresentedArtifacts()) == 0 {
return nil
}
var notes []string