Merge lane-app2: keep both lanes' reviewed work

Compose the parallel lane (lane-app2) with the work already on main,
preserving both intents rather than picking one side:

- lane-app2's modernised run graph (rounded tonal nodes, pill terminals,
  chipped outcome labels, pass/fail emphasis and active-stage/edge motion)
  plus its remembered list filters/sort and last-run badges, and the
  app-owned run-status palette.
- main's cross-fading loading/empty/error states, animated list items and
  the single geometry token file (Dimens.kt + DimensTest).

Conflicts resolved in android/README.md (kept both appended sections),
RunStatus.kt (kept the shared ColoredChip extraction and made it animate
under MotionQuick), PipelineListScreen.kt (filters/sort/badges composed with
the StateCrossfade/load-phase presentation and animateListItem rows),
RunDetailScreen.kt (kept both the artifact-selection and graph-palette
imports) and RunHistoryScreen.kt (the cross-faded load branch now passes
sort/filters through, and both empty branches keep the Clear filters action
with animated items). LoadPhase.Empty now carries an optional recovery
action so the crossfade can still offer Clear filters. The graph's new
geometry literals moved onto Dimens.kt GRAPH_* tokens so DimensTest passes
and its allow-list shrinks as intended.

Verified: :app:assembleDebug and :app:testDebugUnitTest (259 tests,
0 failures) with the offline Gradle 8.11.1 / JDK 17 toolchain.
This commit is contained in:
2026-10-16 12:04:45 +01:00
32 changed files with 4354 additions and 208 deletions
@@ -21,6 +21,34 @@ 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()
// The chosen list filters, stored as their stable storage keys/encodings and
// resolved (with a default fallback for a stale/unknown value) by the list
// screens, so this repository stays unaware of the UI's filter enums.
private val _runFilterStatuses = MutableStateFlow(prefs.getString(KEY_RUN_FILTER_STATUSES, "").orEmpty())
val runFilterStatuses: StateFlow<String> = _runFilterStatuses.asStateFlow()
private val _runFilterPipeline = MutableStateFlow(prefs.getString(KEY_RUN_FILTER_PIPELINE, "").orEmpty())
val runFilterPipeline: StateFlow<String> = _runFilterPipeline.asStateFlow()
private val _runFilterTimeRange = MutableStateFlow(prefs.getString(KEY_RUN_FILTER_TIME_RANGE, "").orEmpty())
val runFilterTimeRange: StateFlow<String> = _runFilterTimeRange.asStateFlow()
private val _pipelineFilterPresence = MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_PRESENCE, "").orEmpty())
val pipelineFilterPresence: StateFlow<String> = _pipelineFilterPresence.asStateFlow()
private val _pipelineFilterRunStatuses =
MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_RUN_STATUSES, "").orEmpty())
val pipelineFilterRunStatuses: StateFlow<String> = _pipelineFilterRunStatuses.asStateFlow()
fun setServerUrl(value: String) {
val trimmed = value.trim()
_serverUrl.value = trimmed
@@ -33,11 +61,53 @@ 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()
}
fun setRunFilterStatuses(value: String) {
_runFilterStatuses.value = value
prefs.edit().putString(KEY_RUN_FILTER_STATUSES, value).apply()
}
fun setRunFilterPipeline(value: String) {
_runFilterPipeline.value = value
prefs.edit().putString(KEY_RUN_FILTER_PIPELINE, value).apply()
}
fun setRunFilterTimeRange(value: String) {
_runFilterTimeRange.value = value
prefs.edit().putString(KEY_RUN_FILTER_TIME_RANGE, value).apply()
}
fun setPipelineFilterPresence(value: String) {
_pipelineFilterPresence.value = value
prefs.edit().putString(KEY_PIPELINE_FILTER_PRESENCE, value).apply()
}
fun setPipelineFilterRunStatuses(value: String) {
_pipelineFilterRunStatuses.value = value
prefs.edit().putString(KEY_PIPELINE_FILTER_RUN_STATUSES, 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"
const val KEY_RUN_FILTER_STATUSES = "run_filter_statuses"
const val KEY_RUN_FILTER_PIPELINE = "run_filter_pipeline"
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"
}
}
@@ -75,6 +75,17 @@ data class RunGraphState(
val visitedStages: Set<String>,
val takenRoutes: Set<GraphRoute>,
val currentStage: String?,
/**
* True while the server still reports the run as executing. The graph only
* animates a live run; a finished one is drawn settled and static.
*/
val executing: Boolean = false,
/**
* RFC3339 start of the visit currently running for [currentStage], or null
* when the run is not live or that visit's start is unknown. The graph uses
* it for the live ticking elapsed time on the active node.
*/
val currentStageStartedAt: String? = null,
) {
companion object {
fun from(run: RunDetail): RunGraphState {
@@ -91,7 +102,17 @@ data class RunGraphState(
val current = run.currentStage.ifEmpty {
run.steps.lastOrNull()?.stage ?: ""
}
return RunGraphState(stages, routes, current.ifEmpty { null })
val stage = current.ifEmpty { null }
// Only a live run carries a ticking active stage; the matching running
// step's start keeps the timer on the same node as the halo.
val runningSince = if (run.executing && stage != null) {
run.steps.lastOrNull { it.stage == stage && it.status == "running" }
?.startedAt
?.takeIf { it.isNotBlank() }
} else {
null
}
return RunGraphState(stages, routes, stage, run.executing, runningSince)
}
}
}
@@ -48,6 +48,17 @@ 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
/** The stored pipeline/run filter keys; the list screens resolve them to filters. */
val runFilterStatuses: StateFlow<String> = settings.runFilterStatuses
val runFilterPipeline: StateFlow<String> = settings.runFilterPipeline
val runFilterTimeRange: StateFlow<String> = settings.runFilterTimeRange
val pipelineFilterPresence: StateFlow<String> = settings.pipelineFilterPresence
val pipelineFilterRunStatuses: StateFlow<String> = settings.pipelineFilterRunStatuses
private val _serverUrlDraft = MutableStateFlow(settings.serverUrl.value)
val serverUrlDraft: StateFlow<String> = _serverUrlDraft.asStateFlow()
@@ -153,6 +164,20 @@ class AppViewModel(
fun disconnect() = repository.disconnect()
fun setPipelineSort(storageKey: String) = settings.setPipelineSort(storageKey)
fun setRunSort(storageKey: String) = settings.setRunSort(storageKey)
fun setRunFilterStatuses(value: String) = settings.setRunFilterStatuses(value)
fun setRunFilterPipeline(value: String) = settings.setRunFilterPipeline(value)
fun setRunFilterTimeRange(value: String) = settings.setRunFilterTimeRange(value)
fun setPipelineFilterPresence(value: String) = settings.setPipelineFilterPresence(value)
fun setPipelineFilterRunStatuses(value: String) = settings.setPipelineFilterRunStatuses(value)
private fun awaitConnected() {
viewModelScope.launch {
val connected = withTimeoutOrNull(CONNECT_TIMEOUT_MILLIS) {
@@ -12,15 +12,43 @@ 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)
/**
* Non-negative whole seconds from a [start] RFC3339 timestamp to [nowMillis]
* (wall-clock epoch millis), or null when [start] is blank/unparseable. Clamps a
* future/unparseable elapsed to 0 so a live timer never prints a negative or a
* nonsensical value. The one derivation behind the run graph's ticking elapsed
* time, so it is pure and testable without the Compose runtime.
*/
internal fun secondsSince(start: String, nowMillis: Long): Long? =
parseInstant(start)?.let { ((nowMillis - it.toInstant().toEpochMilli()) / 1000).coerceAtLeast(0) }
/**
* 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,178 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
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.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.LocalConfiguration
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.toggleableState
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The tallest a list-filter menu may grow, as a fraction of the window height.
* Derived from the window rather than a fixed row count so the menu stays inside
* the window and clear of the navigation inset no matter how many distinct
* pipelines the runs list contributes (N made the old menu unbounded); beyond
* this the menu scrolls internally.
*/
internal fun filterMenuMaxHeight(screenHeightDp: Int): Dp = (screenHeightDp * 0.85f).dp
/**
* The filter icon's content description. With active filters the count is spoken
* ("Filter runs, 2 filters active") so the badge is not a purely visual signal;
* with none the plain [base] stands.
*/
internal fun filterMenuDescription(base: String, activeCount: Int): String = when {
activeCount <= 0 -> base
activeCount == 1 -> "$base, 1 filter active"
else -> "$base, $activeCount filters active"
}
/**
* The shared list-filter control: a top-bar icon carrying an active-filter count
* badge, opening the caller's [optionContent] plus one [resetLabel] action. It is
* its own action with a distinct glyph and content description, so it cannot
* collide with the adjacent sort or refresh actions, and the same control serves
* both list widths (a `DropdownMenu` is not width-dependent geometry).
*
* [activeCount] is drawn as a numeric badge (0 hides it) and folded into the
* icon's description, so "filters are active" is never colour alone and the
* count is announced. The menu is capped at a window-derived [filterMenuMaxHeight]
* and the reset action is the first item, so the reset is always in view on open
* and the last option is reachable by scrolling rather than clipped; a trailing
* navigation-bar spacer keeps the final option above the gesture inset.
* [optionContent] receives a `dismiss` callback: a single-select entry calls it to
* close the menu, while a multi-select toggle simply omits it to keep the menu
* open.
*/
@Composable
fun FilterMenu(
activeCount: Int,
contentDescription: String,
resetLabel: String,
onReset: () -> Unit,
modifier: Modifier = Modifier,
optionContent: @Composable (dismiss: () -> Unit) -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
val maxMenuHeight = filterMenuMaxHeight(LocalConfiguration.current.screenHeightDp)
val bottomInset = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
Box(modifier) {
BadgedBox(
badge = {
if (activeCount > 0) {
Badge { Text(activeCount.toString()) }
}
},
) {
IconButton(onClick = { expanded = true }) {
Icon(
Icons.Default.FilterList,
contentDescription = filterMenuDescription(contentDescription, activeCount),
)
}
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier.heightIn(max = maxMenuHeight),
) {
Row(
modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = "Filters",
style = pipelinesText().label,
color = MaterialTheme.colorScheme.primary,
)
TextButton(
onClick = {
onReset()
expanded = false
},
enabled = activeCount > 0,
) {
Text(resetLabel)
}
}
HorizontalDivider()
optionContent { expanded = false }
Spacer(Modifier.height(bottomInset))
}
}
}
/**
* One checkable filter entry, sharing the sort menu's leading-check idiom so the
* active value is conveyed by a glyph as well as by text, and exposing the
* checked state to accessibility ([toggleableState] plus [Role.Checkbox]) so
* TalkBack announces which facet is selected rather than only the label. The
* caller decides whether to dismiss: a single-select option closes the menu, a
* multi-select toggle leaves it open so several values can be gathered.
*/
@Composable
fun FilterCheckItem(
label: String,
checked: Boolean,
onClick: () -> Unit,
) {
DropdownMenuItem(
text = { Text(label) },
onClick = onClick,
modifier = Modifier.semantics {
role = Role.Checkbox
toggleableState = if (checked) ToggleableState.On else ToggleableState.Off
},
leadingIcon = {
if (checked) {
Icon(Icons.Default.Check, contentDescription = null)
}
},
)
}
/** A small section caption inside a filter menu (Status/Pipeline/Time range). */
@Composable
fun FilterSectionHeader(label: String) {
Text(
text = label,
style = pipelinesText().label,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
)
}
@@ -17,7 +17,6 @@ import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.PauseCircle
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -65,15 +64,12 @@ fun runStateOf(status: String): RunState = when (status.trim().lowercase()) {
else -> RunState.Unknown
}
/** Colour family for a state, sourced from the app-owned scheme (never colour-only). */
@Composable
fun runStateColor(state: RunState): Color = when (state) {
RunState.Running, RunState.Active -> MaterialTheme.colorScheme.primary
RunState.Queued -> MaterialTheme.colorScheme.secondary
RunState.Succeeded -> MaterialTheme.colorScheme.tertiary
RunState.Failed, RunState.Interrupted -> MaterialTheme.colorScheme.error
RunState.Canceled, RunState.Unknown -> MaterialTheme.colorScheme.onSurfaceVariant
}
/**
* Colour family for a state, from the app-owned [RunStatusPalette] (never
* colour-only: every chip also carries its glyph and label). Pure, so it can be
* asserted in a plain JVM unit test.
*/
fun runStateColor(state: RunState): Color = RunStatusPalette.of(state).color
/** A distinct glyph per state, all from the standard filled material icon set. */
fun runStateIcon(state: RunState): ImageVector = when (state) {
@@ -115,41 +111,65 @@ fun RunStatusIcon(
}
/**
* A colour-coded chip pairing a state glyph with its text label. Its container,
* label and glyph all ease to the new state's colour under [MotionQuick] (the
* glyph's own tint animates in [RunStatusIcon], in step), so a run whose status
* changes while the screen is open visibly transitions instead of silently
* swapping a colour; the chip is identical to the old one once settled.
* A pill pairing a glyph with its text label, coloured by the caller. Shared by
* the run-status chip and the timeline's step-outcome chip so both render one
* shape and neither repeats the layout. The glyph always carries a
* [contentDescription], so state/outcome is never colour alone. Its container,
* label and glyph all ease to the new colour under [MotionQuick], so a status or
* outcome change while the screen is open visibly transitions instead of
* silently swapping a colour; the chip is identical once settled.
*/
@Composable
fun StatusChip(
internal fun ColoredChip(
label: String,
state: RunState,
color: Color,
icon: ImageVector,
contentDescription: String? = label,
modifier: Modifier = Modifier,
) {
val color by animateColorAsState(
targetValue = runStateColor(state),
val animatedColor by animateColorAsState(
targetValue = color,
animationSpec = MotionQuick.spec(),
label = "status-chip-color",
)
Row(
modifier = modifier
.clip(RoundedCornerShape(50))
.background(color.copy(alpha = 0.16f))
.background(animatedColor.copy(alpha = 0.16f))
.padding(horizontal = 8.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
RunStatusIcon(state, contentDescription = label, modifier = Modifier.size(14.dp))
Icon(
imageVector = icon,
contentDescription = contentDescription,
tint = animatedColor,
modifier = Modifier.size(14.dp),
)
Text(
text = label,
color = color,
color = animatedColor,
fontWeight = FontWeight.Medium,
style = pipelinesText().label,
)
}
}
/** A colour-coded chip pairing a state glyph with its text label. */
@Composable
fun StatusChip(
label: String,
state: RunState,
modifier: Modifier = Modifier,
) {
ColoredChip(
label = label,
color = runStateColor(state),
icon = runStateIcon(state),
modifier = modifier,
)
}
/** Convenience: the run's own status word plus its colour-coded chip. */
@Composable
fun RunStatusChip(state: RunState, modifier: Modifier = Modifier) {
@@ -0,0 +1,70 @@
package net.awan.pipelines.ui.components
import androidx.compose.ui.graphics.Color
import net.awan.pipelines.ui.theme.DarkError
/**
* The app-owned run-status palette.
*
* Run status is a *different vocabulary* from the graph's stage outcomes
* ([net.awan.pipelines.ui.graph.GraphPalette]): a run that is `running` is not a
* `skipped` stage, and a `succeeded` run is not the amber the theme uses for a
* positive *stage* outcome. Borrowing Material roles therefore put the wrong hue
* on the two states that matter most — `primary` (mint) made a *running* run read
* green and `tertiary` (amber) made a *succeeded* run read yellow.
*
* Every entry below is instead a deliberate, fixed colour with an explicit
* meaning, tuned for the dark Pipelines surface (`DarkSurface 0xFF0E1513`,
* over which the chip label is drawn). The contrast of each colour against that
* surface is *measured* by `RunStatusPaletteTest`, never judged by eye. Status is
* never colour-only: every entry keeps its own material glyph ([runStateIcon])
* and its text label ([RunState.label]).
*/
internal object RunStatusPalette {
/** One status colour plus the one-line reason it is that hue. */
data class Entry(val color: Color, val rationale: String)
/** In progress: the conventional blue. Green would read as already finished. */
private val Running =
Entry(Color(0xFF7FB2F0), "blue: in progress; green would read as already finished")
/** Finished well: the conventional green. Amber/tertiary would read as a warning. */
private val Succeeded =
Entry(Color(0xFF7FE0A8), "green: completed successfully; amber would read as a warning")
/** Failure: the app's error red, the one alarm colour the scheme already owns. */
private val Failed =
Entry(DarkError, "the app error red: an explicit failure, never a soft warning hue")
/** Stopped by the operator mid-flight: amber, a warning that is not a failure. */
private val Interrupted =
Entry(Color(0xFFE8C06A), "amber: stopped by the operator, a warning distinct from failure red")
/** Operator-cancelled: muted grey so a deliberate stop is quiet, not alarming. */
private val Canceled =
Entry(Color(0xFF889391), "muted grey: an operator cancel is quiet, not the failure red")
/** Waiting to start: neutral grey, deliberately not a hue that reads as running. */
private val Queued =
Entry(Color(0xFF9AA6A2), "neutral grey: waiting, clearly not the in-progress blue")
/** Unknown/blank status: the safe, low-key fallback. */
private val Unknown =
Entry(Color(0xFFBEC9C5), "neutral surface grey: an unrecognised status stays low-key")
/**
* The entry for [state]. [RunState.Active] shares [Running] (it is the server's
* `active` usage bucket, i.e. work in progress). Pure, so the palette is
* unit-testable without the Compose runtime.
*/
fun of(state: RunState): Entry = when (state) {
RunState.Running, RunState.Active -> Running
RunState.Succeeded -> Succeeded
RunState.Failed -> Failed
RunState.Interrupted -> Interrupted
RunState.Canceled -> Canceled
RunState.Queued -> Queued
RunState.Unknown -> Unknown
}
}
@@ -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
},
)
}
}
}
@@ -50,8 +50,18 @@ fun ErrorState(message: String, onRetry: (() -> Unit)? = null, modifier: Modifie
}
}
/**
* An empty-list message. [actionLabel]/[onAction] add one recovery action (the
* "nothing matches the current filters" case offers Clear filters); both are
* omitted for the "nothing exists" case, where there is nothing to clear.
*/
@Composable
fun EmptyState(message: String, modifier: Modifier = Modifier) {
fun EmptyState(
message: String,
modifier: Modifier = Modifier,
actionLabel: String? = null,
onAction: (() -> Unit)? = null,
) {
Column(
modifier = modifier.fillMaxSize().padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
@@ -63,6 +73,11 @@ fun EmptyState(message: String, modifier: Modifier = Modifier) {
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (actionLabel != null && onAction != null) {
Button(onClick = onAction, modifier = Modifier.padding(top = 16.dp)) {
Text(actionLabel)
}
}
}
}
@@ -84,8 +99,12 @@ sealed interface LoadPhase {
/** The load failed and there is no data to fall back to. */
data class Error(val message: String) : LoadPhase
/** The load succeeded but there is nothing to show; [message] explains it. */
data class Empty(val message: String) : LoadPhase
/**
* The load succeeded but there is nothing to show; [message] explains it and
* [actionLabel] optionally labels one recovery action (the "nothing matches
* the current filters" case offers Clear filters).
*/
data class Empty(val message: String, val actionLabel: String? = null) : LoadPhase
/** The loaded content. */
data object Content : LoadPhase
@@ -96,7 +115,8 @@ sealed interface LoadPhase {
* no data wins, then a load with no data, then an empty result; anything else is
* [LoadPhase.Content]. [emptyMessage] is non-null exactly when the pane is empty
* and is the text to show, captured so a fading-out empty branch never reads a
* changed query.
* changed query; [emptyActionLabel] labels the one recovery action offered with
* that text (both are captured at classification).
*
* When stale data is present neither loading nor an error replaces it: the
* screen keeps showing the data and surfaces the error inline, so [hasData]
@@ -107,10 +127,11 @@ fun listLoadPhase(
error: String?,
hasData: Boolean,
emptyMessage: String?,
emptyActionLabel: String? = null,
): LoadPhase = when {
error != null && !hasData -> LoadPhase.Error(error)
loading && !hasData -> LoadPhase.Loading
emptyMessage != null -> LoadPhase.Empty(emptyMessage)
emptyMessage != null -> LoadPhase.Empty(emptyMessage, emptyActionLabel)
else -> LoadPhase.Content
}
@@ -0,0 +1,99 @@
package net.awan.pipelines.ui.graph
import net.awan.pipelines.data.protocol.GraphEdge
import net.awan.pipelines.data.protocol.RunGraphState
import kotlin.math.PI
import kotlin.math.sin
/**
* How a stage node is drawn under a run:
*
* - [Active]: the stage the live run is executing right now; it carries a
* pulsing halo, and its live elapsed time is drawn under its label.
* - [Visited]: a stage the run already visited (or any stage in the
* definition-only view); it settles into its static fill/border.
* - [Unvisited]: a stage the run did not reach; drawn hollow, never animating.
*
* A finished run has no [Active] node, so nothing animates once it stops.
*/
internal enum class NodeMotion { Active, Visited, Unvisited }
/**
* How an edge is drawn under a run:
*
* - [Flowing]: an executed route while the run is live; its stroke carries a
* moving dot that reads the direction of travel.
* - [Settled]: an executed route under a finished run; a plain static stroke.
* - [Unvisited]: a route the run did not take; dashed and arrowless.
*/
internal enum class EdgeMotion { Flowing, Settled, Unvisited }
/**
* Whether the graph may animate at all, from the three independent gates:
* the run must still be executing (never animate a finished run), the system
* must have animations enabled (honour the OS/animation-scale setting), and the
* graph must be on screen (a backgrounded graph is paused). Pure, so the
* decision is asserted in a unit test rather than inferred from a frame clock.
*
* When this is false while the run is live, the graph still marks the active
* stage statically (see [ACTIVE_HALO_STATIC_ALPHA] and the drawn elapsed time),
* so "animations off" is a static but unmistakable running state, not a blank.
*/
internal fun graphShouldAnimate(
runState: RunGraphState?,
animationsEnabled: Boolean,
onScreen: Boolean,
): Boolean = runState?.executing == true && animationsEnabled && onScreen
/**
* The motion state of the stage [key] under [runState]. Pure and the single
* definition the drawing and the tests share: the definition-only view
* ([runState] == null) is entirely visited/static, an unvisited key is idle, and
* only the stage the live run is on is [NodeMotion.Active]. The live stage wins
* over the visited check, so it is unmistakably active even in the brief window
* before its step has been recorded in [RunGraphState.visitedStages].
*/
internal fun nodeMotion(key: String, runState: RunGraphState?): NodeMotion = when {
runState == null -> NodeMotion.Visited
runState.executing && key == runState.currentStage -> NodeMotion.Active
key !in runState.visitedStages -> NodeMotion.Unvisited
else -> NodeMotion.Visited
}
/**
* The motion state of [edge] under [runState]: an executed route flows while the
* run is live and settles once it finishes, and an untaken route is idle. The
* definition-only view ([runState] == null) is settled (static), as before.
*/
internal fun edgeMotion(edge: GraphEdge, runState: RunGraphState?): EdgeMotion = when {
!edgeIsExecuted(edge, runState) -> EdgeMotion.Unvisited
runState?.executing == true -> EdgeMotion.Flowing
else -> EdgeMotion.Settled
}
/**
* The active-node halo strength for a 0..1 animation [phase]: a smooth
* sinusoid that rises and falls once per cycle, never stepping between two
* values (a pulse, not a blink). Bounded to `[PULSE_MIN, PULSE_MAX]` so the
* halo is always visible and never fully transparent, and periodic in [phase]
* so it is seamless at the wrap. Pure, so the rhythm is asserted without any
* frame-timing.
*/
internal fun pulseAlpha(phase: Float): Float {
val t = ((phase % 1f) + 1f) % 1f
val wave = (sin(t * 2.0 * PI) + 1.0) / 2.0
return (PULSE_MIN + (PULSE_MAX - PULSE_MIN) * wave).toFloat()
}
/** Faintest the active halo ever gets; never invisible, never a blink-off. */
private const val PULSE_MIN = 0.35f
/** Strongest the active halo gets at the peak of a pulse. */
private const val PULSE_MAX = 0.9f
/**
* The fixed active-halo strength drawn when animation is off (the system
* setting, or a paused graph): clearly marked, just not moving. Within the
* [pulseAlpha] range so the static state looks like a frozen pulse.
*/
internal const val ACTIVE_HALO_STATIC_ALPHA = 0.85f
@@ -94,6 +94,36 @@ internal fun graphNodeKind(terminal: Boolean, key: String, type: String?): Graph
else -> GraphNodeKind.Custom
}
/**
* A more vivid version of [color] with the same hue, value and alpha: the HSV
* saturation is scaled by [factor] and clamped to 1. Used to make an executed
* pass/fail edge stroke stronger without changing its outcome hue, so both
* terminal colours get more punch while staying recognisably success/failure.
*
* Pure sRGB maths. A non-finite/non-positive [factor], an achromatic colour or
* one already at full saturation returns [color] unchanged, so callers never get
* NaN and every input is safe.
*/
internal fun boostSaturation(color: Color, factor: Float): Color {
if (!factor.isFinite() || factor <= 0f) return color
val r = color.red
val g = color.green
val b = color.blue
val max = maxOf(r, g, b)
val min = minOf(r, g, b)
val delta = max - min
if (max <= 0f || delta <= 0f) return color
val current = delta / max
val saturation = (current * factor).coerceAtMost(1f)
if (saturation <= current) return color
val hue = (when (max) {
r -> ((g - b) / delta + 6f) % 6f
g -> (b - r) / delta + 2f
else -> (r - g) / delta + 4f
}) * 60f
return Color.hsv(hue, saturation, max, color.alpha)
}
/**
* WCAG relative luminance of [color] (sRGB), the building block of the WCAG
* contrast ratio. Pure so the palette's legibility is measured in a unit test
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,246 @@
package net.awan.pipelines.ui.screens
import java.time.LocalDate
import java.time.ZoneId
import net.awan.pipelines.data.protocol.PipelineSummary
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.parseInstant
/**
* The run-list time windows offered by the filter control. [storageKey] is the
* stable value persisted in SharedPreferences; [fromStorage] tolerates a stale,
* unknown or blank stored value by returning [Default] ("any time").
*/
enum class RunTimeRange(val label: String, val storageKey: String) {
AnyTime("Any time", "any_time"),
Today("Today", "today"),
Last7Days("Last 7 days", "last_7_days"),
Last30Days("Last 30 days", "last_30_days");
companion object {
val Default = AnyTime
fun fromStorage(value: String?): RunTimeRange =
entries.firstOrNull { it.storageKey == value } ?: Default
}
}
/**
* Whether the pipeline list only shows pipelines that have (or have not)
* recorded a run, persisted like [RunTimeRange]. [Default] is no narrowing.
*/
enum class RunPresence(val label: String, val storageKey: String) {
Any("Any", "any"),
HasRuns("Has runs", "has_runs"),
NoRuns("No runs", "no_runs");
companion object {
val Default = Any
fun fromStorage(value: String?): RunPresence =
entries.firstOrNull { it.storageKey == value } ?: Default
}
}
/**
* The statuses a run filter can select. The server's own run vocabulary
* (internal/pipeline/runs.go: queued/running/succeeded/failed/canceled/
* interrupted); the app-only `active` usage bucket and the `unknown` fallback
* are deliberately not offered, so a status filter always names a real state.
*/
internal val RUN_STATUS_FILTERS: List<RunState> = listOf(
RunState.Queued,
RunState.Running,
RunState.Succeeded,
RunState.Failed,
RunState.Canceled,
RunState.Interrupted,
)
/** Adds [state] when absent, removes it when present — the multi-select toggle. */
internal fun Set<RunState>.toggle(state: RunState): Set<RunState> =
if (state in this) this - state else this + state
/**
* The stable stored form of a status set: the states' server status words in
* ordinal order, comma-joined. [RunState.label] is that word and is unique per
* state, so the encoding round-trips and stays meaningful in the prefs file.
*/
internal fun encodeRunStates(states: Set<RunState>): String =
states.sortedBy { it.ordinal }.joinToString(",") { it.label }
/** Decodes [encodeRunStates], dropping unknown or blank tokens rather than crashing. */
internal fun decodeRunStates(value: String?): Set<RunState> =
value.orEmpty().split(',').mapNotNull { token ->
val word = token.trim()
RunState.entries.firstOrNull { it.label == word }
}.toSet()
/**
* The runs-list filters, each defaulting to "no narrowing" so the default value
* filters nothing. [activeCount] is the number of active facets (one per
* status/pipeline/time choice), used for the control's badge.
*/
data class RunFilters(
val statuses: Set<RunState> = emptySet(),
val pipelineId: Long? = null,
val timeRange: RunTimeRange = RunTimeRange.Default,
) {
val activeCount: Int
get() = (if (statuses.isNotEmpty()) 1 else 0) +
(if (pipelineId != null) 1 else 0) +
(if (timeRange != RunTimeRange.Default) 1 else 0)
val isActive: Boolean get() = activeCount > 0
companion object {
val Default = RunFilters()
fun fromStorage(statuses: String?, pipelineId: String?, timeRange: String?): RunFilters =
RunFilters(
statuses = decodeRunStates(statuses),
pipelineId = pipelineId?.trim()?.takeIf { it.isNotEmpty() }?.toLongOrNull(),
timeRange = RunTimeRange.fromStorage(timeRange),
)
}
}
/**
* 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.
*/
data class PipelineFilters(
val presence: RunPresence = RunPresence.Default,
val lastRunStatuses: Set<RunState> = emptySet(),
) {
val activeCount: Int
get() = (if (presence != RunPresence.Default) 1 else 0) +
(if (lastRunStatuses.isNotEmpty()) 1 else 0)
val isActive: Boolean get() = activeCount > 0
companion object {
val Default = PipelineFilters()
fun fromStorage(presence: String?, lastRunStatuses: String?): PipelineFilters =
PipelineFilters(
presence = RunPresence.fromStorage(presence),
lastRunStatuses = decodeRunStates(lastRunStatuses),
)
}
}
/** True when [run] is in [statuses]; an empty set means "any status". */
internal fun runMatchesStatuses(run: RunSummary, statuses: Set<RunState>): Boolean =
statuses.isEmpty() || runStateOf(run.status) in statuses
/** True when [run] belongs to [pipelineId]; null means "any pipeline". */
internal fun runMatchesPipeline(run: RunSummary, pipelineId: Long?): Boolean =
pipelineId == null || run.pipelineId == pipelineId
/** The run's start date in [zone], or null when blank/unparseable. */
internal fun runLocalDate(createdAt: String, zone: ZoneId): LocalDate? =
parseInstant(createdAt)?.atZoneSameInstant(zone)?.toLocalDate()
/**
* True when [run] falls inside [range] relative to [today]. A blank/unparseable
* timestamp and a future-dated run (clock skew) never match a finite window;
* [RunTimeRange.AnyTime] matches everything. The window is inclusive calendar
* days ending today: "last 7 days" covers today and the six days before it.
*/
internal fun runMatchesTimeRange(
run: RunSummary,
range: RunTimeRange,
today: LocalDate,
zone: ZoneId,
): Boolean {
if (range == RunTimeRange.AnyTime) return true
val date = runLocalDate(run.createdAt, zone) ?: return false
if (date.isAfter(today)) return false
return when (range) {
RunTimeRange.Today -> date == today
RunTimeRange.Last7Days -> !date.isBefore(today.minusDays(6))
RunTimeRange.Last30Days -> !date.isBefore(today.minusDays(29))
RunTimeRange.AnyTime -> true
}
}
/** Every run facet combined with AND. */
internal fun runMatchesFilters(
run: RunSummary,
filters: RunFilters,
today: LocalDate,
zone: ZoneId,
): Boolean =
runMatchesStatuses(run, filters.statuses) &&
runMatchesPipeline(run, filters.pipelineId) &&
runMatchesTimeRange(run, filters.timeRange, today, zone)
/** Narrows [runs] by [filters]; the default filters change nothing. */
internal fun filterRuns(
runs: List<RunSummary>,
filters: RunFilters,
today: LocalDate,
zone: ZoneId,
): List<RunSummary> =
if (!filters.isActive) runs else runs.filter { runMatchesFilters(it, filters, today, zone) }
/** True when [presence] is satisfied by whether the pipeline [hasRun]. */
internal fun pipelineMatchesPresence(presence: RunPresence, hasRun: Boolean): Boolean = when (presence) {
RunPresence.Any -> true
RunPresence.HasRuns -> hasRun
RunPresence.NoRuns -> !hasRun
}
/**
* True when [latestRun]'s status is in [statuses]; an empty set means "any
* status" and a pipeline with no run never matches a selected status (there is
* no last-run status to compare), so the filter genuinely narrows.
*/
internal fun pipelineMatchesLastRunStatus(latestRun: RunSummary?, statuses: Set<RunState>): Boolean =
statuses.isEmpty() || (latestRun != null && runStateOf(latestRun.status) in statuses)
/** Every pipeline run facet combined with AND. */
internal fun pipelineMatchesFilters(filters: PipelineFilters, latestRun: RunSummary?): Boolean =
pipelineMatchesPresence(filters.presence, latestRun != null) &&
pipelineMatchesLastRunStatus(latestRun, filters.lastRunStatuses)
/**
* 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.
*/
internal fun filterPipelines(
pipelines: List<PipelineSummary>,
filters: PipelineFilters,
latestRuns: Map<Long, RunSummary>,
runsKnown: Boolean = true,
): List<PipelineSummary> {
if (!filters.isActive || !runsKnown) return pipelines
return pipelines.filter { pipelineMatchesFilters(filters, latestRuns[it.id]) }
}
/** One selectable pipeline in the run filter, named from its runs. */
internal data class PipelineFilterOption(val id: Long, val name: String)
/**
* The distinct pipelines present in [runs], each named by its most recent
* non-blank run name and ordered case-insensitively by name then id, so the
* run-list pipeline filter needs no separate pipeline fetch. A blank name falls
* back to the id so the entry is never unlabelled.
*/
internal fun pipelineFilterOptions(runs: List<RunSummary>): List<PipelineFilterOption> {
val names = LinkedHashMap<Long, String>()
for (run in runs) {
val current = names[run.pipelineId]
if (current == null || current.isBlank()) names[run.pipelineId] = run.name
}
return names.map { (id, name) -> PipelineFilterOption(id, name.ifBlank { "Pipeline $id" }) }
.sortedWith(
compareBy<PipelineFilterOption, String>(String.CASE_INSENSITIVE_ORDER) { it.name }
.thenBy { it.id },
)
}
@@ -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))
@@ -0,0 +1,103 @@
package net.awan.pipelines.ui.screens
import java.time.Duration
import java.time.OffsetDateTime
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"
/**
* The last-run facts one pipeline row shows: the status chip's [state], how long
* ago the run started, its recorded duration and its run id. Kept as a plain data
* class so the join and its edge cases (no runs, ties, unknown status) are
* unit-testable without composing anything.
*/
internal data class PipelineRunBadge(
val runId: Long,
val state: RunState,
val ranAgo: String?,
val duration: String?,
)
/**
* The last-run secondary line, e.g. `2h ago · 1m 5s · run 42`. Missing fragments
* (an unparseable start, a run still executing) are omitted so no blank separator
* is ever printed; the run id is always present.
*/
internal fun PipelineRunBadge.metaLine(): String = buildList {
ranAgo?.let(::add)
duration?.let(::add)
add("run $runId")
}.joinToString(" · ")
/**
* Joins list_runs (the whole history, delivered newest-first) onto pipelines by
* pipeline id: one badge per pipeline that has run, the most recent run winning.
* The input order never matters — recency is decided from the timestamps, with the
* higher run id breaking an exact tie — so a pipeline with no runs is simply
* absent from the result (the caller renders [NO_RUNS_RECORDED] for it). No server
* field is involved; this is a pure client-side join.
*/
internal fun pipelineRunBadges(
runs: List<RunSummary>,
now: OffsetDateTime,
): 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
}
/** 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)
val b = parseInstant(current.createdAt)
if (a != null && b != null) {
val order = a.compareTo(b)
if (order != 0) return order > 0
}
return candidate.id > current.id
}
/**
* A compact "how long ago" for a run's start: `just now` under a minute, then
* `Nm ago`/`Nh ago`/`Nd ago`, the same integer rhythm as [formatDuration]. Null
* when the timestamp is blank or unparseable, so the caller omits the fragment
* instead of printing a blank. A future start (clock skew) reads as `just now`,
* never a negative age.
*/
internal fun formatRanAgo(createdAt: String, now: OffsetDateTime): String? {
val start = parseInstant(createdAt) ?: return null
val seconds = Duration.between(start, now).seconds.coerceAtLeast(0)
return when {
seconds < 60 -> "just now"
seconds < 3600 -> "${seconds / 60}m ago"
seconds < 86_400 -> "${seconds / 3600}h ago"
else -> "${seconds / 86_400}d ago"
}
}
@@ -1,7 +1,9 @@
package net.awan.pipelines.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
@@ -14,6 +16,7 @@ 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
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@ -27,18 +30,26 @@ 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
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import java.time.OffsetDateTime
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.FilterCheckItem
import net.awan.pipelines.ui.components.FilterMenu
import net.awan.pipelines.ui.components.FilterSectionHeader
import net.awan.pipelines.ui.components.ListRow
import net.awan.pipelines.ui.components.LoadPhase
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.PaneIdentity
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.RunStatusChip
import net.awan.pipelines.ui.components.SortMenu
import net.awan.pipelines.ui.components.StateCrossfade
import net.awan.pipelines.ui.components.animateListItem
import net.awan.pipelines.ui.components.listLoadPhase
@@ -55,9 +66,40 @@ fun PipelineListScreen(
covered: Boolean = false,
) {
val state by vm.pipelines.collectAsStateWithLifecycle()
val runsState by vm.runs.collectAsStateWithLifecycle()
val sortKey by vm.pipelineSort.collectAsStateWithLifecycle()
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("") }
LaunchedEffect(Unit) { vm.refreshPipelines() }
// 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.
LaunchedEffect(Unit) {
vm.refreshPipelines()
vm.refreshRuns()
}
// "How long ago" is anchored once per composition, not recomputed per row.
val now = remember { OffsetDateTime.now() }
// 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.
val runsKnown = runsState.data != null
val onClearFilters: () -> Unit = {
vm.setPipelineFilterPresence("")
vm.setPipelineFilterRunStatuses("")
query = ""
}
// A covered pane shows its compact identity only; the search field and list
// must never be drawn squeezed into the peek strip.
@@ -79,7 +121,26 @@ fun PipelineListScreen(
title = { Text("Pipelines") },
windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
actions = {
IconButton(onClick = vm::refreshPipelines) {
PipelineFilterControl(
filters = filters,
onPresence = { vm.setPipelineFilterPresence(it.storageKey) },
onRunStatuses = { vm.setPipelineFilterRunStatuses(encodeRunStates(it)) },
onClear = onClearFilters,
)
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()
vm.refreshRuns()
},
) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh pipelines")
}
},
@@ -95,33 +156,58 @@ fun PipelineListScreen(
singleLine = true,
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
)
val pipelines = (state.data ?: emptyList())
.filter { it.name.contains(query, ignoreCase = true) }
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 queryActive = query.isNotBlank()
val filtersActive = filters.isActive && runsKnown
StateCrossfade(
phase = listLoadPhase(
loading = state.loading,
error = state.error,
hasData = state.data != null,
emptyMessage = if (pipelines.isEmpty()) {
if (query.isBlank()) "No pipelines are defined on this server."
else "No pipelines match \"$query\"."
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.
"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 {
"No pipelines match the current filters."
}
} else {
null
},
emptyActionLabel = if (items.isEmpty() && all.isNotEmpty()) "Clear filters" else null,
),
) { phase ->
when (phase) {
LoadPhase.Loading -> LoadingState("Loading pipelines…")
is LoadPhase.Error -> ErrorState(phase.message, onRetry = vm::refreshPipelines)
is LoadPhase.Empty -> EmptyState(phase.message)
is LoadPhase.Empty -> EmptyState(
phase.message,
actionLabel = phase.actionLabel,
onAction = if (phase.actionLabel != null) onClearFilters else null,
)
LoadPhase.Content -> LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(vertical = 8.dp),
) {
items(pipelines, key = { it.id }) { pipeline ->
items(items, key = { it.id }) { pipeline ->
PipelineRow(
pipeline = pipeline,
selected = pipeline.id == selectedId,
badge = badges[pipeline.id],
runsKnown = runsKnown,
onClick = { onOpen(pipeline.id, pipeline.version) },
modifier = animateListItem(),
)
@@ -140,15 +226,55 @@ 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.
*/
@Composable
private fun PipelineFilterControl(
filters: PipelineFilters,
onPresence: (RunPresence) -> Unit,
onRunStatuses: (Set<RunState>) -> Unit,
onClear: () -> Unit,
) {
FilterMenu(
activeCount = filters.activeCount,
contentDescription = "Filter pipelines",
resetLabel = "Clear filters",
onReset = onClear,
) { dismiss ->
FilterSectionHeader("Runs")
RunPresence.entries.forEach { presence ->
FilterCheckItem(presence.label, filters.presence == presence) {
onPresence(presence)
dismiss()
}
}
HorizontalDivider()
FilterSectionHeader("Last run status")
RUN_STATUS_FILTERS.forEach { state ->
FilterCheckItem(state.label, state in filters.lastRunStatuses) {
onRunStatuses(filters.lastRunStatuses.toggle(state))
}
}
}
}
/**
* One pipeline as a row of the shared real list: a leading workflow glyph, the
* name as the title and the id/version/stage-count as the secondary line. The
* row is selected when its pipeline is the one open in the detail pane.
* name as the title, the id/version/stage-count as the secondary line and the
* last-run facts (status chip, how long ago, duration, run id) below. The row is
* selected when its pipeline is the one open in the detail pane. Before the run
* history has loaded the last-run line is omitted; once it has, a pipeline with
* no recorded run says so explicitly.
*/
@Composable
private fun PipelineRow(
pipeline: PipelineSummary,
selected: Boolean,
badge: PipelineRunBadge?,
runsKnown: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
@@ -185,5 +311,29 @@ private fun PipelineRow(
overflow = TextOverflow.Ellipsis,
)
}
if (runsKnown) {
if (badge == null) {
Text(
NO_RUNS_RECORDED,
style = text.meta,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
} else {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
RunStatusChip(badge.state)
Text(
badge.metaLine(),
style = text.meta,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
}
@@ -53,6 +53,7 @@ import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.ArtifactGroup
import net.awan.pipelines.ui.LoadState
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.components.ColoredChip
import net.awan.pipelines.ui.components.DetailTabBody
import net.awan.pipelines.ui.components.DetailTabs
import net.awan.pipelines.ui.components.ErrorState
@@ -70,6 +71,7 @@ import net.awan.pipelines.ui.components.detailLoadPhase
import net.awan.pipelines.ui.components.rememberPaneContent
import net.awan.pipelines.ui.components.rememberSectionExpansion
import net.awan.pipelines.ui.components.runDetailTabs
import net.awan.pipelines.ui.components.runStateIcon
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.displayText
import net.awan.pipelines.ui.formatDuration
@@ -78,6 +80,8 @@ import net.awan.pipelines.ui.graph.ArtifactGallery
import net.awan.pipelines.ui.graph.ArtifactSelection
import net.awan.pipelines.ui.graph.ArtifactSelectionScaffold
import net.awan.pipelines.ui.graph.WorkflowGraph
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.theme.pipelinesText
@@ -418,7 +422,11 @@ private fun RunGraphTab(
onStageTap: (String, Int) -> Unit,
) {
val text = pipelinesText()
val runState = remember(run.id, run.steps) { RunGraphState.from(run) }
// Keyed on the fields RunGraphState.from reads (steps, executing, current
// stage) so a run that finishes without a new step still stops animating.
val runState = remember(run.id, run.steps, run.executing, run.currentStage) {
RunGraphState.from(run)
}
// Grouped once per step-list change; the sheet opened from the graph starts on
// the most recent visit of the tapped stage.
val timeline = remember(run.steps) { runTimeline(run.steps) }
@@ -435,7 +443,7 @@ private fun RunGraphTab(
Text("This server did not include the run graph.", style = text.meta)
} else {
Text(
"Executed stages and routes are highlighted; the rest are dimmed. Pinch to zoom, drag to pan, tap a stage for details.",
"The running stage pulses with its elapsed time and executed routes flow; a finished run settles, and with animations off the running stage stays marked. Solid means executed, dashed and outlined not executed; executed success and failure routes are drawn thickest. Pinch to zoom, drag to pan, tap a stage for details.",
style = text.meta,
)
WorkflowGraph(
@@ -662,6 +670,13 @@ private fun TimelineRow(entry: TimelineEntry, onClick: () -> Unit) {
val text = pipelinesText()
val state = runStateOf(entry.step.outcome.ifBlank { entry.step.status })
val chipLabel = entry.outcomeLabel.ifBlank { state.label }
// A visit's chip and glyph are a *stage outcome*, not the run status, so they
// take the graph's outcome palette and agree with the workflow graph instead
// of being mapped through the run-status colours (the two are different
// vocabularies). Built once per scheme, from the same factory the graph uses.
val scheme = MaterialTheme.colorScheme
val outcomeColors = remember(scheme) { graphColors(scheme) }
val outcomeTint = outcomeColor(entry.step.outcome.ifBlank { entry.step.status }, outcomeColors)
Row(
modifier = Modifier
.fillMaxWidth()
@@ -674,6 +689,7 @@ private fun TimelineRow(entry: TimelineEntry, onClick: () -> Unit) {
state = state,
contentDescription = "Visit ${entry.visit} ${entry.stageKey}: ${state.label}",
modifier = Modifier.size(18.dp),
tint = outcomeTint,
)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Row(
@@ -687,7 +703,7 @@ private fun TimelineRow(entry: TimelineEntry, onClick: () -> Unit) {
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
StatusChip(label = chipLabel, state = state)
ColoredChip(label = chipLabel, color = outcomeTint, icon = runStateIcon(state))
if (hasArtifacts(entry.step)) {
Icon(
imageVector = Icons.Default.AttachFile,
@@ -22,6 +22,7 @@ import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@ -49,11 +50,16 @@ import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.RunStatusChip
import net.awan.pipelines.ui.components.RunStatusIcon
import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.FilterCheckItem
import net.awan.pipelines.ui.components.FilterMenu
import net.awan.pipelines.ui.components.FilterSectionHeader
import net.awan.pipelines.ui.components.ListRow
import net.awan.pipelines.ui.components.LoadPhase
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.StateCrossfade
import net.awan.pipelines.ui.components.animateListItem
import net.awan.pipelines.ui.components.listLoadPhase
@@ -76,8 +82,25 @@ fun RunHistoryScreen(
covered: Boolean = false,
) {
val state by vm.runs.collectAsStateWithLifecycle()
val sortKey by vm.runSort.collectAsStateWithLifecycle()
val sort = RunSort.fromStorage(sortKey)
val statusFilterKey by vm.runFilterStatuses.collectAsStateWithLifecycle()
val pipelineFilterKey by vm.runFilterPipeline.collectAsStateWithLifecycle()
val timeRangeKey by vm.runFilterTimeRange.collectAsStateWithLifecycle()
val filters = RunFilters.fromStorage(statusFilterKey, pipelineFilterKey, timeRangeKey)
LaunchedEffect(Unit) { vm.refreshRuns() }
val onClearFilters: () -> Unit = {
vm.setRunFilterStatuses("")
vm.setRunFilterPipeline("")
vm.setRunFilterTimeRange("")
}
// The pipeline filter choices come from the runs already in hand, folded once
// per history load rather than rebuilt on every recomposition.
val pipelineOptions = remember(state.data) {
pipelineFilterOptions(state.data?.runs.orEmpty())
}
// A covered pane shows its compact identity only; the usage block, sticky day
// headers and run rows must never be drawn squeezed into the peek strip.
if (covered) {
@@ -98,6 +121,22 @@ fun RunHistoryScreen(
title = { Text(if (filterPipelineId == null) "Runs" else "Runs for this pipeline") },
windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
actions = {
RunFilterControl(
filters = filters,
pipelines = pipelineOptions,
onStatuses = { vm.setRunFilterStatuses(encodeRunStates(it)) },
onPipeline = { vm.setRunFilterPipeline(it?.toString().orEmpty()) },
onTimeRange = { vm.setRunFilterTimeRange(it.storageKey) },
onClear = onClearFilters,
)
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")
}
@@ -129,8 +168,11 @@ fun RunHistoryScreen(
runs = state.data?.runs.orEmpty(),
filterPipelineId = filterPipelineId,
selectedRunId = selectedRunId,
sort = sort,
filters = filters,
error = state.error,
onOpenRun = onOpenRun,
onClearFilters = onClearFilters,
modifier = Modifier.padding(padding),
)
}
@@ -138,6 +180,55 @@ fun RunHistoryScreen(
}
}
/**
* The runs-list filter control: status (multi-select), pipeline (single-select)
* and time range, each section labelled inside one menu, with the shared
* active-count badge and one Clear filters action.
*/
@Composable
private fun RunFilterControl(
filters: RunFilters,
pipelines: List<PipelineFilterOption>,
onStatuses: (Set<RunState>) -> Unit,
onPipeline: (Long?) -> Unit,
onTimeRange: (RunTimeRange) -> Unit,
onClear: () -> Unit,
) {
FilterMenu(
activeCount = filters.activeCount,
contentDescription = "Filter runs",
resetLabel = "Clear filters",
onReset = onClear,
) { dismiss ->
FilterSectionHeader("Status")
RUN_STATUS_FILTERS.forEach { state ->
FilterCheckItem(state.label, state in filters.statuses) {
onStatuses(filters.statuses.toggle(state))
}
}
HorizontalDivider()
FilterSectionHeader("Pipeline")
FilterCheckItem("Any pipeline", filters.pipelineId == null) {
onPipeline(null)
dismiss()
}
pipelines.forEach { option ->
FilterCheckItem(option.name, filters.pipelineId == option.id) {
onPipeline(option.id)
dismiss()
}
}
HorizontalDivider()
FilterSectionHeader("Time range")
RunTimeRange.entries.forEach { range ->
FilterCheckItem(range.label, filters.timeRange == range) {
onTimeRange(range)
dismiss()
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun RunHistoryContent(
@@ -145,20 +236,27 @@ private fun RunHistoryContent(
runs: List<RunSummary>,
filterPipelineId: Long?,
selectedRunId: Long?,
sort: RunSort,
filters: RunFilters,
error: String?,
onOpenRun: (Long) -> Unit,
onClearFilters: () -> 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) {
val filtered = if (filterPipelineId == null) {
runs
} else {
runs.filter { it.pipelineId == filterPipelineId }
}
val zone = ZoneId.systemDefault()
groupRunsByDay(filtered, LocalDate.now(zone), zone)
val zone = ZoneId.systemDefault()
val today = LocalDate.now(zone)
// The structural pipeline scope (a run list opened for one pipeline) and the
// user's filters both narrow, with AND semantics; the run history is folded
// once here, not per recomposition.
val scoped = remember(runs, filterPipelineId) {
if (filterPipelineId == null) runs else runs.filter { it.pipelineId == filterPipelineId }
}
val matched = remember(scoped, filters, today, zone) { filterRuns(scoped, filters, today, zone) }
// 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(matched, today, zone, sort) {
groupRunsByDay(matched, today, zone, runComparator(sort))
}
LazyColumn(
@@ -170,13 +268,24 @@ private fun RunHistoryContent(
UsageMetrics(usage, Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
}
}
if (groups.isEmpty()) {
if (scoped.isEmpty()) {
// Nothing exists at all: no filter could reveal a run, so there is no
// clear action.
item(key = "runs-empty") {
Text(
EmptyState(
"No runs have been recorded yet.",
style = pipelinesText().body,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = animateListItem(Modifier.padding(24.dp)),
modifier = animateListItem(),
)
}
} else if (matched.isEmpty()) {
// Runs exist but every one is filtered out: distinguish this from the
// "nothing exists" case and offer the one clear action.
item(key = "runs-filtered-empty") {
EmptyState(
message = "No runs match the current filters.",
actionLabel = "Clear filters",
onAction = onClearFilters,
modifier = animateListItem(),
)
}
} else {
@@ -372,24 +481,26 @@ 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) }
}
internal fun dayLabel(createdAt: String, today: LocalDate, zone: ZoneId): String {
val date = runDate(createdAt, zone) ?: return "Unknown date"
val date = runLocalDate(createdAt, zone) ?: return "Unknown date"
return when (date) {
today -> "Today"
today.minusDays(1) -> "Yesterday"
@@ -397,12 +508,5 @@ internal fun dayLabel(createdAt: String, today: LocalDate, zone: ZoneId): String
}
}
private fun runDate(createdAt: String, zone: ZoneId): LocalDate? {
if (createdAt.isBlank()) return null
return runCatching {
OffsetDateTime.parse(createdAt).atZoneSameInstant(zone).toLocalDate()
}.getOrNull()
}
private val DAY_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM yyyy")
private val START_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM HH:mm")
@@ -81,3 +81,71 @@ internal const val WIDE_RAIL_WIDTH_DP = 200
/** Comfortable max text width for a tab body on a wide window. */
const val DETAIL_MAX_WIDTH_DP = 840
// ---- Workflow graph geometry (ui/graph/WorkflowGraph.kt) -------------------
// The graph's node, edge and legend geometry. These are named here like every
// other app dimension so the graph file imports them instead of writing raw dp
// literals; the values are unchanged from the graph's own tokens.
/** Workflow-graph node width. */
internal val GRAPH_NODE_WIDTH = 150.dp
/** Workflow-graph node minimum height. */
internal val GRAPH_NODE_MIN_HEIGHT = 76.dp
/** Workflow-graph node port spacing. */
internal val GRAPH_NODE_PORT_SPACING = 14.dp
/** Workflow-graph node horizontal gap. */
internal val GRAPH_NODE_H_GAP = 168.dp
/** Workflow-graph content padding. */
internal val GRAPH_PAD = 40.dp
/** Workflow-graph edge-lane spacing. */
internal val GRAPH_EDGE_LANE_SPACING = 34.dp
/** Workflow-graph terminal-row gap. */
internal val GRAPH_TERMINAL_ROW_GAP = 88.dp
/** Workflow-graph edge-track step. */
internal val GRAPH_EDGE_TRACK_STEP = 26.dp
/** Workflow-graph node hairline border. */
internal val GRAPH_NODE_BORDER = 1.dp
/** Workflow-graph selected node border. */
internal val GRAPH_NODE_BORDER_SELECTED = 3.dp
/** Bottom inset of the active node's elapsed-time badge. */
internal val GRAPH_ELAPSED_INSET = 4.dp
/** Workflow-graph orthogonal route corner radius. */
internal val GRAPH_ROUTE_CORNER_RADIUS = 7.dp
/** Tonal outcome-chip horizontal padding. */
internal val GRAPH_EDGE_CHIP_PAD_X = 2.dp
/** Tonal outcome-chip vertical padding. */
internal val GRAPH_EDGE_CHIP_PAD_Y = 1.dp
/** Tonal outcome-chip corner radius. */
internal val GRAPH_EDGE_CHIP_CORNER = 2.dp
/** Legend swatch width. */
internal val GRAPH_LEGEND_SWATCH_WIDTH = 22.dp
/** Legend swatch height. */
internal val GRAPH_LEGEND_SWATCH_HEIGHT = 10.dp
/** How far outside a node the active halo sits. */
internal val GRAPH_ACTIVE_HALO_GAP = 6.dp
/** How thick the active halo ring is. */
internal val GRAPH_ACTIVE_HALO_STROKE = 4.dp
/** Padding applied when fitting the graph to its viewport. */
internal val GRAPH_FIT_PADDING = 16.dp
/** Least graph span kept visible when clamping pan. */
internal val GRAPH_MIN_VISIBLE = 48.dp
@@ -2,6 +2,7 @@ package net.awan.pipelines.data.protocol
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -77,5 +78,34 @@ class GraphSemanticsTest {
assertEquals(setOf("a", "b", "#failure", "#success"), state.visitedStages)
assertTrue(GraphRoute("a", "error", "#failure") in state.takenRoutes)
assertEquals("b", state.currentStage)
// A finished run animates nothing: no executing flag, no live start.
assertFalse(state.executing)
assertNull(state.currentStageStartedAt)
}
@Test
fun runGraphStateCarriesTheLiveStageAndItsStart() {
val run = RunDetail(
id = 2,
name = "demo",
status = "running",
executing = true,
currentStage = "b",
steps = listOf(
RunStep(
sequence = 1,
stage = "a",
status = "succeeded",
startedAt = "2026-10-16T07:00:00Z",
finishedAt = "2026-10-16T07:01:00Z",
),
RunStep(sequence = 2, stage = "b", status = "running", startedAt = "2026-10-16T07:01:00Z"),
),
)
val state = RunGraphState.from(run)
assertTrue(state.executing)
assertEquals("b", state.currentStage)
// The timer rides on the stage the run is on, from that visit's start.
assertEquals("2026-10-16T07:01:00Z", state.currentStageStartedAt)
}
}
@@ -33,6 +33,19 @@ class FormatTest {
assertNull(formatDuration("2026-10-15T02:05:00Z", "2026-10-15T02:00:00Z"))
}
@Test
fun secondsSinceCountsFromTheStartAndIsSafe() {
// 2026-10-15T02:00:00Z in epoch millis, plus a minute and a bit.
val startMillis = parseInstant("2026-10-15T02:00:00Z")!!.toInstant().toEpochMilli()
assertEquals(0L, secondsSince("2026-10-15T02:00:00Z", startMillis))
assertEquals(125L, secondsSince("2026-10-15T02:00:00Z", startMillis + 125_000))
// A start in the future clamps to 0 rather than going negative.
assertEquals(0L, secondsSince("2026-10-15T02:00:00Z", startMillis - 5_000))
// Blank or unparseable starts are "no elapsed", never a fabricated value.
assertNull(secondsSince("", startMillis))
assertNull(secondsSince("not a timestamp", startMillis))
}
@Test
fun fileChangesSummaryOmitsBlankParts() {
assertEquals("", fileChangesSummary(StageFileChanges()))
@@ -0,0 +1,29 @@
package net.awan.pipelines.ui.components
import androidx.compose.ui.unit.dp
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class FilterMenuTest {
// --- menu height ------------------------------------------------------------
@Test
fun menuHeightGrowsWithTheWindowAndStaysPositive() {
assertEquals(0.85f * 700f, filterMenuMaxHeight(700).value, 0.01f)
assertTrue(filterMenuMaxHeight(360) > 0.dp)
assertTrue(filterMenuMaxHeight(700) > filterMenuMaxHeight(360))
}
// --- accessibility description ---------------------------------------------
@Test
fun descriptionAnnouncesTheActiveCount() {
assertEquals("Filter runs", filterMenuDescription("Filter runs", 0))
assertEquals("Filter runs, 1 filter active", filterMenuDescription("Filter runs", 1))
assertEquals("Filter runs, 2 filters active", filterMenuDescription("Filter runs", 2))
// A negative count (defensive) is treated as no filters, never "-1 filters".
assertEquals("Filter pipelines", filterMenuDescription("Filter pipelines", -1))
}
}
@@ -0,0 +1,73 @@
package net.awan.pipelines.ui.components
import androidx.compose.ui.graphics.Color
import net.awan.pipelines.ui.graph.contrastRatio
import net.awan.pipelines.ui.theme.DarkError
import net.awan.pipelines.ui.theme.DarkPrimary
import net.awan.pipelines.ui.theme.DarkTertiary
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class RunStatusPaletteTest {
/** The dark Pipelines surface every status chip/label is drawn on. */
private val darkSurface = Color(0xFF0E1513)
@Test
fun everyStatusColourMeetsWcagAaOnTheDarkSurface() {
RunState.entries.forEach { state ->
val ratio = contrastRatio(runStateColor(state), darkSurface)
assertTrue("$state contrast $ratio < 4.5", ratio >= 4.5)
}
}
@Test
fun succeededIsGreenNotTheOldAmberTertiary() {
val green = runStateColor(RunState.Succeeded)
assertTrue("green must dominate: $green", green.green > green.red && green.green > green.blue)
assertNotEquals(DarkTertiary, green)
}
@Test
fun runningAndActiveAreTheSameBlueNotTheOldMintPrimary() {
listOf(RunState.Running, RunState.Active).forEach { state ->
val blue = runStateColor(state)
assertTrue("blue must dominate: $blue", blue.blue > blue.red && blue.blue > blue.green)
assertNotEquals(DarkPrimary, blue)
}
assertEquals(runStateColor(RunState.Running), runStateColor(RunState.Active))
}
@Test
fun failedIsTheAppErrorRed() {
assertEquals(DarkError, runStateColor(RunState.Failed))
}
@Test
fun interruptedIsAmberAndDistinctFromFailure() {
val amber = runStateColor(RunState.Interrupted)
assertTrue(
"amber needs red>blue and green>blue: $amber",
amber.red > amber.blue && amber.green > amber.blue,
)
assertNotEquals(DarkError, amber)
}
@Test
fun queuedIsNeutralNotRunningBlue() {
val queued = runStateColor(RunState.Queued)
assertNotEquals(runStateColor(RunState.Running), queued)
val spread = maxOf(queued.red, queued.green, queued.blue) -
minOf(queued.red, queued.green, queued.blue)
assertTrue("queued should be near-grey: $queued", spread < 0.1f)
}
@Test
fun everyEntryHasARationale() {
RunState.entries.forEach { state ->
assertTrue("$state needs a rationale", RunStatusPalette.of(state).rationale.isNotBlank())
}
}
}
@@ -0,0 +1,147 @@
package net.awan.pipelines.ui.graph
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.GraphRoute
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.data.protocol.Stage
import net.awan.pipelines.data.protocol.edges
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.abs
/**
* The graph's motion is a pure decision: which node/edge is in which visual
* state, and whether the graph animates at all, are functions of the run state
* only. These tests assert that policy directly, with no frame clock, so a
* finished run, a paused graph and the animations-off setting are all covered
* without timing a single frame.
*/
class GraphMotionTest {
private fun stage(key: String, edges: Map<String, String>) = Stage(key = key, edges = edges)
private fun graph() = Graph(
stages = listOf(
stage("planner", mapOf("success" to "implementer", "error" to "#failure")),
stage("implementer", mapOf("success" to "reviewer", "error" to "#failure")),
stage("reviewer", mapOf("success" to "#success", "error" to "#failure")),
),
)
private fun takenRoute() = graph().edges().first { it.source == "planner" && it.outcome == "success" }
private fun untakenRoute() = graph().edges().first { it.source == "planner" && it.outcome == "error" }
/** A live run paused on `implementer`, with a recorded start for the tick. */
private fun liveRun(): RunGraphState {
val taken = takenRoute()
return RunGraphState(
visitedStages = setOf("planner", "implementer"),
takenRoutes = setOf(GraphRoute(taken.source, taken.outcome, taken.target)),
currentStage = "implementer",
executing = true,
currentStageStartedAt = "2026-10-16T07:36:56+01:00",
)
}
private fun finishedRun(): RunGraphState =
liveRun().copy(executing = false, currentStageStartedAt = null)
@Test
fun graphAnimatesOnlyForALiveRunOnScreenWithAnimationsEnabled() {
val live = liveRun()
assertTrue(graphShouldAnimate(live, animationsEnabled = true, onScreen = true))
// None of the three gates alone is enough.
assertFalse("finished runs never animate", graphShouldAnimate(finishedRun(), true, true))
assertFalse("animations disabled", graphShouldAnimate(live, animationsEnabled = false, onScreen = true))
assertFalse("off screen", graphShouldAnimate(live, animationsEnabled = true, onScreen = false))
assertFalse("definition view", graphShouldAnimate(null, animationsEnabled = true, onScreen = true))
}
@Test
fun theRunningStageIsTheOnlyActiveNode() {
val live = liveRun()
assertEquals(NodeMotion.Active, nodeMotion("implementer", live))
assertEquals(NodeMotion.Visited, nodeMotion("planner", live))
assertEquals(NodeMotion.Unvisited, nodeMotion("reviewer", live))
assertEquals(NodeMotion.Unvisited, nodeMotion("#success", live))
}
/**
* The live stage is active even before its step is recorded: [visitedStages]
* comes from the recorded steps, so a just-started stage can lag it. The halo
* must not depend on that ordering.
*/
@Test
fun theExecutingStageIsActiveEvenBeforeItsStepIsRecorded() {
val noStepsYet = RunGraphState(
visitedStages = emptySet(),
takenRoutes = emptySet(),
currentStage = "implementer",
executing = true,
currentStageStartedAt = "2026-10-16T07:36:56+01:00",
)
assertEquals(NodeMotion.Active, nodeMotion("implementer", noStepsYet))
}
@Test
fun aFinishedRunHasNoActiveNode() {
val finished = finishedRun()
assertEquals(NodeMotion.Visited, nodeMotion("implementer", finished))
assertEquals(NodeMotion.Visited, nodeMotion("planner", finished))
assertEquals(NodeMotion.Unvisited, nodeMotion("reviewer", finished))
}
@Test
fun theDefinitionViewIsEntirelySettledAndStatic() {
for (key in listOf("planner", "implementer", "reviewer", "#success", "#failure")) {
assertEquals(key, NodeMotion.Visited, nodeMotion(key, null))
}
}
@Test
fun takenRoutesFlowOnlyWhileTheRunIsLive() {
assertEquals(EdgeMotion.Flowing, edgeMotion(takenRoute(), liveRun()))
assertEquals(EdgeMotion.Settled, edgeMotion(takenRoute(), finishedRun()))
assertEquals(EdgeMotion.Unvisited, edgeMotion(untakenRoute(), liveRun()))
assertEquals(EdgeMotion.Unvisited, edgeMotion(untakenRoute(), finishedRun()))
// Definition view: every route is executed, so settled/static (as before).
assertEquals(EdgeMotion.Settled, edgeMotion(takenRoute(), null))
assertEquals(EdgeMotion.Settled, edgeMotion(untakenRoute(), null))
}
/**
* The active halo is a smooth pulse, not a blink: it stays visible, changes
* gradually between samples, both rises and falls, wraps seamlessly, and has
* a clear peak (not two alternating values).
*/
@Test
fun pulseAlphaIsABoundedSmoothNonBinaryRhythm() {
var previous = pulseAlpha(0f)
var sawIncrease = false
var sawDecrease = false
for (i in 1..100) {
val value = pulseAlpha(i / 100f)
assertTrue("in (0,1]: $value", value > 0f && value <= 1f)
assertTrue("always visible: $value", value > 0.2f)
if (value > previous) sawIncrease = true
if (value < previous) sawDecrease = true
assertTrue("continuous at $i ($value vs $previous)", abs(value - previous) < 0.1f)
previous = value
}
assertTrue("rises then falls", sawIncrease && sawDecrease)
// Periodic: the cycle wraps without a jump.
assertEquals(pulseAlpha(0f), pulseAlpha(1f), 0.0001f)
// A clear peak early in the cycle and a trough later; not a two-value blink.
assertTrue(pulseAlpha(0.25f) > pulseAlpha(0.75f))
assertTrue(pulseAlpha(0.25f) - pulseAlpha(0.75f) > 0.2f)
}
@Test
fun staticHaloIsClearlyVisible() {
assertTrue(ACTIVE_HALO_STATIC_ALPHA in 0.5f..1f)
assertTrue(ACTIVE_HALO_STATIC_ALPHA > 0f)
}
}
@@ -1,7 +1,10 @@
package net.awan.pipelines.ui.graph
import androidx.compose.ui.graphics.Color
import net.awan.pipelines.data.protocol.GraphEdge
import net.awan.pipelines.data.protocol.GraphRoute
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunGraphState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@@ -98,6 +101,108 @@ class GraphPaletteTest {
assertTrue(contrastRatio(errorRole, darkSurface) >= 4.5)
}
/**
* The emphasis helper keeps the outcome hue and value and only raises
* saturation, so a stronger pass/fail stroke is still recognisably the same
* success/failure colour.
*/
@Test
fun boostSaturationRaisesSaturationButKeepsHueValueAndAlpha() {
val base = successRole
val boosted = boostSaturation(base, 1.6f)
assertTrue(saturationOf(boosted) > saturationOf(base))
assertEquals(hueOf(base), hueOf(boosted), 1f)
assertEquals(valueOf(base), valueOf(boosted), 0.001f)
assertEquals(base.alpha, boosted.alpha, 0.001f)
// A second hue is left on its own hue, not shifted toward the first.
val red = errorRole
assertEquals(hueOf(red), hueOf(boostSaturation(red, 1.6f)), 1f)
}
@Test
fun boostSaturationIsSafeAndClampedAtTheEdges() {
val base = successRole
// A no-op factor, and invalid factors, return the colour unchanged.
assertEquals(base, boostSaturation(base, 1f))
assertEquals(base, boostSaturation(base, 0f))
assertEquals(base, boostSaturation(base, -1f))
assertEquals(base, boostSaturation(base, Float.NaN))
// Achromatic colours have no saturation to raise.
assertEquals(Color.Gray, boostSaturation(Color.Gray, 2f))
// An already fully-saturated colour clamps at 1 instead of overshooting.
assertEquals(Color.Red, boostSaturation(Color.Red, 2f))
}
/**
* Only an executed pass/fail edge is emphasised: its stroke is the stronger
* same-hue colour, while a non-pass/fail edge and a not-executed edge keep
* their exact outcome colour.
*/
@Test
fun onlyExecutedPassFailStrokesAreSaturatedFurther() {
val colors = colors()
val success = GraphEdge(1, "a", "success", Protocol.SUCCESS_END, "success")
val blocked = GraphEdge(2, "a", "blocked", Protocol.FAILURE_END, "blocked")
val error = GraphEdge(3, "b", "error", Protocol.FAILURE_END, "error")
val executed = RunGraphState(
visitedStages = setOf("a"),
takenRoutes = setOf(GraphRoute("a", "success", Protocol.SUCCESS_END)),
currentStage = "a",
)
val baseSuccess = outcomeColor("success", colors)
val strokeSuccess = edgeStrokeColor(success, executed, colors)
assertEquals(hueOf(baseSuccess), hueOf(strokeSuccess), 1f)
assertTrue(saturationOf(strokeSuccess) > saturationOf(baseSuccess))
// A non-pass/fail edge and a not-executed pass/fail edge are untouched.
assertEquals(outcomeColor("blocked", colors), edgeStrokeColor(blocked, executed, colors))
assertEquals(outcomeColor("error", colors), edgeStrokeColor(error, executed, colors))
}
/** Hue in degrees, matching the conversion [boostSaturation] uses. */
private fun hueOf(color: Color): Float {
val max = maxOf(color.red, color.green, color.blue)
val min = minOf(color.red, color.green, color.blue)
val delta = max - min
if (delta == 0f) return 0f
val h = when (max) {
color.red -> ((color.green - color.blue) / delta + 6f) % 6f
color.green -> (color.blue - color.red) / delta + 2f
else -> (color.red - color.green) / delta + 4f
}
return h * 60f
}
private fun saturationOf(color: Color): Float {
val max = maxOf(color.red, color.green, color.blue)
val min = minOf(color.red, color.green, color.blue)
return if (max <= 0f) 0f else (max - min) / max
}
private fun valueOf(color: Color): Float = maxOf(color.red, color.green, color.blue)
/**
* [tonalFill] blends a raised surface toward the accent by the given fraction,
* so a node/label fill carries a subtle tint of its semantic colour while
* staying a surface; the fraction is clamped so a caller never overshoots.
*/
@Test
fun tonalFillBlendsTowardTheAccentAndClampsTheFraction() {
val surface = darkSurface
val accent = Color(0xFFFF0000)
// Both endpoints are reproduced exactly on the channel.
assertEquals(surface.red, tonalFill(surface, accent, 0f).red, 0.0001f)
assertEquals(accent.red, tonalFill(surface, accent, 1f).red, 0.0001f)
// A mid tint sits strictly between the two and keeps the surface's alpha.
val mid = tonalFill(surface, accent, 0.2f)
assertTrue(mid.red > surface.red && mid.red < accent.red)
assertEquals(surface.alpha, mid.alpha, 0.0001f)
// Out-of-range fractions clamp to the endpoints instead of overshooting.
assertEquals(surface.red, tonalFill(surface, accent, -1f).red, 0.0001f)
assertEquals(accent.red, tonalFill(surface, accent, 2f).red, 0.0001f)
}
@Test
fun nodeKindIsDeterministicAndCoversEveryKind() {
assertEquals(GraphNodeKind.Model, graphNodeKind(false, "planner", null))
@@ -4,9 +4,13 @@ import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.unit.Density
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.GraphRoute
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.data.protocol.Stage
import net.awan.pipelines.data.protocol.edges
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -484,6 +488,166 @@ class WorkflowGraphTest {
}
}
/**
* The executed/inactive predicates are the one definition of the two states:
* the definition-only view (no run) is entirely executed, and under a run
* only the visited stages and recorded routes are.
*/
@Test
fun executedPredicatesSeparateDefinitionViewFromaRun() {
val graph = sampleGraph()
val taken = graph.edges().first { it.source == "planner" && it.outcome == "success" }
val notTaken = graph.edges().first { it.source == "planner" && it.outcome == "error" }
// No run selected: every stage and route is executed (definition view,
// unchanged today).
assertTrue(stageIsExecuted("planner", null))
assertTrue(stageIsExecuted("ui_reviewer", null))
assertTrue(edgeIsExecuted(taken, null))
val runState = RunGraphState(
visitedStages = setOf("planner", "implementer"),
takenRoutes = setOf(GraphRoute("planner", "success", "implementer")),
currentStage = "implementer",
)
assertTrue(stageIsExecuted("planner", runState))
assertTrue(stageIsExecuted("implementer", runState))
assertFalse(stageIsExecuted("reviewer", runState))
assertFalse(stageIsExecuted("#success", runState))
assertTrue(edgeIsExecuted(taken, runState))
assertFalse(edgeIsExecuted(notTaken, runState))
}
/**
* The emphasis contract: an executed `success`/`error` edge uses the widest
* named stroke token, every other executed outcome a finer one and a
* not-executed edge the finest, with the arrowhead scaled to match. The
* definition-only view applies the same pass/fail emphasis.
*/
@Test
fun executedPassFailEdgesAreTheWidest() {
val graph = sampleGraph()
val success = graph.edges().first { it.outcome == "success" }
val error = graph.edges().first { it.outcome == "error" }
val other = graph.edges().first { it.outcome == "blocked" }
val untaken = graph.edges().first { it.outcome == "rejected" }
val runState = RunGraphState(
visitedStages = setOf("planner", "implementer", "reviewer"),
takenRoutes = setOf(
GraphRoute(success.source, success.outcome, success.target),
GraphRoute(error.source, error.outcome, error.target),
GraphRoute(other.source, other.outcome, other.target),
),
currentStage = "reviewer",
)
val passFailWidth = edgeStrokeWidth(success, runState)
assertEquals(passFailWidth, edgeStrokeWidth(error, runState), 0.001f)
assertTrue(edgeStrokeWidth(other, runState) < passFailWidth)
assertTrue(edgeStrokeWidth(untaken, runState) < edgeStrokeWidth(other, runState))
assertTrue(edgeStrokeWidth(untaken, runState) > 0f)
// The arrowhead scales with the heavier stroke.
assertEquals(edgeArrowHeadSize(success, runState), edgeArrowHeadSize(error, runState), 0.001f)
assertTrue(edgeArrowHeadSize(success, runState) > edgeArrowHeadSize(other, runState))
// The definition-only view emphasises the same pass/fail edges.
assertEquals(passFailWidth, edgeStrokeWidth(success, null), 0.001f)
assertTrue(isEmphasizedEdge(success, runState))
assertFalse(isEmphasizedEdge(other, runState))
assertFalse(isEmphasizedEdge(untaken, runState))
}
/** Only `success` and `error` are the decisive, emphasised outcomes. */
@Test
fun onlySuccessAndErrorArePassFailOutcomes() {
assertTrue(isPassFailOutcome("success"))
assertTrue(isPassFailOutcome("error"))
for (outcome in listOf("blocked", "rejected", "skipped", "exhausted", "approved", "done", "")) {
assertFalse(outcome, isPassFailOutcome(outcome))
}
}
/**
* The not-executed dash pattern is a real on/off rhythm, not a faded tint: a
* positive, even-length interval list so a dashed stroke reads differently
* from the solid executed one.
*/
@Test
fun inactiveDashPatternIsARealDashRhythm() {
assertTrue(INACTIVE_DASH_INTERVALS.isNotEmpty())
assertEquals(0, INACTIVE_DASH_INTERVALS.size % 2)
assertTrue(INACTIVE_DASH_INTERVALS.all { it > 0f && it.isFinite() })
}
/**
* The one-line legend names both states, executed first, with exactly one
* entry flagged executed so the two swatches cannot both claim solid.
*/
@Test
fun legendNamesBothStatesWithExecutedFirst() {
assertEquals(listOf("Executed", "Not executed"), GRAPH_LEGEND.map { it.label })
assertTrue(GRAPH_LEGEND.first().executed)
assertFalse(GRAPH_LEGEND.last().executed)
assertEquals(1, GRAPH_LEGEND.count { it.executed })
}
/**
* The node label the graph shows is readable: a terminal's all-caps keyword
* becomes title case (no unnecessary all-caps), while a stage keeps its
* declared key.
*/
@Test
fun nodeDisplayLabelsAreReadableAndKeepStageKeys() {
assertEquals("Success", nodeDisplayLabel(Protocol.SUCCESS_END))
assertEquals("Failure", nodeDisplayLabel(Protocol.FAILURE_END))
assertEquals("ui_reviewer", nodeDisplayLabel("ui_reviewer"))
assertEquals("planner", nodeDisplayLabel("planner"))
}
/**
* A heavier line always carries a proportionally larger filled arrowhead: one
* consistent scale ties the head length to the stroke width, so the pass/fail
* head dominates exactly as its stroke does.
*/
@Test
fun arrowHeadScalesWithTheStrokeItTerminates() {
val graph = sampleGraph()
val success = graph.edges().first { it.outcome == "success" }
val other = graph.edges().first { it.outcome == "blocked" }
val runState = RunGraphState(
visitedStages = setOf(success.source, other.source),
takenRoutes = setOf(
GraphRoute(success.source, success.outcome, success.target),
GraphRoute(other.source, other.outcome, other.target),
),
currentStage = success.source,
)
val successRatio = edgeArrowHeadSize(success, runState) / edgeStrokeWidth(success, runState)
val otherRatio = edgeArrowHeadSize(other, runState) / edgeStrokeWidth(other, runState)
assertEquals(successRatio, otherRatio, 0.001f)
assertTrue(edgeArrowHeadSize(success, runState) > edgeArrowHeadSize(other, runState))
}
/**
* The rounded-corner cut at a route bend is the shared radius, floored to half
* the shorter adjacent segment so two cut-backs can never meet or cross; a
* degenerate adjacent segment yields no cut instead of dividing by zero. It
* works on the already-measured segment lengths, so a bend measures them once.
*/
@Test
fun cornerCutNeverExceedsHalfTheShorterSegment() {
val radius = 18f
// Both adjacent segments are long enough to take the full radius.
assertEquals(radius, cornerCutRadius(100f, 100f, radius), 0.001f)
// A short incoming segment halves the cut.
assertEquals(10f, cornerCutRadius(20f, 100f, radius), 0.001f)
// A short outgoing segment halves the cut.
assertEquals(15f, cornerCutRadius(100f, 30f, radius), 0.001f)
// A degenerate adjacent segment yields no cut.
assertEquals(0f, cornerCutRadius(0f, 100f, radius), 0.001f)
}
private fun assertNoSharedRuns(layout: GraphLayout) {
val edges = layout.edges
for (i in edges.indices) {
@@ -0,0 +1,231 @@
package net.awan.pipelines.ui.screens
import java.time.LocalDate
import java.time.ZoneOffset
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.ui.components.RunState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ListFilterTest {
private val today = LocalDate.of(2026, 10, 16)
private val zone = ZoneOffset.UTC
private fun pipeline(id: Long, name: String = "p$id") =
PipelineSummary(id = id, name = name, version = 1, stages = 1)
private fun run(
id: Long,
pipelineId: Long = 1,
name: String = "p$pipelineId",
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 runFiltersFromStorageParsesEveryFacetAndFallsBackForStaleValues() {
assertEquals(
RunFilters(setOf(RunState.Succeeded, RunState.Failed), 7L, RunTimeRange.Last7Days),
RunFilters.fromStorage("succeeded,failed", "7", "last_7_days"),
)
// An unknown status token is dropped rather than crashing.
assertEquals(
setOf(RunState.Succeeded),
RunFilters.fromStorage("succeeded,bogus", null, null).statuses,
)
// Stale/blank/unknown values fall back to the defaults.
assertEquals(RunFilters.Default, RunFilters.fromStorage(null, null, null))
assertEquals(RunFilters.Default, RunFilters.fromStorage("", "", ""))
assertEquals(RunFilters.Default, RunFilters.fromStorage("nope", "not-a-number", "no_such_range"))
}
@Test
fun pipelineFiltersFromStorageParsesAndFallsBack() {
assertEquals(
PipelineFilters(RunPresence.NoRuns, setOf(RunState.Failed)),
PipelineFilters.fromStorage("no_runs", "failed"),
)
assertEquals(PipelineFilters.Default, PipelineFilters.fromStorage(null, null))
assertEquals(PipelineFilters.Default, PipelineFilters.fromStorage("garbage", "garbage"))
}
@Test
fun encodeDecodeRoundTripsAndToleratesGarbage() {
val states = setOf(RunState.Failed, RunState.Queued)
assertEquals(states, decodeRunStates(encodeRunStates(states)))
// Ordinal order, so the stored string is stable whatever the set order.
assertEquals("queued,failed", encodeRunStates(states))
assertEquals(emptySet<RunState>(), decodeRunStates(""))
assertEquals(emptySet<RunState>(), decodeRunStates(null))
assertEquals(setOf(RunState.Running), decodeRunStates("bogus,running,,"))
}
// --- run status -------------------------------------------------------------
@Test
fun anEmptyStatusSetMatchesAnyStatus() {
assertTrue(runMatchesStatuses(run(1, status = "running"), emptySet()))
assertTrue(runMatchesStatuses(run(1, status = ""), emptySet()))
}
@Test
fun statusFilterIsTheUnionOfTheSelectedStates() {
val statuses = setOf(RunState.Failed, RunState.Canceled)
assertTrue(runMatchesStatuses(run(1, status = "failed"), statuses))
assertTrue(runMatchesStatuses(run(2, status = "canceled"), statuses))
assertFalse(runMatchesStatuses(run(3, status = "succeeded"), statuses))
// The app-only buckets are not offered, so they never match a selection.
assertFalse(runMatchesStatuses(run(4, status = "active"), statuses))
assertFalse(runMatchesStatuses(run(5, status = "made-up"), statuses))
}
// --- run pipeline -----------------------------------------------------------
@Test
fun pipelineFilterMatchesOnlyThatPipelineAndNullMeansAny() {
assertTrue(runMatchesPipeline(run(1, pipelineId = 5), 5))
assertFalse(runMatchesPipeline(run(1, pipelineId = 5), 6))
assertTrue(runMatchesPipeline(run(1, pipelineId = 5), null))
}
// --- run time range ---------------------------------------------------------
@Test
fun timeRangeWindowsAreInclusiveCalendarDaysEndingToday() {
fun at(date: String) = run(1, createdAt = "${date}T09:00:00Z")
// Today.
assertTrue(runMatchesTimeRange(at("2026-10-16"), RunTimeRange.Today, today, zone))
assertFalse(runMatchesTimeRange(at("2026-10-15"), RunTimeRange.Today, today, zone))
// Last 7 days covers today and the six days before it.
assertTrue(runMatchesTimeRange(at("2026-10-16"), RunTimeRange.Last7Days, today, zone))
assertTrue(runMatchesTimeRange(at("2026-10-10"), RunTimeRange.Last7Days, today, zone))
assertFalse(runMatchesTimeRange(at("2026-10-09"), RunTimeRange.Last7Days, today, zone))
// Last 30 days covers today and the twenty-nine days before it.
assertTrue(runMatchesTimeRange(at("2026-09-17"), RunTimeRange.Last30Days, today, zone))
assertFalse(runMatchesTimeRange(at("2026-09-16"), RunTimeRange.Last30Days, today, zone))
// Any time matches an old run and a blank timestamp alike.
assertTrue(runMatchesTimeRange(at("2020-01-01"), RunTimeRange.AnyTime, today, zone))
assertTrue(runMatchesTimeRange(run(1, createdAt = ""), RunTimeRange.AnyTime, today, zone))
}
@Test
fun blankOrFutureTimestampsNeverMatchAFiniteRange() {
assertFalse(runMatchesTimeRange(run(1, createdAt = ""), RunTimeRange.Today, today, zone))
assertFalse(runMatchesTimeRange(run(1, createdAt = "not-a-date"), RunTimeRange.Last7Days, today, zone))
// A future-dated run (clock skew) is outside every past window.
assertFalse(runMatchesTimeRange(run(1, createdAt = "2026-10-17T09:00:00Z"), RunTimeRange.Today, today, zone))
assertFalse(runMatchesTimeRange(run(1, createdAt = "2026-10-17T09:00:00Z"), RunTimeRange.Last7Days, today, zone))
}
// --- run combination --------------------------------------------------------
@Test
fun defaultRunFiltersNarrowNothing() {
val runs = listOf(run(1, status = "running", createdAt = ""), run(2, status = "failed"))
assertEquals(runs, filterRuns(runs, RunFilters.Default, today, zone))
}
@Test
fun runFacetsCombineWithAnd() {
val filters = RunFilters(
statuses = setOf(RunState.Succeeded),
pipelineId = 2L,
timeRange = RunTimeRange.Today,
)
val runs = listOf(
// Right status but wrong pipeline.
run(1, pipelineId = 1, status = "succeeded", createdAt = "2026-10-16T08:00:00Z"),
// Right pipeline but wrong status.
run(2, pipelineId = 2, status = "failed", createdAt = "2026-10-16T08:00:00Z"),
// Right pipeline/status but outside today.
run(3, pipelineId = 2, status = "succeeded", createdAt = "2026-10-10T08:00:00Z"),
// The one match.
run(4, pipelineId = 2, status = "succeeded", createdAt = "2026-10-16T08:00:00Z"),
)
assertEquals(listOf(4L), filterRuns(runs, filters, today, zone).map { it.id })
}
// --- pipeline run facets ----------------------------------------------------
@Test
fun presenceSplitsPipelinesByWhetherTheyHaveARecordedRun() {
assertTrue(pipelineMatchesPresence(RunPresence.Any, hasRun = false))
assertTrue(pipelineMatchesPresence(RunPresence.HasRuns, hasRun = true))
assertFalse(pipelineMatchesPresence(RunPresence.HasRuns, hasRun = false))
assertTrue(pipelineMatchesPresence(RunPresence.NoRuns, hasRun = false))
assertFalse(pipelineMatchesPresence(RunPresence.NoRuns, hasRun = true))
}
@Test
fun lastRunStatusExcludesRunlessPipelinesAndEmptyMeansAny() {
val failed = setOf(RunState.Failed)
assertTrue(pipelineMatchesLastRunStatus(run(1, status = "failed"), failed))
assertFalse(pipelineMatchesLastRunStatus(run(1, status = "succeeded"), failed))
// No run at all: there is no last-run status, so a selection never matches.
assertFalse(pipelineMatchesLastRunStatus(null, failed))
// An empty selection matches a runless pipeline and any status.
assertTrue(pipelineMatchesLastRunStatus(null, emptySet()))
assertTrue(pipelineMatchesLastRunStatus(run(1, status = "running"), emptySet()))
}
@Test
fun defaultPipelineFiltersNarrowNothing() {
val pipelines = listOf(pipeline(1), pipeline(2))
assertEquals(pipelines, filterPipelines(pipelines, PipelineFilters.Default, emptyMap()))
}
@Test
fun pipelineFiltersCombineWithAnd() {
val filters = PipelineFilters(
presence = RunPresence.HasRuns,
lastRunStatuses = setOf(RunState.Failed),
)
val latest = mapOf(
1L to run(1, pipelineId = 1, status = "succeeded"),
2L to run(2, pipelineId = 2, status = "failed"),
)
val pipelines = listOf(pipeline(1), pipeline(2), pipeline(3))
// No runs (3) fails presence; succeeded last run (1) fails the status.
assertEquals(listOf(2L), filterPipelines(pipelines, filters, latest).map { it.id })
}
@Test
fun pipelineFiltersLeaveTheListUnfilteredUntilRunsAreKnown() {
val filters = PipelineFilters(presence = RunPresence.NoRuns)
val pipelines = listOf(pipeline(1))
// Runs not loaded yet: filtering by them would briefly hide everything.
assertEquals(pipelines, filterPipelines(pipelines, filters, emptyMap(), runsKnown = false))
// Once known, the filter applies (pipeline 1 has no run).
assertEquals(pipelines, filterPipelines(pipelines, filters, emptyMap(), runsKnown = true))
}
// --- pipeline options -------------------------------------------------------
@Test
fun pipelineFilterOptionsAreDistinctNamedFromRunsAndSorted() {
val runs = listOf(
run(1, pipelineId = 7, name = "Zeta"),
run(2, pipelineId = 3, name = "alpha"),
run(3, pipelineId = 7, name = "Zeta"),
run(4, pipelineId = 9, name = ""),
)
val options = pipelineFilterOptions(runs)
assertEquals(listOf(3L, 9L, 7L), options.map { it.id })
assertEquals(listOf("alpha", "Pipeline 9", "Zeta"), options.map { it.name })
assertEquals(3, options.size)
}
}
@@ -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 })
}
}
@@ -0,0 +1,123 @@
package net.awan.pipelines.ui.screens
import java.time.OffsetDateTime
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.ui.components.RunState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class PipelineLastRunTest {
private val now = OffsetDateTime.parse("2026-10-16T12:00:00Z")
private fun run(
id: Long,
pipelineId: Long,
createdAt: String,
finishedAt: String = createdAt,
status: String = "succeeded",
) = RunSummary(
id = id,
pipelineId = pipelineId,
createdAt = createdAt,
finishedAt = finishedAt,
status = status,
)
@Test
fun mostRecentRunWinsEvenWhenTheInputIsNotNewestFirst() {
// Deliberately unsorted: the newer start must win regardless of order.
val badges = pipelineRunBadges(
listOf(
run(7, 10, "2026-10-16T09:00:00Z"),
run(2, 10, "2026-10-16T11:00:00Z"),
run(5, 11, "2026-10-16T08:00:00Z"),
),
now,
)
assertEquals(2L, badges.getValue(10L).runId)
assertEquals(5L, badges.getValue(11L).runId)
}
@Test
fun noRunsYieldsNoBadges() {
assertTrue(pipelineRunBadges(emptyList(), now).isEmpty())
}
@Test
fun unknownPipelineIdIsAbsentFromTheJoin() {
val badges = pipelineRunBadges(listOf(run(1, 10, "2026-10-16T10:00:00Z")), now)
assertEquals(1L, badges.getValue(10L).runId)
assertNull(badges[99L])
}
@Test
fun equalTimestampsBreakTheTieByTheHigherRunId() {
val badges = pipelineRunBadges(
listOf(
run(4, 10, "2026-10-16T10:00:00Z"),
run(9, 10, "2026-10-16T10:00:00Z"),
),
now,
)
assertEquals(9L, badges.getValue(10L).runId)
}
@Test
fun unparseableTimestampsFallBackToRunIdWithoutCrashing() {
val badges = pipelineRunBadges(
listOf(run(3, 10, ""), run(8, 10, "not-a-date")),
now,
)
assertEquals(8L, badges.getValue(10L).runId)
assertNull(badges.getValue(10L).ranAgo)
}
@Test
fun unknownStatusWordYieldsAnUnknownStateNotACrash() {
val badge = pipelineRunBadges(
listOf(run(1, 10, "2026-10-16T10:00:00Z", status = "something-new")),
now,
).getValue(10L)
assertEquals(RunState.Unknown, badge.state)
// The id still renders even when only the status word is unrecognised.
assertTrue(badge.metaLine().endsWith("run 1"))
}
@Test
fun metaLineCarriesAgoDurationAndRunId() {
val badge = pipelineRunBadges(
listOf(run(42, 10, "2026-10-16T11:00:00Z", finishedAt = "2026-10-16T11:01:05Z")),
now,
).getValue(10L)
assertEquals("1h ago · 1m 5s · run 42", badge.metaLine())
}
@Test
fun metaLineOmitsAMissingDuration() {
// A running run has no finished_at, so the duration fragment is dropped.
val badge = pipelineRunBadges(
listOf(run(42, 10, "2026-10-16T11:00:00Z", finishedAt = "", status = "running")),
now,
).getValue(10L)
assertEquals("1h ago · run 42", badge.metaLine())
}
@Test
fun formatRanAgoCoversEachScaleAndRejectsBadInput() {
assertEquals("just now", formatRanAgo("2026-10-16T11:59:30Z", now))
assertEquals("just now", formatRanAgo("2026-10-16T12:05:00Z", now))
assertEquals("5m ago", formatRanAgo("2026-10-16T11:55:00Z", now))
assertEquals("3h ago", formatRanAgo("2026-10-16T09:00:00Z", now))
assertEquals("2d ago", formatRanAgo("2026-10-14T12:00:00Z", now))
assertNull(formatRanAgo("", now))
assertNull(formatRanAgo("not-a-date", now))
}
@Test
fun noRunsWordingIsTheExplicitConstant() {
assertEquals("no runs recorded", NO_RUNS_RECORDED)
}
}
@@ -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 })
}
}
@@ -45,14 +45,11 @@ class DimensTest {
"20.dp" to "List icon glyph size and code-block inner padding (20dp).",
"48.dp" to "Minimum touch target and graph minimum visible span (48dp).",
// Workflow-graph pixel geometry (layout by design, not screen spacing).
"26.dp" to "Workflow-graph lane spacing (26dp).",
"64.dp" to "Workflow-graph terminal gap (64dp).",
"132.dp" to "Workflow-graph node width and horizontal gap (132dp).",
"260.dp" to "Collapsed workflow-graph panel minimum height (GRAPH_PANEL_MIN_HEIGHT).",
// Workflow-graph pixel geometry now lives in ui/theme/Dimens.kt as the
// GRAPH_* tokens, so no graph literal remains here.
// Component container sizes.
"56.dp" to "Artifact thumbnail and graph minimum node height (coincides with PEEK_WIDTH_DP but is content size here).",
"56.dp" to "Artifact thumbnail size (coincides with PEEK_WIDTH_DP but is content size here).",
"96.dp" to "Artifact grid preferred tile edge (ARTIFACT_TILE_DP).",
"320.dp" to "Code block maximum height (CODE_BLOCK_MAX_HEIGHT).",