Files
pipelines/internal/server/session_export_test.go
T
alan 95362134aa 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.
2026-10-18 10:06:49 +01:00

215 lines
7.9 KiB
Go

package server
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// sessionExportBody is a minimal native export envelope with a user and an
// assistant turn, used by the fake CLI below.
const sessionExportBody = `{"info":{"id":"ses_run"},"messages":[` +
`{"info":{"id":"m1","role":"user"},"text":"do the task"},` +
`{"info":{"id":"m2","role":"assistant"},"parts":[` +
`{"type":"text","text":"done"},` +
`{"type":"tool","name":"shell","state":{"status":"completed","input":{"cmd":"ls"},"content":[{"type":"text","text":"output here"}]}}]}]}`
// sessionExportCLI points PIPELINES_OPENCODE at a fake `opencode export` that
// returns sessionExportBody, so the runner's real export path runs.
func sessionExportCLI(t *testing.T) {
t.Helper()
path := filepath.Join(t.TempDir(), "opencode")
script := "#!/bin/sh\n" +
"[ \"$1\" = export ] && shift || { [ \"$1\" = session ] && [ \"$2\" = export ] && shift 2 || exit 8; }\n" +
"[ \"$1\" = ses_run ] || exit 9\n" +
"cat <<'EOF'\n" + sessionExportBody + "\nEOF\n"
if err := os.WriteFile(path, []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_OPENCODE", path)
}
// sessionExportRunner runs one stage that records a session for the run, so the
// runner's post-stage export has an owner to read. The export seam is supplied by
// the caller; ready gates the stage until the test has captured the run id.
func sessionExportRunner(t *testing.T, backend string, seam func(stage.SessionExportRequest) (stage.SessionExportResult, error)) (*runHandler, *pipeline.Store, int64) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
store, err := pipeline.Open(filepath.Join(t.TempDir(), "session.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
if _, err := store.Submit(ctx, "session-export", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, err := store.List(ctx)
if err != nil {
t.Fatal(err)
}
handler := Handler(ctx, store).(*runHandler)
t.Cleanup(func() { cancel(); WaitRuns(handler) })
handler.runner.artifactsRoot = t.TempDir()
if seam != nil {
handler.runner.exportSession = func(_ context.Context, request stage.SessionExportRequest) (stage.SessionExportResult, error) {
return seam(request)
}
}
ready := make(chan struct{})
var runID int64
handler.runner.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
<-ready
if err := handler.runner.store.RunSession(ctx, runID, 1, "ses_run", true, backend, ""); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run, err := handler.runner.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "session", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
runID = run.ID
close(ready)
handler.runner.wg.Wait()
return handler, store, run.ID
}
// 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)
if err != nil {
t.Fatal(err)
}
if detail.Status != "succeeded" || len(detail.Steps) != 1 {
t.Fatalf("unexpected run: %+v", detail)
}
step := detail.Steps[0]
if step.Status != "completed" || step.Outcome != "success" {
t.Fatalf("export changed the stage result: %+v", step)
}
if len(step.Transcript) > 32<<10 || strings.Contains(step.Transcript, "do the task") || strings.Contains(step.Transcript, "session.md") {
t.Fatalf("transcript was changed by the export: %q", step.Transcript)
}
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.HTML != "session.html" || step.SessionExport.Messages != 2 || step.SessionExport.HTMLBytes == 0 {
t.Fatalf("export evidence wrong: %+v", step.SessionExport)
}
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()
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")
}
}
// TestRunnerSessionExportFailureTruncationAndUnavailableHarness proves the three
// non-success export outcomes are recorded as evidence and never fail the run.
func TestRunnerSessionExportFailureTruncationAndUnavailableHarness(t *testing.T) {
cases := []struct {
name string
backend string
seam func(stage.SessionExportRequest) (stage.SessionExportResult, error)
wantSrc string
wantDiag string
wantTrunc bool
}{
{
name: "failure",
backend: "v2",
seam: func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
return stage.SessionExportResult{}, errors.New("native session export failed")
},
wantSrc: "native_export",
wantDiag: "native session export failed",
},
{
name: "truncated",
backend: "v2",
seam: func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
return stage.SessionExportResult{Source: "native_export", Truncated: true, Messages: 3}, nil
},
wantSrc: "native_export",
wantTrunc: true,
},
{
name: "unavailable",
backend: "pi",
seam: nil,
wantSrc: "unavailable",
wantDiag: "harness has no native export path",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
handler, store, runID := sessionExportRunner(t, tc.backend, tc.seam)
detail, err := store.GetRun(context.Background(), runID)
if err != nil {
t.Fatal(err)
}
if detail.Status != "succeeded" {
t.Fatalf("export outcome failed the run: %+v", detail.Status)
}
step := detail.Steps[0]
if step.Status != "completed" || step.Outcome != "success" {
t.Fatalf("export changed the stage result: %+v", step)
}
if step.SessionExport == nil || step.SessionExport.Source != tc.wantSrc {
t.Fatalf("export evidence wrong: %+v", step.SessionExport)
}
if tc.wantDiag != "" && !strings.Contains(step.SessionExport.Diagnostic, tc.wantDiag) {
t.Fatalf("diagnostic %q missing %q", step.SessionExport.Diagnostic, tc.wantDiag)
}
if step.SessionExport.Truncated != tc.wantTrunc {
t.Fatalf("truncated = %v, want %v", step.SessionExport.Truncated, tc.wantTrunc)
}
if tc.wantSrc == "unavailable" {
if artifacts, _, _ := handler.runner.scanArtifacts(runID, 1, filepath.Join(handler.runner.artifactsRoot, fmt.Sprint(runID), "1")); len(artifacts) != 0 {
t.Fatalf("unavailable harness wrote files: %+v", artifacts)
}
}
})
}
}