From 95150c79c5c270faef4023f19ab95ac1a2b56638 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 17:13:35 +0100 Subject: [PATCH 1/5] Render every artifact in the shared gallery, with file-type icons Standardise the artifacts gallery so the run summary and the stage pane render one tile per artifact instead of images as a grid and everything else as a plain list. - Artifacts.kt: ArtifactTile now covers both shapes - an image/video fills the cell with a thumbnail (a video shows its poster frame with a play badge), anything else shows its file-type icon with the name and size beneath it; the grid, share/copy actions and multi-select are unchanged and the capture wording is untouched. - ArtifactType.kt (new): pure ArtifactKind classification from content type plus name extension fallback, and artifactIcon(kind) mapping each kind to a distinct glyph. - ArtifactImage.kt: ArtifactVideoFrame/rememberArtifactVideoFrame extract a poster frame via MediaMetadataRetriever over an in-memory MediaDataSource; the shared memoized-preview scaffold is factored into rememberArtifactPreview. - ArtifactViewer.kt: full-screen viewer takes a video flag and shows the poster frame. - Format.kt: add isVideoContentType; drop the now-unused artifactMetaLine. - Dimens.kt: ARTIFACT_TYPE_ICON_DP, ARTIFACT_PLAY_BADGE_DP, ARTIFACT_TILE_ACTION_DP tokens. - Tests: new ArtifactTypeTest (type-to-icon mapping, extension fallback, distinct glyphs); FormatTest updated for the removed helper. - android/README.md documents the pass. android/ only; no new dependencies beyond material-icons-extended. --- android/README.md | 139 +++++++ .../main/java/net/awan/pipelines/ui/Format.kt | 14 +- .../awan/pipelines/ui/graph/ArtifactImage.kt | 123 +++++- .../awan/pipelines/ui/graph/ArtifactType.kt | 133 ++++++ .../awan/pipelines/ui/graph/ArtifactViewer.kt | 31 +- .../net/awan/pipelines/ui/graph/Artifacts.kt | 385 ++++++++++-------- .../net/awan/pipelines/ui/theme/Dimens.kt | 15 +- .../java/net/awan/pipelines/ui/FormatTest.kt | 15 +- .../pipelines/ui/graph/ArtifactTypeTest.kt | 77 ++++ 9 files changed, 724 insertions(+), 208 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactType.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactTypeTest.kt diff --git a/android/README.md b/android/README.md index 9ad86191..1181de66 100644 --- a/android/README.md +++ b/android/README.md @@ -3441,3 +3441,142 @@ native 2208x1840 @420 at the end. returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, `Content-Length: 17928873`. + +## One artifacts gallery everywhere, with a type icon for non-media (16 Oct 2026) + +The gallery was already a grid, but only for images: non-image artifacts fell +through to a plain one-per-row list beneath it, so the same run rendered two +different ways. This pass makes `ArtifactGallery` the single rendering path for +every artifact (the run summary and the stage pane's per-visit section already +both use it) and gives non-media files a tile too. `android/` only; no +dependency was added (the new glyphs are `material-icons-extended`), no run was +started from the app, and every `adb` command targeted `emulator-5554` (never +`emulator-5556` or the attached Pixel). + +- **One tile, two shapes.** `ui/graph/Artifacts.kt`'s `ArtifactTile` replaces the + old `ArtifactTile` + `ArtifactRow` split. An image fills the cell with its + thumbnail; a video shows its still/poster frame with a centred play marker on + top; anything else shows its file-type icon with the artifact's name and + human-readable size beneath it, all in the same width-derived grid. The grid is + still built from non-lazy chunked `Row`s, so it never nests a scrollable inside + the Summary `LazyColumn` or the pane's scroll. +- **Type-to-icon mapping.** The new pure `ui/graph/ArtifactType.kt` classifies an + artifact from its content type (parameters tolerated) and, when the server's + sniff is generic, its name's extension, into `ArtifactKind` + (Image/Video/Audio/Pdf/Json/Archive/Spreadsheet/Log/Code/Document/Other), and + `artifactIcon(kind)` gives each kind a distinct shape (PDF, JSON, archive, + spreadsheet, log, code, document, audio, generic file). `Format.kt` gained the + companion `isVideoContentType` predicate beside `isImageContentType`. +- **Video poster frame.** `ui/graph/ArtifactImage.kt` gained + `ArtifactVideoFrame`/`rememberArtifactVideoFrame`: the artifact's bytes are + fetched through the same bounded cache as an image and the representative sync + frame is extracted with the platform `MediaMetadataRetriever` over an in-memory + `MediaDataSource` (no temp file, no new dependency, no inline playback). The + full-screen viewer takes a `video` flag and shows that frame (its open action + plays the clip externally); a fetch/extraction failure falls back to the video + glyph rather than a fabricated image. +- **Actions kept.** Tap opens the viewer for an image/video and the existing + external-open action for anything else; every tile keeps its share control, a + non-media tile adds the copy-link control, and long-press / multi-select, the + contextual bar, bulk copy/share and the selection semantics are unchanged. + The capture summary and partial-capture notes are byte-for-byte unchanged. +- **Geometry from tokens, not literals.** `ui/theme/Dimens.kt` gains + `ARTIFACT_TYPE_ICON_DP` (28dp), `ARTIFACT_PLAY_BADGE_DP` (32dp) and + `ARTIFACT_TILE_ACTION_DP` (32dp); the tile still stretches `ARTIFACT_TILE_DP` + cells across the measured width via the unchanged pure `artifactGrid`. + +Review follow-up (same pass, no UI change): the two preview state-holders +duplicated the whole memoize-through-caches scaffold, so it is now one private +`rememberArtifactPreview(url, maxDim, keyTag, fetchBytes, derive)` that both +`rememberArtifactBitmap` and `rememberArtifactVideoFrame` delegate to (the +`keyTag` keeps the two cache entries apart); the video fallback draws +`artifactIcon(ArtifactKind.Video)` instead of a hardcoded `Icons.Filled.Movie`; +and the now-unused `Format.kt` `artifactMetaLine` helper (its last caller was the +deleted non-image row) was removed with its `FormatTest` cases. + +Verified on this tree (macOS, Homebrew `openjdk@25`, +`JAVA_HOME=/opt/homebrew/opt/openjdk@25/libexec/openjdk.jdk/Contents/Home`, +Gradle 9.7.1, `ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--offline`): + +- `gradle --offline :app:testDebugUnitTest --rerun-tasks` → `BUILD SUCCESSFUL`; + the 31 test-result XMLs aggregate to **265 tests, 0 failures, 0 errors, 0 + skipped** (the new `ui/graph/ArtifactTypeTest` has 6 cases: the media kinds + from the content type, the named kinds, the extension fallback for a generic + sniff, the never-crash `Other` fallback, the explicit type-to-icon mapping, and + that no two kinds share a glyph). `ArtifactGalleryTest` still covers the grid + sizing (narrow → fewer, larger cells; wider → more preferred-shaped columns; + degenerate inputs). `compileDebugKotlin` emits no warnings. +- `gradle --offline :app:assembleDebug --rerun-tasks --no-build-cache` succeeded + → `app-debug.apk` **18,011,393 bytes**, sha256 + `faa9df077c960b23eef4afbac1b7effa1a50180eabcee2d638cabb232974cfa8`. +- On `emulator-5554` (native 2076x2152 @390; `wm size`/`wm density` used for the + narrow pass and reset afterwards) against the live server + `ws://10.0.2.2:8080/connect`, driven with `adb shell input` and `uiautomator + dump`; every capture was written with + `android/scripts/capture_png.sh -s emulator-5554` (validated PNG, named display + id) into `…/artifacts/140/1/`. Run 136's `implementer` visit 1 is a real mixed + set: five `image/png` screenshots plus `chat_stub_approval.py` + (`text/plain`, code glyph) and `stub.log` (`text/plain`, log glyph). + - **Wide** (2076x2152 ≈ 532dp): `evidence_wide_run136_summary_gallery.png` + shows the five thumbnails with their share controls and, in the same grid, + the `.py` tile with the `<>` code glyph and the `.log` tile with the log + glyph, each with its name and `9.3 KiB` / `220 B` beneath it and the copy + + share actions; `evidence_wide_run136_stage_pane.png` shows the same gallery in + the stage pane under the unchanged `Artifacts · 7 recorded · partial capture` + wording and the `1 files excluded from artifact capture.` note. + - **Narrow** (1080x2340 @480 ≈ 360dp): + `evidence_narrow_run136_summary_gallery.png` and + `evidence_narrow_run136_stage_pane.png` show three cells per row with the + thumbnails and the code/log type tiles still legible. + - Tapping a thumbnail opened the full-screen viewer + (`evidence_wide_run136_image_viewer.png`; `uiautomator dump` reported the + `01_approval_pending.png` image plus `Open … externally`, `Copy link …` and + `Close viewer`), and the non-media tiles' `Copy link to …` / `Share …` + controls are present in the accessibility tree. + - `adb -s emulator-5554 logcat -d | grep -cE 'FATAL EXCEPTION|E + AndroidRuntime'` returned 0; the emulator display was reset to native + 2076x2152 @390 afterwards. +- **APK publish.** `app-debug.apk` copied to + `…/artifacts/140/1/pipelines-debug-wip-c700b28.apk` (`c700b28` = short + `HEAD`); `shasum -a 256` matched. `curl -I + http://10.0.0.249:8080/artifacts/140/1/pipelines-debug-wip-c700b28.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: + application/vnd.android.package-archive`, `Content-Length: 18011393`, and a + streamed `GET | shasum -a 256` returned the same `faa9df07…` as the local file. + At ~17.2 MiB it exceeds the server's 8 MiB per-file inventory cap, so it is + served by direct URL only. + +Not verified in this pass: a **video** artifact does not exist on the live server +and starting a run is forbidden, so the play-marker/poster-frame render is +covered only by the `artifactKind` unit test (`video/mp4 → Video`) and the code +path, not by a device capture; the non-media external-open tap was not driven +(no handler is guaranteed on the emulator); multi-select/bulk share were not +re-exercised on device (their code is unchanged from the previous pass); the +light theme and `:app:lintDebug` were not run (the only known lint issues are the +two pre-existing `NewApi` errors for `android:windowLightNavigationBar`). + +### Review fixes (same pass) + +The review's three findings were addressed with no intended UI change, and the +two build checks were re-run on the resulting tree: + +- `gradle --offline :app:testDebugUnitTest --rerun-tasks` → `BUILD SUCCESSFUL`; + the 31 result XMLs again aggregate to **265 tests, 0 failures, 0 errors, 0 + skipped** (the removed `artifactMetaLine` assertions were replaced by + `isVideoContentType` coverage in the same `FormatTest` method). +- `gradle --offline :app:assembleDebug --rerun-tasks --no-build-cache` succeeded + → `app-debug.apk` **18,011,393 bytes**, sha256 + `2adaf03e5ac0bdb29b012d1487a0e10917f8ebabda973ddc63c7315b6df25dda`; it was + published to `…/artifacts/140/3/pipelines-debug-wip-c700b28.apk` and + `curl -I http://10.0.0.249:8080/artifacts/140/3/pipelines-debug-wip-c700b28.apk` + returned `HTTP/1.1 200 OK`, `Content-Length: 18011393`, with a streamed + `GET | shasum -a 256` matching the local `2adaf03e…`. + +The device render was **not** re-captured: `emulator-5554` is shared and, while +this pass ran, another lane replaced the installed app with a build whose dex has +no `ArtifactType` class (`dumpsys package … lastUpdateTime` moved from this pass's +`16:24:02` install to `16:24:20`, and the installed `base.apk` sha no longer +matched `2adaf03e…`), so any capture could not be attributed to this build. The +wide/narrow captures above predate the refactor; the refactor changes no UI +pixels, so they remain representative of the gallery this code renders. + 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 eccc2799..3b31e260 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 @@ -9,7 +9,6 @@ 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 /** @@ -138,6 +137,12 @@ fun humanBytes(size: Long): String { /** Whether an artifact's content type is an image the sheet can preview. */ fun isImageContentType(contentType: String): Boolean = contentType.startsWith("image/") +/** + * Whether an artifact's content type is a video. Videos are shown in the gallery + * as a still/poster frame with a play marker; they are never decoded inline. + */ +fun isVideoContentType(contentType: String): Boolean = contentType.startsWith("video/") + /** * The "capture pending" wording shared by a running visit's summary and the * run-level empty state, so the two never spell it differently. @@ -176,10 +181,3 @@ fun artifactCaptureNotes(step: RunStep): List = 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/graph/ArtifactImage.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactImage.kt index d08faec2..7e74ec59 100644 --- 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 @@ -2,6 +2,8 @@ package net.awan.pipelines.ui.graph import android.graphics.Bitmap import android.graphics.BitmapFactory +import android.media.MediaDataSource +import android.media.MediaMetadataRetriever import android.util.LruCache import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box @@ -28,6 +30,7 @@ import kotlinx.coroutines.withContext import net.awan.pipelines.ui.theme.ARTIFACT_PROGRESS_DP import net.awan.pipelines.ui.theme.ARTIFACT_PROGRESS_STROKE_DP import net.awan.pipelines.ui.theme.ARTIFACT_THUMB_DP +import net.awan.pipelines.ui.theme.ARTIFACT_TYPE_ICON_DP /** * Encoded artifact bytes, fetched at most once per url and kept in memory so a @@ -126,9 +129,25 @@ internal fun rememberArtifactBitmap( url: String?, maxDim: Int, fetchBytes: suspend (String) -> ByteArray?, +): ArtifactImageState = rememberArtifactPreview(url, maxDim, "", fetchBytes, ::decodeSampled) + +/** + * The shared memoized-preview scaffold behind [rememberArtifactBitmap] and + * [rememberArtifactVideoFrame]: a null [url] is [ArtifactImageState.Unavailable] + * with no request attempted, otherwise the bytes are fetched once through + * [ArtifactBytesCache] and [derive] runs off the main thread, its bitmap cached + * under a [keyTag]-tagged key (so an image and a video of one url never collide). + */ +@Composable +private fun rememberArtifactPreview( + url: String?, + maxDim: Int, + keyTag: String, + fetchBytes: suspend (String) -> ByteArray?, + derive: (ByteArray, Int) -> Bitmap?, ): ArtifactImageState { if (url == null) return ArtifactImageState.Unavailable - val key = "$url@$maxDim" + val key = "$url@$keyTag$maxDim" var state by remember(key) { mutableStateOf(ArtifactImageState.Loading) } LaunchedEffect(key) { artifactBitmapCache.get(key)?.let { @@ -142,7 +161,7 @@ internal fun rememberArtifactBitmap( return@LaunchedEffect } ArtifactBytesCache.put(url, bytes) - val bitmap = withContext(Dispatchers.IO) { decodeSampled(bytes, maxDim) } + val bitmap = withContext(Dispatchers.IO) { derive(bytes, maxDim) } if (bitmap == null) { state = ArtifactImageState.Error } else { @@ -153,6 +172,106 @@ internal fun rememberArtifactBitmap( return state } +/** + * A video tile's still/poster frame: the artifact's bytes are fetched through the + * same bounded, off-main-thread path as an image ([rememberArtifactBitmap]'s + * cache), then the first sync frame is extracted with the platform + * [MediaMetadataRetriever] and cached. [url] null (no configured server) shows + * [ArtifactImageState.Unavailable] and issues no request; a fetch or extraction + * failure shows [ArtifactImageState.Error]. Unlike an image there is no honest + * "still" without a decodable frame, so both non-`Ready` states fall back to the + * video glyph the gallery would otherwise use. + */ +@Composable +internal fun ArtifactVideoFrame( + url: String?, + contentDescription: String?, + fetchBytes: suspend (String) -> ByteArray?, + modifier: Modifier = Modifier, + size: Dp = ARTIFACT_THUMB_DP, +) { + val state = rememberArtifactVideoFrame(url, VIDEO_FRAME_MAX_DIM, fetchBytes) + Box(modifier.size(size), contentAlignment = Alignment.Center) { + when (val current = state) { + is ArtifactImageState.Ready -> Image( + bitmap = current.bitmap.asImageBitmap(), + contentDescription = contentDescription, + contentScale = ContentScale.Crop, + modifier = Modifier.size(size), + ) + ArtifactImageState.Loading -> CircularProgressIndicator( + modifier = Modifier.size(ARTIFACT_PROGRESS_DP), + strokeWidth = ARTIFACT_PROGRESS_STROKE_DP, + ) + ArtifactImageState.Unavailable, ArtifactImageState.Error -> Icon( + imageVector = artifactIcon(ArtifactKind.Video), + contentDescription = contentDescription, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(ARTIFACT_TYPE_ICON_DP), + ) + } + } +} + +/** + * The state of a video's poster frame at up to [maxDim] on its longest edge (0 + * for the platform's native resolution). Same caching and off-main-thread + * behaviour as [rememberArtifactBitmap]; the full-size viewer shares it so a + * video's still is extracted once. + */ +@Composable +internal fun rememberArtifactVideoFrame( + url: String?, + maxDim: Int, + fetchBytes: suspend (String) -> ByteArray?, +): ArtifactImageState = rememberArtifactPreview(url, maxDim, "video", fetchBytes, ::extractVideoFrame) + +/** + * The representative sync frame of [bytes] as a [maxDim]-bounded bitmap (native + * when [maxDim] <= 0), or null when the bytes are not a decodable video (or the + * platform retriever fails). Runs off the main thread; the bytes are handed over + * through an in-memory [MediaDataSource], so no temporary file is written. + */ +private fun extractVideoFrame(bytes: ByteArray, maxDim: Int): Bitmap? = runCatching { + val retriever = MediaMetadataRetriever() + try { + retriever.setDataSource(ByteArrayMediaDataSource(bytes)) + retriever.getFrameAtTime(-1L, MediaMetadataRetriever.OPTION_CLOSEST_SYNC) + } finally { + runCatching { retriever.release() } + } +}.getOrNull()?.let { scaleToMaxDim(it, maxDim) } + +/** The in-memory [MediaDataSource] over fetched video [data] (no temp file). */ +private class ByteArrayMediaDataSource(private val data: ByteArray) : MediaDataSource() { + override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int { + if (position < 0 || position >= data.size) return -1 + val count = minOf(size.toLong(), data.size - position).toInt() + System.arraycopy(data, position.toInt(), buffer, offset, count) + return count + } + + override fun getSize(): Long = data.size.toLong() + + override fun close() = Unit +} + +/** [bitmap] scaled so its longest edge is at most [maxDim] (native when <= 0). */ +private fun scaleToMaxDim(bitmap: Bitmap, maxDim: Int): Bitmap { + val longest = maxOf(bitmap.width, bitmap.height) + if (maxDim <= 0 || longest <= maxDim || longest == 0) return bitmap + val scale = maxDim.toFloat() / longest + return Bitmap.createScaledBitmap( + bitmap, + (bitmap.width * scale).toInt().coerceAtLeast(1), + (bitmap.height * scale).toInt().coerceAtLeast(1), + true, + ) +} + +/** Longest edge of a video poster-frame decode (the same shape as an image thumbnail). */ +private const val VIDEO_FRAME_MAX_DIM = 320 + /** * Decodes [bytes], downsampling to roughly [maxDim] on the longest edge when * [maxDim] > 0 (so the list never holds full-resolution bitmaps), or at full diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactType.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactType.kt new file mode 100644 index 00000000..15037562 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactType.kt @@ -0,0 +1,133 @@ +package net.awan.pipelines.ui.graph + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.InsertDriveFile +import androidx.compose.material.icons.filled.AudioFile +import androidx.compose.material.icons.filled.Code +import androidx.compose.material.icons.filled.DataObject +import androidx.compose.material.icons.filled.Description +import androidx.compose.material.icons.filled.FolderZip +import androidx.compose.material.icons.filled.Image +import androidx.compose.material.icons.filled.Movie +import androidx.compose.material.icons.filled.PictureAsPdf +import androidx.compose.material.icons.automirrored.filled.ReceiptLong +import androidx.compose.material.icons.filled.TableChart +import androidx.compose.ui.graphics.vector.ImageVector +import net.awan.pipelines.ui.isImageContentType +import net.awan.pipelines.ui.isVideoContentType + +/** + * What an artifact's file type is, from the app's point of view: the two media + * kinds the gallery previews (image, video) and the file kinds it labels with a + * type icon (everything else). It is the one classification the gallery branches + * on, so the grid, the tile and the icon can never disagree about a file. + */ +internal enum class ArtifactKind { + Image, + Video, + Audio, + Pdf, + Json, + Archive, + Spreadsheet, + Log, + Code, + Document, + Other, +} + +/** + * The gallery kind of an artifact from its [contentType] (server-sniffed, may + * carry parameters) and its [name] (the extension is the fallback when the sniff + * is generic `text/plain`/`application/octet-stream`). Image and video are + * recognised straight from the content type; the rest are matched by the + * normalised mime first, then by the name's extension. Pure and total, so the + * type-to-icon mapping is unit-tested without a device. + */ +internal fun artifactKind(contentType: String, name: String): ArtifactKind { + if (isImageContentType(contentType)) return ArtifactKind.Image + if (isVideoContentType(contentType)) return ArtifactKind.Video + val mime = contentType.substringBefore(';').trim().lowercase() + val ext = name.substringAfterLast('.', "").lowercase() + return when { + mime.startsWith("audio/") -> ArtifactKind.Audio + mime == "application/pdf" || ext == "pdf" -> ArtifactKind.Pdf + mime.contains("json") || ext == "json" -> ArtifactKind.Json + mime in ARCHIVE_MIMES || ext in ARCHIVE_EXTENSIONS -> ArtifactKind.Archive + mime in SPREADSHEET_MIMES || ext in SPREADSHEET_EXTENSIONS -> ArtifactKind.Spreadsheet + ext == "log" -> ArtifactKind.Log + mime == "text/html" -> ArtifactKind.Document + mime in CODE_MIMES || ext in CODE_EXTENSIONS -> ArtifactKind.Code + mime.startsWith("text/") || mime in DOCUMENT_MIMES || ext in DOCUMENT_EXTENSIONS -> ArtifactKind.Document + else -> ArtifactKind.Other + } +} + +/** + * The glyph that names [kind] in the gallery: a distinct [ImageVector] per kind + * (its own shape, not colour alone), so a document, archive, log, code file, JSON + * payload and PDF are told apart at a glance. Pure, so the mapping is unit-tested. + */ +internal fun artifactIcon(kind: ArtifactKind): ImageVector = when (kind) { + ArtifactKind.Image -> Icons.Filled.Image + ArtifactKind.Video -> Icons.Filled.Movie + ArtifactKind.Audio -> Icons.Filled.AudioFile + ArtifactKind.Pdf -> Icons.Filled.PictureAsPdf + ArtifactKind.Json -> Icons.Filled.DataObject + ArtifactKind.Archive -> Icons.Filled.FolderZip + ArtifactKind.Spreadsheet -> Icons.Filled.TableChart + ArtifactKind.Log -> Icons.AutoMirrored.Filled.ReceiptLong + ArtifactKind.Code -> Icons.Filled.Code + ArtifactKind.Document -> Icons.Filled.Description + ArtifactKind.Other -> Icons.AutoMirrored.Filled.InsertDriveFile +} + +private val ARCHIVE_EXTENSIONS = + setOf("zip", "tar", "gz", "tgz", "bz2", "xz", "rar", "7z", "jar", "war") + +private val ARCHIVE_MIMES = setOf( + "application/zip", + "application/gzip", + "application/x-tar", + "application/x-7z-compressed", + "application/x-rar-compressed", + "application/java-archive", +) + +private val SPREADSHEET_EXTENSIONS = setOf("csv", "tsv", "xls", "xlsx", "ods") + +private val SPREADSHEET_MIMES = setOf( + "text/csv", + "text/tab-separated-values", + "application/vnd.ms-excel", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", +) + +private val CODE_EXTENSIONS = setOf( + "kt", "kts", "java", "go", "py", "rb", "php", "rs", "c", "h", "cc", "cpp", + "hpp", "cs", "js", "jsx", "ts", "tsx", "mjs", "cjs", "swift", "scala", "sh", + "bash", "zsh", "fish", "ps1", "sql", "yaml", "yml", "toml", "ini", "xml", + "gradle", "properties", "proto", +) + +private val CODE_MIMES = setOf( + "application/xml", + "application/x-yaml", + "application/javascript", + "text/javascript", + "text/x-python", + "text/x-java-source", + "text/x-kotlin", + "application/x-sh", + "application/x-httpd-php", + "application/sql", +) + +private val DOCUMENT_EXTENSIONS = + setOf("txt", "md", "markdown", "rst", "doc", "docx", "odt", "rtf", "html", "htm") + +private val DOCUMENT_MIMES = setOf( + "application/msword", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/rtf", +) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt index f32013ce..9cca040f 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt @@ -61,10 +61,12 @@ import net.awan.pipelines.ui.theme.pipelinesText import kotlin.math.abs /** - * The full-screen image viewer opened by tapping a gallery thumbnail (the run - * summary grid, the per-visit artifacts list and the stage pane all render - * through [ArtifactGallery], so they all open this). It replaces the former - * small centred dialog rather than stacking on top of it. + * The full-screen media viewer opened by tapping a gallery tile (the run summary + * grid, the per-visit artifacts section and the stage pane all render through + * [ArtifactGallery], so they all open this): an image at full size, or a video's + * poster frame (the platform retriever extracts it, [video] = true) with the + * external-open action to actually play it. It replaces the former small centred + * dialog rather than stacking on top of it. * * It is a [Dialog] whose window is laid out edge to edge (`decorFitsSystemWindows * = false`): the dark [MaterialTheme.colorScheme.scrim] backdrop fills the whole @@ -87,6 +89,7 @@ internal fun ArtifactViewer( name: String, fetchBytes: suspend (String) -> ByteArray?, onDismiss: () -> Unit, + video: Boolean = false, ) { Dialog( onDismissRequest = onDismiss, @@ -131,11 +134,23 @@ internal fun ArtifactViewer( .background(MaterialTheme.colorScheme.scrim) .windowInsetsPadding(paneSafeArea()), ) { - when (val state = rememberArtifactBitmap(url, FULL_RESOLUTION, fetchBytes)) { + val state = if (video) { + rememberArtifactVideoFrame(url, FULL_RESOLUTION, fetchBytes) + } else { + rememberArtifactBitmap(url, FULL_RESOLUTION, fetchBytes) + } + when (state) { is ArtifactImageState.Ready -> ZoomableArtifact(state.bitmap, name, url, onDismiss) - ArtifactImageState.Loading -> ViewerMessage("Loading image…", spinner = true) - ArtifactImageState.Error -> ViewerMessage("Couldn't load image.") - ArtifactImageState.Unavailable -> ViewerMessage("Image unavailable.") + ArtifactImageState.Loading -> ViewerMessage( + if (video) "Loading video frame…" else "Loading image…", + spinner = true, + ) + ArtifactImageState.Error -> ViewerMessage( + if (video) "Couldn't load the video frame." else "Couldn't load image.", + ) + ArtifactImageState.Unavailable -> ViewerMessage( + if (video) "Video unavailable." else "Image unavailable.", + ) } ArtifactViewerActions( name = name, 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 index 03dfaf6a..16c00c3b 100644 --- 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 @@ -9,24 +9,24 @@ import androidx.compose.foundation.border import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape 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.Check import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Share import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.LocalContentColor 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 @@ -41,6 +41,7 @@ import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @@ -50,13 +51,14 @@ import net.awan.pipelines.data.protocol.StageArtifact import net.awan.pipelines.data.transport.ServerUrl import net.awan.pipelines.ui.ArtifactGroup import net.awan.pipelines.ui.artifactCaptureNotes -import net.awan.pipelines.ui.artifactMetaLine import net.awan.pipelines.ui.artifactsSummary import net.awan.pipelines.ui.components.copyText -import net.awan.pipelines.ui.isImageContentType +import net.awan.pipelines.ui.humanBytes import net.awan.pipelines.ui.theme.ARTIFACT_BADGE_DP -import net.awan.pipelines.ui.theme.ARTIFACT_THUMB_DP +import net.awan.pipelines.ui.theme.ARTIFACT_PLAY_BADGE_DP +import net.awan.pipelines.ui.theme.ARTIFACT_TILE_ACTION_DP import net.awan.pipelines.ui.theme.ARTIFACT_TILE_DP +import net.awan.pipelines.ui.theme.ARTIFACT_TYPE_ICON_DP import net.awan.pipelines.ui.theme.SPACING_M import net.awan.pipelines.ui.theme.SPACING_S import net.awan.pipelines.ui.theme.SPACING_XS @@ -70,7 +72,7 @@ import net.awan.pipelines.ui.theme.pipelinesText * 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 + * When no server URL is configured the tiles still show (name/size/type) but the * open/copy actions are disabled and a hint is shown. */ @Composable @@ -112,17 +114,18 @@ internal fun ArtifactsSection( } /** - * The artifacts gallery: one group per (stage, visit) with a header, the group's - * image artifacts as a grid of thumbnails (a tap opens the full-size view) and - * its non-image artifacts as rows with name, size, content type and open/copy. - * Every url is resolved with [ServerUrl.resolveArtifactUrl], so nothing here - * hardcodes a host. The grid is built from non-lazy chunked [Row]s, so it never - * nests a scrollable inside the Summary [LazyColumn] or the pane's scroll. + * The artifacts gallery: one group per (stage, visit) with a header and every + * artifact as a tile in a grid. An image shows its thumbnail, a video its + * still/poster frame with a play marker on top, and anything else its file-type + * icon with the name and size beneath it. Every url is resolved with + * [ServerUrl.resolveArtifactUrl], so nothing here hardcodes a host. The grid is + * built from non-lazy chunked [Row]s, so it never nests a scrollable inside the + * Summary [LazyColumn] or the pane's scroll. * * The grid geometry is derived from the measured width (one [BoxWithConstraints], * see [artifactGrid]): as many cells as fit at the preferred [ARTIFACT_TILE_DP] - * shape, stretched to fill the row, so a wide window shows several thumbnails per - * row and a narrow one shows fewer, larger ones — never a fixed column count. + * shape, stretched to fill the row, so a wide window shows several tiles per row + * and a narrow one shows fewer, larger ones — never a fixed column count. */ @Composable internal fun ArtifactGallery( @@ -149,9 +152,7 @@ internal fun ArtifactGallery( style = text.sectionHeader, ) } - val images = group.artifacts.filter { isImageContentType(it.contentType) } - val others = group.artifacts.filterNot { isImageContentType(it.contentType) } - images.chunked(grid.columns).forEach { rowArtifacts -> + group.artifacts.chunked(grid.columns).forEach { rowArtifacts -> Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(ARTIFACT_TILE_SPACING_DP), @@ -172,15 +173,6 @@ internal fun ArtifactGallery( } } } - others.forEach { artifact -> - ArtifactRow( - artifact = artifact, - configuredServerUrl = configuredServerUrl, - fetchArtifactBytes = fetchArtifactBytes, - selection = selection, - onSelectionChange = onSelectionChange, - ) - } } } } @@ -209,22 +201,24 @@ internal fun artifactGrid(availableWidth: Dp, preferred: Dp, spacing: Dp): Artif /** * The absolute url a gallery artifact is previewed/opened at, or null when it * cannot be resolved against the configured server (blank or invalid). The one - * place a gallery artifact url is resolved, shared by the image tile and the - * non-image row so the two can never disagree. A null must never reach a fetch: - * a server-relative url has no scheme and can never load, so the tile renders the - * distinct "unavailable" state instead of the failure mark. + * place a gallery artifact url is resolved, shared by every tile so they can + * never disagree. A null must never reach a fetch: a server-relative url has no + * scheme and can never load, so the tile renders the distinct "unavailable" + * state instead of the failure mark. */ internal fun resolvedArtifactUrl(artifact: StageArtifact, configuredServerUrl: String): String? = ServerUrl.resolveArtifactUrl(configuredServerUrl, artifact.url) /** - * One image artifact as a square thumbnail that opens the full-size view. A - * long-press enters artifact selection on this item; while selection mode is - * active a tap toggles it instead of opening, and the selected cell gets the - * app's selected treatment (a tonal ring + check badge in the shared - * secondaryContainer/onSecondaryContainer roles, and the `selected` semantics - * state). The per-item share control is hidden while selecting so the whole cell - * is the toggle target. + * One gallery tile. An image or video fills the cell with its thumbnail (a video + * with a play marker on top) and opens the full-screen viewer on tap; any other + * type shows its file-type icon with the name and size beneath it and opens + * externally on tap. A long-press enters artifact selection on this item; while + * selection mode is active a tap toggles it instead of opening, and the selected + * cell gets the app's selected treatment (a tonal ring + check badge in the + * shared secondaryContainer/onSecondaryContainer roles, and the `selected` + * semantics state). The per-item actions are hidden while selecting so the whole + * cell is the toggle target. */ @OptIn(ExperimentalFoundationApi::class) @Composable @@ -236,10 +230,15 @@ private fun ArtifactTile( selection: ArtifactSelection, onSelectionChange: (ArtifactSelection) -> Unit, ) { - // Resolve once per (url, configuration), not on every recomposition. + val context = LocalContext.current + // Resolve and classify once per data change, not on every recomposition. val resolved = remember(artifact.url, configuredServerUrl) { resolvedArtifactUrl(artifact, configuredServerUrl) } + val kind = remember(artifact.contentType, artifact.name) { + artifactKind(artifact.contentType, artifact.name) + } + val media = kind == ArtifactKind.Image || kind == ArtifactKind.Video var showFull by remember(artifact.url) { mutableStateOf(false) } val selected = selection.contains(artifact.url) @@ -247,6 +246,13 @@ private fun ArtifactTile( Modifier .size(tile) .clip(MaterialTheme.shapes.medium) + .background( + if (selected) { + MaterialTheme.colorScheme.secondaryContainer + } else { + MaterialTheme.colorScheme.surfaceContainerHigh + }, + ) .then( if (selected) { Modifier.border(3.dp, MaterialTheme.colorScheme.secondary, MaterialTheme.shapes.medium) @@ -256,10 +262,12 @@ private fun ArtifactTile( ) .combinedClickable( onClick = { - if (selection.active) { - onSelectionChange(selection.toggle(artifact.url)) - } else if (resolved != null) { - showFull = true + when { + selection.active -> onSelectionChange(selection.toggle(artifact.url)) + // An image or video opens the full-screen viewer; any + // other type uses the existing open action. + media -> if (resolved != null) showFull = true + else -> openArtifact(context, resolved) } }, onLongClick = { onSelectionChange(selection.enter(artifact.url)) }, @@ -267,20 +275,20 @@ private fun ArtifactTile( ) .semantics { this.selected = selected }, ) { - // Pass the resolved url (null when there is no configured server): a - // null never triggers a relative-url fetch, it shows the distinct - // "unavailable" state instead of the failure mark. - ArtifactImage( - url = resolved, - contentDescription = "Preview of ${artifact.name}", - maxDim = THUMBNAIL_MAX_DIM, - fetchBytes = fetchArtifactBytes, - size = tile, - ) + if (media) { + ArtifactMediaPreview( + kind = kind, + name = artifact.name, + resolved = resolved, + fetchArtifactBytes = fetchArtifactBytes, + tile = tile, + ) + } else { + ArtifactTypeLabel(kind = kind, artifact = artifact) + } if (selection.active) { - // While the gallery is selecting, no item exposes its own share - // control: every tap toggles, so only the selected cells carry the - // check badge and the whole tile stays a toggle target. + // While the gallery is selecting, no item exposes its own actions: + // every tap toggles, so only the selected cells carry the check badge. if (selected) { Box( Modifier @@ -298,21 +306,20 @@ private fun ArtifactTile( } } } else { - // The share control is its own hit area over the thumbnail: it - // consumes the tap, so sharing never falls through to open the - // full-size view. - ArtifactShareButton( + // The per-item share (and, for a non-media tile, copy) controls are + // their own hit areas over the tile: they consume the tap, so an + // action never falls through to open the artifact. + ArtifactTileActions( artifact = artifact, resolved = resolved, fetchArtifactBytes = fetchArtifactBytes, - modifier = Modifier.align(Alignment.TopEnd), - scrim = true, + media = media, ) } } // The tap opens the full-screen viewer (one shared instance across the run - // summary grid, the per-visit list and the stage pane, so they never + // summary grid, the per-visit section and the stage pane, so they never // disagree); there is no separate smaller preview to stack on top of it. if (showFull && resolved != null) { ArtifactViewer( @@ -320,135 +327,155 @@ private fun ArtifactTile( name = artifact.name, fetchBytes = fetchArtifactBytes, onDismiss = { showFull = false }, + video = kind == ArtifactKind.Video, ) } } /** - * One non-image artifact: a file glyph, name, size/type and open/share/copy - * actions. A long-press enters artifact selection on this item; while selection - * mode is active a tap toggles it and the row wears the app's selected treatment - * (the secondaryContainer/onSecondaryContainer roles the list rows use, plus the - * `selected` semantics state), with the per-item actions swapped for a check. - * When not selecting, a tap opens the artifact. + * A media tile's content: the image thumbnail, or a video's still/poster frame + * with a centred play marker on top of it. Both load through the same bounded, + * off-main-thread cache, so a media tile never re-hits the network on a + * recomposition. */ -@OptIn(ExperimentalFoundationApi::class) @Composable -private fun ArtifactRow( - artifact: StageArtifact, - configuredServerUrl: String, +private fun BoxScope.ArtifactMediaPreview( + kind: ArtifactKind, + name: String, + resolved: String?, fetchArtifactBytes: suspend (String) -> ByteArray?, - selection: ArtifactSelection, - onSelectionChange: (ArtifactSelection) -> Unit, + tile: Dp, ) { - 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) { - resolvedArtifactUrl(artifact, configuredServerUrl) - } - val metaLine = remember(artifact) { artifactMetaLine(artifact) } - val selected = selection.contains(artifact.url) - - Surface( - shape = MaterialTheme.shapes.medium, - color = if (selected) { - MaterialTheme.colorScheme.secondaryContainer - } else { - MaterialTheme.colorScheme.surfaceContainerHigh - }, - contentColor = if (selected) { - MaterialTheme.colorScheme.onSecondaryContainer - } else { - LocalContentColor.current - }, - modifier = Modifier - .fillMaxWidth() - .combinedClickable( - onClick = { - if (selection.active) { - onSelectionChange(selection.toggle(artifact.url)) - } else { - openArtifact(context, resolved) - } - }, - onLongClick = { onSelectionChange(selection.enter(artifact.url)) }, - onLongClickLabel = "Select ${artifact.name}", - ) - .semantics { this.selected = selected }, - ) { - Row( - modifier = Modifier.padding(horizontal = SPACING_S, vertical = SPACING_S), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(SPACING_M), + if (kind == ArtifactKind.Video) { + ArtifactVideoFrame( + url = resolved, + contentDescription = "Poster frame of $name", + fetchBytes = fetchArtifactBytes, + size = tile, + ) + Box( + Modifier + .align(Alignment.Center) + .size(ARTIFACT_PLAY_BADGE_DP) + .background( + MaterialTheme.colorScheme.scrim.copy(alpha = ARTIFACT_ACTION_SCRIM_ALPHA), + CircleShape, + ), + contentAlignment = Alignment.Center, ) { - Box( - Modifier.size(ARTIFACT_THUMB_DP).clip(MaterialTheme.shapes.small), - contentAlignment = Alignment.Center, - ) { - Icon( - imageVector = Icons.AutoMirrored.Filled.InsertDriveFile, - contentDescription = null, - tint = LocalContentColor.current, - ) - } - Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(SPACING_XXS)) { - Text( - artifact.name.ifBlank { "(unnamed artifact)" }, - style = text.cardTitle, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - Text( - metaLine, - style = text.meta, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - } - if (selection.active) { - // While selecting, the row's own open/copy/share controls are - // hidden so a tap anywhere on it toggles the selection instead - // of acting on the single item; only the selected row shows the - // check. - if (selected) { - Icon( - imageVector = Icons.Default.Check, - contentDescription = null, - modifier = Modifier.padding(horizontal = SPACING_M), - ) - } - } else { - IconButton( - onClick = { openArtifact(context, resolved) }, - enabled = resolved != null, - ) { - Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = "Open ${artifact.name}") - } - IconButton( - onClick = { resolved?.let { clipboard.copyText(it) } }, - enabled = resolved != null, - ) { - Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to ${artifact.name}") - } - ArtifactShareButton( - artifact = artifact, - resolved = resolved, - fetchArtifactBytes = fetchArtifactBytes, - ) - } + Icon( + imageVector = Icons.Default.PlayArrow, + contentDescription = "Play $name", + tint = MaterialTheme.colorScheme.inverseSurface, + ) } + } else { + // Pass the resolved url (null when there is no configured server): a + // null never triggers a relative-url fetch, it shows the distinct + // "unavailable" state instead of the failure mark. + ArtifactImage( + url = resolved, + contentDescription = "Preview of $name", + maxDim = THUMBNAIL_MAX_DIM, + fetchBytes = fetchArtifactBytes, + size = tile, + ) } } /** - * The share action every artifact item carries (the gallery's image cells and - * its file rows): a 48dp [IconButton] target, an accurate content description, - * and a click that launches the platform share chooser. It is the item's own - * child action, so a tap on it never opens the image or the item. [scrim] adds - * the translucent backing the viewer uses so the icon stays legible over a - * bright image. + * A non-media tile's content: its file-type glyph ([artifactIcon]) with the + * artifact's name and human-readable size beneath it, centred in the cell. The + * action strip is pinned to the cell's top corners, away from this centred + * column, so a compact tile never draws its glyph or text under the actions. + */ +@Composable +private fun ArtifactTypeLabel(kind: ArtifactKind, artifact: StageArtifact) { + val text = pipelinesText() + val size = remember(artifact.sizeBytes) { humanBytes(artifact.sizeBytes) } + Column( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = SPACING_XS, vertical = SPACING_XS), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Icon( + imageVector = artifactIcon(kind), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(ARTIFACT_TYPE_ICON_DP), + ) + Text( + artifact.name.ifBlank { "(unnamed artifact)" }, + style = text.label, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = SPACING_XXS), + ) + Text( + size, + style = text.meta, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, + ) + } +} + +/** + * The compact per-item actions strip a tile shows while not selecting: the share + * control at the end, and — for a non-media tile — the copy-link control at the + * start, so both the existing open (the tile's own tap) and copy actions stay + * reachable from the gallery. A media tile taps through to the viewer, which + * carries its own copy action, so it shows only share. + */ +@Composable +private fun BoxScope.ArtifactTileActions( + artifact: StageArtifact, + resolved: String?, + fetchArtifactBytes: suspend (String) -> ByteArray?, + media: Boolean, +) { + Row( + modifier = Modifier.align(Alignment.TopStart).fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + if (media) { + Spacer(Modifier.size(ARTIFACT_TILE_ACTION_DP)) + } else { + ArtifactCopyButton(artifact = artifact, resolved = resolved) + } + ArtifactShareButton( + artifact = artifact, + resolved = resolved, + fetchArtifactBytes = fetchArtifactBytes, + modifier = Modifier.size(ARTIFACT_TILE_ACTION_DP), + scrim = media, + ) + } +} + +/** The compact copy-link control a non-media tile carries. */ +@Composable +private fun ArtifactCopyButton(artifact: StageArtifact, resolved: String?) { + val clipboard = LocalClipboardManager.current + IconButton( + onClick = { resolved?.let { clipboard.copyText(it) } }, + enabled = resolved != null, + modifier = Modifier.size(ARTIFACT_TILE_ACTION_DP), + ) { + Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to ${artifact.name}") + } +} + +/** + * The share action every artifact tile carries: a compact [IconButton] target, an + * accurate content description, and a click that launches the platform share + * chooser. It is the item's own child action, so a tap on it never opens the + * image or the item. [scrim] adds the translucent backing the viewer uses so the + * icon stays legible over a bright image. */ @Composable private fun ArtifactShareButton( @@ -491,5 +518,5 @@ internal fun openArtifact(context: Context, url: String?) { /** Longest edge of a list thumbnail decode. */ private const val THUMBNAIL_MAX_DIM = 160 -/** Gap between gallery thumbnails; shared by the row arrangement and the fitting. */ +/** Gap between gallery tiles; shared by the row arrangement and the fitting. */ private val ARTIFACT_TILE_SPACING_DP = SPACING_S diff --git a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt index 80f9712f..2e4c298d 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt @@ -188,9 +188,22 @@ internal val GRAPH_PANEL_MIN_HEIGHT = 320.dp /** Preferred side of one square gallery thumbnail tile. */ internal val ARTIFACT_TILE_DP = 96.dp -/** Side of an inline artifact thumbnail and a non-image row's leading glyph box. */ +/** Side of an inline artifact thumbnail (a media preview or the viewer's). */ internal val ARTIFACT_THUMB_DP = 56.dp +/** File-type glyph inside a non-media gallery tile. */ +internal val ARTIFACT_TYPE_ICON_DP = 28.dp + +/** Play marker drawn over a video tile's poster frame. */ +internal val ARTIFACT_PLAY_BADGE_DP = 32.dp + +/** + * Compact per-item action target overlaid on a gallery tile (share, or copy on a + * non-media tile); smaller than the 48dp standalone target because the whole tile + * is also a tap target. + */ +internal val ARTIFACT_TILE_ACTION_DP = 32.dp + /** Check-badge glyph on a selected gallery tile. */ internal val ARTIFACT_BADGE_DP = 16.dp 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 faa52a29..7f4f6506 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 @@ -87,20 +87,15 @@ class FormatTest { } @Test - fun artifactContentTypeAndMetaLine() { + fun artifactContentTypePredicates() { 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 = "")), - ) + // Gallery-kind classification (ArtifactTypeTest) builds on this predicate. + assertTrue(isVideoContentType("video/mp4")) + assertFalse(isVideoContentType("image/png")) + assertFalse(isVideoContentType("")) } @Test diff --git a/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactTypeTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactTypeTest.kt new file mode 100644 index 00000000..57060c12 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactTypeTest.kt @@ -0,0 +1,77 @@ +package net.awan.pipelines.ui.graph + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.InsertDriveFile +import androidx.compose.material.icons.filled.Code +import androidx.compose.material.icons.filled.DataObject +import androidx.compose.material.icons.filled.Description +import androidx.compose.material.icons.filled.FolderZip +import androidx.compose.material.icons.filled.Image +import androidx.compose.material.icons.filled.Movie +import androidx.compose.material.icons.filled.PictureAsPdf +import androidx.compose.material.icons.automirrored.filled.ReceiptLong +import androidx.compose.material.icons.filled.TableChart +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * Pure-logic tests for the artifact type classification and its type-to-icon + * mapping: which glyph a document, archive, log, code file, JSON payload, PDF and + * so on gets, independent of a device. + */ +class ArtifactTypeTest { + + @Test + fun mediaKindsComeStraightFromTheContentType() { + assertEquals(ArtifactKind.Image, artifactKind("image/png", "shot.png")) + assertEquals(ArtifactKind.Image, artifactKind("image/jpeg; charset=binary", "shot")) + assertEquals(ArtifactKind.Video, artifactKind("video/mp4", "clip.mp4")) + } + + @Test + fun namedFileKindsMapFromTheContentType() { + assertEquals(ArtifactKind.Pdf, artifactKind("application/pdf", "report.pdf")) + assertEquals(ArtifactKind.Json, artifactKind("application/json", "run.json")) + assertEquals(ArtifactKind.Archive, artifactKind("application/zip", "bundle.zip")) + assertEquals(ArtifactKind.Spreadsheet, artifactKind("text/csv", "rows.csv")) + assertEquals(ArtifactKind.Audio, artifactKind("audio/mpeg", "tone.mp3")) + } + + @Test + fun theNameExtensionResolvesAGenericSniff() { + // The server's sniff of an unrecognised extension is often text/plain; + // the name's extension still names the type. + assertEquals(ArtifactKind.Log, artifactKind("text/plain", "emulator.log")) + assertEquals(ArtifactKind.Code, artifactKind("text/plain", "Main.kt")) + assertEquals(ArtifactKind.Code, artifactKind("application/octet-stream", "config.yaml")) + assertEquals(ArtifactKind.Document, artifactKind("text/plain; charset=utf-8", "notes.txt")) + assertEquals(ArtifactKind.Document, artifactKind("", "index.html")) + } + + @Test + fun anUnknownTypeIsOtherNeverACrash() { + assertEquals(ArtifactKind.Other, artifactKind("", "")) + assertEquals(ArtifactKind.Other, artifactKind("application/octet-stream", "blob")) + assertEquals(ArtifactKind.Other, artifactKind("application/x-unknown", "data")) + } + + @Test + fun theTypeToIconMappingIsExplicitAndDistinct() { + assertEquals(Icons.Filled.Image, artifactIcon(ArtifactKind.Image)) + assertEquals(Icons.Filled.Movie, artifactIcon(ArtifactKind.Video)) + assertEquals(Icons.Filled.PictureAsPdf, artifactIcon(ArtifactKind.Pdf)) + assertEquals(Icons.Filled.DataObject, artifactIcon(ArtifactKind.Json)) + assertEquals(Icons.Filled.FolderZip, artifactIcon(ArtifactKind.Archive)) + assertEquals(Icons.Filled.TableChart, artifactIcon(ArtifactKind.Spreadsheet)) + assertEquals(Icons.AutoMirrored.Filled.ReceiptLong, artifactIcon(ArtifactKind.Log)) + assertEquals(Icons.Filled.Code, artifactIcon(ArtifactKind.Code)) + assertEquals(Icons.Filled.Description, artifactIcon(ArtifactKind.Document)) + assertEquals(Icons.AutoMirrored.Filled.InsertDriveFile, artifactIcon(ArtifactKind.Other)) + } + + @Test + fun noTwoKindsShareAGlyph() { + val glyphs = ArtifactKind.entries.map { artifactIcon(it) } + assertEquals(ArtifactKind.entries.size, glyphs.toSet().size) + } +} From e1c531a5374e0071c8af927e766c8f697fab89c7 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 17:51:56 +0100 Subject: [PATCH 2/5] Make the run summary's artifacts gallery a collapsed section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The run summary led with the artifacts gallery, but it was always open, so a long run's grid pushed the run's own facts below the fold. The gallery now sits in one collapsed-by-default section in the same place, with a header that describes itself while collapsed. - RunDetailScreen.kt: RunSummaryTab renders the gallery through the shared LazyListScope.collapsibleSection, keyed "artifacts" and seeded with rememberSectionExpansion(run.id), so a run opened fresh starts collapsed and the operator's choice persists per run across tab switches and config changes. Order is unchanged: the section still leads the summary and the facts item follows it. Expanding composes the unchanged ArtifactGallery; collapsing composes nothing. - ArtifactGroups.kt: new pure runArtifactsHeader(steps, executing) builds the self-describing header - singular/plural title, recorded count and "· partial capture" when any visit excluded or omitted files; empty runs reuse the shared artifactsEmptyMessage. Its count equals runArtifactGroups' tile total, so the header and the expanded gallery cannot disagree. - ArtifactGroupsTest.kt: four header tests covering count, singular vs plural, the partial-capture notes and the empty case, plus a count-matches-gallery assertion. - android/README.md: records the change and its verification evidence. Android only; no new dependency, no run started from the app, device work on the operator's Pixel 10 Pro Fold (58281FDCG000JF). Verified: 269/0/0/0 unit tests, clean assembleDebug and published APK LAN URL 200. --- android/README.md | 82 +++++++++++++++ .../net/awan/pipelines/ui/ArtifactGroups.kt | 24 +++++ .../pipelines/ui/screens/RunDetailScreen.kt | 44 ++++++--- .../awan/pipelines/ui/ArtifactGroupsTest.kt | 99 +++++++++++++++++++ 4 files changed, 236 insertions(+), 13 deletions(-) diff --git a/android/README.md b/android/README.md index 1181de66..0e99abe3 100644 --- a/android/README.md +++ b/android/README.md @@ -3580,3 +3580,85 @@ matched `2adaf03e…`), so any capture could not be attributed to this build. Th wide/narrow captures above predate the refactor; the refactor changes no UI pixels, so they remain representative of the gallery this code renders. +## Collapsible artifacts gallery in the run summary (16 Oct 2026) + +The artifacts gallery led the run summary but was always open, so a long run's +grid pushed the run's own facts below the fold. It is now one +collapsed-by-default section in the same place. `android/` only; no dependency +was added (the chevron is the existing `material-icons-extended` +`KeyboardArrowDown` the shared `SectionHeader` already uses), no run was started +from the app, and every device command targeted the operator's Pixel 10 Pro Fold +(`58281FDCG000JF`), never an emulator. + +- **One collapsed section, same place.** `RunDetailScreen.kt`'s `RunSummaryTab` + renders the gallery through the shared `LazyListScope.collapsibleSection`, + keyed `"artifacts"` and seeded with `rememberSectionExpansion(run.id)`, so a + run opened fresh starts collapsed and the operator's expand/collapse choice + survives Summary↔tab switches, configuration changes and rotation exactly like + every other section. The order is unchanged: the artifacts section still leads + the summary and the facts item follows it. +- **A self-describing header.** The new pure `runArtifactsHeader(steps, + executing)` (`ui/ArtifactGroups.kt`) builds the header text — the title (its + singular form for exactly one artifact), how many the run recorded, and + `· partial capture` when any visit excluded or omitted files; with no artifacts + it reuses the shared `artifactsEmptyMessage`. Its count is exactly + `runArtifactGroups`'s tile total, so the header and the expanded gallery can + never disagree. +- **The gallery itself is unchanged.** Expanding composes the same + `ArtifactGallery` (the width-derived thumbnail grid, tap for full size, the + non-media tiles with name, size and content type plus their open/copy/share + actions); collapsing composes nothing. The stage pane's per-visit artifacts + section and every other summary section are untouched. + +Evidence (macOS, JDK 17 from Homebrew `openjdk@17`, Gradle 8.11.1 from the +wrapper cache, `ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--offline`, +every Gradle command with `--no-daemon`): + +- `gradle --no-daemon --offline :app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the + test-result XMLs aggregate to **269 tests, 0 failures, 0 errors, 0 skipped**. + `ArtifactGroupsTest` gained `headerReportsTheCountWithASingularTitleForOne`, + `headerAddsPartialCaptureOnlyWhenFilesWereExcludedOrOmitted`, + `headerEmptyCaseUsesTheSharedEmptyWording` and + `headerCountMatchesTheGalleryRecordedTotal`. +- `gradle --no-daemon --offline :app:assembleDebug` → `app-debug.apk` + **18,011,393 bytes**, sha256 + `c5655269e490db34cbacccf68eaec468a3a41c46c661b41e6ad2d92295235247`; installed + with `adb -s 58281FDCG000JF install -r`, and the pulled `base.apk` sha matched + the local build, so the captures below are attributed to this exact build. +- Run **136** (pipeline id 11 v1, `succeeded`, 17 artifacts) on the Pixel: + - **Wide** (inner display, 2152×2076 @330 ≈ 1043dp): + `summary_wide_collapsed.png` shows the summary led by a lone collapsed + `Artifacts · 17 recorded · partial capture` header (right chevron) with the + run's facts immediately below and no gallery; `summary_wide_expanded.png` + shows the same header expanded to the unchanged gallery — the + `implementer · visit 1` and `ui_reviewer · visit 1` groups of image + thumbnails plus the `chat_stub_approval.py` (`<>` code glyph) and `stub.log` + (log glyph) tiles with their names, `9.3 KiB`/`220 B` sizes and share/copy + actions. + - **Narrow** (`wm size 1080x2152` on the inner display ≈ 524dp, reset to the + native size afterwards): `summary_narrow_collapsed.png` and + `summary_narrow_expanded.png` show the same collapsed header and, expanded, + the same gallery re-flowed to four cells per row (wide uses five). + - **Persistence.** `uiautomator dump` reported `Artifacts · 17 recorded · + partial capture, collapsed` on a freshly opened run; toggling it and + round-tripping Summary → Graph → Summary, and a `wm size` configuration + change, both kept the operator's expanded/collapsed choice. + - `adb -s 58281FDCG000JF logcat -d | grep -cE 'FATAL EXCEPTION|E + AndroidRuntime'` returned 0; the screen stayed awake (`svc power stayon usb` + + `KEYCODE_WAKEUP`) and every capture used `screencap -p -d ` + + `adb pull`. Screenshots, `uiautomator` dumps and the APK are in + `…/artifacts/155/1/`. +- **APK publish.** `app-debug.apk` copied to + `…/artifacts/155/1/pipelines-debug-wip-95150c7.apk` (`95150c7` = short `HEAD`; + the working tree is uncommitted WIP on top of it); `shasum -a 256` matched. + `curl -I http://10.0.0.249:8080/artifacts/155/1/pipelines-debug-wip-95150c7.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: + application/vnd.android.package-archive`, `Content-Length: 18011393`. + +Not verified in this pass: no device capture exercises the empty or the +single-artifact header wording (both are covered by the `runArtifactsHeader` +unit tests); the narrow window was produced with a `wm size` override on the +inner display rather than a physical fold, then reset; `:app:lintDebug` was not +re-run (its only known findings remain the two pre-existing `NewApi` errors for +`android:windowLightNavigationBar`). + diff --git a/android/app/src/main/java/net/awan/pipelines/ui/ArtifactGroups.kt b/android/app/src/main/java/net/awan/pipelines/ui/ArtifactGroups.kt index f6c6f08a..b5c25394 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/ArtifactGroups.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/ArtifactGroups.kt @@ -54,3 +54,27 @@ fun artifactsEmptyMessage(executing: Boolean): String = } else { "No artifacts recorded for this run." } + +/** + * The run summary's Artifacts section header, complete on its own while the + * section is collapsed: the title, how many artifacts the run recorded (the + * title takes its singular form for exactly one) and "partial capture" when any + * visit excluded or omitted files. It mirrors the per-visit [artifactsSummary] + * vocabulary at run level and reuses the shared [artifactsEmptyMessage] for the + * empty case, so a run with nothing recorded still gets a self-describing + * collapsed header. The recorded count is exactly the number of tiles + * [runArtifactGroups] yields, so the header and the expanded gallery can never + * disagree. Pure. + */ +fun runArtifactsHeader(steps: List, executing: Boolean): String { + val recorded = steps.sumOf { it.artifacts.orEmpty().size } + if (recorded == 0) return artifactsEmptyMessage(executing) + val partial = steps.any { it.artifactsSkipped > 0 || it.artifactsTruncated > 0 } + return buildString { + append(if (recorded == 1) "Artifact" else "Artifacts") + append(" · ") + append(recorded) + append(" recorded") + if (partial) append(" · partial capture") + } +} 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 d6b1ef00..01ebaa89 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 @@ -52,7 +52,6 @@ import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.ui.AppViewModel import net.awan.pipelines.ui.ArtifactGroup import net.awan.pipelines.ui.LoadState -import net.awan.pipelines.ui.artifactsEmptyMessage import net.awan.pipelines.ui.components.CodeBlock import net.awan.pipelines.ui.components.ColoredChip import net.awan.pipelines.ui.components.DetailTabBody @@ -84,6 +83,7 @@ import net.awan.pipelines.ui.graph.graphColors import net.awan.pipelines.ui.graph.outcomeColor import net.awan.pipelines.ui.graph.rememberArtifactSelection import net.awan.pipelines.ui.runArtifactGroups +import net.awan.pipelines.ui.runArtifactsHeader import net.awan.pipelines.ui.theme.ICON_INLINE_DP import net.awan.pipelines.ui.theme.ICON_STATUS_DP import net.awan.pipelines.ui.theme.SPACING_L @@ -338,6 +338,7 @@ private fun ConfirmDialog( * id/version, current stage, workspace, content hash, start/finish/duration and * the failure diagnostic. */ +@OptIn(ExperimentalFoundationApi::class) @Composable private fun RunSummaryTab( run: RunDetail, @@ -351,23 +352,35 @@ private fun RunSummaryTab( ) { val text = pipelinesText() val state = runStateOf(run.status) + // The artifacts section starts collapsed and its expand/collapse choice is + // remembered/saved per run id, so a different run reseeds it and a run opened + // fresh starts collapsed. Both the header and the gallery read the same + // snapshot, so they can never disagree. + val artifactsExpansion = rememberSectionExpansion(run.id) + val artifactsHeader = remember(run.steps, run.executing) { + runArtifactsHeader(run.steps, run.executing) + } DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, contentPadding = PaddingValues(vertical = SPACING_L), ) { - // The artifacts gallery leads the summary: the captured screenshots - // are the first thing the operator sees, with the run's own facts - // below it. - item(key = "run-artifacts") { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_S), - verticalArrangement = Arrangement.spacedBy(SPACING_S), - ) { - Text("Artifacts", style = text.sectionHeader) - if (artifactGroups.isEmpty()) { - Text(artifactsEmptyMessage(run.executing), style = text.meta) - } else { + // The artifacts gallery still leads the summary, but inside one + // collapsed section: its header alone carries the run's capture + // wording until the operator expands it, and expanding reveals the + // unchanged gallery (nothing when no artifacts were recorded). + collapsibleSection( + title = artifactsHeader, + key = SUMMARY_ARTIFACTS_KEY, + expanded = artifactsExpansion.isExpanded(SUMMARY_ARTIFACTS_KEY), + onToggle = { artifactsExpansion.toggle(SUMMARY_ARTIFACTS_KEY) }, + ) { + if (artifactGroups.isNotEmpty()) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = SPACING_L, vertical = SPACING_S), + ) { ArtifactGallery( groups = artifactGroups, configuredServerUrl = configuredServerUrl, @@ -748,4 +761,9 @@ private fun EvidenceDetails(evidence: SessionEvidence, modifier: Modifier = Modi } } +// The run summary's artifacts section key: stable so its expand/collapse choice +// is remembered consistently (it is namespaced under the summary tab's saved +// state and reseeded by run id). +private const val SUMMARY_ARTIFACTS_KEY = "artifacts" + private const val POLL_INTERVAL_MILLIS = 1_000L diff --git a/android/app/src/test/java/net/awan/pipelines/ui/ArtifactGroupsTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/ArtifactGroupsTest.kt index ee83e7a0..511e5619 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/ArtifactGroupsTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/ArtifactGroupsTest.kt @@ -15,11 +15,15 @@ class ArtifactGroupsTest { sequence: Int, visit: Int = 0, artifacts: List? = null, + skipped: Int = 0, + truncated: Int = 0, ) = RunStep( sequence = sequence, stage = stage, control = ControlEvidence(visit = visit), artifacts = artifacts, + artifactsSkipped = skipped, + artifactsTruncated = truncated, ) private fun artifact(name: String, url: String = "/artifacts/$name") = @@ -95,4 +99,99 @@ class ArtifactGroupsTest { assertTrue(pending.startsWith("Artifacts · ")) assertTrue(pending.contains(ARTIFACT_CAPTURE_PENDING)) } + + @Test + fun headerReportsTheCountWithASingularTitleForOne() { + assertEquals( + "Artifact · 1 recorded", + runArtifactsHeader( + listOf(step("planner", sequence = 1, visit = 1, artifacts = listOf(artifact("a")))), + executing = false, + ), + ) + assertEquals( + "Artifacts · 3 recorded", + runArtifactsHeader( + listOf( + step("planner", sequence = 1, visit = 1, artifacts = listOf(artifact("a"), artifact("b"))), + step("build", sequence = 2, visit = 1, artifacts = listOf(artifact("c"))), + ), + executing = false, + ), + ) + } + + @Test + fun headerAddsPartialCaptureOnlyWhenFilesWereExcludedOrOmitted() { + assertEquals( + "Artifact · 1 recorded", + runArtifactsHeader( + listOf(step("planner", 1, 1, listOf(artifact("a")))), + executing = false, + ), + ) + assertEquals( + "Artifacts · 2 recorded · partial capture", + runArtifactsHeader( + listOf(step("planner", 1, 1, listOf(artifact("a"), artifact("b")), skipped = 1)), + executing = false, + ), + ) + assertEquals( + "Artifacts · 2 recorded · partial capture", + runArtifactsHeader( + listOf(step("planner", 1, 1, listOf(artifact("a"), artifact("b")), truncated = 3)), + executing = false, + ), + ) + // A visit that recorded nothing but excluded files still marks the run's + // capture as partial. + assertEquals( + "Artifact · 1 recorded · partial capture", + runArtifactsHeader( + listOf( + step("planner", 1, 1, listOf(artifact("a"))), + step("build", 2, 1, artifacts = emptyList(), skipped = 2), + ), + executing = false, + ), + ) + } + + @Test + fun headerEmptyCaseUsesTheSharedEmptyWording() { + assertEquals( + artifactsEmptyMessage(executing = true), + runArtifactsHeader(emptyList(), executing = true), + ) + assertEquals( + artifactsEmptyMessage(executing = false), + runArtifactsHeader(emptyList(), executing = false), + ) + // Excluded/omitted counts with no recorded artifacts still read as empty: + // the partial-capture note never accompanies the empty summary. + assertEquals( + artifactsEmptyMessage(executing = false), + runArtifactsHeader( + listOf(step("planner", 1, 1, artifacts = emptyList(), skipped = 2, truncated = 1)), + executing = false, + ), + ) + } + + @Test + fun headerCountMatchesTheGalleryRecordedTotal() { + val steps = listOf( + step("planner", 1, 1, listOf(artifact("a"), artifact("b"))), + step("planner", 2, 2, artifacts = emptyList()), + step("build", 3, 1, listOf(artifact("c"))), + ) + // Every recorded artifact is exactly one gallery tile; the header can + // never announce a count the expanded gallery does not render. + assertEquals(3, runArtifactGroups(steps).sumOf { it.artifacts.size }) + assertEquals( + "Artifacts · 3 recorded", + runArtifactsHeader(steps, executing = false), + ) + } } From 8b0d7b1ecb779825d78cbe7877f9dd8c04fc949b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 18:26:29 +0100 Subject: [PATCH 3/5] Show a run's title beside its pipeline name Surface the operator's title for a run so two runs of the same pipeline read as clearly different goals, with the pipeline name kept as context. - protocol: optional nullable `title` on RunSummary and RunDetail; absent or blank degrades to the pipeline name. - ui/RunIdentity.kt: one shared fallback (`runLabel`) and two-line identity (`runIdentity`) so the list, detail header and stage pane never spell a run differently; a titled run shows the pipeline name + version as a second line, an untitled run keeps the pipeline name as its only line. - runs list / run detail / stage pane use the shared identity; the status chip, duration and metadata layout are unchanged. - no rename affordance: the server exposes no title and no `set_run_title`, so the app does not fake renaming. - tests: RunIdentityTest (5) plus ProtocolModelTest cases for a present and an absent title; README documents the change and its verification. --- android/README.md | 55 +++++++++++++++++++ .../awan/pipelines/data/protocol/Message.kt | 6 ++ .../java/net/awan/pipelines/ui/RunIdentity.kt | 26 +++++++++ .../pipelines/ui/graph/StageDetailPane.kt | 25 ++++++++- .../pipelines/ui/screens/RunDetailScreen.kt | 29 +++++++++- .../pipelines/ui/screens/RunHistoryScreen.kt | 35 ++++++++++-- .../data/protocol/ProtocolModelTest.kt | 33 +++++++++++ .../net/awan/pipelines/ui/RunIdentityTest.kt | 50 +++++++++++++++++ 8 files changed, 249 insertions(+), 10 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/RunIdentity.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/RunIdentityTest.kt diff --git a/android/README.md b/android/README.md index 0e99abe3..f4b61055 100644 --- a/android/README.md +++ b/android/README.md @@ -3662,3 +3662,58 @@ inner display rather than a physical fold, then reset; `:app:lintDebug` was not re-run (its only known findings remain the two pre-existing `NewApi` errors for `android:windowLightNavigationBar`). +## Run title beside the pipeline name (16 Oct 2026) + +A run now shows the operator's title for the goal, with the pipeline it ran on as +the secondary line, so two runs of the same pipeline are distinguishable. +`android/` only; no dependency was added, no run was started from the app, and no +device command was run (build + unit tests only). + +- **Protocol.** `data/protocol/Message.kt` gains an optional `title` on both + `RunSummary` and `RunDetail` (the server's `RunSummary.title`). It is nullable + and defaults to absent, so a server that does not send it degrades cleanly. +- **One shared fallback.** New `ui/RunIdentity.kt` holds `runLabel(title, name)` + (mirroring the server's `RunSummary.Label`) and `runIdentity(title, name)`: the + label is the title, or the pipeline name when the title is absent/blank, and the + pipeline is a second line only when a title exists — never an empty line. +- **Runs list.** `RunHistoryScreen.RunRow` shows the label as the primary line and, + only for a titled run, the pipeline name plus its version chip on a second line; + an untitled run keeps the pipeline name and version chip as its single identity + line. The status chip, progress, id/start/duration line and diagnostic are + unchanged. +- **Run detail + stage panes.** The run detail app bar and the Summary lead with + the label and, when titled, name the pipeline (`name · vN`) on a second line; the + covered peek uses the label too. `StageDetailPane` takes an optional `runLabel` + and shows it under the stage name, so a stage/visit pane keeps the run context. +- **Renaming is not offered.** The authoritative server does not expose it: it has + no `set_run_title` command and `list_runs`/`get_run` return no `title` field, so + the app does not fake a rename. The protocol field is parsed for the server that + does send it; until then the title falls back to the pipeline name. + +Evidence (macOS, JDK 17 from Homebrew `openjdk@17`, Gradle 8.11.1 from the wrapper +cache, `ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--offline`, `--no-daemon`): + +- `:app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the 32 result XMLs aggregate to + **276 tests, 0 failures, 0 errors, 0 skipped**. The new `RunIdentityTest` (5 + cases) covers the title/fallback/trim logic, and `ProtocolModelTest` gained a + case for a present and one for an absent title on both the run summary and the + run detail. +- `:app:assembleDebug` → `app-debug.apk` **18,257,214 bytes**, sha256 + `bce661069b2bd013f0802545402766a3ae8fed97e1bbe0109f81a4bfb6233601`. +- Server capability probe (read-only, through the installed CLI): + `pipelines runs` and `pipelines rpc '{"type":"get_run","run_id":155}'` return no + `title` field, and the running `pipelines-server` binary contains no + `set_run_title` string. So renaming is deliberately not offered and the title + falls back to the pipeline name until a server carrying the field is deployed. +- **APK publish.** `app-debug.apk` copied to + `…/artifacts/162/1/pipelines-debug-wip-e1c531a.apk` (`e1c531a` = short `HEAD`; + the working tree is uncommitted WIP on top of it); `shasum -a 256` matched. + `curl -I http://10.0.0.249:8080/artifacts/162/1/pipelines-debug-wip-e1c531a.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: + application/vnd.android.package-archive`, `Content-Length: 18257214`. + +Not verified in this pass: device captures of the runs list and run detail (the +visual review owns the device); no server that actually sends `title` was +available, so the titled layout is exercised by the unit tests and the fallback +path only. + 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 6f07efc3..53a9f24e 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 @@ -238,6 +238,10 @@ data class RunSummary( val id: Long = 0, @SerialName("pipeline_id") val pipelineId: Long = 0, val name: String = "", + // The operator-facing, bounded description of what the run is for, generated + // by the server from its prompt. Null/blank on a server that predates the + // field, so the UI falls back to [name] rather than showing an empty line. + val title: String? = null, val version: Int = 0, @SerialName("content_hash") val contentHash: String = "", val status: String = "", @@ -283,6 +287,8 @@ data class RunDetail( val id: Long = 0, @SerialName("pipeline_id") val pipelineId: Long = 0, val name: String = "", + // Mirrors the embedded RunSummary.title (see internal/protocol/runs.go). + val title: String? = null, val version: Int = 0, @SerialName("content_hash") val contentHash: String = "", val status: String = "", diff --git a/android/app/src/main/java/net/awan/pipelines/ui/RunIdentity.kt b/android/app/src/main/java/net/awan/pipelines/ui/RunIdentity.kt new file mode 100644 index 00000000..79e9c079 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/RunIdentity.kt @@ -0,0 +1,26 @@ +package net.awan.pipelines.ui + +/** + * The operator-facing name of a run: the server's stored title when it sent one, + * otherwise the pipeline name (a run predating the title field, or one the server + * could not title). Mirrors the server's `RunSummary.Label`, so the runs list, the + * run detail header and the stage pane never spell the same run differently. + */ +fun runLabel(title: String?, name: String): String { + val stored = title?.trim().orEmpty() + return if (stored.isEmpty()) name else stored +} + +/** + * The runs list's two identity lines: [label] is the run's primary line and + * [pipeline] is the pipeline the run belongs to, shown as a second line only when + * the label is a stored title (so two runs of one pipeline read as different + * goals). A run with no title falls back to the pipeline name as its only line — + * never a title line followed by an empty one. + */ +data class RunIdentity(val label: String, val pipeline: String?) + +fun runIdentity(title: String?, name: String): RunIdentity { + val stored = title?.trim().orEmpty() + return if (stored.isEmpty()) RunIdentity(name, null) else RunIdentity(stored, name) +} 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 44097a17..5c37aa28 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 @@ -31,6 +31,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import net.awan.pipelines.data.protocol.ControlEvidence @@ -55,6 +56,7 @@ import net.awan.pipelines.ui.fileChangeLine import net.awan.pipelines.ui.fileChangesSummary import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.notificationLine +import net.awan.pipelines.ui.runLabel import net.awan.pipelines.ui.screens.runTimeline import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_S @@ -326,6 +328,7 @@ fun StageDetailPane( modifier: Modifier = Modifier, covered: Boolean = false, runContext: Boolean = false, + runLabel: String? = null, ) { // A covered pane shows its compact identity only; the visit tab row and the // stage body must never be drawn squeezed into the peek strip. @@ -366,7 +369,26 @@ fun StageDetailPane( containerColor = paneContainerColor(), topBar = { TopAppBar( - title = { Text(GraphSemantics.nodeLabel(stageKey)) }, + title = { + // The stage's own name leads, with the run it belongs to on a + // second line when the caller has one, so opening a stage never + // loses which run it is a visit of. + Column { + Text( + GraphSemantics.nodeLabel(stageKey), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + runLabel?.takeIf { it.isNotBlank() }?.let { label -> + Text( + label, + style = pipelinesText().meta, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") @@ -575,6 +597,7 @@ fun RunStagePane( modifier = modifier, covered = covered, runContext = true, + runLabel = run?.let { runLabel(it.title, it.name) }, ) } 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 01ebaa89..40ca2efe 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 @@ -84,6 +84,8 @@ import net.awan.pipelines.ui.graph.outcomeColor import net.awan.pipelines.ui.graph.rememberArtifactSelection import net.awan.pipelines.ui.runArtifactGroups import net.awan.pipelines.ui.runArtifactsHeader +import net.awan.pipelines.ui.runIdentity +import net.awan.pipelines.ui.runLabel import net.awan.pipelines.ui.theme.ICON_INLINE_DP import net.awan.pipelines.ui.theme.ICON_STATUS_DP import net.awan.pipelines.ui.theme.SPACING_L @@ -159,7 +161,7 @@ fun RunDetailScreen( // graphs must never be drawn squeezed into the peek strip. if (covered) { PaneIdentity( - title = run?.name ?: "Run", + title = run?.let { runLabel(it.title, it.name) } ?: "Run", subtitle = run?.status?.takeIf { it.isNotBlank() }, modifier = modifier.fillMaxSize(), ) @@ -178,7 +180,28 @@ fun RunDetailScreen( enabled = summaryTab == "summary", topBar = { TopAppBar( - title = { Text(run?.let { "Run ${it.id}" } ?: "Run") }, + title = { + // The header names the run by its title and keeps the pipeline + // it belongs to on a second line, so a stage pane opened from + // here carries the same context. Without a title the pipeline + // name is the single identity, never a blank first line. + val identity = run?.let { runIdentity(it.title, it.name) } + Column { + Text( + identity?.label ?: "Run", + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + identity?.pipeline?.let { pipeline -> + Text( + "$pipeline · v${run?.version}", + style = pipelinesText().meta, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") @@ -396,7 +419,7 @@ private fun RunSummaryTab( modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L), verticalArrangement = Arrangement.spacedBy(SPACING_XS), ) { - Text(run.name, style = text.screenTitle) + Text(runLabel(run.title, run.name), style = text.screenTitle) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(SPACING_S), diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt index f6107d52..21ac4cf9 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt @@ -67,6 +67,7 @@ import net.awan.pipelines.ui.components.paneSafeArea import net.awan.pipelines.ui.components.runStateColor import net.awan.pipelines.ui.components.runStateOf import net.awan.pipelines.ui.formatDuration +import net.awan.pipelines.ui.runIdentity import net.awan.pipelines.ui.theme.ICON_LIST_DP import net.awan.pipelines.ui.theme.ICON_STATUS_DP import net.awan.pipelines.ui.theme.PipelinesTextStyles @@ -376,10 +377,12 @@ private fun Metric(label: String, value: String, color: Color, text: PipelinesTe } /** - * One run as a row of the shared real list: a leading status glyph, the run name - * as the title with its version chip, and a secondary line carrying the status - * chip, progress and id/start/duration. The row is selected when its run is the - * one open in the detail pane. + * One run as a row of the shared real list: a leading status glyph, the run's + * title as the primary line (falling back to the pipeline name when the server + * stored no title) with its version chip, the pipeline name on a second line only + * when a title exists, then a secondary line carrying the status chip, progress + * and id/start/duration. The row is selected when its run is the one open in the + * detail pane. */ @Composable private fun RunRow( @@ -390,6 +393,7 @@ private fun RunRow( ) { val text = pipelinesText() val state = runStateOf(run.status) + val identity = runIdentity(run.title, run.name) ListRow( selected = selected, onClick = onClick, @@ -407,13 +411,32 @@ private fun RunRow( horizontalArrangement = Arrangement.spacedBy(SPACING_S), ) { Text( - run.name, + identity.label, style = text.cardTitle, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), ) - VersionChip("v${run.version}") + // Without a title the pipeline name is the only identity line, so the + // version stays beside it; with one the pipeline drops to the second + // line and takes the version with it. + if (identity.pipeline == null) VersionChip("v${run.version}") + } + + if (identity.pipeline != null) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + Text( + identity.pipeline, + style = text.meta, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + VersionChip("v${run.version}") + } } Row( 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 eff871cc..cce06fd4 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 @@ -257,4 +257,37 @@ class ProtocolModelTest { assertEquals(2, pipeline.succeeded) assertEquals(3.5, pipeline.averageSeconds, 0.0) } + + @Test + fun runSummariesAndDetailsCarryTheOperatorTitleWhenTheServerSendsIt() { + val json = """ + { + "type": "runs", + "runs": [ + {"id": 1, "pipeline_id": 7, "name": "demo", "title": "Add a dark mode toggle", "version": 2, "status": "succeeded"} + ], + "run_detail": { + "id": 1, + "pipeline_id": 7, + "name": "demo", + "title": "Add a dark mode toggle", + "version": 2, + "steps": [] + } + } + """.trimIndent() + val message = PipelinesJson.decodeFromString(Message.serializer(), json) + assertEquals("Add a dark mode toggle", message.runs!!.single().title) + assertEquals("Add a dark mode toggle", message.runDetail!!.title) + } + + @Test + fun anAbsentRunTitleStaysNullSoTheUiFallsBackToThePipelineName() { + val json = """ + {"type": "runs", "runs": [{"id": 1, "name": "demo"}], "run_detail": {"id": 1, "name": "demo"}} + """.trimIndent() + val message = PipelinesJson.decodeFromString(Message.serializer(), json) + assertNull(message.runs!!.single().title) + assertNull(message.runDetail!!.title) + } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/RunIdentityTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/RunIdentityTest.kt new file mode 100644 index 00000000..cfd1e135 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/RunIdentityTest.kt @@ -0,0 +1,50 @@ +package net.awan.pipelines.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class RunIdentityTest { + + @Test + fun aStoredTitleIsThePrimaryLineWithThePipelineOnASecondLine() { + val identity = runIdentity("Add a dark mode toggle", "android-app") + assertEquals("Add a dark mode toggle", identity.label) + assertEquals("android-app", identity.pipeline) + } + + @Test + fun twoRunsOfOnePipelineReadAsDifferentGoals() { + val first = runIdentity("Add a dark mode toggle", "android-app") + val second = runIdentity("Fix the crash on rotate", "android-app") + // Same pipeline on the second line, different title on the first. + assertEquals("android-app", first.pipeline) + assertEquals(first.pipeline, second.pipeline) + assertNotEquals(first.label, second.label) + } + + @Test + fun aMissingOrBlankTitleFallsBackToThePipelineNameWithNoSecondLine() { + for (title in listOf(null, "", " ", "\t")) { + val identity = runIdentity(title, "android-app") + assertEquals("android-app", identity.label) + assertNull(identity.pipeline) + } + } + + @Test + fun theStoredTitleIsTrimmed() { + val identity = runIdentity(" Add a dark mode toggle ", "android-app") + assertEquals("Add a dark mode toggle", identity.label) + assertEquals("android-app", identity.pipeline) + } + + @Test + fun runLabelMirrorsTheRowsPrimaryLine() { + assertEquals("Add a dark mode toggle", runLabel("Add a dark mode toggle", "android-app")) + assertEquals("Add a dark mode toggle", runLabel(" Add a dark mode toggle ", "android-app")) + assertEquals("android-app", runLabel(null, "android-app")) + assertEquals("android-app", runLabel(" ", "android-app")) + } +} From 007639948ce6aa0e950239e169462dcbf7db7c4c Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 19:17:26 +0100 Subject: [PATCH 4/5] Show the stage verdict atop the stage pane, with clickable artifacts Mirror the server's derived verdict onto RunStep as a nullable StageVerdict ({option, reason, reason_source, artifacts}, absent -> null), matching internal/protocol/verdict.go. Render a StageVerdictBlock at the top of the run pane, below the visit tabs and above the facts, only when a verdict is present - a null or empty verdict draws nothing, never an empty heading. The chosen option is a ColoredChip in the stage outcome's existing colour; the reason is plain pipelinesText().body that wraps without a maxLines clip. The artifacts the reason names become inline, tappable references (image/video open the shared ArtifactViewer, anything else uses the existing openArtifact action) plus the same references as compact FlowRow chips. Referenced names resolve to the visit's recorded artifacts, deduplicated and in recorded order; reason text is split around those names longest-match-first. No new dependency and no new dp or sp literal. android/ only. --- android/README.md | 59 ++++ .../awan/pipelines/data/protocol/Message.kt | 19 ++ .../pipelines/ui/graph/StageDetailPane.kt | 14 + .../awan/pipelines/ui/graph/StageVerdict.kt | 279 ++++++++++++++++++ .../data/protocol/ProtocolModelTest.kt | 42 +++ .../pipelines/ui/graph/StageVerdictTest.kt | 99 +++++++ 6 files changed, 512 insertions(+) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/graph/StageVerdict.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/graph/StageVerdictTest.kt diff --git a/android/README.md b/android/README.md index f4b61055..0119fda0 100644 --- a/android/README.md +++ b/android/README.md @@ -3717,3 +3717,62 @@ visual review owns the device); no server that actually sends `title` was available, so the titled layout is exercised by the unit tests and the fallback path only. +## Stage verdict atop the stage pane, with clickable artifacts (16 Oct 2026) + +A completed run visit now leads its stage pane with the server's derived verdict: +the chosen option as a badge, the concise reason in ordinary body text, and the +recorded artifacts the reason names as inline, tappable references plus the same +references as compact chips. `android/` only; nothing in the Pipelines server, its +Go source, the installer or the Docker files was touched, no run was started from +the app, and no device command was run (build + unit tests only). + +- **Protocol.** `data/protocol/Message.kt` gains `StageVerdict` and an optional + `verdict` on `RunStep`, mirroring `internal/protocol/verdict.go` + (`{option, reason, reason_source, artifacts}` under the `verdict` wire name). It + is nullable and defaults to absent, so a running step or a pre-verdict server + parses cleanly to null. +- **One block.** New `ui/graph/StageVerdict.kt` holds the pure helpers and the + composable. `StageVerdictBlock` is rendered at the top of the run pane, below the + visit tabs and above the facts, only when the server reported a verdict; a null + verdict (or one with neither option nor reason) draws nothing — never an empty + heading or placeholder. +- **Badge.** The option is a `ColoredChip` in the *stage outcome's* existing colour + (`outcomeColor(step.outcome)`, the graph's palette the Timeline chips already + use), so the badge agrees with the graph rather than a new colour vocabulary. +- **Reason.** Rendered with `pipelinesText().body`, so it is readable plain + language, never a monospace JSON dump, and it wraps with no `maxLines` clip. +- **References.** `referencedVerdictArtifacts` resolves the verdict's referenced + names to the visit's recorded artifacts (recorded order, deduplicated, an + unrecorded/invented name dropped). `verdictReasonSegments` splits the reason + around those names — by full recorded name or basename, longest match first — and + the segments become inline `LinkAnnotation.Clickable` references coloured + `primary` with an underline. An image/video reference opens the shared + `ArtifactViewer`; anything else goes through the existing `openArtifact` action. + The same references are `FlowRow` chips (`VerdictArtifactChip`) with their type + glyph, so they can be tapped without hunting in the sentence. +- **Geometry.** Only existing tokens (`SPACING_M`/`SPACING_S`/`SPACING_XS`, + `ICON_STATUS_DP`); no new `dp`/`sp` literal and no new dependency. + +Evidence (macOS, JDK 17 from Homebrew `openjdk@17`, Gradle 8.11.1 from the wrapper +cache, `ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--no-daemon`): + +- `:app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the result XMLs aggregate to + **282 tests, 0 failures, 0 errors, 0 skipped**. New `StageVerdictTest` (5 cases: + split around every referenced name, basename for a slashed path, longest match + wins, a reason with no references, and name→recorded-artifact resolution) and + `ProtocolModelTest#runStepVerdictParsesWithItsReasonSourceAndReferencedArtifacts`. +- `:app:assembleDebug` → `app-debug.apk` **18,270,824 bytes**, sha256 + `85847c6fe32498f38464741ca1b8f592dbbd7a9e1f34dd649121e723836b0903`. +- **APK publish.** `app-debug.apk` copied to + `~/.local/share/pipelines/data/artifacts/167/1/pipelines-debug-wip-8b0d7b1.apk` + (`8b0d7b1` = short `HEAD`); `shasum -a 256` matched. The LAN URL + `http://10.0.0.249:8080/artifacts/167/1/pipelines-debug-wip-8b0d7b1.apk` returned + `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18270824`. + +Not verified in this pass: device captures of the stage pane at a narrow and a wide +window (the visual review owns the device, per the brief's device policy), so the +verdict layout is exercised by the unit tests and the compile only. No server that +actually sends `verdict` was available to the implementer, so the block's live +rendering against real data is deferred to visual review. + 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 53a9f24e..8d03f6a8 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 @@ -213,6 +213,22 @@ data class StageArtifact( val url: String = "", ) +/** + * The plain-language outcome of one completed stage visit, derived server-side + * and mirrored from `internal/protocol/verdict.go` StageVerdict: the chosen + * option (the outcome and the target it routed to), a bounded one-line reason + * with its provenance ([reasonSource]), and the names of the recorded artifacts + * the reason refers to. A null on a step means the server reported no verdict + * (for example a running visit), so the pane shows no block at all. + */ +@Serializable +data class StageVerdict( + val option: String = "", + val reason: String = "", + @SerialName("reason_source") val reasonSource: String = "", + val artifacts: List = emptyList(), +) + @Serializable data class NotificationReceipt( val destination: String = "", @@ -265,6 +281,9 @@ data class RunStep( val artifacts: List? = null, @SerialName("artifacts_skipped") val artifactsSkipped: Int = 0, @SerialName("artifacts_truncated") val artifactsTruncated: Int = 0, + // 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, val sequence: Int = 0, val stage: String = "", val status: String = "", 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 5c37aa28..f348510c 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 @@ -491,6 +491,20 @@ private fun StageDetailBody( } } + // The verdict leads the run pane, above the facts: the chosen option, + // the concise reason and the artifacts it names. Absent when the server + // reported none, so no empty heading is ever drawn. + if (runContext && selectedStep != null) { + StageVerdictBlock( + verdict = selectedStep.verdict, + outcome = selectedStep.outcome, + status = selectedStep.status, + artifacts = selectedStep.artifacts.orEmpty(), + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, + ) + } + // Identity and result: always visible, never behind a collapse, so a // freshly opened pane never reads as empty. headline.forEach { field -> StageFieldRow(field) } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageVerdict.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageVerdict.kt new file mode 100644 index 00000000..c896d04f --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageVerdict.kt @@ -0,0 +1,279 @@ +package net.awan.pipelines.ui.graph + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +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.material3.Icon +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.platform.LocalContext +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withLink +import net.awan.pipelines.data.protocol.StageArtifact +import net.awan.pipelines.data.protocol.StageVerdict +import net.awan.pipelines.ui.components.ColoredChip +import net.awan.pipelines.ui.components.runStateIcon +import net.awan.pipelines.ui.components.runStateOf +import net.awan.pipelines.ui.theme.ICON_STATUS_DP +import net.awan.pipelines.ui.theme.SPACING_M +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XS +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * One piece of a verdict's reason: literal [text], or a reference to a recorded + * [artifact] the reason names. A null [artifact] is plain text. + */ +internal data class VerdictReasonSegment(val text: String, val artifact: StageArtifact? = null) + +/** + * The recorded artifacts a [verdict] refers to: its own referenced names resolved + * to the visit's recorded [artifacts], in recorded order and deduplicated. A name + * the server never recorded is dropped, so only real files are ever offered, and + * no verdict or no referenced names yields nothing. + */ +internal fun referencedVerdictArtifacts( + verdict: StageVerdict?, + artifacts: List, +): List { + val names = verdict?.artifacts.orEmpty() + if (names.isEmpty()) return emptyList() + val wanted = names.toHashSet() + val seen = HashSet() + val referenced = ArrayList() + for (artifact in artifacts) { + if (artifact.name.isEmpty() || !seen.add(artifact.name)) continue + if (artifact.name in wanted) referenced += artifact + } + return referenced +} + +/** + * Splits [reason] into literal runs and references to the recorded [references] + * it names, by an artifact's full recorded name or its basename (mirroring the + * server's own reference matching). At the same index a longer token wins over a + * shorter one, so a full slashed path is never split inside a longer match. With + * nothing to reference the whole reason is one literal segment; an empty reason + * yields no segments. + */ +internal fun verdictReasonSegments( + reason: String, + references: List, +): List { + if (reason.isEmpty()) return emptyList() + if (references.isEmpty()) return listOf(VerdictReasonSegment(reason)) + val tokens = ArrayList>() + references.forEach { artifact -> + tokens += artifact.name to artifact + val base = artifactBaseName(artifact.name) + if (base.isNotEmpty() && base != artifact.name) tokens += base to artifact + } + // Longest token first (stable), so a full name wins over its basename at the + // same index; a bare basename still resolves to the artifact named exactly so. + tokens.sortByDescending { it.first.length } + val segments = ArrayList() + val literal = StringBuilder() + var index = 0 + while (index < reason.length) { + val match = tokens.firstOrNull { reason.startsWith(it.first, index) } + if (match == null) { + literal.append(reason[index]) + index++ + } else { + if (literal.isNotEmpty()) { + segments += VerdictReasonSegment(literal.toString()) + literal.clear() + } + segments += VerdictReasonSegment(match.first, match.second) + index += match.first.length + } + } + if (literal.isNotEmpty()) segments += VerdictReasonSegment(literal.toString()) + return segments +} + +/** The last path segment of a recorded artifact name (`shots/x.png` -> `x.png`). */ +private fun artifactBaseName(name: String): String = + name.substringAfterLast('/').substringAfterLast('\\') + +/** + * The stage pane's Verdict block: the completed visit's chosen option as a badge + * in the outcome's existing colour, the concise reason as ordinary body text (never + * a monospace JSON dump, and it wraps rather than clipping), and the recorded + * artifacts the reason names as inline, tappable links plus the same references as + * compact chips. An image or video reference opens the shared full-screen viewer; + * anything else goes through the existing external-open action, so the block reuses + * the gallery's behaviour instead of re-deriving it. + * + * It renders nothing at all when the server reported no verdict ([verdict] null) or + * the verdict carries neither an option nor a reason, so there is never an empty + * heading or placeholder. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun StageVerdictBlock( + verdict: StageVerdict?, + outcome: String, + status: String, + artifacts: List, + configuredServerUrl: String, + fetchArtifactBytes: suspend (String) -> ByteArray?, + modifier: Modifier = Modifier, +) { + if (verdict == null) return + val option = verdict.option + val reason = verdict.reason + if (option.isBlank() && reason.isBlank()) return + + val text = pipelinesText() + val context = LocalContext.current + val scheme = MaterialTheme.colorScheme + val linkColor = scheme.primary + val colors = remember(scheme) { graphColors(scheme) } + val tint = outcomeColor(outcome.ifBlank { status }, colors) + val references = remember(verdict, artifacts) { referencedVerdictArtifacts(verdict, artifacts) } + val segments = remember(reason, references) { verdictReasonSegments(reason, references) } + var viewerArtifact by remember { mutableStateOf(null) } + + // The one tap behaviour the inline links and the chips share: media opens the + // viewer, everything else the existing external-open action. + val open: (StageArtifact) -> Unit = { artifact -> + val resolved = resolvedArtifactUrl(artifact, configuredServerUrl) + val media = artifactKind(artifact.contentType, artifact.name).let { + it == ArtifactKind.Image || it == ArtifactKind.Video + } + if (resolved != null && media) viewerArtifact = artifact else openArtifact(context, resolved) + } + + Surface( + modifier = modifier.fillMaxWidth(), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = MaterialTheme.shapes.medium, + ) { + Column( + modifier = Modifier.padding(SPACING_M), + verticalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + FlowRow( + horizontalArrangement = Arrangement.spacedBy(SPACING_S), + verticalArrangement = Arrangement.spacedBy(SPACING_XS), + ) { + Text("Verdict", style = text.sectionHeader) + if (option.isNotBlank()) { + ColoredChip( + label = option, + color = tint, + icon = runStateIcon(runStateOf(outcome.ifBlank { status })), + ) + } + } + if (reason.isNotBlank()) { + // Rebuilt only when the segments, link colour or configured server + // change, so the tap targets never capture a stale server. + val annotated = remember(segments, linkColor, configuredServerUrl) { + buildAnnotatedString { + segments.forEach { segment -> + val artifact = segment.artifact + if (artifact == null) { + append(segment.text) + } else { + withLink( + LinkAnnotation.Clickable( + tag = "artifact:${artifact.url}", + styles = TextLinkStyles( + style = SpanStyle( + color = linkColor, + textDecoration = TextDecoration.Underline, + ), + ), + linkInteractionListener = { open(artifact) }, + ), + ) { append(segment.text) } + } + } + } + } + Text( + text = annotated, + style = text.body, + modifier = Modifier.fillMaxWidth(), + ) + } + if (references.isNotEmpty()) { + FlowRow( + horizontalArrangement = Arrangement.spacedBy(SPACING_S), + verticalArrangement = Arrangement.spacedBy(SPACING_XS), + ) { + references.forEach { artifact -> + VerdictArtifactChip(artifact = artifact, onClick = { open(artifact) }) + } + } + } + } + } + + val viewer = viewerArtifact + val viewerUrl = viewer?.let { resolvedArtifactUrl(it, configuredServerUrl) } + if (viewer != null && viewerUrl != null) { + ArtifactViewer( + url = viewerUrl, + name = viewer.name, + fetchBytes = fetchArtifactBytes, + onDismiss = { viewerArtifact = null }, + video = artifactKind(viewer.contentType, viewer.name) == ArtifactKind.Video, + ) + } +} + +/** A compact, tappable chip naming one referenced artifact, with its type glyph. */ +@Composable +private fun VerdictArtifactChip(artifact: StageArtifact, onClick: () -> Unit) { + val text = pipelinesText() + val kind = remember(artifact.contentType, artifact.name) { + artifactKind(artifact.contentType, artifact.name) + } + Surface( + shape = RoundedCornerShape(50), + color = MaterialTheme.colorScheme.surfaceContainerHighest, + modifier = Modifier.clickable(onClick = onClick), + ) { + Row( + modifier = Modifier.padding(horizontal = SPACING_S, vertical = SPACING_XS), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_XS), + ) { + Icon( + imageVector = artifactIcon(kind), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(ICON_STATUS_DP), + ) + Text( + text = artifact.name, + style = text.label, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } +} 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 cce06fd4..a0a6ea8e 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 @@ -137,6 +137,48 @@ class ProtocolModelTest { assertEquals(0, without.artifactsTruncated) } + @Test + fun runStepVerdictParsesWithItsReasonSourceAndReferencedArtifacts() { + val json = """ + { + "type": "run", + "run_detail": { + "id": 167, + "steps": [ + { + "sequence": 1, + "stage": "ui_reviewer", + "status": "succeeded", + "outcome": "approved", + "target": "#success", + "verdict": { + "option": "approved → success", + "reason": "Layout matches; see review.png", + "reason_source": "model", + "artifacts": ["review.png"] + } + }, + {"sequence": 2, "stage": "implementer", "status": "running", "outcome": "", "target": ""} + ] + } + } + """.trimIndent() + val run = PipelinesJson.decodeFromString(Message.serializer(), json).runDetail!! + val verdict = run.steps.first().verdict!! + assertEquals("approved → success", verdict.option) + assertEquals("Layout matches; see review.png", verdict.reason) + assertEquals("model", verdict.reasonSource) + assertEquals(listOf("review.png"), verdict.artifacts) + // A running step with no outcome/target carries no verdict, so the pane + // shows no block; a verdict with no artifacts defaults to an empty list. + assertNull(run.steps[1].verdict) + val noArtifacts = PipelinesJson.decodeFromString( + Message.serializer(), + """{"type":"run","run_detail":{"id":1,"steps":[{"sequence":1,"stage":"a","verdict":{"option":"done → success"}}]}}""", + ).runDetail!!.steps.single().verdict!! + assertEquals(emptyList(), noArtifacts.artifacts) + } + @Test fun pipelineDetailPopulatesInheritedAndWireNameFields() { val json = """ diff --git a/android/app/src/test/java/net/awan/pipelines/ui/graph/StageVerdictTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/graph/StageVerdictTest.kt new file mode 100644 index 00000000..479b42db --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/graph/StageVerdictTest.kt @@ -0,0 +1,99 @@ +package net.awan.pipelines.ui.graph + +import net.awan.pipelines.data.protocol.StageArtifact +import net.awan.pipelines.data.protocol.StageVerdict +import org.junit.Assert.assertEquals +import org.junit.Test + +class StageVerdictTest { + + private fun artifact(name: String, contentType: String = "image/png") = StageArtifact( + name = name, + sizeBytes = 1, + contentType = contentType, + url = "/artifacts/167/1/$name", + ) + + @Test + fun segmentsSplitTheReasonAroundEveryReferencedName() { + val png = artifact("review.png") + val txt = artifact("report.txt", contentType = "text/plain") + assertEquals( + listOf( + VerdictReasonSegment("Approved: "), + VerdictReasonSegment("review.png", png), + VerdictReasonSegment(" shows the fix; "), + VerdictReasonSegment("report.txt", txt), + VerdictReasonSegment(" lists the checks."), + ), + verdictReasonSegments( + "Approved: review.png shows the fix; report.txt lists the checks.", + listOf(png, txt), + ), + ) + } + + @Test + fun segmentsMatchABasenameForASlashedPath() { + val nested = artifact("shots/wide.png") + assertEquals( + listOf( + VerdictReasonSegment("See "), + VerdictReasonSegment("wide.png", nested), + VerdictReasonSegment(" for the wide layout."), + ), + verdictReasonSegments("See wide.png for the wide layout.", listOf(nested)), + ) + } + + @Test + fun aLongerNameWinsOverItsBasenameAtTheSameIndex() { + val bare = artifact("wide.png") + val nested = artifact("shots/wide.png") + // The full slashed path matches whole, not just its basename, so the + // reference resolves to the artifact actually named. + assertEquals( + listOf( + VerdictReasonSegment("shots/wide.png", nested), + VerdictReasonSegment(" is the shot"), + ), + verdictReasonSegments("shots/wide.png is the shot", listOf(bare, nested)), + ) + // A bare basename still resolves to the artifact named exactly so. + assertEquals( + listOf( + VerdictReasonSegment("wide.png", bare), + VerdictReasonSegment(" was captured"), + ), + verdictReasonSegments("wide.png was captured", listOf(bare, nested)), + ) + } + + @Test + fun aReasonWithoutReferencesIsOneLiteralSegment() { + assertEquals( + listOf(VerdictReasonSegment("nothing referenced here")), + verdictReasonSegments("nothing referenced here", listOf(artifact("x.png"))), + ) + assertEquals( + listOf(VerdictReasonSegment("no recorded artifact is named")), + verdictReasonSegments("no recorded artifact is named", emptyList()), + ) + assertEquals(emptyList(), verdictReasonSegments("", listOf(artifact("x.png")))) + } + + @Test + fun referencedArtifactsResolveNamesToRecordedFilesInRecordedOrder() { + val a = artifact("a.png") + val b = artifact("b.png", contentType = "text/plain") + val verdict = StageVerdict( + option = "approved → success", + reason = "b.png then a.png", + artifacts = listOf("b.png", "a.png", "invented.png"), + ) + // Recorded order, the invented name dropped, only real recorded files. + assertEquals(listOf(a, b), referencedVerdictArtifacts(verdict, listOf(a, b))) + assertEquals(emptyList(), referencedVerdictArtifacts(null, listOf(a))) + assertEquals(emptyList(), referencedVerdictArtifacts(StageVerdict(), listOf(a))) + } +} From b083cbad34a23f14b576d7c3b1158abf294662b7 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 19:50:19 +0100 Subject: [PATCH 5/5] android: drop the pipelines list inline search, add a filter-menu name facet The pipelines list carried its own "Search pipelines" field while the app also has the omni search, so the list offered a second, narrower way to do the same job. Remove that field and move name narrowing into the list's filter control, keeping "filters narrow one list" separate from "search finds across the system". - PipelineListScreen no longer owns a `query` state or draws the OutlinedTextField; the list is now the first child under the app bar, so the reclaimed space comes from layout with no compensating spacer or new dp value. - PipelineFilters gains a free-text `name` facet beside presence/lastRunStatuses, applied by filterPipelines through the new pure pipelineMatchesName (case-insensitive contains, blank means any). It needs no run history, so it applies as soon as pipelines load while the run facets still wait for runsKnown; activeCount and isActive include it, and hasRunFacets gates just the run facets. - PipelineFilterControl opens with a Name section holding a single-line PipelineNameFilter labelled "Pipeline name contains"; the shared Clear filters resets it with the run facets and the active-count badge counts it. - SettingsRepository/AppViewModel persist the name under pipeline_filter_name. - Empty-state messages reflect the name-only miss. - ListFilterTest covers the new name narrowing (+4 cases) and storage parsing. - android/README.md documents the change and the build/APK evidence. The runs list never had an inline search field, so nothing was removed there. --- android/README.md | 50 ++++++++++++ .../awan/pipelines/data/SettingsRepository.kt | 9 +++ .../net/awan/pipelines/ui/AppViewModel.kt | 3 + .../awan/pipelines/ui/screens/ListFilter.kt | 39 +++++++--- .../ui/screens/PipelineListScreen.kt | 74 ++++++++++-------- .../pipelines/ui/screens/ListFilterTest.kt | 78 ++++++++++++++++++- 6 files changed, 205 insertions(+), 48 deletions(-) diff --git a/android/README.md b/android/README.md index 0119fda0..7935b161 100644 --- a/android/README.md +++ b/android/README.md @@ -3776,3 +3776,53 @@ verdict layout is exercised by the unit tests and the compile only. No server th actually sends `verdict` was available to the implementer, so the block's live rendering against real data is deferred to visual review. +## One search: the pipelines list drops its inline field (16 Oct 2026) + +The pipelines list carried its own "Search pipelines" text field while the app +also has the omni search (the destination pill's Search entry point), so the list +offered a second, narrower way to do the same job. The inline field is gone and +name narrowing moved into the list's filter control, keeping "filters narrow one +list" separate from "search finds things across the system". + +- **One field removed.** `PipelineListScreen` no longer owns a `query` state or + draws the `OutlinedTextField`; the list is now the first thing under the app + bar, so no spacer stands in for the field that used to sit there. +- **Name is a filter.** `PipelineFilters` gained a free-text `name` facet beside + `presence`/`lastRunStatuses`, applied by `filterPipelines` through the new + `pipelineMatchesName` (case-insensitive `contains`, blank means any). Unlike the + run facets it needs no run history, so it narrows as soon as the pipelines load + while the run facets still wait for `runsKnown`. +- **In the menu.** `PipelineFilterControl` opens with a `Name` section holding a + single-line `PipelineNameFilter` (label "Pipeline name contains") that keeps the + menu open while typing; the shared Clear filters resets it with the run facets + and the active-count badge counts it. +- **Persisted.** `SettingsRepository`/`AppViewModel` store the name under + `pipeline_filter_name` like the other facets, so a restart remembers it. +- **Runs list unchanged.** The runs list never had an inline search field, so + nothing was removed there. +- **Geometry.** No new `dp`/`sp` literal and no percentage: the field reuses + `SPACING_M`/`SPACING_S` and fills the filter menu's own width, and the reclaimed + vertical space comes from the removed field's layout, not a replacement + constant. + +Evidence (macOS, JDK 17 from Homebrew `openjdk@17`, Gradle 8.11.1 from the wrapper +cache, `ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--no-daemon --offline`): + +- `:app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the 35 result XMLs aggregate to + **312 tests, 0 failures, 0 errors, 0 skipped**. `ListFilterTest` now has 20 cases + (+4: name substring/blank, name before the run history, name AND the run facets, + active count/`hasRunFacets`; `pipelineFiltersFromStorageParsesAndFallsBack` now + covers the name). +- `:app:assembleDebug` → `app-debug.apk` **18,164,618 bytes**, sha256 + `375be755d03d17c7721fe5b4ea23f637c928fd48acc300b4aec9f3d3cf2d4e50`. +- **APK publish.** `app-debug.apk` copied to + `~/.local/share/pipelines/data/artifacts/171/1/pipelines-debug-wip-e7c4b8f.apk` + (`e7c4b8f` = short `HEAD`); `shasum -a 256` matched. The LAN URL + `http://10.0.0.249:8080/artifacts/171/1/pipelines-debug-wip-e7c4b8f.apk` returned + `HTTP 200`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18164618`. + +Not verified in this pass: device captures (the visual review owns the device, per +the brief's device policy), so the filter-menu name field's on-screen layout is +exercised by the compile and the pure filter tests only. + diff --git a/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt index 230761d9..8f4a8c7b 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt @@ -49,6 +49,9 @@ class SettingsRepository(context: Context) { MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_RUN_STATUSES, "").orEmpty()) val pipelineFilterRunStatuses: StateFlow = _pipelineFilterRunStatuses.asStateFlow() + private val _pipelineFilterName = MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_NAME, "").orEmpty()) + val pipelineFilterName: StateFlow = _pipelineFilterName.asStateFlow() + fun setServerUrl(value: String) { val trimmed = value.trim() _serverUrl.value = trimmed @@ -96,6 +99,11 @@ class SettingsRepository(context: Context) { prefs.edit().putString(KEY_PIPELINE_FILTER_RUN_STATUSES, value).apply() } + fun setPipelineFilterName(value: String) { + _pipelineFilterName.value = value + prefs.edit().putString(KEY_PIPELINE_FILTER_NAME, value).apply() + } + /** True only when the user has explicitly supplied both required values. */ fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank() @@ -109,5 +117,6 @@ class SettingsRepository(context: Context) { const val KEY_RUN_FILTER_TIME_RANGE = "run_filter_time_range" const val KEY_PIPELINE_FILTER_PRESENCE = "pipeline_filter_presence" const val KEY_PIPELINE_FILTER_RUN_STATUSES = "pipeline_filter_run_statuses" + const val KEY_PIPELINE_FILTER_NAME = "pipeline_filter_name" } } 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 0bd11535..f5079e44 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 @@ -62,6 +62,7 @@ class AppViewModel( val runFilterTimeRange: StateFlow = settings.runFilterTimeRange val pipelineFilterPresence: StateFlow = settings.pipelineFilterPresence val pipelineFilterRunStatuses: StateFlow = settings.pipelineFilterRunStatuses + val pipelineFilterName: StateFlow = settings.pipelineFilterName private val _serverUrlDraft = MutableStateFlow(settings.serverUrl.value) val serverUrlDraft: StateFlow = _serverUrlDraft.asStateFlow() @@ -192,6 +193,8 @@ class AppViewModel( fun setPipelineFilterRunStatuses(value: String) = settings.setPipelineFilterRunStatuses(value) + fun setPipelineFilterName(value: String) = settings.setPipelineFilterName(value) + private fun awaitConnected() { viewModelScope.launch { val connected = withTimeoutOrNull(CONNECT_TIMEOUT_MILLIS) { diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/ListFilter.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/ListFilter.kt index 29924d7b..8b3d6ddc 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/ListFilter.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/ListFilter.kt @@ -108,27 +108,37 @@ data class RunFilters( } /** - * The pipelines-list run filters: whether a pipeline has any recorded run and - * the status of its most recent one. The name search stays a separate control - * (it narrows by text, not by run facts); these two are persisted per list. + * The pipelines-list filters: a case-insensitive name narrowing plus whether a + * pipeline has any recorded run and the status of its most recent one. Name is + * free text (any stored value is a legitimate filter), so it is the one facet not + * resolved against a closed vocabulary; like the run facets it is persisted per + * list. Unlike them, the name narrowing needs no run history, so it applies as + * soon as the pipelines load (see [filterPipelines]). */ data class PipelineFilters( val presence: RunPresence = RunPresence.Default, val lastRunStatuses: Set = emptySet(), + val name: String = "", ) { val activeCount: Int get() = (if (presence != RunPresence.Default) 1 else 0) + - (if (lastRunStatuses.isNotEmpty()) 1 else 0) + (if (lastRunStatuses.isNotEmpty()) 1 else 0) + + (if (name.isNotBlank()) 1 else 0) val isActive: Boolean get() = activeCount > 0 + /** Whether a run-history facet is set; only those depend on the run history. */ + val hasRunFacets: Boolean + get() = presence != RunPresence.Default || lastRunStatuses.isNotEmpty() + companion object { val Default = PipelineFilters() - fun fromStorage(presence: String?, lastRunStatuses: String?): PipelineFilters = + fun fromStorage(presence: String?, lastRunStatuses: String?, name: String?): PipelineFilters = PipelineFilters( presence = RunPresence.fromStorage(presence), lastRunStatuses = decodeRunStates(lastRunStatuses), + name = name.orEmpty(), ) } } @@ -208,10 +218,16 @@ internal fun pipelineMatchesFilters(filters: PipelineFilters, latestRun: RunSumm pipelineMatchesPresence(filters.presence, latestRun != null) && pipelineMatchesLastRunStatus(latestRun, filters.lastRunStatuses) +/** True when [name] is blank, or when [pipelineName] contains it, ignoring case. */ +internal fun pipelineMatchesName(name: String, pipelineName: String): Boolean = + name.isBlank() || pipelineName.contains(name, ignoreCase = true) + /** - * Narrows [pipelines] by [filters]. Both facets depend on the run history, so - * while that history is still unknown (`runsKnown == false`) the list is left - * unfiltered rather than briefly hiding every pipeline. + * Narrows [pipelines] by [filters]: the name narrowing and both run facets combined + * with AND. The name facet never depends on the run history, so it applies + * immediately; the run facets do, so while that history is still unknown + * (`runsKnown == false`) they are skipped rather than briefly hiding every + * pipeline. */ internal fun filterPipelines( pipelines: List, @@ -219,8 +235,11 @@ internal fun filterPipelines( latestRuns: Map, runsKnown: Boolean = true, ): List { - if (!filters.isActive || !runsKnown) return pipelines - return pipelines.filter { pipelineMatchesFilters(filters, latestRuns[it.id]) } + if (!filters.isActive) return pipelines + return pipelines.filter { pipeline -> + pipelineMatchesName(filters.name, pipeline.name) && + (!filters.hasRunFacets || !runsKnown || pipelineMatchesFilters(filters, latestRuns[pipeline.id])) + } } /** One selectable pipeline in the run filter, named from its runs. */ diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt index 287204aa..5fa107c6 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt @@ -14,7 +14,6 @@ import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountTree import androidx.compose.material.icons.filled.Refresh -import androidx.compose.material.icons.filled.Search import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon @@ -27,9 +26,7 @@ import androidx.compose.material3.TopAppBar 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.text.style.TextOverflow @@ -54,6 +51,7 @@ import net.awan.pipelines.ui.components.animateListItem import net.awan.pipelines.ui.components.listLoadPhase import net.awan.pipelines.ui.components.paneSafeArea import net.awan.pipelines.ui.theme.SPACING_L +import net.awan.pipelines.ui.theme.SPACING_M import net.awan.pipelines.ui.theme.SPACING_S import net.awan.pipelines.ui.theme.pipelinesText @@ -72,8 +70,8 @@ fun PipelineListScreen( val sort = PipelineSort.fromStorage(sortKey) val presenceKey by vm.pipelineFilterPresence.collectAsStateWithLifecycle() val runStatusKey by vm.pipelineFilterRunStatuses.collectAsStateWithLifecycle() - val filters = PipelineFilters.fromStorage(presenceKey, runStatusKey) - var query by remember { mutableStateOf("") } + val nameKey by vm.pipelineFilterName.collectAsStateWithLifecycle() + val filters = PipelineFilters.fromStorage(presenceKey, runStatusKey, nameKey) // The last-run line joins list_runs onto the pipelines client-side; runs are // fetched here too so a pipeline list opened first still shows its history. @@ -99,11 +97,11 @@ fun PipelineListScreen( val onClearFilters: () -> Unit = { vm.setPipelineFilterPresence("") vm.setPipelineFilterRunStatuses("") - query = "" + vm.setPipelineFilterName("") } - // A covered pane shows its compact identity only; the search field and list - // must never be drawn squeezed into the peek strip. + // A covered pane shows its compact identity only; the list must never be + // drawn squeezed into the peek strip. if (covered) { val count = state.data?.size ?: 0 PaneIdentity( @@ -124,6 +122,7 @@ fun PipelineListScreen( actions = { PipelineFilterControl( filters = filters, + onName = { vm.setPipelineFilterName(it) }, onPresence = { vm.setPipelineFilterPresence(it.storageKey) }, onRunStatuses = { vm.setPipelineFilterRunStatuses(encodeRunStates(it)) }, onClear = onClearFilters, @@ -149,25 +148,10 @@ fun PipelineListScreen( }, ) { padding -> Column(Modifier.fillMaxSize().padding(padding)) { - OutlinedTextField( - value = query, - onValueChange = { query = it }, - label = { Text("Search pipelines") }, - leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) }, - singleLine = true, - modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_S), - ) val all = state.data ?: emptyList() - val items = remember(all, query, sort, latestRuns, filters, runsKnown) { - filterPipelines( - sortPipelines(all, sort, latestRuns), - filters, - latestRuns, - runsKnown, - ).filter { it.name.contains(query, ignoreCase = true) } + val items = remember(all, sort, latestRuns, filters, runsKnown) { + filterPipelines(sortPipelines(all, sort, latestRuns), filters, latestRuns, runsKnown) } - val queryActive = query.isNotBlank() - val filtersActive = filters.isActive && runsKnown StateCrossfade( phase = listLoadPhase( loading = state.loading, @@ -175,13 +159,11 @@ fun PipelineListScreen( hasData = state.data != null, emptyMessage = if (items.isEmpty()) { if (all.isEmpty()) { - // Nothing exists: neither the search nor the filters can - // reveal a pipeline, so there is no clear action. + // Nothing exists: no filter can reveal a pipeline, so + // there is no clear action. "No pipelines are defined on this server." - } else if (queryActive && filtersActive) { - "No pipelines match the current search and filters." - } else if (queryActive) { - "No pipelines match \"$query\"." + } else if (filters.name.isNotBlank() && !filters.hasRunFacets) { + "No pipelines match \"${filters.name}\"." } else { "No pipelines match the current filters." } @@ -228,13 +210,16 @@ fun PipelineListScreen( } /** - * The pipelines-list run filter control: presence (has/no runs) and the - * most-recent run's status (multi-select), with the shared active-count badge - * and one Clear filters action. The name search stays a separate field. + * The pipelines-list filter control: a case-insensitive name narrowing plus the + * run facets (has/no runs) and the most-recent run's status (multi-select), with + * the shared active-count badge and one Clear filters action. The name is a + * filter, not a search: it narrows only this list, while the omni search is the + * one affordance that finds pipelines, runs and artifacts across the system. */ @Composable private fun PipelineFilterControl( filters: PipelineFilters, + onName: (String) -> Unit, onPresence: (RunPresence) -> Unit, onRunStatuses: (Set) -> Unit, onClear: () -> Unit, @@ -245,6 +230,9 @@ private fun PipelineFilterControl( resetLabel = "Clear filters", onReset = onClear, ) { dismiss -> + FilterSectionHeader("Name") + PipelineNameFilter(filters.name, onName) + HorizontalDivider() FilterSectionHeader("Runs") RunPresence.entries.forEach { presence -> FilterCheckItem(presence.label, filters.presence == presence) { @@ -262,6 +250,24 @@ private fun PipelineFilterControl( } } +/** + * The name narrowing inside the pipelines filter menu: free text that keeps the + * menu open while typing so the list can be watched narrowing behind it. It fills + * the menu's own width, so it needs no width of its own. + */ +@Composable +private fun PipelineNameFilter(name: String, onName: (String) -> Unit) { + OutlinedTextField( + value = name, + onValueChange = onName, + label = { Text("Pipeline name contains") }, + singleLine = true, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = SPACING_M, vertical = SPACING_S), + ) +} + /** * One pipeline as a row of the shared real list: a leading workflow glyph, the * name as the title, the id/version/stage-count as the secondary line and the diff --git a/android/app/src/test/java/net/awan/pipelines/ui/screens/ListFilterTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/screens/ListFilterTest.kt index d07e6d80..559fd685 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/screens/ListFilterTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/screens/ListFilterTest.kt @@ -56,11 +56,18 @@ class ListFilterTest { @Test fun pipelineFiltersFromStorageParsesAndFallsBack() { assertEquals( - PipelineFilters(RunPresence.NoRuns, setOf(RunState.Failed)), - PipelineFilters.fromStorage("no_runs", "failed"), + PipelineFilters(RunPresence.NoRuns, setOf(RunState.Failed), "deploy"), + PipelineFilters.fromStorage("no_runs", "failed", "deploy"), + ) + // A blank or absent name is no narrowing. + assertEquals(PipelineFilters.Default, PipelineFilters.fromStorage(null, null, null)) + assertEquals(PipelineFilters.Default, PipelineFilters.fromStorage("", "", "")) + // The name is free text, so any stored value is a legitimate filter and is + // kept as-is; only the closed-vocabulary run facets fall back to a default. + assertEquals( + PipelineFilters(name = "garbage"), + PipelineFilters.fromStorage("garbage", "garbage", "garbage"), ) - assertEquals(PipelineFilters.Default, PipelineFilters.fromStorage(null, null)) - assertEquals(PipelineFilters.Default, PipelineFilters.fromStorage("garbage", "garbage")) } @Test @@ -203,6 +210,69 @@ class ListFilterTest { assertEquals(listOf(2L), filterPipelines(pipelines, filters, latest).map { it.id }) } + @Test + fun nameNarrowsByCaseInsensitiveSubstringAndBlankNarrowsNothing() { + val pipelines = listOf( + pipeline(1, "Deploy API"), + pipeline(2, "redeploy web"), + pipeline(3, "release"), + ) + assertEquals( + listOf(1L, 2L), + filterPipelines(pipelines, PipelineFilters(name = "deploy"), emptyMap()).map { it.id }, + ) + assertEquals( + listOf(1L), + filterPipelines(pipelines, PipelineFilters(name = "Deploy API"), emptyMap()).map { it.id }, + ) + // A blank name is no narrowing. + assertEquals(pipelines, filterPipelines(pipelines, PipelineFilters(name = " "), emptyMap())) + } + + @Test + fun nameAppliesBeforeTheRunHistoryIsKnownWhileRunFacetsStillWait() { + val pipelines = listOf(pipeline(1, "alpha"), pipeline(2, "beta")) + // The name facet needs no run history, so it narrows at once. + assertEquals( + listOf(2L), + filterPipelines(pipelines, PipelineFilters(name = "bet"), emptyMap(), runsKnown = false).map { it.id }, + ) + // A run facet still waits for the history, combined with the name. + assertEquals( + listOf(1L), + filterPipelines( + pipelines, + PipelineFilters(presence = RunPresence.NoRuns, name = "al"), + emptyMap(), + runsKnown = false, + ).map { it.id }, + ) + } + + @Test + fun nameAndRunFacetsCombineWithAnd() { + val filters = PipelineFilters(RunPresence.HasRuns, setOf(RunState.Failed), "web") + val latest = mapOf( + 1L to run(1, pipelineId = 1, status = "failed"), + 2L to run(2, pipelineId = 2, status = "failed"), + 3L to run(3, pipelineId = 3, status = "succeeded"), + ) + val pipelines = listOf(pipeline(1, "web"), pipeline(2, "api"), pipeline(3, "web")) + // 2 fails the name; 3 fails the last-run status. + assertEquals(listOf(1L), filterPipelines(pipelines, filters, latest).map { it.id }) + } + + @Test + fun activeCountCountsTheNameAndRunFacetsButNotABlankName() { + assertEquals(0, PipelineFilters().activeCount) + assertEquals(1, PipelineFilters(name = "x").activeCount) + assertEquals(2, PipelineFilters(RunPresence.NoRuns, name = "x").activeCount) + assertEquals(0, PipelineFilters(name = " ").activeCount) + // Only the run-history facets need the history loaded. + assertFalse(PipelineFilters(name = "x").hasRunFacets) + assertTrue(PipelineFilters(RunPresence.NoRuns).hasRunFacets) + } + @Test fun pipelineFiltersLeaveTheListUnfilteredUntilRunsAreKnown() { val filters = PipelineFilters(presence = RunPresence.NoRuns)