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
@@ -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 })
}
}