diff --git a/android/README.md b/android/README.md index 1bdb419c..82e7be3b 100644 --- a/android/README.md +++ b/android/README.md @@ -443,3 +443,106 @@ physical device was not re-installed by this pass either). with `adb emu kill` plus `kill -9` of any surviving `qemu-system-aarch64-headless`. +## Per-visit artifacts, collapsed defaults, single top inset, APK publish (15 Oct 2026) + +Four changes were implemented in `android/` only. Nothing in the Pipelines +server, its Go source, Docker/compose files or the installer was touched, no run +was started from the app, and the 8 MiB per-file artifact cap +(`internal/server/artifacts.go` `maxArtifactFileBytes`) was left unchanged. + +- **Artifacts.** `RunStep` now models the server's `artifacts` + (`StageArtifact{name, size_bytes, content_type, url}`), `artifacts_skipped` and + `artifacts_truncated` with the exact `internal/protocol/runs.go` wire names. + `ui/graph/Artifacts.kt` renders one row per file (name, `humanBytes` size, + content type) with an open (`ACTION_VIEW`) and a copy-link action, an inline + image thumbnail (OkHttp + `BitmapFactory` with `inSampleSize` off the main + thread, bytes cached once per URL) and a full-size view on tap; other types get + a type icon. URLs are resolved by `ServerUrl.resolveArtifactUrl` against the + configured server URL (ws→http/wss→https, `/connect` dropped), never a + hardcoded host; with no URL configured the actions are disabled and a hint is + shown. Empty/partial states reuse the TUI strings from + `internal/tui/file_changes.go`. The Timeline rows carry a subtle `AttachFile` + indicator (`hasArtifacts`) with a per-visit `contentDescription`. +- **Collapsed defaults + self-describing titles.** `SectionExpansionState` now + persists the set of *expanded* keys (default empty), so every inner section in + the run detail (input/output/evidence) and pipeline detail (Versions, Source) + starts collapsed while operator choices still survive configuration changes. + Evidence section titles are built by `evidenceSectionTitle`, e.g. + `Evidence - step 4, ui_reviewer visit 1, opencode`, correlating + `SessionEvidence.sequence` with the run's steps once per data change; a blank + field key already falls back to its prefix and never yields an empty title. +- **Top inset.** The outer `Scaffold` in `PipelinesApp` now uses + `contentWindowInsets = WindowInsets(0, 0, 0, 0)` so the inner Material 3 app + bars own the status-bar inset exactly once (removing the duplicate top band); + the floating pill clears the navigation bar via + `windowInsetsPadding(WindowInsets.navigationBars)`. While the connection banner + is visible it owns the status-bar inset (padding inside its `Surface`) and the + `NavHost` below consumes `statusBars` so the app bar is not double-padded. +- **APK publish.** `:app:assembleDebug` produced + `app/build/outputs/apk/debug/app-debug.apk` (18,181,943 bytes, sha256 + `41c9df314da40bb19df7e3d90f27a83339a275768cefee537c4ba796efe01eab`, rebuilt + after the follow-up fixes below), copied to + `~/.local/share/pipelines/data/artifacts/58/1/pipelines-debug-d00bd37.apk` + (`d00bd37` = short SHA of the last commit touching `android/`) with a matching + `shasum -a 256`. At 17.3 MiB it exceeds the 8 MiB per-file inventory cap + (`internal/server/artifacts.go` `maxArtifactFileBytes = 8 << 20`), so it is + served by direct URL but deliberately absent from the step inventory. + +### Follow-up fixes (code review of the first pass) + +- `ui/graph/Artifacts.kt` hoists its derivations with `remember(step)` / + `remember(artifact.url, configuredServerUrl)` / `remember(artifact)` so the + summary text, the partial-capture notes, the resolved URL, the image test and + the meta line are computed once per data change, never per recomposition. +- `ArtifactBytesCache` is a byte-bounded `LruCache` (16 MiB) rather than an + unbounded map, so a long session cannot retain every fetched artifact. +- `artifactCaptureNotes` returns no notes for an empty artifact list, matching + `internal/tui/file_changes.go` `artifactLines` (which returns nothing when the + list is empty); the empty-state summary is unchanged. +- The field-section title fallback is the pure `fieldSectionTitle`, covered by + `TimelineTest#fieldSectionTitleFallsBackToPrefixAndIsNeverEmpty`. + +Evidence actually obtained in this pass (macOS, JDK 17 from Homebrew +`openjdk@17`, Gradle 8.11.1 from the wrapper cache, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `:app:testDebugUnitTest` reported **103 tests, 0 failures** (new + `ProtocolModelTest#runStepArtifactsParseWithExactWireNamesOrAbsent`, + `FormatTest` cases for `humanBytes`/`artifactMetaLine`/`artifactsSummary`/ + `artifactCaptureNotes`, `ServerUrlTest#resolvesArtifactUrlAgainstTheConfiguredServerUrl` + and `resolveArtifactUrlReturnsNullWhenUnconfiguredOrBlank`, + `DetailTabsTest#sectionsStartCollapsedAndToggleIsRemembered`, and `TimelineTest` + cases for `hasArtifacts`/`evidenceSectionTitle`/`fieldSectionTitle`). +- `:app:assembleDebug` succeeded (18,181,943-byte debug APK). +- `:app:lintDebug` still reports the two pre-existing `NewApi` errors for + `android:windowLightNavigationBar` (minSdk 26) in `res/values/themes.xml` and + `res/values-night/themes.xml`; those files were not modified by this change. + +Verified against the live server (running as +`pipelines-server -addr 0.0.0.0:8080`, the app configured +`ws://10.0.2.2:8080/connect`; LAN address `10.0.0.249` from `ipconfig getifaddr en0`): + +- The published APK is served at + `http://10.0.0.249:8080/artifacts/58/1/pipelines-debug-d00bd37.apk` (LAN), not a + hardcoded `localhost`/`10.0.2.2` host. `curl -I` returned `HTTP/1.1 200 OK`, + `Content-Type: application/vnd.android.package-archive`, `Content-Length: + 18181943`; a streamed `GET` piped to `shasum -a 256` returned + `41c9df314da40bb19df7e3d90f27a83339a275768cefee537c4ba796efe01eab`, equal to the + local `app-debug.apk`. +- Run 55 step 4's real artifacts are served: + `curl -I http://10.0.0.249:8080/artifacts/55/4/graph_crop_error_rejected.png` + → 200, `image/png`, 52,168 bytes and + `.../swatch_error_vs_rejected.png` → 200, `image/png`, 5,008 bytes. +- The server has no HTTP inventory endpoint (only `GET /artifacts/…`, + `GET /healthz`, `GET /connect`); the step inventory is delivered over the + websocket and clips entries larger than `maxArtifactFileBytes` (8 MiB), so the + 17.3 MiB APK is intentionally absent from it. + +Not verified in this pass — no device was attached (`adb devices` listed no +devices, and no emulator was running): the on-device/emulator narrow/wide +before/after screenshots for the top inset and the collapsed sections, the +`logcat` sweep and the install on the Pixel 10 Pro Fold. The previous pass's +emulator screenshots for the artifacts sheet (narrow/wide run detail) are in +`~/.local/share/pipelines/data/artifacts/58/3/`. + + diff --git a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt index 088261ef..7ddf2975 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt @@ -72,6 +72,9 @@ class PipelinesRepository( suspend fun getRunEvidence(id: Long): List = client.call(Message(type = Protocol.GET_RUN_EVIDENCE, runId = id)).evidence ?: emptyList() + /** Fetches an artifact's bytes (image preview) over the shared HTTP client. */ + suspend fun fetchArtifactBytes(url: String): ByteArray = client.fetchBytes(url) + suspend fun startRun( pipelineId: Long, version: Int, 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 4b4a0288..6f07efc3 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 @@ -199,6 +199,20 @@ data class StageFileChanges( val diagnostic: String? = null, ) +/** + * One file a stage left in its artifacts directory. Mirrors + * internal/protocol/runs.go StageArtifact exactly: observed server-side + * evidence, not a model's claim. An absent artifact list means nothing was + * recorded for the visit (including historical steps). + */ +@Serializable +data class StageArtifact( + val name: String = "", + @SerialName("size_bytes") val sizeBytes: Long = 0, + @SerialName("content_type") val contentType: String = "", + val url: String = "", +) + @Serializable data class NotificationReceipt( val destination: String = "", @@ -242,6 +256,11 @@ data class RunStep( val control: ControlEvidence? = null, @SerialName("file_changes") val fileChanges: StageFileChanges? = null, val notifications: List? = null, + // Absent (null) means the step carried no artifact field; an empty list means + // an explicitly recorded, empty capture. Mirrors internal/protocol/runs.go. + val artifacts: List? = null, + @SerialName("artifacts_skipped") val artifactsSkipped: Int = 0, + @SerialName("artifacts_truncated") val artifactsTruncated: Int = 0, val sequence: Int = 0, val stage: String = "", val status: String = "", diff --git a/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt b/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt index 2e43d153..b4a8d9f1 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt @@ -122,6 +122,19 @@ class PipelinesClient( } } + /** + * Fetches raw bytes for a resolved artifact url over the existing OkHttp + * client on the IO dispatcher. Used for image previews; never part of the + * run poll. A non-2xx response or an empty body is an error. + */ + suspend fun fetchBytes(url: String): ByteArray = withContext(ioDispatcher) { + val request = Request.Builder().url(url).build() + httpClient.newCall(request).execute().use { response -> + if (!response.isSuccessful) throw IOException("HTTP ${response.code} for $url") + response.body?.bytes() ?: throw IOException("empty response body for $url") + } + } + private fun open() { val current = endpoint ?: return attempt += 1 diff --git a/android/app/src/main/java/net/awan/pipelines/data/transport/ServerUrl.kt b/android/app/src/main/java/net/awan/pipelines/data/transport/ServerUrl.kt index d3e91554..9e98f4d2 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/transport/ServerUrl.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/transport/ServerUrl.kt @@ -82,4 +82,30 @@ object ServerUrl { secure = secure, ) } + + /** + * Resolves a server-relative artifact url (for example + * `/artifacts/55/4/shot.png`) against the configured server URL by reusing + * [validate]'s host/port/secure and mapping ws/wss to http/https, dropping the + * `/connect` websocket path. Never hardcodes a host: a blank or invalid + * configuration, or a blank path, yields null so the UI can disable actions. + * + * An already-absolute `http(s)://` url is returned unchanged. + */ + fun resolveArtifactUrl(configured: String, artifactUrl: String): String? { + val relative = artifactUrl.trim() + if (relative.isEmpty()) return null + if (relative.startsWith("http://") || relative.startsWith("https://")) return relative + val validated = validate(configured) + if (!validated.valid || validated.host.isNullOrBlank()) return null + val origin = buildString { + append(if (validated.secure) "https" else "http").append("://").append(validated.host) + val defaultPort = if (validated.secure) 443 else 80 + if (validated.port > 0 && validated.port != defaultPort) { + append(':').append(validated.port) + } + } + val path = if (relative.startsWith("/")) relative else "/$relative" + return origin + path + } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt index fa9b9f08..37b1a14a 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt @@ -188,6 +188,10 @@ class AppViewModel( fun loadEvidence(id: Long) = load(_evidence) { repository.getRunEvidence(id) } + /** Fetches an artifact's bytes for an inline image preview; null on failure. */ + suspend fun fetchArtifactBytes(url: String): ByteArray? = + runCatching { repository.fetchArtifactBytes(url) }.getOrNull() + /** * Drops any previously loaded evidence so a different run never shows the * previous run's records. Evidence is then fetched on demand, never polled. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/Format.kt b/android/app/src/main/java/net/awan/pipelines/ui/Format.kt index c5b19ba3..d13ddadb 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/Format.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/Format.kt @@ -8,6 +8,8 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import net.awan.pipelines.data.protocol.FileChange import net.awan.pipelines.data.protocol.NotificationReceipt +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.StageArtifact import net.awan.pipelines.data.protocol.StageFileChanges /** Human duration between two RFC3339 timestamps, or null when unavailable. */ @@ -85,3 +87,61 @@ fun fileChangesSummary(changes: StageFileChanges): String = buildString { append("${changes.skipped} skipped") } } + +/** + * Human-readable byte size, matching internal/tui/file_changes.go humanBytes + * exactly: whole bytes under 1 KiB, otherwise one decimal with a binary unit + * (KiB/MiB/GiB/TiB/PiB/EiB). The single formatter for every size the UI shows. + */ +fun humanBytes(size: Long): String { + val unit = 1024L + if (size < unit) return "$size B" + var div = unit + var exp = 0 + var value = size / unit + while (value >= unit) { + div *= unit + exp++ + value /= unit + } + return String.format(java.util.Locale.US, "%.1f %ciB", size.toDouble() / div.toDouble(), "KMGTPE"[exp]) +} + +/** Whether an artifact's content type is an image the sheet can preview. */ +fun isImageContentType(contentType: String): Boolean = contentType.startsWith("image/") + +/** + * The artifacts summary label, mirroring internal/tui/file_changes.go + * artifactsSummary: "capture pending" while the visit runs, "not recorded for + * this visit" for a finished visit with no artifacts, otherwise the recorded + * count plus " · partial capture" when files were excluded or omitted. + */ +fun artifactsSummary(step: RunStep): String { + val artifacts = step.artifacts.orEmpty() + if (artifacts.isEmpty()) { + val state = if (step.status == "running") "capture pending" else "not recorded for this visit" + return "Artifacts · $state" + } + var label = "Artifacts · ${artifacts.size} recorded" + if (step.artifactsSkipped > 0 || step.artifactsTruncated > 0) label += " · partial capture" + return label +} + +/** + * The partial-capture notes, mirroring internal/tui/file_changes.go artifactLines: + * one line per non-zero count, and nothing when the capture was complete. An + * empty artifact list yields no notes at all (the TUI returns nothing for it), so + * the notes never accompany the empty-state summary. + */ +fun artifactCaptureNotes(step: RunStep): List = buildList { + if (step.artifacts.isNullOrEmpty()) return@buildList + if (step.artifactsSkipped > 0) add("${step.artifactsSkipped} files excluded from artifact capture.") + if (step.artifactsTruncated > 0) add("${step.artifactsTruncated} files omitted by artifact capture limits.") +} + +/** + * One artifact's meta line: its human-readable size and content type. A blank or + * missing content type never renders as a dangling separator. + */ +fun artifactMetaLine(artifact: StageArtifact): String = + "${humanBytes(artifact.sizeBytes)} · ${artifact.contentType.ifBlank { "unknown type" }}" diff --git a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt index 3673fb24..f68ca8e7 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt @@ -5,11 +5,16 @@ 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.WindowInsets +import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape @@ -47,6 +52,7 @@ import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument +import net.awan.pipelines.data.transport.ConnectionState import net.awan.pipelines.ui.components.ConnectionBanner import net.awan.pipelines.ui.components.EmptyState import net.awan.pipelines.ui.screens.PipelineDetailScreen @@ -94,11 +100,17 @@ fun PipelinesApp(vm: AppViewModel) { } // No bottomBar: the destinations float over the content as a pill (below). - // Scaffold still applies the system-bar insets to [padding], so the pill - // clears the navigation bar/gesture area; the Column reserves + // + // Exactly one layer owns the top inset. The outer Scaffold's content insets + // are zeroed so it no longer reserves the status bar on top of the inner + // screens' app bars (a Material 3 TopAppBar already applies the status-bar + // inset), which removed the duplicate top band. The bottom is owned by each + // screen's Scaffold, and the floating pill explicitly clears the navigation + // bar/gesture area via windowInsetsPadding. The Column reserves // DESTINATION_PILL_RESERVE at the bottom so no scrollable content is - // permanently hidden behind it. The same pill is used on both window widths. - Scaffold { padding -> + // permanently hidden behind the pill. + val bannerVisible = connectionState !is ConnectionState.Connected + Scaffold(contentWindowInsets = WindowInsets(0, 0, 0, 0)) { padding -> Box(Modifier.fillMaxSize().padding(padding)) { Column(Modifier.fillMaxSize().padding(bottom = DESTINATION_PILL_RESERVE)) { ConnectionBanner( @@ -109,7 +121,17 @@ fun PipelinesApp(vm: AppViewModel) { NavHost( navController = navController, startDestination = "pipelines", - modifier = Modifier.weight(1f), + // While the banner is visible it owns the status-bar inset, so + // the inner app bars below must not apply it a second time. + modifier = Modifier + .weight(1f) + .then( + if (bannerVisible) { + Modifier.consumeWindowInsets(WindowInsets.statusBars) + } else { + Modifier + }, + ), ) { composable("pipelines") { if (wide) { @@ -166,6 +188,7 @@ fun PipelinesApp(vm: AppViewModel) { onSelect = onNavigate, modifier = Modifier .align(Alignment.BottomEnd) + .windowInsetsPadding(WindowInsets.navigationBars) .padding(end = 16.dp, bottom = 16.dp), ) } @@ -175,7 +198,8 @@ fun PipelinesApp(vm: AppViewModel) { /** * The Pipelines/Runs/Settings destinations as a floating rounded pill at the * bottom right: the three destinations as icons, inset from the bottom/right - * edges (the Scaffold padding applies the system-bar insets), each a 48dp touch + * edges (it clears the navigation bar/gesture area via windowInsetsPadding), + * each a 48dp touch * target. Selection is a tonal container plus the `Role.Tab` selected * accessibility state — never colour alone — and tapping switches destination * through the caller's existing navigate/popUpTo logic. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/ConnectionBanner.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/ConnectionBanner.kt index 0e15de4b..cc50fdcc 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/components/ConnectionBanner.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/ConnectionBanner.kt @@ -2,8 +2,11 @@ package net.awan.pipelines.ui.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBars +import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text @@ -71,7 +74,12 @@ private fun Banner( ) { Surface(color = container, contentColor = contentColor, modifier = modifier.fillMaxWidth()) { Row( - modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + // The banner sits directly under the status bar (the outer Scaffold + // zeroes its content insets), so it owns the status-bar inset: the + // padding is inside the Surface so the banner colour covers the bar. + modifier = Modifier + .windowInsetsPadding(WindowInsets.statusBars) + .padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/DetailTabs.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/DetailTabs.kt index 11d60467..c95467d3 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/components/DetailTabs.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/DetailTabs.kt @@ -252,32 +252,33 @@ fun DetailTabBody( } /** - * Remembers which inner sections are collapsed, keyed by their stable section - * key and saved across configuration changes, defaulting every section to - * expanded. A collapsed set is persisted (as an [ArrayList] the Bundle can hold). + * Remembers which inner sections are expanded, keyed by their stable section + * key and saved across configuration changes. Every section starts collapsed the + * first time a screen is opened (the initial set is empty); the operator's own + * expand/collapse choices are persisted (as an [ArrayList] a Bundle can hold). */ @Stable class SectionExpansionState internal constructor( - private val collapsed: androidx.compose.runtime.MutableState>, + private val expanded: androidx.compose.runtime.MutableState>, ) { - fun isExpanded(key: String): Boolean = key !in collapsed.value + fun isExpanded(key: String): Boolean = key in expanded.value fun toggle(key: String) { - collapsed.value = if (key in collapsed.value) collapsed.value - key else collapsed.value + key + expanded.value = if (key in expanded.value) expanded.value - key else expanded.value + key } } -private val collapsedKeysSaver: Saver, ArrayList> = Saver( +private val expandedKeysSaver: Saver, ArrayList> = Saver( save = { ArrayList(it) }, restore = { it.toSet() }, ) @Composable fun rememberSectionExpansion(vararg inputs: Any?): SectionExpansionState { - val collapsed = rememberSaveable(*inputs, stateSaver = collapsedKeysSaver) { + val expanded = rememberSaveable(*inputs, stateSaver = expandedKeysSaver) { mutableStateOf(emptySet()) } - return remember(collapsed) { SectionExpansionState(collapsed) } + return remember(expanded) { SectionExpansionState(expanded) } } private const val WIDE_RAIL_WIDTH_DP = 200 diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactImage.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactImage.kt new file mode 100644 index 00000000..9a594b46 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactImage.kt @@ -0,0 +1,147 @@ +package net.awan.pipelines.ui.graph + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.util.LruCache +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * Encoded artifact bytes, fetched at most once per url and kept in memory so a + * recomposition or a second preview never re-hits the network. Bounded by total + * bytes so a long session never grows without limit; a single artifact larger + * than the budget is simply evicted rather than retained. The fetch itself runs + * on the repository's IO dispatcher. + */ +internal object ArtifactBytesCache { + private val cache = object : LruCache(MAX_CACHED_BYTES) { + override fun sizeOf(key: String, value: ByteArray): Int = value.size + } + + fun get(url: String): ByteArray? = cache.get(url) + + fun put(url: String, bytes: ByteArray) { + cache.put(url, bytes) + } +} + +/** Total encoded bytes held for artifact previews (16 MiB). */ +private const val MAX_CACHED_BYTES = 16 * 1024 * 1024 + +/** Decoded previews, keyed by url + requested sample size, bounded by count. */ +private val artifactBitmapCache = object : LruCache(MAX_CACHED_BITMAPS) { + override fun sizeOf(key: String, value: Bitmap): Int = 1 +} + +private const val MAX_CACHED_BITMAPS = 24 + +/** Nothing is shown until the bytes arrive, and a failure is shown, not crashed. */ +private sealed interface ArtifactImageState { + data object Loading : ArtifactImageState + data object Error : ArtifactImageState + data class Ready(val bitmap: Bitmap) : ArtifactImageState +} + +/** + * An inline artifact preview. Fetching and decoding happen off the main thread + * and are cached; [maxDim] requests a thumbnail-sized decode (a full-resolution + * bitmap is only used for the explicit full-size view, [maxDim] <= 0). + */ +@Composable +internal fun ArtifactImage( + url: String, + contentDescription: String?, + maxDim: Int, + fetchBytes: suspend (String) -> ByteArray?, + modifier: Modifier = Modifier, + size: Dp = 56.dp, +) { + val state = rememberArtifactBitmap(url, maxDim, fetchBytes) + Box(modifier.size(size), contentAlignment = Alignment.Center) { + when (val current = state) { + is ArtifactImageState.Ready -> Image( + bitmap = current.bitmap.asImageBitmap(), + contentDescription = contentDescription, + contentScale = ContentScale.Fit, + modifier = Modifier.size(size), + ) + ArtifactImageState.Loading -> Text("…", style = MaterialTheme.typography.bodySmall) + ArtifactImageState.Error -> Text( + "!", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + } +} + +@Composable +private fun rememberArtifactBitmap( + url: String, + maxDim: Int, + fetchBytes: suspend (String) -> ByteArray?, +): ArtifactImageState { + val key = "$url@$maxDim" + var state by remember(key) { mutableStateOf(ArtifactImageState.Loading) } + LaunchedEffect(key) { + artifactBitmapCache.get(key)?.let { + state = ArtifactImageState.Ready(it) + return@LaunchedEffect + } + val bytes = ArtifactBytesCache.get(url) + ?: runCatching { withContext(Dispatchers.IO) { fetchBytes(url) } }.getOrNull() + if (bytes == null) { + state = ArtifactImageState.Error + return@LaunchedEffect + } + ArtifactBytesCache.put(url, bytes) + val bitmap = withContext(Dispatchers.IO) { decodeSampled(bytes, maxDim) } + if (bitmap == null) { + state = ArtifactImageState.Error + } else { + artifactBitmapCache.put(key, bitmap) + state = ArtifactImageState.Ready(bitmap) + } + } + return state +} + +/** + * Decodes [bytes], downsampling to roughly [maxDim] on the longest edge when + * [maxDim] > 0 (so the list never holds full-resolution bitmaps), or at full + * resolution when [maxDim] <= 0. Returns null on malformed data instead of + * throwing. + */ +private fun decodeSampled(bytes: ByteArray, maxDim: Int): Bitmap? = try { + if (maxDim <= 0) { + BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + } else { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + var sample = 1 + while (bounds.outWidth / sample > maxDim || bounds.outHeight / sample > maxDim) { + sample *= 2 + } + val options = BitmapFactory.Options().apply { inSampleSize = sample } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) + } +} catch (_: Throwable) { + null +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/Artifacts.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/Artifacts.kt new file mode 100644 index 00000000..ec277d68 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/Artifacts.kt @@ -0,0 +1,218 @@ +package net.awan.pipelines.ui.graph + +import android.content.Context +import android.content.Intent +import android.net.Uri +import androidx.compose.foundation.clickable +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.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.InsertDriveFile +import androidx.compose.material.icons.automirrored.filled.OpenInNew +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Image +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.StageArtifact +import net.awan.pipelines.data.transport.ServerUrl +import net.awan.pipelines.ui.artifactCaptureNotes +import net.awan.pipelines.ui.artifactMetaLine +import net.awan.pipelines.ui.artifactsSummary +import net.awan.pipelines.ui.isImageContentType +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * The per-visit artifacts section for the stage detail sheet: the summary line + * (matching the TUI's empty/partial wording), one row per file, and the + * partial-capture notes. The single artifacts rendering path; it resolves each + * url against the configured server URL and never hardcodes a host. + * + * When no server URL is configured the rows still show (name/size/type) but the + * open/copy actions are disabled and a hint is shown. + */ +@Composable +internal fun ArtifactsSection( + step: RunStep, + configuredServerUrl: String, + fetchArtifactBytes: suspend (String) -> ByteArray?, + modifier: Modifier = Modifier, +) { + val text = pipelinesText() + // Derived once per data change, never per recomposition (performance requirement). + val artifacts = remember(step) { step.artifacts.orEmpty() } + val summary = remember(step) { artifactsSummary(step) } + val notes = remember(step) { artifactCaptureNotes(step) } + Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(summary, style = text.label, color = MaterialTheme.colorScheme.primary) + if (configuredServerUrl.isBlank()) { + Text( + "Set the server URL in Settings to open or copy artifact links.", + style = text.meta, + ) + } + artifacts.forEach { artifact -> + ArtifactRow(artifact, configuredServerUrl, fetchArtifactBytes) + } + notes.forEach { note -> Text(note, style = text.meta) } + } +} + +/** One artifact: a type thumbnail (or inline preview), name, size/type, actions. */ +@Composable +private fun ArtifactRow( + artifact: StageArtifact, + configuredServerUrl: String, + fetchArtifactBytes: suspend (String) -> ByteArray?, +) { + val text = pipelinesText() + val context = LocalContext.current + val clipboard = LocalClipboardManager.current + // Resolve/format once per (url, configuration), not on every recomposition. + val resolved = remember(artifact.url, configuredServerUrl) { + ServerUrl.resolveArtifactUrl(configuredServerUrl, artifact.url) + } + val isImage = remember(artifact.contentType) { isImageContentType(artifact.contentType) } + val metaLine = remember(artifact) { artifactMetaLine(artifact) } + var showFull by remember(artifact.url) { mutableStateOf(false) } + + Surface( + shape = RoundedCornerShape(12.dp), + color = MaterialTheme.colorScheme.surfaceContainer, + modifier = Modifier.fillMaxWidth(), + ) { + Row( + modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + val thumbModifier = Modifier + .size(56.dp) + .clip(RoundedCornerShape(8.dp)) + if (isImage && resolved != null) { + ArtifactImage( + url = resolved, + contentDescription = "Preview of ${artifact.name}", + maxDim = THUMBNAIL_MAX_DIM, + fetchBytes = fetchArtifactBytes, + modifier = thumbModifier.clickable { showFull = true }, + ) + } else { + Box(thumbModifier, contentAlignment = Alignment.Center) { + Icon( + imageVector = if (isImage) Icons.Default.Image else Icons.AutoMirrored.Filled.InsertDriveFile, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + artifact.name.ifBlank { "(unnamed artifact)" }, + style = text.cardTitle, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + Text( + metaLine, + style = text.meta, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + IconButton( + onClick = { openArtifact(context, resolved) }, + enabled = resolved != null, + ) { + Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = "Open ${artifact.name}") + } + IconButton( + onClick = { resolved?.let { clipboard.setText(AnnotatedString(it)) } }, + enabled = resolved != null, + ) { + Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to ${artifact.name}") + } + } + } + + if (showFull && resolved != null) { + FullSizeArtifactDialog( + url = resolved, + name = artifact.name, + fetchBytes = fetchArtifactBytes, + onDismiss = { showFull = false }, + ) + } +} + +/** The explicit full-resolution view, opened by tapping an image thumbnail. */ +@Composable +private fun FullSizeArtifactDialog( + url: String, + name: String, + fetchBytes: suspend (String) -> ByteArray?, + onDismiss: () -> Unit, +) { + val text = pipelinesText() + Dialog(onDismissRequest = onDismiss) { + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + ) { + Column( + modifier = Modifier.padding(12.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + name.ifBlank { "Artifact" }, + style = text.cardTitle, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + ArtifactImage( + url = url, + contentDescription = name, + maxDim = 0, + fetchBytes = fetchBytes, + size = FULL_SIZE_PREVIEW_DP.dp, + ) + } + } + } +} + +/** Opens the resolved artifact url externally, tolerating a missing handler. */ +private fun openArtifact(context: Context, url: String?) { + if (url == null) return + runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } +} + +/** Longest edge of a list thumbnail decode. */ +private const val THUMBNAIL_MAX_DIM = 160 + +/** Fixed box for the full-size preview. */ +private const val FULL_SIZE_PREVIEW_DP = 320 diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailSheet.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailSheet.kt index 5c4843e7..1f14dc38 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailSheet.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailSheet.kt @@ -238,6 +238,8 @@ fun StageDetailSheet( graph: Graph, runSteps: List = emptyList(), initialVisitIndex: Int = 0, + configuredServerUrl: String = "", + fetchArtifactBytes: suspend (String) -> ByteArray? = { null }, onDismiss: () -> Unit, ) { val text = pipelinesText() @@ -294,11 +296,16 @@ fun StageDetailSheet( Text("Definition", style = text.sectionHeader, modifier = Modifier.padding(top = 8.dp)) definition.forEach { field -> StageFieldRow(field) } } - if (run.isNotEmpty()) { + if (selectedStep != null) { Text("This run", style = text.sectionHeader, modifier = Modifier.padding(top = 8.dp)) run.forEach { field -> StageFieldRow(field) } + ArtifactsSection( + step = selectedStep, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, + ) } - if (definition.isEmpty() && run.isEmpty()) { + if (definition.isEmpty() && selectedStep == null) { Text("No details recorded for this node.", style = text.meta) } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt index 241eb132..4071f8cc 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt @@ -151,7 +151,9 @@ fun PipelineDetailScreen( @Composable private fun PipelineSummaryTab(detail: PipelineDetail, wide: Boolean, modifier: Modifier) { val text = pipelinesText() - var versionsExpanded by rememberSaveable { mutableStateOf(true) } + // The first time the detail is opened every inner section starts collapsed; + // the operator's own choice is still remembered/saved. + var versionsExpanded by rememberSaveable { mutableStateOf(false) } DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt index 0d247423..2b16e743 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt @@ -13,6 +13,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.AttachFile import androidx.compose.material.icons.filled.Cancel import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Replay @@ -46,6 +47,7 @@ import kotlinx.serialization.json.JsonElement import net.awan.pipelines.data.ErrorMessages import net.awan.pipelines.data.protocol.RunDetail import net.awan.pipelines.data.protocol.RunGraphState +import net.awan.pipelines.data.protocol.RunStep import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.ui.AppViewModel import net.awan.pipelines.ui.LoadState @@ -79,6 +81,7 @@ fun RunDetailScreen( ) { val state by vm.runDetail.collectAsStateWithLifecycle() val evidenceState by vm.evidence.collectAsStateWithLifecycle() + val configuredServerUrl by vm.configuredServerUrl.collectAsStateWithLifecycle() var confirmCancel by remember { mutableStateOf(false) } var confirmRetry by remember { mutableStateOf(false) } var actionError by remember { mutableStateOf(null) } @@ -152,7 +155,12 @@ fun RunDetailScreen( // Only the selected tab's content composes (one scroll container each). when (tab.key) { "summary" -> RunSummaryTab(run, wide, contentModifier) - "graph" -> RunGraphTab(run, contentModifier) + "graph" -> RunGraphTab( + run = run, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = vm::fetchArtifactBytes, + modifier = contentModifier, + ) "input" -> RunFieldSectionsTab( emptyMessage = "No input recorded.", keyPrefix = "input", @@ -169,11 +177,18 @@ fun RunDetailScreen( ) "evidence" -> RunEvidenceTab( evidenceState = evidenceState, + steps = run.steps, onLoadEvidence = { vm.loadEvidence(runId) }, wide = wide, modifier = contentModifier, ) - else -> RunTimelineTab(run, wide, contentModifier) + else -> RunTimelineTab( + run = run, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = vm::fetchArtifactBytes, + wide = wide, + modifier = contentModifier, + ) } } } @@ -298,7 +313,12 @@ private fun RunSummaryTab(run: RunDetail, wide: Boolean, modifier: Modifier) { * is the scroll container, so an expanded panel scrolls instead of clipping. */ @Composable -private fun RunGraphTab(run: RunDetail, modifier: Modifier) { +private fun RunGraphTab( + run: RunDetail, + configuredServerUrl: String, + fetchArtifactBytes: suspend (String) -> ByteArray?, + modifier: Modifier, +) { val text = pipelinesText() val runState = remember(run.id, run.steps) { RunGraphState.from(run) } // Grouped once per step-list change; the sheet opened from the graph starts on @@ -341,6 +361,8 @@ private fun RunGraphTab(run: RunDetail, modifier: Modifier) { // Every recorded visit for the stage, opening on the most recent one. runSteps = visits, initialVisitIndex = (visits.size - 1).coerceAtLeast(0), + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, onDismiss = { selectedStage = null }, ) } @@ -376,7 +398,7 @@ private fun RunFieldSectionsTab( } } else { entries.forEach { (key, value) -> - val label = key.ifBlank { keyPrefix } + val label = fieldSectionTitle(key, keyPrefix) val sectionKey = "$keyPrefix-$key" collapsibleSection( title = label, @@ -403,6 +425,7 @@ private fun RunFieldSectionsTab( @Composable private fun RunEvidenceTab( evidenceState: LoadState>, + steps: List, onLoadEvidence: () -> Unit, wide: Boolean, modifier: Modifier, @@ -410,6 +433,9 @@ private fun RunEvidenceTab( val text = pipelinesText() val evidence = evidenceState.data.orEmpty() val expansion = rememberSectionExpansion(evidence) + // Correlate each evidence record with its step once per data change, by the + // protocol's shared sequence, never per recomposition. + val stepBySequence = remember(steps) { steps.associateBy { it.sequence } } DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, @@ -451,7 +477,7 @@ private fun RunEvidenceTab( else -> evidence.forEach { record -> val sectionKey = "evidence-${record.sequence}-${record.sessionId}" collapsibleSection( - title = "Evidence ${record.sequence}", + title = evidenceSectionTitle(record, stepBySequence[record.sequence]), key = sectionKey, expanded = expansion.isExpanded(sectionKey), onToggle = { expansion.toggle(sectionKey) }, @@ -469,6 +495,37 @@ private fun RunEvidenceTab( } } +/** + * A field section's title: the field's own name, falling back to the section + * prefix (input/output) so a blank or missing key never yields an empty title. + */ +internal fun fieldSectionTitle(key: String, keyPrefix: String): String = key.ifBlank { keyPrefix } + +/** + * A self-describing evidence-section title: the step, and when the matching + * step is known the stage and visit, plus the backend (or, when absent, the + * session id) identity. Never a bare index; falls back gracefully when the + * record cannot be correlated with a step. + */ +internal fun evidenceSectionTitle(record: SessionEvidence, step: RunStep?): String { + val parts = ArrayList() + if (record.sequence > 0) parts += "step ${record.sequence}" + if (step != null) { + val visit = step.control?.visit?.takeIf { it > 0 } + val stage = buildString { + if (step.stage.isNotBlank()) append(step.stage) + if (visit != null) { + if (isNotEmpty()) append(' ') + append("visit $visit") + } + } + if (stage.isNotBlank()) parts += stage + } + val identity = record.backend.ifBlank { record.sessionId } + if (identity.isNotBlank()) parts += identity + return if (parts.isEmpty()) "Evidence" else "Evidence - " + parts.joinToString(", ") +} + /** * The Timeline tab: one compact line per recorded visit (stage name, visit * number, outcome chip and duration plus a brief description) and nothing else. @@ -478,7 +535,13 @@ private fun RunEvidenceTab( */ @OptIn(ExperimentalFoundationApi::class) @Composable -private fun RunTimelineTab(run: RunDetail, wide: Boolean, modifier: Modifier) { +private fun RunTimelineTab( + run: RunDetail, + configuredServerUrl: String, + fetchArtifactBytes: suspend (String) -> ByteArray?, + wide: Boolean, + modifier: Modifier, +) { val text = pipelinesText() // Grouped once per step-list change, not per recomposition. val timeline = remember(run.steps) { runTimeline(run.steps) } @@ -518,6 +581,8 @@ private fun RunTimelineTab(run: RunDetail, wide: Boolean, modifier: Modifier) { runSteps = timeline.visitsByStage[key].orEmpty(), // Open on the exact visit that was tapped. initialVisitIndex = sheetVisit, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, onDismiss = { sheetStage = null }, ) } @@ -560,6 +625,14 @@ private fun TimelineRow(entry: TimelineEntry, onClick: () -> Unit) { modifier = Modifier.weight(1f), ) StatusChip(label = chipLabel, state = state) + if (hasArtifacts(entry.step)) { + Icon( + imageVector = Icons.Default.AttachFile, + contentDescription = "Visit ${entry.visit} has recorded artifacts", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(14.dp), + ) + } if (entry.duration != null) { Text(entry.duration, style = text.meta, maxLines = 1) } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/Timeline.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/Timeline.kt index 125b0326..d41160bb 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/Timeline.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/Timeline.kt @@ -75,3 +75,10 @@ internal fun timelineDescription(step: RunStep): String { if (step.target.isNotBlank()) return "→ ${GraphSemantics.nodeLabel(step.target)}" return "" } + +/** + * Whether a visit recorded any artifacts. The single predicate behind the + * timeline's subtle artifact indicator, so the timeline and the sheet never + * disagree about whether a visit produced files. + */ +internal fun hasArtifacts(step: RunStep): Boolean = !step.artifacts.isNullOrEmpty() diff --git a/android/app/src/test/java/net/awan/pipelines/data/protocol/ProtocolModelTest.kt b/android/app/src/test/java/net/awan/pipelines/data/protocol/ProtocolModelTest.kt index 90c5e395..eff871cc 100644 --- a/android/app/src/test/java/net/awan/pipelines/data/protocol/ProtocolModelTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/data/protocol/ProtocolModelTest.kt @@ -96,6 +96,47 @@ class ProtocolModelTest { assertEquals(11L, decoded.runId) } + @Test + fun runStepArtifactsParseWithExactWireNamesOrAbsent() { + val json = """ + { + "type": "run", + "run_detail": { + "id": 55, + "steps": [ + { + "sequence": 4, + "stage": "ui_reviewer", + "status": "succeeded", + "artifacts": [ + {"name": "graph_crop_error_rejected.png", "size_bytes": 52168, "content_type": "image/png", "url": "/artifacts/55/4/graph_crop_error_rejected.png"}, + {"name": "swatch_error_vs_rejected.png", "size_bytes": 5008, "content_type": "image/png", "url": "/artifacts/55/4/swatch_error_vs_rejected.png"} + ], + "artifacts_skipped": 1, + "artifacts_truncated": 2 + }, + {"sequence": 5, "stage": "reviewer", "status": "succeeded"} + ] + } + } + """.trimIndent() + val run = PipelinesJson.decodeFromString(Message.serializer(), json).runDetail!! + val withArtifacts = run.steps.first() + assertEquals(2, withArtifacts.artifacts!!.size) + val first = withArtifacts.artifacts!!.first() + assertEquals("graph_crop_error_rejected.png", first.name) + assertEquals(52168L, first.sizeBytes) + assertEquals("image/png", first.contentType) + assertEquals("/artifacts/55/4/graph_crop_error_rejected.png", first.url) + assertEquals(1, withArtifacts.artifactsSkipped) + assertEquals(2, withArtifacts.artifactsTruncated) + // A step without them yields a null list and zero counts. + val without = run.steps[1] + assertNull(without.artifacts) + assertEquals(0, without.artifactsSkipped) + assertEquals(0, without.artifactsTruncated) + } + @Test fun pipelineDetailPopulatesInheritedAndWireNameFields() { val json = """ diff --git a/android/app/src/test/java/net/awan/pipelines/data/transport/ServerUrlTest.kt b/android/app/src/test/java/net/awan/pipelines/data/transport/ServerUrlTest.kt index 5d6a5d67..3b666a93 100644 --- a/android/app/src/test/java/net/awan/pipelines/data/transport/ServerUrlTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/data/transport/ServerUrlTest.kt @@ -2,6 +2,7 @@ package net.awan.pipelines.data.transport import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -61,4 +62,40 @@ class ServerUrlTest { assertEquals(ServerUrl.ErrorKind.EMPTY, ServerUrl.validate(" ").kind) assertEquals(ServerUrl.ErrorKind.UNSUPPORTED_SCHEME, ServerUrl.validate("host:8080/connect").kind) } + + @Test + fun resolvesArtifactUrlAgainstTheConfiguredServerUrl() { + // ws -> http, keeping the explicit non-default port and dropping /connect. + assertEquals( + "http://192.168.1.20:8081/artifacts/55/4/graph_crop_error_rejected.png", + ServerUrl.resolveArtifactUrl( + "ws://192.168.1.20:8081/connect", + "/artifacts/55/4/graph_crop_error_rejected.png", + ), + ) + // wss -> https. + assertEquals( + "https://pipelines.example/artifacts/1/1/a.png", + ServerUrl.resolveArtifactUrl("wss://pipelines.example/connect", "/artifacts/1/1/a.png"), + ) + // A default port is dropped; a relative path without a leading slash works. + assertEquals( + "http://host:8080/artifacts/1/1/a.png", + ServerUrl.resolveArtifactUrl("ws://host:8080", "artifacts/1/1/a.png"), + ) + // An already-absolute url passes through unchanged. + assertEquals( + "https://cdn.example/a.png", + ServerUrl.resolveArtifactUrl("ws://host:8080/connect", "https://cdn.example/a.png"), + ) + } + + @Test + fun resolveArtifactUrlReturnsNullWhenUnconfiguredOrBlank() { + assertNull(ServerUrl.resolveArtifactUrl("", "/artifacts/1/1/a.png")) + assertNull(ServerUrl.resolveArtifactUrl(" ", "/artifacts/1/1/a.png")) + assertNull(ServerUrl.resolveArtifactUrl("ws://host:8080/connect", " ")) + // An invalid configuration is never silently resolved to a hardcoded host. + assertNull(ServerUrl.resolveArtifactUrl("http://host:8080/connect", "/a.png")) + } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt index 1ffe13f4..dfd748f3 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt @@ -2,9 +2,13 @@ package net.awan.pipelines.ui import net.awan.pipelines.data.protocol.FileChange import net.awan.pipelines.data.protocol.NotificationReceipt +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.StageArtifact import net.awan.pipelines.data.protocol.StageFileChanges 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 FormatTest { @@ -56,4 +60,63 @@ class FormatTest { notificationLine(NotificationReceipt(status = "delivered", destination = "ntfy")), ) } + + @Test + fun humanBytesMatchesTheGoFormatter() { + assertEquals("0 B", humanBytes(0)) + assertEquals("1023 B", humanBytes(1023)) + assertEquals("1.0 KiB", humanBytes(1024)) + // The two real run 55 step 4 PNG sizes. + assertEquals("50.9 KiB", humanBytes(52168)) + assertEquals("4.9 KiB", humanBytes(5008)) + assertEquals("1.0 MiB", humanBytes(1024L * 1024)) + assertEquals("1.5 GiB", humanBytes(1610612736L)) + } + + @Test + fun artifactContentTypeAndMetaLine() { + assertTrue(isImageContentType("image/png")) + assertTrue(isImageContentType("image/jpeg")) + assertFalse(isImageContentType("application/pdf")) + assertFalse(isImageContentType("")) + assertEquals( + "50.9 KiB · image/png", + artifactMetaLine(StageArtifact(name = "a.png", sizeBytes = 52168, contentType = "image/png")), + ) + // A blank content type never renders a dangling separator. + assertEquals( + "4.9 KiB · unknown type", + artifactMetaLine(StageArtifact(name = "b", sizeBytes = 5008, contentType = "")), + ) + } + + @Test + fun artifactsSummaryAndNotesMirrorTheTui() { + // Running visit with no artifacts: capture pending. + assertEquals("Artifacts · capture pending", artifactsSummary(RunStep(status = "running"))) + // Finished visit with no artifacts: not recorded. + assertEquals( + "Artifacts · not recorded for this visit", + artifactsSummary(RunStep(status = "succeeded")), + ) + // Recorded artifacts: count, plus partial capture only when counts are set. + val plain = RunStep(artifacts = listOf(StageArtifact(), StageArtifact())) + assertEquals("Artifacts · 2 recorded", artifactsSummary(plain)) + val partial = RunStep(artifacts = listOf(StageArtifact()), artifactsSkipped = 1, artifactsTruncated = 2) + assertEquals("Artifacts · 1 recorded · partial capture", artifactsSummary(partial)) + assertEquals( + listOf( + "1 files excluded from artifact capture.", + "2 files omitted by artifact capture limits.", + ), + artifactCaptureNotes(partial), + ) + assertEquals(emptyList(), artifactCaptureNotes(plain)) + // No artifacts recorded: the TUI emits no artifact lines, so no notes + // accompany the empty-state summary even when counts are set. + assertEquals( + emptyList(), + artifactCaptureNotes(RunStep(artifactsSkipped = 1, artifactsTruncated = 2)), + ) + } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/components/DetailTabsTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/components/DetailTabsTest.kt index e77c8d64..013b2135 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/components/DetailTabsTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/components/DetailTabsTest.kt @@ -1,6 +1,8 @@ package net.awan.pipelines.ui.components +import androidx.compose.runtime.mutableStateOf import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -54,4 +56,19 @@ class DetailTabsTest { assertEquals(2, clampTabIndex(99, 3)) assertEquals(0, clampTabIndex(1, 0)) } + + @Test + fun sectionsStartCollapsedAndToggleIsRemembered() { + val state = SectionExpansionState(mutableStateOf>(emptySet())) + // Every section is collapsed by default, including one never toggled. + assertFalse(state.isExpanded("input-prompt")) + assertFalse(state.isExpanded("evidence-4")) + // Toggling expands exactly that key; the choice survives (state is stored). + state.toggle("evidence-4") + assertTrue(state.isExpanded("evidence-4")) + assertFalse(state.isExpanded("input-prompt")) + // Toggling again collapses it, persisting the operator's own choice. + state.toggle("evidence-4") + assertFalse(state.isExpanded("evidence-4")) + } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/screens/TimelineTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/screens/TimelineTest.kt index e56cfc9a..0f6ec8a6 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/screens/TimelineTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/screens/TimelineTest.kt @@ -2,7 +2,10 @@ package net.awan.pipelines.ui.screens import net.awan.pipelines.data.protocol.ControlEvidence import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.SessionEvidence +import net.awan.pipelines.data.protocol.StageArtifact import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -112,4 +115,41 @@ class TimelineTest { ) assertEquals("2m 5s", timeline.entries.single().duration) } + + @Test + fun hasArtifactsIsTrueOnlyWhenFilesWereRecorded() { + assertFalse(hasArtifacts(RunStep(sequence = 1, stage = "a"))) + // An explicitly empty capture is not an artifact. + assertFalse(hasArtifacts(RunStep(sequence = 1, stage = "a", artifacts = emptyList()))) + assertTrue(hasArtifacts(RunStep(sequence = 1, stage = "a", artifacts = listOf(StageArtifact(name = "x.png"))))) + } + + @Test + fun fieldSectionTitleFallsBackToPrefixAndIsNeverEmpty() { + assertEquals("plan", fieldSectionTitle("plan", "input")) + // A blank/missing key falls back to the section prefix, never empty. + assertEquals("input", fieldSectionTitle("", "input")) + assertEquals("output", fieldSectionTitle(" ", "output")) + assertTrue(fieldSectionTitle("", "input").isNotBlank()) + } + + @Test + fun evidenceSectionTitleDescribesStepStageVisitAndIdentity() { + val step = RunStep( + sequence = 4, + stage = "ui_reviewer", + control = ControlEvidence(visit = 1), + ) + assertEquals( + "Evidence - step 4, ui_reviewer visit 1, opencode", + evidenceSectionTitle(SessionEvidence(sequence = 4, backend = "opencode"), step), + ) + // Unmatched evidence still names the step and falls back to the session id. + assertEquals( + "Evidence - step 4, sess-9", + evidenceSectionTitle(SessionEvidence(sequence = 4, sessionId = "sess-9"), null), + ) + // Never a bare index and never empty, even with nothing to say. + assertEquals("Evidence", evidenceSectionTitle(SessionEvidence(), null)) + } }