From 752e7618376a130b6a781822e71284615cfde700 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 17 Oct 2026 19:55:56 +0100 Subject: [PATCH] android: read a stage's exported session from the run view Add a Session section to the stage detail that appears only when the visit's session export actually wrote a file, beside the artifacts it was written with, and opens the transcript on a click like any artifact. - Derive the section from the recorded `session_export` matched against the step's artifact listing (`sessionExportFiles`), so a visit with no export - a non-OpenCode harness, an export failure, or a pre-export server - lists no empty section, mirroring internal/protocol/runs.go and the server's export. - Default to the markdown export rendered with the app's existing markdown renderer (new lazy `MarkdownBlocks` reusing `MarkdownBlock`), and when both files exist offer the html export through an "HTML view" toggle in a WebView for fidelity; html is the default only when markdown is absent. - Behave like the artifacts around it: the same Scaffold/TopAppBar/back chrome, the shared ArtifactBytesCache so the file is fetched once and never loaded twice, decode/parse off the main thread so a several-hundred-kilobyte session stays responsive in a lazy block list, and a failed fetch shown as its own in-pane error without hiding the other sections. - `SessionExport` protocol model and `RunStep.session_export`, with the unit tests for section presence, fetch/render, fetch failure isolation and a large session. Checked the packaged templates and the packaged authoring skill references: the session export's server-side behaviour is already documented in references/delivery.md and references/operations.md (landed with the server change), and no packaged reference or template describes the Android stage pane's sections, so none of them needs updating for this client-only change. Verified before commit (recorded by the independent code review on this tree): compileDebugKotlin, testDebugUnitTest (forced rerun) and assembleDebug all BUILD SUCCESSFUL, 554 tests / 0 failures across 61 classes, SessionExportTest 9/0/0. --- .../awan/pipelines/data/protocol/Message.kt | 25 ++ .../net/awan/pipelines/ui/chat/Markdown.kt | 28 +- .../awan/pipelines/ui/graph/SessionExport.kt | 316 ++++++++++++++++++ .../pipelines/ui/graph/StageDetailPane.kt | 68 +++- .../pipelines/ui/graph/SessionExportTest.kt | 149 +++++++++ 5 files changed, 570 insertions(+), 16 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/graph/SessionExport.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/graph/SessionExportTest.kt diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt index 1fa78fd3..bf656260 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt @@ -283,6 +283,28 @@ data class SessionEvidence( val diagnostic: String? = null, ) +/** + * The recorded evidence of one stage's session file export, mirroring + * internal/protocol/runs.go SessionExport exactly: 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. An + * absent (null) value means the step recorded no export (a non-OpenCode harness, + * a failed export or a pre-export server), so no Session section is shown. + */ +@Serializable +data class SessionExport( + @SerialName("session_id") val sessionId: String = "", + val backend: String = "", + val source: String = "", + val markdown: String = "", + val html: String = "", + @SerialName("markdown_bytes") val markdownBytes: Long = 0, + @SerialName("html_bytes") val htmlBytes: Long = 0, + val messages: Int = 0, + val truncated: Boolean = false, + val diagnostic: String = "", +) + @Serializable data class RunSummary( val id: Long = 0, @@ -318,6 +340,9 @@ data class RunStep( // The server's derived plain-language verdict; absent (null) on a running step // or a pre-verdict server, so the pane shows no block. val verdict: StageVerdict? = null, + // The step's recorded session file export; absent (null) when the visit has + // none, so the stage pane lists no Session section. + @SerialName("session_export") val sessionExport: SessionExport? = null, val sequence: Int = 0, val stage: String = "", val status: String = "", diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/Markdown.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/Markdown.kt index b59c2840..fa0e9a6a 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/Markdown.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/Markdown.kt @@ -6,12 +6,15 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme @@ -319,8 +322,31 @@ internal fun MarkdownText(text: String, modifier: Modifier = Modifier) { } } +/** + * Renders already-parsed [blocks] as markdown in a lazy list, one block per item, + * so a large document (an exported session of several hundred kilobytes) composes + * only the blocks on screen instead of every block up front. The caller parses + * once and passes the result here ([MarkdownText] is the eager variant for short + * prose), so the same [MarkdownBlock] renderer draws both and there is no second + * markdown implementation. + */ @Composable -private fun MarkdownBlock(block: MdBlock) { +internal fun MarkdownBlocks( + blocks: List, + modifier: Modifier = Modifier, + contentPadding: PaddingValues = PaddingValues(vertical = CHAT_ITEM_GAP), +) { + LazyColumn( + modifier = modifier, + contentPadding = contentPadding, + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + ) { + itemsIndexed(blocks) { _, block -> MarkdownBlock(block) } + } +} + +@Composable +internal fun MarkdownBlock(block: MdBlock) { val texts = pipelinesText() when (block) { is MdHeading -> Text( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/SessionExport.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/SessionExport.kt new file mode 100644 index 00000000..dd2f89cd --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/SessionExport.kt @@ -0,0 +1,316 @@ +package net.awan.pipelines.ui.graph + +import android.webkit.WebView +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.viewinterop.AndroidView +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import net.awan.pipelines.data.protocol.GraphSemantics +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.StageArtifact +import net.awan.pipelines.ui.chat.MarkdownBlocks +import net.awan.pipelines.ui.chat.MdBlock +import net.awan.pipelines.ui.chat.parseMarkdown +import net.awan.pipelines.ui.theme.SPACING_L +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * The session export's files of one visit, resolved against the visit's recorded + * artifacts. Either file may be missing (a partially exported or truncated + * listing); a visit with neither has no export to show. + */ +internal data class SessionExportFiles( + val markdown: StageArtifact?, + val html: StageArtifact?, +) + +/** + * The files [step]'s session export actually wrote, matched by the names the + * server recorded in `session_export` against the step's artifact listing. Null + * when the visit recorded no export, when it recorded only a limitation (a Pi + * harness, `source: "unavailable"`, or a failure with a diagnostic and no file + * names) or when the listing holds neither recorded file. The stage pane derives + * the Session section from exactly this, so a section is never listed for a visit + * that has no session file to open. + */ +internal fun sessionExportFiles(step: RunStep): SessionExportFiles? { + val export = step.sessionExport ?: return null + val markdownName = export.markdown.takeIf { it.isNotBlank() } + val htmlName = export.html.takeIf { it.isNotBlank() } + if (markdownName == null && htmlName == null) return null + val artifacts = step.artifacts.orEmpty() + val markdown = markdownName?.let { name -> artifacts.firstOrNull { it.name == name } } + val html = htmlName?.let { name -> artifacts.firstOrNull { it.name == name } } + if (markdown == null && html == null) return null + return SessionExportFiles(markdown = markdown, html = html) +} + +/** The two ways of reading an exported session: the rendered markdown or the html document. */ +internal enum class SessionView { Markdown, Html } + +/** + * The view the session section opens in: the markdown export, rendered with the + * app's existing markdown renderer, is the default. The html export is only the + * default when there is no markdown to render; otherwise it is reached through the + * section's own "HTML view" toggle and shown in a WebView for fidelity. + */ +internal fun defaultSessionView(files: SessionExportFiles): SessionView = + if (files.markdown != null) SessionView.Markdown else SessionView.Html + +/** Whether the operator can switch between the two exports (both were written). */ +internal fun sessionViewToggle(files: SessionExportFiles): Boolean = + files.markdown != null && files.html != null + +/** The file the section shows in [view], or null when that export is missing. */ +internal fun sessionArtifact(files: SessionExportFiles, view: SessionView): StageArtifact? = + when (view) { + SessionView.Markdown -> files.markdown + SessionView.Html -> files.html + } + +/** + * One exported session file, loaded: its markdown parsed into the app's shared + * blocks, its html kept as the document text, its absence a distinct error. A null + * url means no server was configured to fetch it from. + */ +internal sealed interface SessionLoad { + data object Loading : SessionLoad + data object Unavailable : SessionLoad + data object Error : SessionLoad + data class Markdown(val blocks: List) : SessionLoad + data class Html(val document: String) : SessionLoad +} + +/** + * Classifies one fetched session file: a failed fetch ([bytes] null) is a distinct + * error state, never rendered as an empty session, and a fetched file decodes to + * its view. Pure, so the decode/parse and the failure branch are unit tested. + */ +internal fun sessionLoad(bytes: ByteArray?, markdown: Boolean): SessionLoad = + if (bytes == null) SessionLoad.Error else decodeSessionFile(bytes, markdown) + +/** + * Decodes one session file: markdown into the shared parsed blocks, html into its + * document text. Pure (the UTF-8 decode replaces malformed sequences rather than + * throwing), so the viewer passes it off the main thread and it is unit tested. + */ +internal fun decodeSessionFile(bytes: ByteArray, markdown: Boolean): SessionLoad { + val text = bytes.toString(Charsets.UTF_8) + return if (markdown) SessionLoad.Markdown(parseMarkdown(text)) else SessionLoad.Html(text) +} + +/** + * The Session section pane: the exported session of the selected visit, read like + * the artifacts beside it. The markdown export is the default and is rendered with + * the app's existing markdown renderer in a lazy list (one parsed block per item), + * so a session of several hundred kilobytes scrolls without composing every block. + * When both files were exported the section offers an "HTML view" toggle that + * swaps in the html document in a WebView for fidelity, and switches back. The + * context line and the visit tabs stay pinned above the scroll, exactly as the + * other section panes keep their chrome. + * + * The file is fetched once per url through the app's shared artifact byte cache and + * the fetch/parse run off the main thread, so switching views or reopening the pane + * never re-hits the network and never blocks the pane. A missing server URL shows + * that state, and a failed fetch shows its own error in this pane only: the stage + * screen and every other section are unaffected. + */ +@Composable +internal fun SessionExportSection( + stageKey: String, + step: RunStep, + runSteps: List, + visitIndex: Int, + onVisitIndexChange: (Int) -> Unit, + configuredServerUrl: String, + fetchArtifactBytes: suspend (String) -> ByteArray?, + modifier: Modifier = Modifier, +) { + val text = pipelinesText() + val files = remember(step) { sessionExportFiles(step) } + Column(modifier.fillMaxSize()) { + if (files == null) { + SessionHeader(stageKey, runSteps, visitIndex, onVisitIndexChange) { + Text("No session was exported for this visit.", style = text.meta) + } + return@Column + } + var view by rememberSaveable(step.sequence, files.markdown?.url, files.html?.url) { + mutableStateOf(defaultSessionView(files)) + } + val toggle = sessionViewToggle(files) + val artifact = sessionArtifact(files, view) + val url = artifact?.let { resolvedArtifactUrl(it, configuredServerUrl) } + SessionHeader(stageKey, runSteps, visitIndex, onVisitIndexChange) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + Text( + if (view == SessionView.Markdown) "Markdown" else "HTML", + style = text.label, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.weight(1f), + ) + if (toggle) { + OutlinedButton( + onClick = { + view = if (view == SessionView.Markdown) SessionView.Html else SessionView.Markdown + }, + ) { + Text(if (view == SessionView.Markdown) "HTML view" else "Markdown view") + } + } + } + } + SessionBody( + load = rememberSessionLoad(url, view == SessionView.Markdown, fetchArtifactBytes), + modifier = Modifier.weight(1f), + ) + } +} + +/** + * The session pane's pinned header: the context line naming the stage and the + * visit tabs, followed by the caller's [content] (the view toggle, or the + * missing-export notice). It stays above the session's own scroll, exactly as the + * other section panes keep their chrome. + */ +@Composable +private fun SessionHeader( + stageKey: String, + runSteps: List, + visitIndex: Int, + onVisitIndexChange: (Int) -> Unit, + content: @Composable () -> Unit, +) { + val text = pipelinesText() + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = SPACING_L, vertical = SPACING_L), + verticalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + Text(GraphSemantics.nodeLabel(stageKey), style = text.meta) + StageVisitTabs(runSteps.size, visitIndex, onVisitIndexChange) + content() + } +} + +/** + * The loaded session file's body: the parsed markdown in a lazy list, the html in + * a WebView, or the loading/unavailable/error notice. The one branch that draws a + * session, so the markdown and html paths share the section's fetch and state. + */ +@Composable +private fun SessionBody(load: SessionLoad, modifier: Modifier = Modifier) { + when (load) { + SessionLoad.Loading -> SessionNotice( + message = "Loading session…", + modifier = modifier, + spinner = true, + ) + SessionLoad.Unavailable -> SessionNotice( + message = "Set the server URL in Settings to open the session.", + modifier = modifier, + ) + SessionLoad.Error -> SessionNotice( + message = "Couldn't load the exported session.", + modifier = modifier, + ) + is SessionLoad.Markdown -> MarkdownBlocks(blocks = load.blocks, modifier = modifier) + is SessionLoad.Html -> SessionHtml(document = load.document, modifier = modifier) + } +} + +/** A centred loading/unavailable/error notice, in the section's own pane only. */ +@Composable +private fun SessionNotice(message: String, modifier: Modifier = Modifier, spinner: Boolean = false) { + Box(modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + Column( + modifier = Modifier.padding(SPACING_L), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + if (spinner) CircularProgressIndicator() + Text(message, style = pipelinesText().meta) + } + } +} + +/** + * The html export in a WebView. The markdown default is rendered natively; the + * html is the fidelity fallback for the structure the app's renderer does not + * reproduce. The document is self-contained, so it is loaded with a null base URL + * (no file or network origin), scripting is off, and the view is destroyed with + * the composition. + */ +@Composable +private fun SessionHtml(document: String, modifier: Modifier = Modifier) { + val context = LocalContext.current + val webView = remember { + WebView(context).apply { + settings.javaScriptEnabled = false + settings.builtInZoomControls = true + settings.displayZoomControls = false + } + } + LaunchedEffect(document) { + webView.loadDataWithBaseURL(null, document, "text/html", "utf-8", null) + } + DisposableEffect(webView) { + onDispose { webView.destroy() } + } + AndroidView(factory = { webView }, modifier = modifier.fillMaxWidth()) +} + +/** + * Loads the resolved session [url] once and classifies it. A null url is + * [SessionLoad.Unavailable] with no request attempted. The bytes are fetched + * through the app's shared [ArtifactBytesCache], so re-opening the section or + * switching views reuses them instead of loading the file a second time; the + * decode and markdown parse run off the main thread so a large session never + * blocks the UI. A canceled effect (the url or view changed) never publishes its + * stale result. + */ +@Composable +private fun rememberSessionLoad( + url: String?, + markdown: Boolean, + fetchBytes: suspend (String) -> ByteArray?, +): SessionLoad { + if (url == null) return SessionLoad.Unavailable + var load by remember(url) { mutableStateOf(SessionLoad.Loading) } + LaunchedEffect(url, markdown) { + val cached = ArtifactBytesCache.get(url) + val bytes = cached ?: runCatching { + withContext(Dispatchers.IO) { fetchBytes(url) } + }.getOrNull() + if (cached == null && bytes != null) ArtifactBytesCache.put(url, bytes) + load = withContext(Dispatchers.Default) { sessionLoad(bytes, markdown) } + } + return load +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt index 838a5cbb..72b89b44 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt @@ -210,28 +210,35 @@ internal val STAGE_RESULT_SECTIONS: List = listOf( internal const val STAGE_EVIDENCE_KEY = "run" internal const val STAGE_EVIDENCE_TITLE = "This run" +/** The session section key/title (the visit's exported session files). */ +internal const val STAGE_SESSION_KEY = "session" +internal const val STAGE_SESSION_TITLE = "Session" + /** * One section of the stage screen: its stable [key] (what the pane selection and * the section pane address it by), its own [title], the [fields] it shows when it - * is a plain field section, and [artifacts] when it is the per-visit gallery - * (which renders the shared [ArtifactsSection] instead of [fields]). + * is a plain field section, [artifacts] when it is the per-visit gallery (which + * renders the shared [ArtifactsSection] instead of [fields]), and [session] when + * it is the visit's exported session (which renders [SessionExportSection]). */ internal data class StageSectionSpec( val key: String, val title: String, val fields: List = emptyList(), val artifacts: Boolean = false, + val session: Boolean = false, ) /** * The ordered sections of the stage screen for one stage and visit: a run pane - * leads with the visit's Artifacts gallery, then Output, Input and the remaining - * evidence (`This run`); the stage's own definition is the last section in both - * contexts and the only section when there is no run. Blank field sections are - * skipped; the artifacts section always shows for a reached visit, even when the - * visit recorded none, so the operator always finds the gallery. Pure, so the - * compact stage screen's list and the section pane's content are derived from - * exactly the same spec. + * leads with the visit's Artifacts gallery, then its exported Session when it has + * one, then Output, Input and the remaining evidence (`This run`); the stage's own + * definition is the last section in both contexts and the only section when there + * is no run. Blank field sections are skipped; the artifacts section always shows + * for a reached visit, even when the visit recorded none, so the operator always + * finds the gallery, while the Session section appears only when the visit's + * session export wrote a file. Pure, so the compact stage screen's list and the + * section pane's content are derived from exactly the same spec. */ internal fun stageSectionSpecs( stageKey: String, @@ -246,13 +253,27 @@ internal fun stageSectionSpecs( val selectedStep = runSteps.getOrNull(clampVisitIndex(visitIndex, runSteps.size)) if (runContext && selectedStep != null) { val runFields = runStepFields(selectedStep) + // The visit's exported session, when it has one, sits directly beside the + // artifacts it was written with: both are the visit's recorded files, and + // the operator reads them the same way. A visit without an export lists no + // Session row at all, rather than an empty section. + val session = sessionExportFiles(selectedStep) != null STAGE_RESULT_SECTIONS.forEach { section -> when (section) { - StageResultSection.Artifacts -> specs += StageSectionSpec( - key = section.key, - title = section.title, - artifacts = true, - ) + StageResultSection.Artifacts -> { + specs += StageSectionSpec( + key = section.key, + title = section.title, + artifacts = true, + ) + if (session) { + specs += StageSectionSpec( + key = STAGE_SESSION_KEY, + title = STAGE_SESSION_TITLE, + session = true, + ) + } + } StageResultSection.Output -> { val fields = runFields.filter { it.label == "Output" } if (fields.isNotEmpty()) specs += StageSectionSpec(section.key, section.title, fields) @@ -699,7 +720,9 @@ fun StageSectionPane( * its own top spacing, and — for a visit's result section — the visit tab row, * so the operator can switch visits in place. The stage definition skips the tab * row (it does not change per visit). Plain sections render their rows; the - * artifacts section renders the shared [ArtifactsSection] gallery. + * artifacts section renders the shared [ArtifactsSection] gallery; the session + * section renders [SessionExportSection], which owns its own lazy/large-content + * scroll instead of the eager one below. */ @Composable private fun StageSectionBody( @@ -717,6 +740,21 @@ private fun StageSectionBody( modifier: Modifier = Modifier, ) { val text = pipelinesText() + if (spec?.session == true && step != null) { + DetailTabBody(wide, modifier) { columnModifier -> + SessionExportSection( + stageKey = stageKey, + step = step, + runSteps = runSteps, + visitIndex = visitIndex, + onVisitIndexChange = onVisitIndexChange, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, + modifier = columnModifier, + ) + } + return + } DetailTabBody(wide, modifier) { columnModifier -> Column( modifier = columnModifier diff --git a/android/app/src/test/java/net/awan/pipelines/ui/graph/SessionExportTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/graph/SessionExportTest.kt new file mode 100644 index 00000000..2ba69cf1 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/graph/SessionExportTest.kt @@ -0,0 +1,149 @@ +package net.awan.pipelines.ui.graph + +import net.awan.pipelines.data.protocol.Graph +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.SessionExport +import net.awan.pipelines.data.protocol.Stage +import net.awan.pipelines.data.protocol.StageArtifact +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SessionExportTest { + + private val nativeExport = SessionExport( + sessionId = "ses_1", + backend = "v2", + source = "native_export", + markdown = "session.md", + html = "session.html", + markdownBytes = 12, + htmlBytes = 34, + messages = 2, + ) + + @Test + fun aVisitWithNoSessionExportHasNoFiles() { + assertNull(sessionExportFiles(RunStep())) + // A limitation-only export (a Pi harness) records names for nothing and + // must not produce an empty section. + assertNull( + sessionExportFiles( + RunStep( + sessionExport = SessionExport(source = "unavailable", diagnostic = "no native export path"), + artifacts = listOf(artifact("session.md", "text/markdown")), + ), + ), + ) + } + + @Test + fun theRecordedExportNamesResolveToTheListedArtifacts() { + val artifacts = listOf( + artifact("shot.png", "image/png"), + artifact("session.md", "text/markdown"), + artifact("session.html", "text/html"), + ) + val files = sessionExportFiles(RunStep(sessionExport = nativeExport, artifacts = artifacts)) + ?: error("expected files") + assertEquals("session.md", files.markdown?.name) + assertEquals("session.html", files.html?.name) + assertEquals(SessionView.Markdown, defaultSessionView(files)) + assertTrue(sessionViewToggle(files)) + assertEquals(files.markdown, sessionArtifact(files, SessionView.Markdown)) + assertEquals(files.html, sessionArtifact(files, SessionView.Html)) + } + + @Test + fun htmlIsTheDefaultAndTheOnlyViewWhenMarkdownIsMissing() { + val export = SessionExport(html = "session.html", source = "native_export") + val files = sessionExportFiles( + RunStep(sessionExport = export, artifacts = listOf(artifact("session.html", "text/html"))), + ) ?: error("expected files") + assertNull(files.markdown) + assertEquals(SessionView.Html, defaultSessionView(files)) + // The toggle only exists when both exports were written; a single export + // has nothing to switch to. + assertFalse(sessionViewToggle(files)) + assertNull(sessionArtifact(files, SessionView.Markdown)) + } + + @Test + fun aTruncatedListingOrAnAbsentOneLeavesNoFilesToShow() { + assertNull(sessionExportFiles(RunStep(sessionExport = nativeExport))) + assertNull(sessionExportFiles(RunStep(sessionExport = nativeExport, artifacts = emptyList()))) + assertNull( + sessionExportFiles( + RunStep(sessionExport = nativeExport, artifacts = listOf(artifact("other.log", "text/plain"))), + ), + ) + } + + @Test + fun theSessionSectionAppearsBesideTheArtifactsOnlyWhenTheExportExists() { + val graph = Graph(stages = listOf(Stage(key = "implementer", type = "model", prompt = "do"))) + val artifacts = listOf(artifact("session.md", "text/markdown"), artifact("session.html", "text/html")) + val withSession = RunStep( + status = "completed", + outcome = "success", + sessionExport = nativeExport, + artifacts = artifacts, + ) + val specs = stageSectionSpecs("implementer", graph, listOf(withSession), visitIndex = 0, runContext = true) + val keys = specs.map { it.key } + assertEquals(listOf("artifacts", "session", "definition"), keys) + val session = specs.first { it.key == "session" } + assertEquals("Session", session.title) + assertTrue(session.session) + // The Session row is the visit's own chrome; the plain definition context + // never lists it. + assertFalse( + stageSectionSpecs("implementer", graph, listOf(withSession), visitIndex = 0, runContext = false) + .any { it.session }, + ) + } + + @Test + fun aVisitWithoutAnExportListsNoSessionSection() { + val graph = Graph(stages = listOf(Stage(key = "s", type = "model"))) + val step = RunStep(status = "completed", outcome = "success", sessionExport = null) + assertFalse(stageSectionSpecs("s", graph, listOf(step), visitIndex = 0, runContext = true).any { it.session }) + } + + @Test + fun aFailedFetchIsItsOwnErrorAndNeverAnEmptySession() { + assertEquals(SessionLoad.Error, sessionLoad(bytes = null, markdown = true)) + assertEquals(SessionLoad.Error, sessionLoad(bytes = null, markdown = false)) + } + + @Test + fun aFetchedFileDecodesToItsView() { + val bytes = "# Title\n\nbody".toByteArray() + assertTrue(sessionLoad(bytes, markdown = true) is SessionLoad.Markdown) + val html = sessionLoad(bytes, markdown = false) + assertTrue(html is SessionLoad.Html) + assertEquals("# Title\n\nbody", (html as SessionLoad.Html).document) + } + + @Test + fun aLargeSessionParsesIntoBlocksOffTheViewer() { + // Several hundred kilobytes of markdown: the viewer parses it once into + // blocks (off the main thread) and composes them lazily, so this must not + // fail, throw or drop the document. + val large = buildString { + repeat(6_000) { index -> + append("# Heading $index\n\n") + append("A body line with *emphasis*, `code` and a [link](https://example.test/$index).\n\n") + } + } + assertTrue(large.length > 300_000) + val load = sessionLoad(large.toByteArray(), markdown = true) + assertTrue(load is SessionLoad.Markdown) + assertTrue((load as SessionLoad.Markdown).blocks.size >= 6_000) + } + + private fun artifact(name: String, contentType: String): StageArtifact = + StageArtifact(name = name, sizeBytes = 1, contentType = contentType, url = "/artifacts/9/1/$name") +}