Remember sort options for the pipelines and runs lists

Add a per-list sort control to each top bar and persist the choice in
SharedPreferences so it survives restarts.

- ui/screens/ListSort.kt: PipelineSort and RunSort enums plus pure
  comparators with explicit tie-breaks, and sortPipelines/sortRuns.
  ServerOrder/NewestFirst remain the defaults; a still-executing or
  unparseable-timestamp run sorts last.
- ui/components/SortMenu.kt: the shared top-bar control, a distinct
  IconButton opening a Material 3 DropdownMenu of every option plus a
  divider and Reset, with the active choice checked.
- data/SettingsRepository.kt + ui/AppViewModel.kt: store the sort key
  per list as a StateFlow; fromStorage falls back to the default for a
  stale/unknown/blank value.
- ui/Format.kt: share parseInstant and durationSeconds so the printed
  duration and the sort key cannot disagree; PipelineLastRun.kt reuses
  the shared latest-run fold.
- PipelineListScreen.kt/RunHistoryScreen.kt wire the control and sort;
  groupRunsByDay preserves the comparator's order.
- ListSortTest.kt covers the comparators and storage fallback;
  RunGroupingTest.kt gains an explicit-order case.

Verified on this tree with :app:testDebugUnitTest (167 tests, 0
failures), assembleDebug, and emulator-5556 persistence, the sort
control, and Reset; captured in android/README.md.
This commit is contained in:
2026-10-16 04:57:53 +01:00
parent 3480461ffb
commit 1c925d72f7
11 changed files with 639 additions and 38 deletions
+123
View File
@@ -1435,3 +1435,126 @@ Verified on this tree (macOS, JDK 17 from Homebrew `openjdk@17`, Gradle 9.7.1,
same `b2255066…` as the local file. The same APK was installed on the emulator
and the pulled installed `base.apk` hashed to `b2255066…`, so the reviewed
source is what was actually rendered.
## Remembered sort options for the pipelines and runs lists (16 Oct 2026)
Both list top bars gained a sort control that opens the choices plus a Reset, and
the choice is remembered per list across restarts. `android/` only; nothing in
the Pipelines server, its Go source, the Docker/compose files or the installer was
touched, no dependency was added (the icons come from the already-declared
`material-icons-extended`), no run was started from the app, and the attached
Pixel 10 Pro Fold was never installed on or driven (every `adb`/emulator command
targeted `emulator-5556`).
- **Pure comparators.** `ui/screens/ListSort.kt` defines the `PipelineSort`
(`ServerOrder` default, `NameAsc`, `NameDesc`, `RecentRun`, `FewestStages`,
`MostStages`) and `RunSort` (`NewestFirst` default, `OldestFirst`,
`LongestDuration`, `ShortestDuration`, `PipelineName`, `Status`) enums plus one
pure `pipelineComparator`/`runComparator` per sort and the `sortPipelines`/
`sortRuns` helpers. Every comparator ends in an explicit tie-break, so equal
primary keys always order the same way; a blank/unparseable timestamp and a run
with no recorded duration (still executing) sort last regardless of direction
instead of crashing. `ServerOrder` is a zero comparator, so the stable sort
preserves the server's own order exactly. `RecentRun` uses the shared
per-pipeline latest-run fold (`latestRunByPipeline`, extracted from the
last-run badge join in `PipelineLastRun.kt`) rather than folding the history
twice.
- **Shared time helpers.** `ui/Format.kt` gained `parseInstant` (moved out of
`PipelineLastRun.kt`) and `durationSeconds`; the existing `formatDuration` now
delegates to `durationSeconds`, so the printed duration and the sort key can
never disagree.
- **Shared control.** `ui/components/SortMenu.kt` is the one top-bar control both
screens use: an `IconButton` (its own glyph and content description, so it
cannot collide with the adjacent Refresh action or a future search entry point)
opening a `DropdownMenu` of the options — the active one carries a leading
check glyph, not colour alone — then a divider and Reset. It has no geometry
literals and anchors correctly at both window widths. The glyph is
`Icons.AutoMirrored.Filled.Sort` (the RTL-aware form, so no `Icons.Default.Sort`
deprecation warning at build time and the arrow mirrors correctly).
- **Persistence.** `data/SettingsRepository.kt` stores each choice as its stable
storage key (`pipeline_sort`, `run_sort`) with a `StateFlow`, exactly like the
server URL/workspace; `AppViewModel` exposes them and their setters. The list
screens resolve the stored string with `PipelineSort.fromStorage`/
`RunSort.fromStorage`, which fall back to the default for a stale, unknown or
blank value (the repository stays unaware of the UI enums).
- **Grouping.** `groupRunsByDay` now takes the ordering comparator and preserves
the order it produces (the default is still newest first, so the default output
is unchanged); the run list groups by day in that order and sorts within a day
by the same comparator.
Verified on this tree (macOS, Homebrew JDK 25 (`openjdk@25`), Gradle 9.7.1,
`ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--offline`):
- `gradle --offline :app:testDebugUnitTest --rerun-tasks` → the 21 test-result XMLs
aggregate to **167 tests, 0 failures, 0 errors, 0 skipped** (the new
`ListSortTest` has 13 cases covering the storage fallback for both enums, server
order, case-insensitive name/stage sorts with their id/name tie-breaks,
recent-run no-run-last and run-id tie-breaks, newest/oldest with unparseable
timestamps last, duration longest/shortest with a still-executing run last and
equal-duration tie-break, pipeline-name/status sorts, and that equal keys order
identically whatever the input order; `RunGroupingTest` gained an explicit-order
case). `compileDebugKotlin` emits no warnings.
- `gradle --offline :app:assembleDebug --rerun-tasks --no-build-cache` (a full
rebuild, so the published binary is exactly this tree) succeeded →
`app-debug.apk` **17,879,721 bytes**, sha256
`cb68fbb13e469e81c15837ba95314a2ab40f1f29f4769e4a615bbc0ce4636a30`.
- On `emulator-5556` (`FoldB_API_36`, 2208x1840, density 420, dark mode) against
the live server `ws://10.0.2.2:8080/connect`, driven with `adb shell input` and
`uiautomator dump`; every capture below was written with
`android/scripts/capture_png.sh -s emulator-5556` (validated PNG, named display
id) into `…/artifacts/87/1/`. The live server's pipeline set churns while the
maintenance workflow runs, so the concrete names differ between captures, but
each ordering was read back from the accessibility tree:
- Wide (2208x1840 ≈ 841dp): tapping `Sort pipelines` opened the six options plus
`Reset` (`01_wide_pipelines_sort_open.png`); choosing `Name Z–A` reordered the
list to descending names and stored `pipeline_sort=name_desc`
(`02_wide_pipelines_name_za.png`). `Sort runs` opened the six run options plus
`Reset` (`03_wide_runs_sort_open.png`); `Oldest first` showed run 1 → 2 → 3 and
stored `run_sort=oldest_first` (`04_wide_runs_oldest_first.png`). The sort icon
and the adjacent `Refresh` stay separate actions at both widths (the icon's own
`Sort pipelines`/`Sort runs` content description sits left of `Refresh …`).
- **Persistence proof.** After setting pipelines `Name Z–A` and runs
`Oldest first`, `run-as net.awan.pipelines cat shared_prefs/pipelines_settings.xml`
showed `pipeline_sort=name_desc`, `run_sort=oldest_first`. `am force-stop
net.awan.pipelines` (verified `pidof` empty) then `am start` and a fresh
`uiautomator dump` showed the pipelines list still in descending-name order
(`05_wide_pipelines_name_za_after_relaunch.png`) and the runs list still oldest
first, run 1 → 2 → 3 (`06_wide_runs_oldest_first_after_relaunch.png`), with no
interaction.
- `Reset` on the pipelines menu restored the server order (id 1 → 5 → 11 → 6 →
4 → 9 → 3) and stored `pipeline_sort=server_order`; `Reset` on the runs menu
restored `run_sort=newest_first` and run 87 → 86 → 85 → 84 → 83 → 82
(`10_narrow_runs_reset_newest_first.png`).
- Narrow (`adb shell wm size 1080x2340` ≈ 411dp; `wm size reset` afterwards):
both `Sort pipelines` and `Sort runs` opened their menus
(`07_narrow_runs_sort_open.png`); `Status` ordered Canceled → Failed → Failed …
and stored `run_sort=status` (`08_narrow_runs_status_sort.png`); `Most recent
run` ordered the rows by recency 10h → 3d → 3d → 4d → 4d → 5d and put the
runless pipeline (`no runs recorded`) last, storing `pipeline_sort=recent_run`
(`09_narrow_pipelines_recent_run.png`).
- **Stale-key tolerance on device.** With `pipeline_sort` and `run_sort` set to
`garbage_key` in `shared_prefs/pipelines_settings.xml` (verified via `run-as …
cat`, then replaced by push + `run-as … cp`) and the app force-stopped and
relaunched, the pipelines list came back in the server's order (id 1 → 5 → 11 →
6 → 4 → 9 → 3, `11_narrow_pipelines_stale_key_falls_back_to_server_order.png`)
and the runs list in newest-first (run 87 → 86 → 85), with no crash.
- `adb -s emulator-5556 logcat -d | grep -c 'FATAL EXCEPTION'` and `… | grep -c
'E AndroidRuntime'` each returned 0; no run was started from the app.
- **APK publish.** `app-debug.apk` was copied to
`~/.local/share/pipelines/data/artifacts/87/1/pipelines-debug-wip-3480461.apk`
(`3480461` = `git rev-parse --short HEAD`); `shasum -a 256` matched. `curl -I
http://10.0.0.249:8080/artifacts/87/1/pipelines-debug-wip-3480461.apk` returned
`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 17879721`, and a streamed `GET | shasum -a 256` returned the
same `cb68fbb1…` as the local file. The deterministic full-rebuild APK was
installed on `emulator-5556` (`adb -s emulator-5556 install -r`) and the pulled
installed `base.apk` hashed to `cb68fbb1…`, so the reviewed source is what was
actually rendered. At 17.1 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: `:app:lintDebug` was not run (its only reported issues
are the two pre-existing `NewApi` errors for `android:windowLightNavigationBar`);
a real hardware fold to the cover display was not exercised (narrow was produced
with `wm size`); no before/after baseline build was captured, since the change is
additive and the default orders are asserted unchanged by the `ServerOrder`/
`NewestFirst` unit tests.
@@ -21,6 +21,15 @@ class SettingsRepository(context: Context) {
private val _workspace = MutableStateFlow(prefs.getString(KEY_WORKSPACE, "").orEmpty())
val workspace: StateFlow<String> = _workspace.asStateFlow()
// The chosen list orderings, stored as their stable storage keys. The value
// is resolved (with a default fallback for a stale/unknown key) by the list
// screens, so this repository stays unaware of the UI's sort enums.
private val _pipelineSort = MutableStateFlow(prefs.getString(KEY_PIPELINE_SORT, "").orEmpty())
val pipelineSort: StateFlow<String> = _pipelineSort.asStateFlow()
private val _runSort = MutableStateFlow(prefs.getString(KEY_RUN_SORT, "").orEmpty())
val runSort: StateFlow<String> = _runSort.asStateFlow()
fun setServerUrl(value: String) {
val trimmed = value.trim()
_serverUrl.value = trimmed
@@ -33,11 +42,23 @@ class SettingsRepository(context: Context) {
prefs.edit().putString(KEY_WORKSPACE, trimmed).apply()
}
fun setPipelineSort(value: String) {
_pipelineSort.value = value
prefs.edit().putString(KEY_PIPELINE_SORT, value).apply()
}
fun setRunSort(value: String) {
_runSort.value = value
prefs.edit().putString(KEY_RUN_SORT, value).apply()
}
/** True only when the user has explicitly supplied both required values. */
fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank()
private companion object {
const val KEY_SERVER_URL = "server_url"
const val KEY_WORKSPACE = "workspace"
const val KEY_PIPELINE_SORT = "pipeline_sort"
const val KEY_RUN_SORT = "run_sort"
}
}
@@ -48,6 +48,10 @@ class AppViewModel(
val configuredServerUrl: StateFlow<String> = settings.serverUrl
val configuredWorkspace: StateFlow<String> = settings.workspace
/** The stored pipeline/run sort keys; the list screens resolve them to a sort. */
val pipelineSort: StateFlow<String> = settings.pipelineSort
val runSort: StateFlow<String> = settings.runSort
private val _serverUrlDraft = MutableStateFlow(settings.serverUrl.value)
val serverUrlDraft: StateFlow<String> = _serverUrlDraft.asStateFlow()
@@ -153,6 +157,10 @@ class AppViewModel(
fun disconnect() = repository.disconnect()
fun setPipelineSort(storageKey: String) = settings.setPipelineSort(storageKey)
fun setRunSort(storageKey: String) = settings.setRunSort(storageKey)
private fun awaitConnected() {
viewModelScope.launch {
val connected = withTimeoutOrNull(CONNECT_TIMEOUT_MILLIS) {
@@ -12,15 +12,32 @@ import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.StageArtifact
import net.awan.pipelines.data.protocol.StageFileChanges
/** Human duration between two RFC3339 timestamps, or null when unavailable. */
fun formatDuration(start: String, end: String): String? {
if (start.isBlank() || end.isBlank()) return null
return runCatching {
val seconds = Duration.between(OffsetDateTime.parse(start), OffsetDateTime.parse(end)).seconds
if (seconds < 0) null else formatDuration(seconds)
}.getOrNull()
/**
* Parses an RFC3339 timestamp, or null when blank or unparseable. The single
* parser every time-reading the UI shares, so a bad timestamp is handled the
* same way everywhere.
*/
internal fun parseInstant(text: String): OffsetDateTime? {
if (text.isBlank()) return null
return runCatching { OffsetDateTime.parse(text) }.getOrNull()
}
/**
* Non-negative whole seconds between two RFC3339 timestamps, or null when either
* is blank/unparseable or the end precedes the start. The numeric counterpart of
* [formatDuration] (which delegates here), so a sort key and the printed
* duration can never disagree.
*/
internal fun durationSeconds(start: String, end: String): Long? {
val from = parseInstant(start) ?: return null
val to = parseInstant(end) ?: return null
return Duration.between(from, to).seconds.takeIf { it >= 0 }
}
/** Human duration between two RFC3339 timestamps, or null when unavailable. */
fun formatDuration(start: String, end: String): String? =
durationSeconds(start, end)?.let(::formatDuration)
/**
* Human duration for a whole number of seconds. The single formatting rule for
* every duration the UI shows (list meta, usage average, run summary, step
@@ -0,0 +1,70 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Box
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Sort
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
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.Modifier
/**
* The shared list-sort control: a top-bar icon that opens [options] plus a
* divider and a Reset entry. It is deliberately its own action with a distinct
* glyph and content description, so it cannot collide with the adjacent Refresh
* action or a future top-bar search entry point; a `DropdownMenu` anchors to the
* icon and works at both window widths (it is not width-dependent geometry).
*
* [selected] draws a leading check on its row, so the active choice is conveyed
* by a glyph as well as by text, never by colour alone.
*/
@Composable
fun <T> SortMenu(
options: List<T>,
selected: T,
label: (T) -> String,
contentDescription: String,
onSelect: (T) -> Unit,
onReset: () -> Unit,
modifier: Modifier = Modifier,
) {
var expanded by remember { mutableStateOf(false) }
Box(modifier) {
IconButton(onClick = { expanded = true }) {
Icon(Icons.AutoMirrored.Filled.Sort, contentDescription = contentDescription)
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
options.forEach { option ->
DropdownMenuItem(
text = { Text(label(option)) },
onClick = {
onSelect(option)
expanded = false
},
leadingIcon = {
if (option == selected) {
Icon(Icons.Default.Check, contentDescription = null)
}
},
)
}
HorizontalDivider()
DropdownMenuItem(
text = { Text("Reset") },
onClick = {
onReset()
expanded = false
},
)
}
}
}
@@ -0,0 +1,123 @@
package net.awan.pipelines.ui.screens
import java.time.OffsetDateTime
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.ui.durationSeconds
import net.awan.pipelines.ui.parseInstant
/**
* The pipeline-list orderings offered by the top-bar sort control. [storageKey]
* is the stable value persisted in SharedPreferences; [fromStorage] tolerates a
* stale, unknown or blank stored value by returning [Default] — the server's own
* order, which the default comparator preserves exactly.
*/
enum class PipelineSort(val label: String, val storageKey: String) {
ServerOrder("Server order", "server_order"),
NameAsc("Name A\u2013Z", "name_asc"),
NameDesc("Name Z\u2013A", "name_desc"),
RecentRun("Most recent run", "recent_run"),
FewestStages("Fewest stages", "fewest_stages"),
MostStages("Most stages", "most_stages");
companion object {
val Default = ServerOrder
fun fromStorage(value: String?): PipelineSort =
entries.firstOrNull { it.storageKey == value } ?: Default
}
}
/**
* The run-list orderings offered by the top-bar sort control. [storageKey] is
* persisted like [PipelineSort]'s; an unknown or stale value resolves to
* [Default] ("newest first").
*/
enum class RunSort(val label: String, val storageKey: String) {
NewestFirst("Newest first", "newest_first"),
OldestFirst("Oldest first", "oldest_first"),
LongestDuration("Longest duration", "longest_duration"),
ShortestDuration("Shortest duration", "shortest_duration"),
PipelineName("Pipeline name", "pipeline_name"),
Status("Status", "status");
companion object {
val Default = NewestFirst
fun fromStorage(value: String?): RunSort =
entries.firstOrNull { it.storageKey == value } ?: Default
}
}
/** The identity comparator used by "server order": a stable sort then keeps the input untouched. */
private val SERVER_ORDER = Comparator<PipelineSummary> { _, _ -> 0 }
/**
* The pure pipeline comparator for [sort]. Every case ends in an explicit
* tie-break (`id` is unique), so pipelines that compare equal on the primary key
* always order the same way rather than depending on the input order.
*
* [latestRuns] maps a pipeline id to that pipeline's most recent run
* (see [latestRunByPipeline]); only [PipelineSort.RecentRun] uses it but it is
* passed in once so the fold is never repeated per comparison.
*/
internal fun pipelineComparator(
sort: PipelineSort,
latestRuns: Map<Long, RunSummary> = emptyMap(),
): Comparator<PipelineSummary> = when (sort) {
PipelineSort.ServerOrder -> SERVER_ORDER
PipelineSort.NameAsc -> compareBy<PipelineSummary, String>(String.CASE_INSENSITIVE_ORDER) { it.name }
.thenBy { it.name }
.thenBy { it.id }
PipelineSort.NameDesc -> compareByDescending<PipelineSummary, String>(String.CASE_INSENSITIVE_ORDER) { it.name }
.thenBy { it.name }
.thenBy { it.id }
PipelineSort.RecentRun -> compareBy<PipelineSummary> { latestRuns[it.id] == null }
.thenByDescending { latestRuns[it.id]?.let { run -> parseInstant(run.createdAt) } ?: OffsetDateTime.MIN }
.thenByDescending { latestRuns[it.id]?.id ?: Long.MIN_VALUE }
.thenBy { it.id }
PipelineSort.FewestStages -> compareBy<PipelineSummary> { it.stages }
.thenBy<PipelineSummary, String>(String.CASE_INSENSITIVE_ORDER) { it.name }
.thenBy { it.id }
PipelineSort.MostStages -> compareByDescending<PipelineSummary> { it.stages }
.thenBy<PipelineSummary, String>(String.CASE_INSENSITIVE_ORDER) { it.name }
.thenBy { it.id }
}
/** Orders [pipelines] by [sort], folding the run history once for the recent-run key. */
internal fun sortPipelines(
pipelines: List<PipelineSummary>,
sort: PipelineSort,
latestRuns: Map<Long, RunSummary> = emptyMap(),
): List<PipelineSummary> = pipelines.sortedWith(pipelineComparator(sort, latestRuns))
/**
* The pure run comparator for [sort]. As with [pipelineComparator], every case
* ends in an explicit tie-break so equal keys always order the same way. A blank
* or unparseable timestamp, and a run with no recorded duration (still
* executing), sort last regardless of direction and never crash.
*/
internal fun runComparator(sort: RunSort): Comparator<RunSummary> = when (sort) {
RunSort.NewestFirst -> compareByDescending<RunSummary> { parseInstant(it.createdAt) ?: OffsetDateTime.MIN }
.thenByDescending { it.id }
RunSort.OldestFirst -> compareBy<RunSummary> { parseInstant(it.createdAt) ?: OffsetDateTime.MAX }
.thenBy { it.id }
RunSort.LongestDuration -> compareBy<RunSummary> { durationSeconds(it.createdAt, it.finishedAt) == null }
.thenByDescending { durationSeconds(it.createdAt, it.finishedAt) ?: Long.MIN_VALUE }
.thenByDescending { parseInstant(it.createdAt) ?: OffsetDateTime.MIN }
.thenByDescending { it.id }
RunSort.ShortestDuration -> compareBy<RunSummary> { durationSeconds(it.createdAt, it.finishedAt) == null }
.thenBy { durationSeconds(it.createdAt, it.finishedAt) ?: Long.MAX_VALUE }
.thenByDescending { parseInstant(it.createdAt) ?: OffsetDateTime.MIN }
.thenByDescending { it.id }
RunSort.PipelineName -> compareBy<RunSummary, String>(String.CASE_INSENSITIVE_ORDER) { it.name }
.thenByDescending { parseInstant(it.createdAt) ?: OffsetDateTime.MIN }
.thenByDescending { it.id }
RunSort.Status -> compareBy<RunSummary, String>(String.CASE_INSENSITIVE_ORDER) { it.status }
.thenByDescending { parseInstant(it.createdAt) ?: OffsetDateTime.MIN }
.thenByDescending { it.id }
}
/** Orders [runs] by [sort]. */
internal fun sortRuns(runs: List<RunSummary>, sort: RunSort): List<RunSummary> =
runs.sortedWith(runComparator(sort))
@@ -6,6 +6,7 @@ import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.parseInstant
/** Shown for a pipeline that appears in list_runs but has recorded no run. */
const val NO_RUNS_RECORDED = "no runs recorded"
@@ -45,22 +46,33 @@ internal fun PipelineRunBadge.metaLine(): String = buildList {
internal fun pipelineRunBadges(
runs: List<RunSummary>,
now: OffsetDateTime,
): Map<Long, PipelineRunBadge> {
): Map<Long, PipelineRunBadge> =
latestRunByPipeline(runs).mapValues { (_, run) -> runBadge(run, now) }
/**
* The most recent run of each pipeline, decided from the timestamps (the higher
* run id breaking an exact tie or a bad timestamp), independent of the input
* order. The one fold shared by the last-run badge join above and the "most
* recent run" pipeline sort, so both agree on which run is the latest.
*/
internal fun latestRunByPipeline(runs: List<RunSummary>): Map<Long, RunSummary> {
val latest = HashMap<Long, RunSummary>()
for (run in runs) {
val current = latest[run.pipelineId]
if (current == null || isMoreRecent(run, current)) latest[run.pipelineId] = run
}
return latest.mapValues { (_, run) ->
PipelineRunBadge(
runId = run.id,
state = runStateOf(run.status),
ranAgo = formatRanAgo(run.createdAt, now),
duration = formatDuration(run.createdAt, run.finishedAt),
)
}
return latest
}
/** The display facts one pipeline row shows for [run], anchored to [now]. */
internal fun runBadge(run: RunSummary, now: OffsetDateTime): PipelineRunBadge =
PipelineRunBadge(
runId = run.id,
state = runStateOf(run.status),
ranAgo = formatRanAgo(run.createdAt, now),
duration = formatDuration(run.createdAt, run.finishedAt),
)
/** Timestamps decide recency; the higher run id breaks an exact tie (or a bad timestamp). */
private fun isMoreRecent(candidate: RunSummary, current: RunSummary): Boolean {
val a = parseInstant(candidate.createdAt)
@@ -89,8 +101,3 @@ internal fun formatRanAgo(createdAt: String, now: OffsetDateTime): String? {
else -> "${seconds / 86_400}d ago"
}
}
private fun parseInstant(text: String): OffsetDateTime? {
if (text.isBlank()) return null
return runCatching { OffsetDateTime.parse(text) }.getOrNull()
}
@@ -41,6 +41,7 @@ import net.awan.pipelines.ui.components.ListRow
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.PaneIdentity
import net.awan.pipelines.ui.components.RunStatusChip
import net.awan.pipelines.ui.components.SortMenu
import net.awan.pipelines.ui.theme.pipelinesText
@OptIn(ExperimentalMaterial3Api::class)
@@ -54,6 +55,8 @@ fun PipelineListScreen(
) {
val state by vm.pipelines.collectAsStateWithLifecycle()
val runsState by vm.runs.collectAsStateWithLifecycle()
val sortKey by vm.pipelineSort.collectAsStateWithLifecycle()
val sort = PipelineSort.fromStorage(sortKey)
var query by remember { mutableStateOf("") }
// The last-run line joins list_runs onto the pipelines client-side; runs are
@@ -65,8 +68,13 @@ fun PipelineListScreen(
// "How long ago" is anchored once per composition, not recomputed per row.
val now = remember { OffsetDateTime.now() }
val badges = remember(runsState.data, now) {
runsState.data?.let { pipelineRunBadges(it.runs, now) }.orEmpty()
// The history is folded to one latest run per pipeline once, feeding both the
// row badges and the "most recent run" ordering rather than folding twice.
val latestRuns = remember(runsState.data) {
runsState.data?.let { latestRunByPipeline(it.runs) }.orEmpty()
}
val badges = remember(latestRuns, now) {
latestRuns.mapValues { (_, run) -> runBadge(run, now) }
}
// Until the run history has loaded, a missing badge is "not known yet", never
// the explicit "no runs recorded" claim.
@@ -90,6 +98,14 @@ fun PipelineListScreen(
TopAppBar(
title = { Text("Pipelines") },
actions = {
SortMenu(
options = PipelineSort.entries,
selected = sort,
label = { it.label },
contentDescription = "Sort pipelines",
onSelect = { vm.setPipelineSort(it.storageKey) },
onReset = { vm.setPipelineSort(PipelineSort.Default.storageKey) },
)
IconButton(
onClick = {
vm.refreshPipelines()
@@ -115,8 +131,10 @@ fun PipelineListScreen(
state.loading && state.data == null -> LoadingState("Loading pipelines…")
state.error != null && state.data == null -> ErrorState(state.error!!, onRetry = vm::refreshPipelines)
else -> {
val items = (state.data ?: emptyList())
.filter { it.name.contains(query, ignoreCase = true) }
val items = remember(state.data, query, sort, latestRuns) {
sortPipelines(state.data ?: emptyList(), sort, latestRuns)
.filter { it.name.contains(query, ignoreCase = true) }
}
if (items.isEmpty()) {
EmptyState(
if (query.isBlank()) "No pipelines are defined on this server."
@@ -51,6 +51,7 @@ import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.ListRow
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.PaneIdentity
import net.awan.pipelines.ui.components.SortMenu
import net.awan.pipelines.ui.components.runStateColor
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.formatDuration
@@ -69,6 +70,8 @@ fun RunHistoryScreen(
covered: Boolean = false,
) {
val state by vm.runs.collectAsStateWithLifecycle()
val sortKey by vm.runSort.collectAsStateWithLifecycle()
val sort = RunSort.fromStorage(sortKey)
LaunchedEffect(Unit) { vm.refreshRuns() }
// A covered pane shows its compact identity only; the usage block, sticky day
@@ -89,6 +92,14 @@ fun RunHistoryScreen(
TopAppBar(
title = { Text(if (filterPipelineId == null) "Runs" else "Runs for this pipeline") },
actions = {
SortMenu(
options = RunSort.entries,
selected = sort,
label = { it.label },
contentDescription = "Sort runs",
onSelect = { vm.setRunSort(it.storageKey) },
onReset = { vm.setRunSort(RunSort.Default.storageKey) },
)
IconButton(onClick = vm::refreshRuns) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh runs")
}
@@ -108,6 +119,7 @@ fun RunHistoryScreen(
runs = state.data?.runs.orEmpty(),
filterPipelineId = filterPipelineId,
selectedRunId = selectedRunId,
sort = sort,
error = state.error,
onOpenRun = onOpenRun,
modifier = Modifier.padding(padding),
@@ -123,20 +135,22 @@ private fun RunHistoryContent(
runs: List<RunSummary>,
filterPipelineId: Long?,
selectedRunId: Long?,
sort: RunSort,
error: String?,
onOpenRun: (Long) -> Unit,
modifier: Modifier = Modifier,
) {
// Day-grouping is derived once per data change (single pass, keyed on the
// stable source list), not per recomposition.
val groups = remember(runs, filterPipelineId) {
// Day-grouping is derived once per data/order change (single pass, keyed on
// the stable source list), not per recomposition. The chosen comparator orders
// the runs first; the groups then follow the order their first run appears in.
val groups = remember(runs, filterPipelineId, sort) {
val filtered = if (filterPipelineId == null) {
runs
} else {
runs.filter { it.pipelineId == filterPipelineId }
}
val zone = ZoneId.systemDefault()
groupRunsByDay(filtered, LocalDate.now(zone), zone)
groupRunsByDay(filtered, LocalDate.now(zone), zone, runComparator(sort))
}
LazyColumn(
@@ -343,17 +357,19 @@ private fun formatRunStart(createdAt: String): String? {
internal data class RunDayGroup(val label: String, val runs: List<RunSummary>)
/**
* Groups runs by calendar day in the device timezone, newest first, preserving
* the order within a day. A blank/unparseable timestamp gets a safe "Unknown
* date" group instead of crashing.
* Groups runs by calendar day in the device timezone, preserving the order
* [order] puts them in (the default is newest first, so the groups come out
* newest day first), and preserving the order within a day. A blank/unparseable
* timestamp gets a safe "Unknown date" group instead of crashing.
*/
internal fun groupRunsByDay(runs: List<RunSummary>, today: LocalDate, zone: ZoneId): List<RunDayGroup> {
val ordered = runs.sortedWith(
compareByDescending<RunSummary> { runDate(it.createdAt, zone) }
.thenByDescending { it.createdAt },
)
internal fun groupRunsByDay(
runs: List<RunSummary>,
today: LocalDate,
zone: ZoneId,
order: Comparator<RunSummary> = runComparator(RunSort.NewestFirst),
): List<RunDayGroup> {
val groups = LinkedHashMap<String, MutableList<RunSummary>>()
for (run in ordered) {
for (run in runs.sortedWith(order)) {
groups.getOrPut(dayLabel(run.createdAt, today, zone)) { mutableListOf() } += run
}
return groups.map { (label, list) -> RunDayGroup(label, list) }
@@ -0,0 +1,183 @@
package net.awan.pipelines.ui.screens
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.data.protocol.RunSummary
import org.junit.Assert.assertEquals
import org.junit.Test
class ListSortTest {
private fun pipeline(
id: Long,
name: String,
stages: Int = 1,
createdAt: String = "2026-10-01T00:00:00Z",
) = PipelineSummary(id = id, name = name, version = 1, stages = stages, createdAt = createdAt)
private fun run(
id: Long,
pipelineId: Long = id,
name: String = "p$id",
status: String = "succeeded",
createdAt: String = "2026-10-16T10:00:00Z",
finishedAt: String = "2026-10-16T10:00:10Z",
) = RunSummary(
id = id,
pipelineId = pipelineId,
name = name,
status = status,
createdAt = createdAt,
finishedAt = finishedAt,
)
// --- stored-value tolerance -------------------------------------------------
@Test
fun pipelineSortFromStorageFallsBackToTheDefaultForStaleOrUnknownValues() {
assertEquals(PipelineSort.Default, PipelineSort.ServerOrder)
for (option in PipelineSort.entries) {
assertEquals(option, PipelineSort.fromStorage(option.storageKey))
}
assertEquals(PipelineSort.ServerOrder, PipelineSort.fromStorage(null))
assertEquals(PipelineSort.ServerOrder, PipelineSort.fromStorage(""))
assertEquals(PipelineSort.ServerOrder, PipelineSort.fromStorage("no_such_sort"))
}
@Test
fun runSortFromStorageFallsBackToTheDefaultForStaleOrUnknownValues() {
assertEquals(RunSort.Default, RunSort.NewestFirst)
for (option in RunSort.entries) {
assertEquals(option, RunSort.fromStorage(option.storageKey))
}
assertEquals(RunSort.NewestFirst, RunSort.fromStorage(null))
assertEquals(RunSort.NewestFirst, RunSort.fromStorage(""))
assertEquals(RunSort.NewestFirst, RunSort.fromStorage("whatever"))
}
// --- pipelines --------------------------------------------------------------
@Test
fun serverOrderKeepsTheInputUntouched() {
val input = listOf(pipeline(7, "Zeta"), pipeline(3, "alpha"), pipeline(5, "Beta"))
assertEquals(listOf(7L, 3L, 5L), sortPipelines(input, PipelineSort.ServerOrder).map { it.id })
}
@Test
fun nameSortsAreCaseInsensitiveAndBreakTiesByTheUniqueId() {
val input = listOf(pipeline(7, "Zebra"), pipeline(3, "apple"), pipeline(9, "APPLE"))
assertEquals(listOf(9L, 3L, 7L), sortPipelines(input, PipelineSort.NameAsc).map { it.id })
// Descending keeps the id tie-break ascending: APPLE(9) before apple(3).
assertEquals(listOf(7L, 9L, 3L), sortPipelines(input, PipelineSort.NameDesc).map { it.id })
}
@Test
fun stageCountSortsBreakTiesByNameThenId() {
// Ids deliberately disagree with name/stage order so the tie-breaks show.
val input = listOf(
pipeline(7, "Alpha", stages = 2),
pipeline(3, "beta", stages = 2),
pipeline(5, "Gamma", stages = 1),
)
assertEquals(listOf(5L, 7L, 3L), sortPipelines(input, PipelineSort.FewestStages).map { it.id })
assertEquals(listOf(7L, 3L, 5L), sortPipelines(input, PipelineSort.MostStages).map { it.id })
}
@Test
fun recentRunSortPutsPipelinesWithoutRunsLastAndNewerRunsFirst() {
val runs = listOf(
run(5, pipelineId = 1, createdAt = "2026-10-16T09:00:00Z"),
run(9, pipelineId = 2, createdAt = "2026-10-16T11:00:00Z"),
)
val latest = latestRunByPipeline(runs)
val input = listOf(pipeline(3, "NoRun"), pipeline(1, "Older"), pipeline(2, "Newer"))
assertEquals(
listOf(2L, 1L, 3L),
sortPipelines(input, PipelineSort.RecentRun, latest).map { it.id },
)
}
@Test
fun recentRunSortBreaksExactTimestampTiesByTheHigherRunId() {
val runs = listOf(
run(4, pipelineId = 1, createdAt = "2026-10-16T10:00:00Z"),
run(8, pipelineId = 2, createdAt = "2026-10-16T10:00:00Z"),
)
val latest = latestRunByPipeline(runs)
val input = listOf(pipeline(1, "A"), pipeline(2, "B"))
assertEquals(
listOf(2L, 1L),
sortPipelines(input, PipelineSort.RecentRun, latest).map { it.id },
)
}
@Test
fun recentRunSortBreaksRunlessPipelinesByTheirOwnId() {
val input = listOf(pipeline(3, "C"), pipeline(1, "A"), pipeline(2, "B"))
assertEquals(
listOf(1L, 2L, 3L),
sortPipelines(input, PipelineSort.RecentRun).map { it.id },
)
}
// --- runs -------------------------------------------------------------------
@Test
fun newestAndOldestFirstPutUnparseableTimestampsLast() {
val input = listOf(
run(3, createdAt = ""),
run(1, createdAt = "2026-10-16T10:00:00Z"),
run(2, createdAt = "2026-10-16T12:00:00Z"),
)
assertEquals(listOf(2L, 1L, 3L), sortRuns(input, RunSort.NewestFirst).map { it.id })
assertEquals(listOf(1L, 2L, 3L), sortRuns(input, RunSort.OldestFirst).map { it.id })
}
@Test
fun durationSortsPutRunsWithoutADurationLastInBothDirections() {
val input = listOf(
run(1, createdAt = "2026-10-16T10:00:00Z", finishedAt = "2026-10-16T10:00:10Z"),
run(2, createdAt = "2026-10-16T10:00:00Z", finishedAt = "2026-10-16T10:10:00Z"),
// Still executing: no finished_at, so no duration.
run(3, createdAt = "2026-10-16T10:00:00Z", finishedAt = ""),
)
assertEquals(listOf(2L, 1L, 3L), sortRuns(input, RunSort.LongestDuration).map { it.id })
assertEquals(listOf(1L, 2L, 3L), sortRuns(input, RunSort.ShortestDuration).map { it.id })
}
@Test
fun durationSortsBreakTiesByNewestStartThenId() {
val input = listOf(
run(1, createdAt = "2026-10-16T09:00:00Z", finishedAt = "2026-10-16T09:00:30Z"),
run(2, createdAt = "2026-10-16T11:00:00Z", finishedAt = "2026-10-16T11:00:30Z"),
)
// Equal 30s durations: newer start (id 2) first.
assertEquals(listOf(2L, 1L), sortRuns(input, RunSort.LongestDuration).map { it.id })
assertEquals(listOf(2L, 1L), sortRuns(input, RunSort.ShortestDuration).map { it.id })
}
@Test
fun pipelineNameAndStatusSortsAreCaseInsensitiveWithExplicitTieBreaks() {
val byName = listOf(
run(1, name = "beta", createdAt = "2026-10-16T10:00:00Z"),
run(2, name = "Alpha", createdAt = "2026-10-16T09:00:00Z"),
)
assertEquals(listOf(2L, 1L), sortRuns(byName, RunSort.PipelineName).map { it.id })
val byStatus = listOf(
run(1, status = "running"),
run(2, status = "failed"),
)
assertEquals(listOf(2L, 1L), sortRuns(byStatus, RunSort.Status).map { it.id })
}
@Test
fun equalKeysAlwaysOrderTheSameWay() {
// Same status and same timestamp: the id descends, so the order is fixed.
val input = listOf(
run(3, status = "succeeded", createdAt = "2026-10-16T10:00:00Z"),
run(1, status = "succeeded", createdAt = "2026-10-16T10:00:00Z"),
)
assertEquals(listOf(3L, 1L), sortRuns(input, RunSort.Status).map { it.id })
assertEquals(listOf(3L, 1L), sortRuns(input.reversed(), RunSort.Status).map { it.id })
}
}
@@ -43,4 +43,19 @@ class RunGroupingTest {
val unknown = groups.first { it.label == "Unknown date" }
assertEquals(setOf(1L, 2L), unknown.runs.map { it.id }.toSet())
}
@Test
fun anExplicitOrderDrivesBothTheGroupOrderAndTheOrderWithinADay() {
val today = LocalDate.of(2026, 10, 15)
val zone = ZoneOffset.UTC
val runs = listOf(
run(3, "2026-10-14T09:00:00Z"),
run(1, "2026-10-15T10:00:00Z"),
run(2, "2026-10-15T08:00:00Z"),
)
val groups = groupRunsByDay(runs, today, zone, runComparator(RunSort.OldestFirst))
// Oldest day first, and within "Today" the earlier start comes first.
assertEquals(listOf("Yesterday", "Today"), groups.take(2).map { it.label })
assertEquals(listOf(2L, 1L), groups[1].runs.map { it.id })
}
}