Merge lane-c: keep the lane's reviewed work

Combine lane-c's incoming work with the local branch.

- PipelinesApp.kt was the only unmerged path: resolution is purely additive over HEAD, keeping HEAD's hoisted selection/onSelectionChange and pendingNav/onPendingNavResolved while adding lane-c's listState wiring and compactLabel/compactIcon.
- graph/StageDetailPane.kt and theme/Dimens.kt auto-merged and retain both sides' changes.
- Incoming branch af68a62 preserved as second parent.
This commit is contained in:
2026-10-16 20:32:11 +01:00
25 changed files with 1862 additions and 387 deletions
@@ -48,6 +48,24 @@ fun formatDuration(start: String, end: String): String? =
internal fun secondsSince(start: String, nowMillis: Long): Long? =
parseInstant(start)?.let { ((nowMillis - it.toInstant().toEpochMilli()) / 1000).coerceAtLeast(0) }
/**
* The time a run has taken so far: while it is still [executing], its live
* elapsed time from its server start timestamp to [nowMillis]; once it has
* finished, its stored total duration. The single rule the runs list's meta line,
* the pipeline last-run line and the run detail summary share, so the same run is
* never described differently in the three places. Null when the start (or, for a
* finished run, the end) is unusable, so the caller omits the value instead of
* printing a blank; a running run with a future start (clock skew) reads as `0s`,
* never a negative.
*/
internal fun runDurationText(
createdAt: String,
finishedAt: String,
executing: Boolean,
nowMillis: Long,
): String? =
if (executing) secondsSince(createdAt, nowMillis)?.let(::formatDuration)
else formatDuration(createdAt, finishedAt)
/**
* Human duration for a whole number of seconds. The single formatting rule for
@@ -29,6 +29,7 @@ import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -183,6 +184,13 @@ fun PipelinesApp(vm: AppViewModel) {
dismissSearch()
}
// One list scroll position each, owned here above the NavHost so it survives
// the destination (and list screen) being recreated when a pane is covered or
// the runs selection changes, as well as a configuration change and process
// death. The list screens only clamp it when the list changed underneath.
val pipelineListState = rememberSaveable(saver = LazyListState.Saver) { LazyListState() }
val runListState = rememberSaveable(saver = LazyListState.Saver) { LazyListState() }
val onNavigate: (TopDestination) -> Unit = { destination ->
if (currentRoute != destination.route) {
navController.navigate(destination.route) {
@@ -234,6 +242,7 @@ fun PipelinesApp(vm: AppViewModel) {
wide = wide,
selection = pipelineSelection,
onSelectionChange = { pipelineSelection = it },
listState = pipelineListState,
onOpenRun = { runId ->
runSelection = PaneSelection(
pane = MasterPane.Detail,
@@ -251,6 +260,7 @@ fun PipelinesApp(vm: AppViewModel) {
onSelectionChange = { runSelection = it },
pendingNav = runSearchNav,
onPendingNavResolved = { runSearchNav = null },
listState = runListState,
)
}
composable("settings") {
@@ -339,6 +349,7 @@ private fun PipelineDestination(
wide: Boolean,
selection: PaneSelection,
onSelectionChange: (PaneSelection) -> Unit,
listState: LazyListState,
onOpenRun: (Long) -> Unit,
) {
val depth = selection.depth
@@ -354,6 +365,8 @@ private fun PipelineDestination(
depth = depth,
wide = wide,
onPopTo = { level -> onSelectionChange(popTo(selection, level)) },
compactLabel = "Pipelines",
compactIcon = Icons.Filled.AccountTree,
backContentDescription = { level -> if (level == 0) "Back to pipelines" else "Back to pipeline" },
pane = { level, covered, paneModifier ->
when (level) {
@@ -365,6 +378,7 @@ private fun PipelineDestination(
modifier = paneModifier,
selectedId = selection.itemId.takeIf { depth >= 1 },
covered = covered,
listState = listState,
)
1 -> rememberPaneContent(
selection.itemId.takeIf { it != 0L }?.let {
@@ -423,6 +437,7 @@ private fun RunsDestination(
onSelectionChange: (PaneSelection) -> Unit,
pendingNav: SearchTarget.Run?,
onPendingNavResolved: () -> Unit,
listState: LazyListState,
) {
val depth = selection.depth
val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) }
@@ -448,6 +463,8 @@ private fun RunsDestination(
depth = depth,
wide = wide,
onPopTo = { level -> onSelectionChange(popTo(selection, level)) },
compactLabel = "Runs",
compactIcon = Icons.Filled.History,
backContentDescription = { level -> if (level == 0) "Back to runs" else "Back to run" },
pane = { level, covered, paneModifier ->
when (level) {
@@ -457,6 +474,7 @@ private fun RunsDestination(
modifier = paneModifier,
selectedRunId = selection.itemId.takeIf { depth >= 1 },
covered = covered,
listState = listState,
)
1 -> rememberPaneContent(
selection.itemId.takeIf { it != 0L }?.let { it to selection.sectionIndex },
@@ -0,0 +1,55 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
/**
* A list's saved scroll position: the index of the first visible item and the
* pixel offset of that item from the viewport's top edge. Both are primitives, so
* the pair round-trips through a Bundle and survives a configuration change or
* process death; it is deliberately independent of any particular list, so the
* restore/clamp rule is pure and unit-testable without a device.
*/
internal data class ListScrollAnchor(val index: Int = 0, val offset: Int = 0)
/**
* The anchor to restore into a list of [itemCount] items: the saved index clamped
* to the nearest valid item, because the list can have shrunk since the anchor was
* written (a filter, a sort, a refresh, items removed). An empty list has no valid
* index, so it stays at the top. The saved pixel offset is kept only when the
* saved item itself survived; a clamped index points at a different item, so it
* starts at its own top rather than part-way down an unrelated row. Never throws,
* and never falls back to the top while the saved item still exists.
*/
internal fun restoredScrollAnchor(anchor: ListScrollAnchor, itemCount: Int): ListScrollAnchor {
if (itemCount <= 0) return ListScrollAnchor()
val index = anchor.index.coerceIn(0, itemCount - 1)
val offset = if (index == anchor.index) anchor.offset else 0
return ListScrollAnchor(index, offset)
}
/**
* Reconciles the live [state] with a list that now has [itemCount] items, so a
* list that changed underneath the operator clamps to the nearest sensible item
* instead of staying past the end (which would draw nothing) or jumping to the
* top. Keyed on [itemCount], so it runs once when the size settles and never on
* the operator's own scrolling — a scroll after coming back is therefore never
* overridden — and an unloaded list ([itemCount] 0) is left alone so a restored
* position is not reset to the top while the data is still on its way.
*/
@Composable
internal fun RestoreListScroll(state: LazyListState, itemCount: Int) {
if (itemCount <= 0) return
LaunchedEffect(itemCount) {
val target = restoredScrollAnchor(
ListScrollAnchor(state.firstVisibleItemIndex, state.firstVisibleItemScrollOffset),
itemCount,
)
if (target.index != state.firstVisibleItemIndex ||
target.offset != state.firstVisibleItemScrollOffset
) {
state.scrollToItem(target.index, target.offset)
}
}
}
@@ -0,0 +1,53 @@
package net.awan.pipelines.ui.components
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.currentStateAsState
import kotlinx.coroutines.delay
/** A live value advances once a second, never per frame. */
private const val LIVE_TICK_MILLIS = 1_000L
/**
* Whether the host activity is resumed. The one background/focus gate every live
* ticking value shares, so a backgrounded app never keeps waking up once a second
* just to repaint a number nobody can see.
*/
@Composable
internal fun hostResumed(): Boolean {
val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState()
return lifecycleState.isAtLeast(Lifecycle.State.RESUMED)
}
/**
* The device clock in epoch millis, advanced once a second while [ticking] is
* true and the host is resumed, and frozen at its last reading otherwise. The
* single ticker behind every live elapsed readout: callers derive their value
* from the server's own start timestamp and this clock, so the numbers stay
* correct after a reconnect (never anchored to when the app happened to load),
* a screen full of running rows runs one coroutine rather than one per row, and
* nothing ticks for a finished run or while the app is backgrounded.
*
* The clock is re-read as the loop (re)starts, so a value frozen while
* backgrounded jumps straight to the correct elapsed on the first frame back.
*/
@Composable
internal fun rememberLiveNowMillis(ticking: Boolean): Long {
var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }
val live = ticking && hostResumed()
LaunchedEffect(live) {
if (!live) return@LaunchedEffect
nowMillis = System.currentTimeMillis()
while (true) {
delay(LIVE_TICK_MILLIS)
nowMillis = System.currentTimeMillis()
}
}
return nowMillis
}
@@ -1,40 +1,119 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.MIN_COVERED_PANE_WIDTH_DP
import net.awan.pipelines.ui.theme.PEEK_WIDTH_DP
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* A covered pane's compact identity: its title and, when there is one, a single
* status/subtitle line, both centred in the peek strip. A covered pane renders
* this instead of its full body, so its tab rail, list, gallery and scrollable
* body are never drawn squeezed into a sliver.
* One labelled statistic a covered pane shows: its [label] (e.g. `runs`) and its
* [value] (e.g. `11`). The label always travels with its value so a reader can
* tell what the number means, and a [detail] statistic is the kind dropped first
* when the strip is too thin.
*/
data class PaneStat(
val label: String,
val value: String,
val detail: Boolean = false,
)
/**
* How much of a covered pane's statistics block fits at a given width: the title
* only ([Title]), the run counts ([Counts]) or the full block including the last
* run and the average duration ([Full]).
*/
internal enum class PaneStatTier { Title, Counts, Full }
/**
* The statistics tier for a covered strip [widthDp]: a strip narrower than one
* tappable peek ([PEEK_WIDTH_DP]) is too thin even for a labelled number, so it
* keeps the title only; a strip at least one minimum covered pane wide plus one
* peek ([MIN_COVERED_PANE_WIDTH_DP] + [PEEK_WIDTH_DP]) has room for the longest
* line (the last run's status and age), so it shows the full block. The
* boundaries reuse the named identity-tier tokens rather than new literals, and
* the decision is pure so it is unit-testable without a device.
*/
internal fun paneStatTier(widthDp: Dp): PaneStatTier = when {
widthDp < PEEK_WIDTH_DP -> PaneStatTier.Title
widthDp < MIN_COVERED_PANE_WIDTH_DP + PEEK_WIDTH_DP -> PaneStatTier.Counts
else -> PaneStatTier.Full
}
/**
* The statistics of [stats] that fit [tier]: nothing at [PaneStatTier.Title]
* (never a bare figure without its label), only the run counts at
* [PaneStatTier.Counts], and every line at [PaneStatTier.Full]. Pure, so the
* degradation rule is asserted in a unit test without composing anything.
*/
internal fun visiblePaneStats(stats: List<PaneStat>, tier: PaneStatTier): List<PaneStat> = when (tier) {
PaneStatTier.Title -> emptyList()
PaneStatTier.Counts -> stats.filterNot { it.detail }
PaneStatTier.Full -> stats
}
/**
* A covered pane's compact identity: its title and, when there are any, a
* compact vertical statistics block, both centred in the peek strip. A covered
* pane renders this instead of its full body, so its tab rail, list, gallery and
* scrollable body are never drawn squeezed into a sliver.
*
* The strip is narrow but the identity is the whole point of it, so the title
* wraps onto a few centered lines rather than becoming an unreadable ellipsis;
* it is the one place a title may legitimately run over more than one line.
* wraps onto a few centered lines rather than becoming an unreadable ellipsis; it
* is the one place a title may legitimately run over more than one line. The
* statistics are secondary to it and degrade with the width ([paneStatTier]):
* each is a label above its own value, only whole statistics are shown, and a
* strip too thin for a labelled number keeps the title alone — never a number
* clipped mid-digit or a figure without its label. [subtitle] remains for the
* panes whose covered identity is a single status/type word (the stage pane)
* rather than statistics, and [icon] is the pane-kind glyph drawn above the
* title.
*/
@Composable
fun PaneIdentity(title: String, subtitle: String? = null, modifier: Modifier = Modifier) {
fun PaneIdentity(
title: String,
subtitle: String? = null,
stats: List<PaneStat> = emptyList(),
icon: ImageVector? = null,
modifier: Modifier = Modifier,
) {
val text = pipelinesText()
Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
// The strip's width is measured here so the statistics block can degrade with
// the space actually available, never from a fixed depth assumption.
BoxWithConstraints(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
val shown = visiblePaneStats(stats, paneStatTier(maxWidth))
Column(
modifier = Modifier.padding(horizontal = SPACING_S, vertical = SPACING_M),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
if (icon != null) {
// Drawn at the vector's own default size, which is exactly what
// [rememberCompactIdentityWidth] measures, so the measured width
// and the drawn identity agree without a new size token.
Icon(imageVector = icon, contentDescription = null)
}
Text(
text = title,
style = text.cardTitle,
@@ -51,6 +130,64 @@ fun PaneIdentity(title: String, subtitle: String? = null, modifier: Modifier = M
overflow = TextOverflow.Ellipsis,
)
}
if (shown.isNotEmpty()) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
shown.forEach { stat ->
// Each statistic is its own label above its value, so the
// number is on a line wide enough for it and never shares a
// line with a label that could push it into an ellipsis.
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = stat.label,
style = text.meta,
textAlign = TextAlign.Center,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = stat.value,
style = text.label,
textAlign = TextAlign.Center,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
}
}
}
/**
* The width one covered edge must have to show its compact identity: the wider of
* the identity [icon]'s own size and the measured width of [label] (the shortest
* label that identifies the pane, measured at runtime with the app's own type
* role and the platform's font metrics), plus the identity's own horizontal
* padding. The platform minimum touch target is the floor, so an edge is never
* derived below what can be tapped; no window percentage, budget or new dp token
* stands in for it. The caller passes this to `SlidingPaneStack`, which uses it as
* the whole covered region's width at every depth.
*/
@Composable
internal fun rememberCompactIdentityWidth(label: String, icon: ImageVector? = null): Dp {
val measurer = rememberTextMeasurer()
val text = pipelinesText()
val density = LocalDensity.current
val minTouch = LocalMinimumInteractiveComponentSize.current
return remember(measurer, label, icon, text, density, minTouch) {
val labelWidth = with(density) {
measurer.measure(
text = AnnotatedString(label),
style = text.cardTitle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
).size.width.toDp()
}
val content = maxOf(labelWidth, icon?.defaultWidth ?: 0.dp)
maxOf(content + SPACING_S * 2, minTouch)
}
}
@@ -11,16 +11,19 @@ import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.systemGestures
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.width
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalLayoutDirection
@@ -32,14 +35,15 @@ import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.MAX_PANE_DEPTH
import net.awan.pipelines.ui.theme.MIN_ACTIVE_PANE_WIDTH_DP
import net.awan.pipelines.ui.theme.MIN_COVERED_PANE_WIDTH_DP
import net.awan.pipelines.ui.theme.PEEK_BUDGET_DP
import net.awan.pipelines.ui.theme.PEEK_WIDTH_DP
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.pipelinesText
// The pane geometry tokens (peek width/budget and the minimum active/covered
// pane widths) live in ui/theme/Dimens.kt, the single source of truth for app
// geometry; this file only derives offsets and widths from them.
// The covered region's width is not a token: it is measured from the compact
// identity a covered pane actually has to show (an icon plus the shortest label
// that identifies it) plus the leading gesture inset, so no screen or constant
// decides how much of a folded window the stack spends. The only fixed values
// left are platform ones: the minimum touch target that keeps an edge tappable
// and the leading system gesture inset this file already reads from the window.
/**
* The one slide timing every pane shares: the [MotionStandard] token, whose
@@ -74,87 +78,73 @@ internal fun paneSlideDelayMillis(level: Int, depth: Int, previousDepth: Int): I
internal fun paneSlideSpec(level: Int, depth: Int, previousDepth: Int): TweenSpec<Dp> =
MotionStandard.spec(delayMillis = paneSlideDelayMillis(level, depth, previousDepth))
/**
* The peek budget actually spent on a wide window: the fixed [PEEK_BUDGET_DP]
* token, reduced only when that would leave the active pane narrower than
* [MIN_ACTIVE_PANE_WIDTH_DP] on a small host. The budget never depends on the
* stack depth, so the active pane keeps a constant width as levels are added.
* Pure so the budget is unit-testable without a device.
*/
internal fun peekBudgetDp(hostWidth: Dp, requested: Dp = PEEK_BUDGET_DP): Dp =
requested.coerceAtMost((hostWidth - MIN_ACTIVE_PANE_WIDTH_DP).coerceAtLeast(0.dp))
/**
* The width of the pane whose open left edge is [offset] on a wide window: from
* that offset to the host's right edge. The active pane therefore measures
* `hostWidth - budget`; a narrow host can never yield a negative width.
* that offset to the host's right edge. The active pane therefore measures the
* host less the covered region; a narrow host can never yield a negative width.
*/
internal fun paneWidthDp(hostWidth: Dp, offset: Dp): Dp =
maxOf(0.dp, hostWidth - offset)
/**
* One covered strip of a wide-window stack, in left-to-right order. [level] is
* the pane whose compact identity it shows; a [folded] count greater than one
* marks a strip that stands in for that many older levels (one edge indicator
* with a count) instead of a single pane, so no covered pane is squeezed below
* the named minimum width.
* One covered pane's visible edge in a wide stack's covered region, in
* left-to-right order. [level] is the pane whose compact identity the edge shows
* (for a folded edge, the newest of the levels it stands in for). [folded] is the
* number of *additional* older levels that edge represents, so those levels
* collapse into its count instead of spending width on each of them.
*/
internal data class PeekStrip(
internal data class PaneEdge(
val level: Int,
val start: Dp,
val width: Dp,
val folded: Int = 1,
val folded: Int = 0,
)
/**
* The covered strips of a wide stack for [covered] covered levels and the fixed
* [budget]. Every shown pane keeps at least `minCovered`; the leftmost strip is
* widened first so that after [startInset] it still leaves [minPeek] tappable,
* and the rest of the budget is then split evenly between the other strips.
* The covered edges of a wide stack for [covered] covered levels, laid out inside
* the one covered region [region]. The region is derived from the measured
* compact-identity width (see [rememberCompactIdentityWidth]) plus the leading
* gesture inset [startInset], and is **the same at every depth**: the nearest
* covered level keeps the whole region less, at most, one thinner edge. The active
* pane's left edge — and therefore its width — is the region, so it never changes
* as levels are added. That is the invariant: opening another level only ever adds
* its own thin edge inside the region, never widens the region.
*
* When [covered] levels cannot each get `minCovered` out of [budget], one strip
* (the leftmost) is reserved as an edge indicator folding the oldest levels into
* a single count, and only the newest levels keep their own peek: the number of
* peeks shown shrinks rather than the width of each. The active pane's left edge
* is therefore still exactly the budget. Pure, so the shared-budget geometry and
* the fold rule need no device; an empty list means nothing is covered.
* The nearest covered level always shows its identity. One older level is shown
* as a thinner edge — the platform minimum touch target [minTouch], the thinnest
* an edge may be and stay tappable after [startInset] — and every level older than
* that collapses into that edge's [PaneEdge.folded] count rather than
* accumulating width. When the region cannot fit that thinner edge as well as a
* full [minTouch] identity, nothing is squeezed below the touch target: the older
* levels fold into the nearest edge's count instead. Pure, so the invariant, the
* thin edge and the fold rule need no device; an empty list means nothing is
* covered.
*/
internal fun peekStripsDp(
internal fun coveredEdgesDp(
covered: Int,
budget: Dp,
region: Dp,
minTouch: Dp,
startInset: Dp,
minPeek: Dp,
minCovered: Dp = MIN_COVERED_PANE_WIDTH_DP,
): List<PeekStrip> {
if (covered <= 0 || budget <= 0.dp) return emptyList()
// How many covered panes the budget can show at the minimum width. When some
// levels have to fold, one of those slots is spent on the edge indicator.
val capacity = if (minCovered > 0.dp) (budget.value / minCovered.value).toInt() else covered
val fold = covered > capacity
val shown = if (fold) (capacity - 1).coerceAtLeast(0) else covered
val folded = covered - shown
val slots = shown + if (fold) 1 else 0
val first = minOf(budget, maxOf(budget / slots, startInset + minPeek))
val rest = budget - first
val steps = slots - 1
val starts = ArrayList<Dp>(slots + 1)
starts += 0.dp
starts += first
for (i in 1 until slots) {
starts += first + rest * i / steps
): List<PaneEdge> {
if (covered <= 0 || region <= 0.dp) return emptyList()
val nearest = covered - 1
if (covered == 1) return listOf(PaneEdge(nearest, 0.dp, region))
// The thinner older edge keeps one touch target after the leading inset; the
// nearest identity needs one too, or the older levels fold into its count.
val older = startInset + minTouch
return if (region >= older + minTouch) {
listOf(
PaneEdge(
level = (covered - 2).coerceAtLeast(0),
start = 0.dp,
width = older,
folded = (covered - 2).coerceAtLeast(0),
),
PaneEdge(nearest, older, region - older),
)
} else {
listOf(PaneEdge(nearest, 0.dp, region, folded = covered - 1))
}
val strips = ArrayList<PeekStrip>(slots)
var slot = 0
if (fold) {
strips += PeekStrip(folded - 1, starts[0], starts[1] - starts[0], folded = folded)
slot = 1
}
for (i in 0 until shown) {
val level = folded + i
val s = slot + i
strips += PeekStrip(level, starts[s], starts[s + 1] - starts[s])
}
return strips
}
/**
@@ -180,18 +170,21 @@ internal fun paneSafeArea(): WindowInsets = WindowInsets.safeDrawing
*
* On a **narrow** window ([wide] false) it is not a stack at all: there is no
* peek and no leftover strip, and each opened pane is a full-window screen that
* slides in over the last. On a **wide** window ([wide] true) the panes stack,
* but the space spent on the covered panes is a single fixed budget shared
* between them: the active pane's left edge is always exactly the budget, so it
* keeps a constant width and the stack never consumes more than the budget
* however deep it gets.
* slides in over the last. On a **wide** window ([wide] true) the panes stack:
* the covered panes sit under the active one, each showing its left edge, and the
* covered region's width is not a constant but is measured from the compact
* identity a covered edge has to show ([compactLabel], see
* [rememberCompactIdentityWidth]) plus the leading gesture inset. The active
* pane's left edge is always exactly that region, so its width is the same at
* every depth: opening another level only adds its own thin edge inside the
* region and never resizes the panes already there.
*
* A covered pane shows a compact identity only (its pane composable is told
* [covered] and is expected to render just a title/status), constrained to the
* visible strip, so its full body is never drawn into a sliver. When the budget
* cannot give every covered pane the named minimum width, the oldest levels
* fold into a single edge indicator carrying their count rather than being
* squeezed.
* visible edge, so its full body is never drawn into a sliver. The nearest
* covered level shows its identity; one older level is a thinner edge and every
* older level than that folds into that edge's count ([coveredEdgesDp]), so no
* level is ever squeezed below the platform minimum touch target.
*
* [depth] is the number of visible panes minus one (0..[MAX_PANE_DEPTH]);
* [pane] composes the level's content. The stack mounts a level while it is open
@@ -211,13 +204,15 @@ internal fun paneSafeArea(): WindowInsets = WindowInsets.safeDrawing
* are retargeted in reverse, and several levels closing in one tap reverse in
* order. A covered pane is hidden from accessibility and made non-interactive so
* TalkBack focus follows the top pane and a tap can never leak through to a
* covered one; on a wide window only its peek strip stays tappable.
* covered one; on a wide window only its edge stays tappable.
*/
@Composable
fun SlidingPaneStack(
depth: Int,
wide: Boolean,
onPopTo: (Int) -> Unit,
compactLabel: String,
compactIcon: ImageVector? = null,
modifier: Modifier = Modifier,
backContentDescription: (Int) -> String = { "Back" },
pane: @Composable (level: Int, covered: Boolean, modifier: Modifier) -> Unit,
@@ -236,48 +231,27 @@ fun SlidingPaneStack(
// The strip/compact identity area: the host clear of the top/bottom insets.
val stripHeight = maxOf(0.dp, maxHeight - topInset - bottomInset)
// Narrow: no peek at all (budget 0, every pane fills the host). Wide: one
// fixed budget shared between the covered panes, folded when it cannot
// give each the named minimum. The platform's minimum interactive size is
// the floor for a tappable strip, never a literal.
val minPeek = maxOf(PEEK_WIDTH_DP, LocalMinimumInteractiveComponentSize.current)
val budget = if (wide) peekBudgetDp(hostWidth) else 0.dp
val strips = peekStripsDp(depth, budget, startInset, minPeek)
val stripByLevel = strips.associateBy { it.level }
val folded = strips.firstOrNull()?.takeIf { it.folded > 1 }?.folded ?: 0
// The active pane always opens at the whole budget (or 0 when narrow).
val activeStart = strips.fold(0.dp) { acc, strip -> acc + strip.width }
// Narrow: no peek at all, so every pane fills the host and the covered
// region is empty. Wide: the region is one measured compact identity plus
// the leading gesture inset; it is the same at every depth, so the active
// pane's width never depends on how deep the stack is. The platform's
// minimum interactive size is the floor for each tappable edge, never a
// literal.
val minTouch = LocalMinimumInteractiveComponentSize.current
val identityWidth = rememberCompactIdentityWidth(compactLabel, compactIcon)
val region = if (wide) identityWidth + startInset else 0.dp
val edges = coveredEdgesDp(depth, region, minTouch, startInset)
val edgeByLevel = edges.associateBy { it.level }
val shownCovered = edges.map { it.level }.toSet()
// The active pane always opens at exactly the covered region's width (0
// when nothing is covered or the window is narrow, so it fills the host).
val activeStart = edges.fold(0.dp) { acc, edge -> acc + edge.width }
// The depth just before the current one, so a pop knows how many levels
// were open (to stagger their reversal). Held stable for a given depth so
// the slide spec never changes part-way through a slide.
val depthTrack = remember { PaneDepthTrack(depth) }
val closingFrom = remember(depth) { depthTrack.previous.also { depthTrack.previous = depth } }
// The folded older levels as one edge indicator with a count, clear of the
// status/nav bars and of the left gesture area; tapping it jumps back to
// the newest folded level.
if (folded > 0) {
val strip = strips.first()
Box(
Modifier
.align(Alignment.TopStart)
.offset(x = startInset, y = topInset)
.width(maxOf(0.dp, strip.width - startInset))
.height(stripHeight)
.clickable(
role = Role.Button,
onClickLabel = backContentDescription(folded - 1),
onClick = { onPopTo(folded - 1) },
)
.semantics {
contentDescription = backContentDescription(folded - 1)
role = Role.Button
},
) {
PaneIdentity("$folded more", null, Modifier.fillMaxSize())
}
}
// Panes 0..MAX are always given their own long-lived animator, in order,
// even while closed, so a retarget slides rather than jumps and the
// animator stays warm; a level beyond the depth waits exactly off the
@@ -285,20 +259,22 @@ fun SlidingPaneStack(
// exact time-reverse of opening.
for (level in 0..MAX_PANE_DEPTH) {
val covered = level < depth
// A level folded into the edge indicator is not drawn on its own.
if (covered && level < folded) continue
val strip = if (covered) stripByLevel[level] else null
// A level folded into an older edge's count is not drawn on its own.
// A narrow window has no edges at all, so every covered level keeps
// composing its full body under the active one, as before.
if (covered && edges.isNotEmpty() && level !in shownCovered) continue
val edge = if (covered) edgeByLevel[level] else null
// An open pane sits at its shared-budget offset; a closed one waits
// exactly off the right edge. Its width is already the width it will
// have when open, so it slides rather than grows.
// An open pane sits at its edge's offset; a closed one waits exactly
// off the right edge. Its width is already the width it will have when
// open, so it slides rather than grows.
val openOffset = when {
level > depth -> hostWidth
level == depth -> activeStart
strip != null -> strip.start
edge != null -> edge.start
else -> 0.dp
}
val openWidth = paneWidthDp(hostWidth, if (level <= depth) openOffset else budget)
val openWidth = paneWidthDp(hostWidth, if (level <= depth) openOffset else region)
val offset by animateDpAsState(
targetValue = openOffset,
animationSpec = paneSlideSpec(level, depth, closingFrom),
@@ -318,20 +294,30 @@ fun SlidingPaneStack(
.fillMaxHeight()
.then(if (level < depth) Modifier.blockPointerInput() else Modifier),
) {
if (strip != null) {
// Constrain the compact identity to the visible strip so it
// is centred in the space the covered pane actually has. It
// rides with the pane's own offset and slides in so it also
// slides back out with it.
val stripInset = if (level == 0) startInset else 0.dp
if (edge != null) {
// Constrain the compact identity to the visible edge so it
// is centred in the space the covered pane actually has, and
// carry this level's share of the folded older levels as a
// count. It rides with the pane's own offset and slides in so
// it also slides back out with it.
val edgeInset = if (edge === edges.first()) startInset else 0.dp
Box(
Modifier
.align(Alignment.TopStart)
.offset(x = stripInset, y = topInset)
.width(maxOf(0.dp, strip.width - stripInset))
.offset(x = edgeInset, y = topInset)
.width(maxOf(0.dp, edge.width - edgeInset))
.height(stripHeight),
) {
pane(level, true, Modifier.fillMaxSize())
if (edge.folded > 0) {
Text(
text = "${edge.folded} more",
style = pipelinesText().meta,
modifier = Modifier
.align(Alignment.TopEnd)
.padding(SPACING_XS),
)
}
}
} else {
pane(level, false, Modifier.fillMaxSize())
@@ -339,26 +325,26 @@ fun SlidingPaneStack(
}
}
// The covered pane's tappable peek (wide windows only): the strip
// The covered pane's tappable edge (wide windows only): the edge
// between this pane's offset and the next pane's, clear of the
// status/nav bars and of the left gesture area. It sits above the
// pane's compact identity so tapping it closes every pane to its
// right; it never overlaps the next pane.
if (strip != null) {
val stripInset = if (level == 0) startInset else 0.dp
if (edge != null) {
val edgeInset = if (edge === edges.first()) startInset else 0.dp
Box(
Modifier
.align(Alignment.TopStart)
.offset(x = strip.start + stripInset, y = topInset)
.width(maxOf(0.dp, strip.width - stripInset))
.offset(x = edge.start + edgeInset, y = topInset)
.width(maxOf(0.dp, edge.width - edgeInset))
.height(stripHeight)
.clickable(
role = Role.Button,
onClickLabel = backContentDescription(level),
onClick = { onPopTo(level) },
onClickLabel = backContentDescription(edge.level),
onClick = { onPopTo(edge.level) },
)
.semantics {
contentDescription = backContentDescription(level)
contentDescription = backContentDescription(edge.level)
role = Role.Button
},
)
@@ -115,11 +115,19 @@ sealed interface LoadPhase {
/**
* Classifies a list pane's [LoadPhase] from its load signals. A failed load with
* 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; [emptyActionLabel] labels the one recovery action offered with
* that text (both are captured at classification).
* no data wins, then a list with no data yet ([loaded] false, or a load in
* flight), 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;
* [emptyActionLabel] labels the one recovery action offered with that text (both
* are captured at classification).
*
* [loaded] is the pane's "data has arrived at least once" signal. Before the
* first load completes the initial state is both not-loading and data-less, and
* without this it would classify as content: a list that has never loaded must
* read as loading, not as an empty list, so a restored scroll position is never
* clamped against a list that is merely not there yet. It defaults to true so a
* pane that has no such signal keeps the previous behaviour.
*
* 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]
@@ -131,9 +139,10 @@ fun listLoadPhase(
hasData: Boolean,
emptyMessage: String?,
emptyActionLabel: String? = null,
loaded: Boolean = true,
): LoadPhase = when {
error != null && !hasData -> LoadPhase.Error(error)
loading && !hasData -> LoadPhase.Loading
!hasData && (loading || !loaded) -> LoadPhase.Loading
emptyMessage != null -> LoadPhase.Empty(emptyMessage, emptyActionLabel)
else -> LoadPhase.Content
}
@@ -11,6 +11,7 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Hub
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -333,6 +334,7 @@ fun StageDetailPane(
PaneIdentity(
title = GraphSemantics.nodeLabel(stageKey),
subtitle = if (stage != null) effectiveStageType(stage.type) else "terminal",
icon = Icons.Filled.Hub,
modifier = modifier.fillMaxSize(),
)
return
@@ -36,7 +36,6 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -75,13 +74,9 @@ import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.currentStateAsState
import kotlin.math.abs
import kotlin.math.hypot
import kotlin.math.roundToInt
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.GraphEdge
@@ -90,6 +85,8 @@ import net.awan.pipelines.data.protocol.GraphSemantics
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.data.protocol.edges
import net.awan.pipelines.ui.components.hostResumed
import net.awan.pipelines.ui.components.rememberLiveNowMillis
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.secondsSince
import net.awan.pipelines.ui.theme.GRAPH_ACTIVE_HALO_GAP
@@ -274,25 +271,18 @@ fun WorkflowGraph(
// finished run; pause when the graph is off screen or when the OS animation
// setting is off. ValueAnimator.areAnimatorsEnabled() reflects the system
// "Remove animations"/animation-scale setting; it is re-read on resume.
val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState()
val onScreen = lifecycleState.isAtLeast(Lifecycle.State.RESUMED)
val onScreen = hostResumed()
val animationsEnabled = remember(onScreen) { ValueAnimator.areAnimatorsEnabled() }
val animate = graphShouldAnimate(runState, animationsEnabled, onScreen)
val phase = rememberPulsePhase(animate)
// The active stage's live ticking elapsed time. The loop only runs while
// animating, so a finished run, a paused/off-screen graph and an
// animations-disabled device never wake up once a second; in those cases the
// value is a static snapshot for a clearly marked running state.
// The active stage's live ticking elapsed time, from the shared clock: it
// runs only while the graph is animating a live stage whose start is known,
// so a finished run, a paused/off-screen graph and an animations-disabled
// device never wake up once a second; in those cases the value is a static
// snapshot for a clearly marked running state.
val activeStartedAt = runState?.currentStageStartedAt
var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }
LaunchedEffect(animate, activeStartedAt) {
if (!animate || activeStartedAt.isNullOrBlank()) return@LaunchedEffect
while (true) {
nowMillis = System.currentTimeMillis()
delay(ELAPSED_TICK_MILLIS)
}
}
val nowMillis = rememberLiveNowMillis(animate && !activeStartedAt.isNullOrBlank())
// Measured once per second (never per frame) so the canvas draw adds no
// allocation for the timer.
val elapsedLayout = remember(activeStartedAt, nowMillis, scheme, density, text) {
@@ -1746,9 +1736,6 @@ private fun rememberPulsePhase(animate: Boolean): Float {
/** One pulse (and one full pass of the edge flow) per this many milliseconds. */
private const val PULSE_PERIOD_MILLIS = 1_600
/** The active stage's elapsed time ticks once a second, never per frame. */
private const val ELAPSED_TICK_MILLIS = 1_000L
/** How much of the pulse strength the active halo's soft glow carries. */
private const val ACTIVE_HALO_GLOW = 0.28f
@@ -0,0 +1,179 @@
package net.awan.pipelines.ui.screens
import java.time.OffsetDateTime
import kotlin.math.roundToLong
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.ui.components.PaneStat
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.durationSeconds
import net.awan.pipelines.ui.formatDuration
/**
* The compact statistics a covered pipeline pane shows, aggregated client-side
* from the run history the app already receives (never a server field). The
* counts mirror the server's own vocabulary (internal/pipeline/stats.go): active
* is a queued/running run, and the average is over the runs that have finished,
* so a still-running run never drags it down.
*
* [lastState]/[lastAgo] are null for a pipeline with no runs (or an id present in
* no history), and [averageSeconds] is null until at least one run has finished;
* the caller shows the rest and omits those lines rather than inventing a value.
*/
internal data class PipelinePeekStats(
val total: Int,
val succeeded: Int,
val failed: Int,
val active: Int,
val lastState: RunState?,
val lastAgo: String?,
val averageSeconds: Long?,
) {
/** The labelled lines, counts first then the last-run/average details. */
fun lines(): List<PaneStat> = buildList {
addAll(countStats(total, succeeded, failed, active))
lastState?.let { add(PaneStat("last", lastLine(it, lastAgo), detail = true)) }
averageSeconds?.let { add(PaneStat("avg", formatDuration(it), detail = true)) }
}
}
/**
* The compact statistics a covered list pane (the pipelines list or the runs
* list) shows: counts by status plus the single most recent run, aggregated
* client-side from the run history. A list has no single pipeline to average, so
* it carries no duration line.
*/
internal data class ListPeekStats(
val total: Int,
val succeeded: Int,
val failed: Int,
val active: Int,
val lastState: RunState?,
val lastAgo: String?,
) {
/** The labelled lines, counts first then the last-activity detail. */
fun lines(): List<PaneStat> = buildList {
addAll(countStats(total, succeeded, failed, active))
lastState?.let { add(PaneStat("last", lastLine(it, lastAgo), detail = true)) }
}
}
/**
* The whole history's labelled statistics, for a covered list pane (the pipelines
* list, or the runs list with no pipeline filter): counts by status plus the
* single most recent run. Empty until that history has loaded, never a zero-run
* claim before the data is in hand.
*/
internal fun listStatLines(runs: List<RunSummary>?, now: OffsetDateTime): List<PaneStat> =
runs?.let { listPeekStats(it, now).lines() }.orEmpty()
/**
* One pipeline's labelled statistics, for a covered pipeline pane (a pipeline's
* detail, or a run open over its pipeline). Empty until both the history has
* loaded and the [pipelineId] is known: an unknown or absent id is "not known
* yet", never the whole history, so a covered run pane can never show the
* server-wide summary as if it were the run's own pipeline. The entry point the
* pipeline-scoped covered panes share, so the "which history, which pipeline"
* wiring lives here instead of at each call site.
*/
internal fun pipelineStatLines(
runs: List<RunSummary>?,
pipelineId: Long?,
now: OffsetDateTime,
): List<PaneStat> = when {
runs == null || pipelineId == null -> emptyList()
else -> pipelinePeekStats(runs, pipelineId, now).lines()
}
/** One pipeline's statistics over the whole run history, anchored to [now]. */
internal fun pipelinePeekStats(
runs: List<RunSummary>,
pipelineId: Long,
now: OffsetDateTime,
): PipelinePeekStats {
val tally = RunTally()
for (run in runs) if (run.pipelineId == pipelineId) tally.add(run)
val newest = tally.newest
return PipelinePeekStats(
total = tally.total,
succeeded = tally.succeeded,
failed = tally.failed,
active = tally.active,
lastState = newest?.let { runStateOf(it.status) },
lastAgo = newest?.let { formatRanAgo(it.createdAt, now) },
averageSeconds = tally.averageSeconds,
)
}
/** The whole history's statistics, anchored to [now]. */
internal fun listPeekStats(runs: List<RunSummary>, now: OffsetDateTime): ListPeekStats {
val tally = RunTally()
for (run in runs) tally.add(run)
val newest = tally.newest
return ListPeekStats(
total = tally.total,
succeeded = tally.succeeded,
failed = tally.failed,
active = tally.active,
lastState = newest?.let { runStateOf(it.status) },
lastAgo = newest?.let { formatRanAgo(it.createdAt, now) },
)
}
/**
* The per-status counts, the completed-duration total and the most recent run,
* folded together in one pass over a history. [add] is called once per run, so a
* scoped summary ([pipelinePeekStats]) never allocates an intermediate filtered
* list or walks the history a second time for the last run.
*/
private class RunTally {
var total = 0
private set
var succeeded = 0
private set
var failed = 0
private set
var active = 0
private set
private var durationSeconds = 0L
private var durationCount = 0
/** The most recent run seen, by the shared [isMoreRecent] rule, or null. */
var newest: RunSummary? = null
private set
/**
* The rounded mean duration over the runs that finished, or null when none
* has. A zero-duration run is a real measurement and is included, not
* dropped.
*/
val averageSeconds: Long?
get() = if (durationCount > 0) (durationSeconds.toDouble() / durationCount).roundToLong() else null
fun add(run: RunSummary) {
total++
when (runStateOf(run.status)) {
RunState.Succeeded -> succeeded++
RunState.Failed -> failed++
RunState.Running, RunState.Queued -> active++
else -> Unit
}
durationSeconds(run.createdAt, run.finishedAt)?.let {
durationSeconds += it
durationCount++
}
val current = newest
if (current == null || isMoreRecent(run, current)) newest = run
}
}
private fun countStats(total: Int, succeeded: Int, failed: Int, active: Int): List<PaneStat> = listOf(
PaneStat("runs", total.toString()),
PaneStat("succeeded", succeeded.toString()),
PaneStat("failed", failed.toString()),
PaneStat("active", active.toString()),
)
/** `succeeded · 2h ago`, or just the status when the timestamp is unusable. */
private fun lastLine(state: RunState, ago: String?): String =
listOfNotNull(state.label, ago).joinToString(" · ")
@@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
@@ -42,6 +43,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import java.time.OffsetDateTime
import net.awan.pipelines.data.ErrorMessages
import net.awan.pipelines.data.protocol.PipelineDetail
import net.awan.pipelines.data.protocol.VersionSummary
@@ -89,6 +91,7 @@ fun PipelineDetailScreen(
covered: Boolean = false,
) {
val state by vm.pipelineDetail.collectAsStateWithLifecycle()
val runsState by vm.runs.collectAsStateWithLifecycle()
var showStart by remember { mutableStateOf(false) }
LaunchedEffect(pipelineId, version) { vm.loadPipeline(pipelineId, version) }
@@ -101,11 +104,18 @@ fun PipelineDetailScreen(
val shownDetail = rememberPaneContent(detail)
// A covered pane shows its compact identity only; the tab rail and section
// body must never be drawn squeezed into the peek strip.
// body must never be drawn squeezed into the peek strip. When the run history
// is in hand the identity carries this pipeline's statistics (run counts, the
// last run and the average duration) instead of a bare version/stage line.
if (covered) {
val now = remember { OffsetDateTime.now() }
val stats = remember(runsState.data, pipelineId, now) {
pipelineStatLines(runsState.data?.runs, pipelineId, now)
}
PaneIdentity(
title = detail?.name ?: "Pipeline",
subtitle = detail?.let { "v$version · ${it.graph.stages.size} stages" },
stats = stats,
icon = Icons.Filled.AccountTree,
modifier = modifier.fillMaxSize(),
)
return
@@ -5,17 +5,18 @@ 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
import net.awan.pipelines.ui.runDurationText
/** 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.
* ago the run started, its time so far ([duration]: the live elapsed while it is
* still running, the recorded total once finished) 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,
@@ -52,8 +53,9 @@ internal fun pipelineRunBadges(
/**
* 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.
* order. One pass, reusing the shared [isMoreRecent] comparison, so it shares the
* "most recent" rule with the covered panes' last-run line without grouping the
* history into intermediate lists.
*/
internal fun latestRunByPipeline(runs: List<RunSummary>): Map<Long, RunSummary> {
val latest = HashMap<Long, RunSummary>()
@@ -70,11 +72,22 @@ internal fun runBadge(run: RunSummary, now: OffsetDateTime): PipelineRunBadge =
runId = run.id,
state = runStateOf(run.status),
ranAgo = formatRanAgo(run.createdAt, now),
duration = formatDuration(run.createdAt, run.finishedAt),
// A still-running run shows the time it has taken so far, recomputed from
// its start timestamp as [now] advances; a finished one its total duration.
duration = runDurationText(
createdAt = run.createdAt,
finishedAt = run.finishedAt,
executing = run.executing,
nowMillis = now.toInstant().toEpochMilli(),
),
)
/** Timestamps decide recency; the higher run id breaks an exact tie (or a bad timestamp). */
private fun isMoreRecent(candidate: RunSummary, current: RunSummary): Boolean {
/**
* Timestamps decide recency; the higher run id breaks an exact tie (or a bad
* timestamp). The one recency rule, shared by the per-pipeline last-run join and
* the covered panes' most-recent-run line.
*/
internal fun isMoreRecent(candidate: RunSummary, current: RunSummary): Boolean {
val a = parseInstant(candidate.createdAt)
val b = parseInstant(current.createdAt)
if (a != null && b != null) {
@@ -86,7 +99,8 @@ private fun isMoreRecent(candidate: RunSummary, current: RunSummary): Boolean {
/**
* 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
* `Nm ago`/`Nh ago`/`Nd ago`, the same integer rhythm as the shared duration
* formatting. 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.
@@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountTree
@@ -34,7 +35,9 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneId
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.EmptyState
@@ -46,6 +49,7 @@ 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.RestoreListScroll
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.RunStatusChip
import net.awan.pipelines.ui.components.SortMenu
@@ -53,6 +57,7 @@ import net.awan.pipelines.ui.components.StateCrossfade
import net.awan.pipelines.ui.components.animateListItem
import net.awan.pipelines.ui.components.listLoadPhase
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.components.rememberLiveNowMillis
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.pipelinesText
@@ -65,6 +70,7 @@ fun PipelineListScreen(
modifier: Modifier = Modifier,
selectedId: Long? = null,
covered: Boolean = false,
listState: LazyListState,
) {
val state by vm.pipelines.collectAsStateWithLifecycle()
val runsState by vm.runs.collectAsStateWithLifecycle()
@@ -82,8 +88,40 @@ fun PipelineListScreen(
vm.refreshRuns()
}
// "How long ago" is anchored once per composition, not recomputed per row.
val now = remember { OffsetDateTime.now() }
// "How long ago" (and a running run's live elapsed) are anchored to a shared
// clock that ticks only while some run in the history is executing and the app
// is resumed, so the last-run line's elapsed advances and stays correct after
// a reconnect (derived from the server's own start timestamps) while a fully
// finished history costs no wakeups.
val live = runsState.data?.runs?.any { it.executing } == true
val nowMillis = rememberLiveNowMillis(live)
val now = remember(nowMillis) {
OffsetDateTime.ofInstant(Instant.ofEpochMilli(nowMillis), ZoneId.systemDefault())
}
// [listState] is owned by the destination, above the panes: a covered pane is a
// different composition (its compact identity is drawn in a strip), so a state
// held here would be discarded and reset the scroll when a detail closes.
// [RestoreListScroll] clamps it when the list changed underneath.
// A covered pane shows its compact identity only; the search field and list
// must never be drawn squeezed into the peek strip. Its statistics are the
// run history's summary, folded once; before the history has loaded the
// identity stays title-only rather than claiming zero runs. Measured before
// the row badges below so the peek never pays for the unshown fold.
if (covered) {
val stats = remember(runsState.data, now) {
listStatLines(runsState.data?.runs, now)
}
PaneIdentity(
title = "Pipelines",
stats = stats,
icon = Icons.Filled.AccountTree,
modifier = modifier.fillMaxSize(),
)
return
}
// 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) {
@@ -102,18 +140,6 @@ fun PipelineListScreen(
query = ""
}
// A covered pane shows its compact identity only; the search field and list
// must never be drawn squeezed into the peek strip.
if (covered) {
val count = state.data?.size ?: 0
PaneIdentity(
title = "Pipelines",
subtitle = if (count > 0) "$count on this server" else null,
modifier = modifier.fillMaxSize(),
)
return
}
Scaffold(
modifier = modifier,
contentWindowInsets = paneSafeArea(),
@@ -189,6 +215,11 @@ fun PipelineListScreen(
null
},
emptyActionLabel = if (items.isEmpty() && all.isNotEmpty()) "Clear filters" else null,
// Before the first load this frame is both data-less and not
// in flight; without [loaded] it would render the "no
// pipelines are defined" empty message against a server that
// has not answered yet.
loaded = state.loaded,
),
) { phase ->
when (phase) {
@@ -199,19 +230,25 @@ fun PipelineListScreen(
actionLabel = phase.actionLabel,
onAction = if (phase.actionLabel != null) onClearFilters else null,
)
LoadPhase.Content -> LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(vertical = SPACING_S),
) {
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(),
)
LoadPhase.Content -> {
// Restores the saved position (clamped to the current,
// possibly shrunken, list) without fighting a later scroll.
RestoreListScroll(listState, items.size)
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(vertical = SPACING_S),
) {
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(),
)
}
}
}
}
@@ -16,6 +16,7 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.DirectionsRun
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.Cancel
import androidx.compose.material.icons.filled.Refresh
@@ -44,6 +45,7 @@ import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.delay
import kotlinx.serialization.json.JsonElement
import java.time.OffsetDateTime
import net.awan.pipelines.data.ErrorMessages
import net.awan.pipelines.data.protocol.RunDetail
import net.awan.pipelines.data.protocol.RunGraphState
@@ -69,13 +71,14 @@ import net.awan.pipelines.ui.components.clampTabIndex
import net.awan.pipelines.ui.components.collapsibleSection
import net.awan.pipelines.ui.components.detailLoadPhase
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.components.rememberLiveNowMillis
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
import net.awan.pipelines.ui.runDurationText
import net.awan.pipelines.ui.graph.ArtifactGallery
import net.awan.pipelines.ui.graph.ArtifactSelection
import net.awan.pipelines.ui.graph.ArtifactSelectionScaffold
@@ -108,6 +111,7 @@ fun RunDetailScreen(
covered: Boolean = false,
) {
val state by vm.runDetail.collectAsStateWithLifecycle()
val runsState by vm.runs.collectAsStateWithLifecycle()
val evidenceState by vm.evidence.collectAsStateWithLifecycle()
val configuredServerUrl by vm.configuredServerUrl.collectAsStateWithLifecycle()
var confirmCancel by remember { mutableStateOf(false) }
@@ -156,11 +160,21 @@ fun RunDetailScreen(
val summaryTab = runDetailTabs.getOrNull(clampTabIndex(selectedSection, runDetailTabs.size))?.key
// A covered pane shows its compact identity only; the tab rail, timeline and
// graphs must never be drawn squeezed into the peek strip.
// graphs must never be drawn squeezed into the peek strip. The run belongs to
// a pipeline, so its identity carries that pipeline's statistics from the run
// history (counts, last run, average) once the history is in hand; until the
// run (and so its pipeline) has loaded the identity stays title-only rather
// than showing the server-wide summary as if it were this run's pipeline.
if (covered) {
val now = remember { OffsetDateTime.now() }
val pipelineId = run?.pipelineId
val stats = remember(runsState.data, pipelineId, now) {
pipelineStatLines(runsState.data?.runs, pipelineId, now)
}
PaneIdentity(
title = run?.name ?: "Run",
subtitle = run?.status?.takeIf { it.isNotBlank() },
stats = stats,
icon = Icons.AutoMirrored.Filled.DirectionsRun,
modifier = modifier.fillMaxSize(),
)
return
@@ -408,7 +422,7 @@ private fun RunSummaryTab(
KeyValueRow("Content hash", run.contentHash, monospace = true)
KeyValueRow("Started", run.createdAt)
KeyValueRow("Finished", run.finishedAt)
KeyValueRow("Duration", formatDuration(run.createdAt, run.finishedAt) ?: "")
RunDurationRow(run)
KeyValueRow("Retry of", if (run.retryOf > 0) "run ${run.retryOf}" else "")
CodeBlock("Diagnostic", run.diagnostic, Modifier.padding(top = SPACING_S))
}
@@ -417,6 +431,20 @@ private fun RunSummaryTab(
}
}
/**
* The run summary's Duration row. A running run's value is live: the shared
* per-second clock is read here, in the row itself, so the tick recomposes only
* this row and never the artifacts gallery or the rest of the summary. The value
* is derived from the server's start timestamp (re-read on resume, so it stays
* correct after a reconnect) and is never frozen at load; a finished run shows
* its stored total duration.
*/
@Composable
private fun RunDurationRow(run: RunDetail) {
val nowMillis = rememberLiveNowMillis(run.executing)
KeyValueRow("Duration", runDurationText(run.createdAt, run.finishedAt, run.executing, nowMillis) ?: "")
}
/**
* The graph tab on its own: the full-height [WorkflowGraph] panel with its Fit
* and expand controls, given the whole content area. The tab's single LazyColumn
@@ -15,9 +15,10 @@ import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
@@ -56,6 +57,7 @@ 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.RestoreListScroll
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.RunStatusChip
import net.awan.pipelines.ui.components.RunStatusIcon
@@ -64,9 +66,11 @@ import net.awan.pipelines.ui.components.StateCrossfade
import net.awan.pipelines.ui.components.animateListItem
import net.awan.pipelines.ui.components.listLoadPhase
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.components.rememberLiveNowMillis
import net.awan.pipelines.ui.components.runStateColor
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.runDurationText
import net.awan.pipelines.ui.theme.ICON_LIST_DP
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
import net.awan.pipelines.ui.theme.PipelinesTextStyles
@@ -86,6 +90,7 @@ fun RunHistoryScreen(
filterPipelineId: Long? = null,
selectedRunId: Long? = null,
covered: Boolean = false,
listState: LazyListState,
) {
val state by vm.runs.collectAsStateWithLifecycle()
val sortKey by vm.runSort.collectAsStateWithLifecycle()
@@ -107,13 +112,26 @@ fun RunHistoryScreen(
pipelineFilterOptions(state.data?.runs.orEmpty())
}
// [listState] is owned by the destination, above the panes: a covered pane is a
// different composition (its compact identity is drawn in a strip), so a state
// held here would be discarded and reset the scroll when a detail closes.
// [RestoreListScroll] clamps it when the history changed underneath.
// 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.
// headers and run rows must never be drawn squeezed into the peek strip. Its
// statistics are the history's status counts and most recent run, folded
// once; a history scoped to one pipeline shows that pipeline's own numbers.
if (covered) {
val count = state.data?.runs?.size ?: 0
val now = remember { OffsetDateTime.now() }
val stats = remember(state.data, filterPipelineId, now) {
val pipelineId = filterPipelineId
if (pipelineId == null) listStatLines(state.data?.runs, now)
else pipelineStatLines(state.data?.runs, pipelineId, now)
}
PaneIdentity(
title = if (filterPipelineId == null) "Runs" else "Runs for this pipeline",
subtitle = if (count > 0) "$count recorded" else null,
stats = stats,
icon = Icons.AutoMirrored.Filled.List,
modifier = modifier.fillMaxSize(),
)
return
@@ -159,6 +177,11 @@ fun RunHistoryScreen(
// usage block and shows the "no runs" line inside the list, where
// the item animation fades it in and out.
emptyMessage = null,
// Before the first history load this frame has no data and no
// in-flight refresh yet; without [loaded] it would read as an
// empty list and the restore below would clamp a restored
// position to the top of the transient one-item list.
loaded = state.loaded,
),
modifier = Modifier.fillMaxSize(),
) { phase ->
@@ -179,6 +202,7 @@ fun RunHistoryScreen(
error = state.error,
onOpenRun = onOpenRun,
onClearFilters = onClearFilters,
listState = listState,
modifier = Modifier.padding(padding),
)
}
@@ -247,6 +271,7 @@ private fun RunHistoryContent(
error: String?,
onOpenRun: (Long) -> Unit,
onClearFilters: () -> Unit,
listState: LazyListState,
modifier: Modifier = Modifier,
) {
val zone = ZoneId.systemDefault()
@@ -265,59 +290,144 @@ private fun RunHistoryContent(
groupRunsByDay(matched, today, zone, runComparator(sort))
}
// The list body built once, in layout order. It is the single source of both
// the LazyColumn's items and their count, so a restored position is clamped to
// the list the column actually draws rather than to a hand-maintained replica
// of it (see [RestoreListScroll]).
val entries = remember(usage, scoped, matched, groups, error) {
runListEntries(
usage = usage,
nothingRecorded = scoped.isEmpty(),
nothingMatched = matched.isEmpty(),
groups = groups,
error = error,
)
}
RestoreListScroll(listState, entries.size)
// One live clock for the whole list: it ticks only while a shown run is
// executing and the app is resumed, and each running row reads its elapsed
// from it rather than starting a coroutine of its own. Elapsed is derived
// from the server's start timestamp, never from when the list loaded, so it
// is still correct after a reconnect; a finished history never ticks.
val live = remember(matched) { matched.any { it.executing } }
val nowMillis = rememberLiveNowMillis(live)
LazyColumn(
state = listState,
modifier = modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = SPACING_L),
) {
if (usage != null) {
item(key = "usage") {
UsageMetrics(usage, Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S))
}
}
if (scoped.isEmpty()) {
// Nothing exists at all: no filter could reveal a run, so there is no
// clear action.
item(key = "runs-empty") {
EmptyState(
"No runs have been recorded yet.",
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 {
groups.forEach { group ->
stickyHeader(key = "day-${group.label}") { DayHeader(group.label) }
items(group.runs, key = { "run-${it.id}" }) { run ->
RunRow(
run = run,
selected = run.id == selectedRunId,
onClick = { onOpenRun(run.id) },
entries.forEach { entry ->
when (entry) {
is RunListEntry.Usage -> item(key = entry.key) {
UsageMetrics(
entry.usage,
Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S),
)
}
is RunListEntry.Empty -> item(key = entry.key) {
EmptyState(
message = entry.message,
actionLabel = entry.actionLabel,
// Only the filtered-empty case offers a clear action, which
// [runListEntries] encodes as a non-null label.
onAction = if (entry.actionLabel != null) onClearFilters else null,
modifier = animateListItem(),
)
}
is RunListEntry.Day -> stickyHeader(key = entry.key) { DayHeader(entry.label) }
is RunListEntry.Run -> item(key = entry.key) {
RunRow(
run = entry.run,
selected = entry.run.id == selectedRunId,
nowMillis = nowMillis,
onClick = { onOpenRun(entry.run.id) },
modifier = animateListItem(),
)
}
is RunListEntry.Error -> item(key = entry.key) {
Text(
entry.message,
color = MaterialTheme.colorScheme.error,
style = pipelinesText().body,
modifier = animateListItem(Modifier.padding(SPACING_L)),
)
}
}
}
if (error != null) {
item(key = "runs-error") {
Text(
error,
color = MaterialTheme.colorScheme.error,
style = pipelinesText().body,
modifier = animateListItem(Modifier.padding(SPACING_L)),
)
}
}
}
/**
* One slot the runs list draws, in layout order: the usage block, the single
* empty-or-grouped body and the optional inline error row. [key] is the stable
* LazyColumn key the list has always used. [runListEntries] builds the whole
* list and both the column and the clamp consume it, so the count a restored
* position is clamped against can never drift from the items the column draws.
*/
internal sealed interface RunListEntry {
val key: String
/** The usage aggregates block, present only when the history has a summary. */
data class Usage(val usage: UsageStats) : RunListEntry {
override val key: String get() = "usage"
}
/**
* The single "nothing recorded"/"nothing matches" line. [actionLabel] is
* non-null exactly when filters hid existing runs, the one case with a clear
* action.
*/
data class Empty(val message: String, val actionLabel: String?) : RunListEntry {
override val key: String
get() = if (actionLabel != null) "runs-filtered-empty" else "runs-empty"
}
/** A sticky day header above a group's runs. */
data class Day(val label: String) : RunListEntry {
override val key: String get() = "day-$label"
}
/** One run row. */
data class Run(val run: RunSummary) : RunListEntry {
override val key: String get() = "run-${run.id}"
}
/** The last load's error, kept inline under the stale rows. */
data class Error(val message: String) : RunListEntry {
override val key: String get() = "runs-error"
}
}
/**
* The runs list's slots in layout order: the usage block when there is one, then
* either the single empty line (nothing recorded, or nothing matching the
* filters) or the day groups, then the inline error row when the last load
* failed over stale data. Pure and single-sourced with the LazyColumn, so its
* size is exactly the list's item count.
*/
internal fun runListEntries(
usage: UsageStats?,
nothingRecorded: Boolean,
nothingMatched: Boolean,
groups: List<RunDayGroup>,
error: String?,
): List<RunListEntry> = buildList {
if (usage != null) add(RunListEntry.Usage(usage))
when {
// Nothing exists at all: no filter could reveal a run, so there is no
// clear action.
nothingRecorded -> add(RunListEntry.Empty("No runs have been recorded yet.", null))
// Runs exist but every one is filtered out: distinguish this from the
// "nothing exists" case and offer the one clear action.
nothingMatched -> add(RunListEntry.Empty("No runs match the current filters.", "Clear filters"))
else -> groups.forEach { group ->
add(RunListEntry.Day(group.label))
group.runs.forEach { add(RunListEntry.Run(it)) }
}
}
if (error != null) add(RunListEntry.Error(error))
}
/** A sticky day header ("Today"/"Yesterday"/date) above each group of runs. */
@@ -378,13 +488,15 @@ private fun Metric(label: String, value: String, color: Color, text: PipelinesTe
/**
* One run as a row of the shared real list: a leading status glyph, the run name
* as the title with its version chip, and a secondary line carrying the status
* chip, progress and id/start/duration. The row is selected when its run is the
* one open in the detail pane.
* chip, progress and id/time. The row is selected when its run is the one open in
* the detail pane. [nowMillis] is the shared live clock, read only by a running
* row so its elapsed value advances.
*/
@Composable
private fun RunRow(
run: RunSummary,
selected: Boolean,
nowMillis: Long,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
@@ -429,7 +541,7 @@ private fun RunRow(
Text(progressText(run), style = text.meta, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text(metaText(run), style = text.meta, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(metaText(run, nowMillis), style = text.meta, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (run.diagnostic.isNotBlank()) {
Text(
@@ -466,13 +578,20 @@ private fun progressText(run: RunSummary): String = buildString {
if (run.currentStage.isNotBlank()) append(" · stage ${run.currentStage}")
}
/** Run id, start time and duration, all via formatDuration for the duration. */
private fun metaText(run: RunSummary): String = buildString {
/**
* Run id and its time. A running run shows how long it has taken so far: a live
* elapsed value computed from its server start timestamp against [nowMillis],
* replacing the start time and advancing as the shared clock ticks. A finished
* run keeps its start time and total duration.
*/
private fun metaText(run: RunSummary, nowMillis: Long): String = buildString {
append("run ${run.id}")
val start = formatRunStart(run.createdAt)
if (start != null) append(" · $start")
val duration = formatDuration(run.createdAt, run.finishedAt)
if (duration != null) append(" · $duration")
if (run.executing) {
runDurationText(run.createdAt, run.finishedAt, executing = true, nowMillis)?.let { append(" · $it") }
} else {
formatRunStart(run.createdAt)?.let { append(" · $it") }
runDurationText(run.createdAt, run.finishedAt, executing = false, nowMillis)?.let { append(" · $it") }
}
}
private fun formatRunStart(createdAt: String): String? {
@@ -58,29 +58,19 @@ internal val ICON_LIST_DP = 20.dp
/** Wide detail-rail tab glyph size. */
internal val ICON_RAIL_DP = 24.dp
// ---- Pane geometry (ui/components/SlidingPaneStack.kt) ---------------------
// The sliding pane stack derives every offset and width from these plus the
// measured host width and the system insets; no screen hardcodes a peek or pane
// width. [PEEK_WIDTH_DP] is the minimum width of one covered pane's tappable
// peek (the "collapsed strip"). [PEEK_BUDGET_DP] is the fixed *total* peek
// budget a wide window may spend on all covered panes together, however deep the
// stack gets. [MIN_ACTIVE_PANE_WIDTH_DP] is the least width worth leaving to the
// active (topmost) pane before the budget has to be reduced.
// [MIN_COVERED_PANE_WIDTH_DP] is the least width a covered pane's compact
// identity needs to stay readable and tappable; when the budget cannot give
// every covered pane this much, the oldest levels are folded into one edge
// indicator instead of being squeezed below it.
// ---- Covered-pane identity tiers (ui/components/PaneIdentity.kt) -----------
// The sliding pane stack no longer derives its width from a token: the covered
// region is measured from the compact identity a covered edge must show (see
// `rememberCompactIdentityWidth`), so there is no fixed peek budget and the
// active pane's width does not depend on the stack's depth. What remains here
// only bounds the *statistics* a covered identity shows once it is drawn: a
// strip narrower than one peek keeps the title alone, and a strip at least one
// minimum covered pane plus one peek wide has room for the full block.
/** Minimum width of one covered pane's tappable peek (the collapsed strip). */
/** Least width a covered identity needs before it shows labelled statistics. */
internal val PEEK_WIDTH_DP = 56.dp
/** Fixed total peek budget a wide window may spend on all covered panes. */
internal val PEEK_BUDGET_DP = 224.dp
/** Least width left to the active (topmost) pane before the budget is reduced. */
internal val MIN_ACTIVE_PANE_WIDTH_DP = 320.dp
/** Least width a covered pane's compact identity needs to stay usable. */
/** Width beyond which a covered identity has room for its full statistics. */
internal val MIN_COVERED_PANE_WIDTH_DP = 112.dp
// ---- Destination pill (ui/PipelinesApp.kt) ---------------------------------
@@ -46,6 +46,36 @@ class FormatTest {
assertNull(secondsSince("not a timestamp", startMillis))
}
@Test
fun runDurationTextIsLiveElapsedWhileRunningAndStoredDurationOnceFinished() {
val start = "2026-10-15T02:00:00Z"
val startMillis = parseInstant(start)!!.toInstant().toEpochMilli()
// A run that just started reads 0s, not a blank or a fabricated value.
assertEquals("0s", runDurationText(start, "", executing = true, nowMillis = startMillis))
// Minute boundary: 59s is still seconds, 60s rolls over to a minute.
assertEquals("59s", runDurationText(start, "", executing = true, nowMillis = startMillis + 59_000))
assertEquals("1m 0s", runDurationText(start, "", executing = true, nowMillis = startMillis + 60_000))
// Hour boundary: 3599s is still minutes and seconds, 3600s rolls to hours.
assertEquals("59m 59s", runDurationText(start, "", executing = true, nowMillis = startMillis + 3_599_000))
assertEquals("1h 0m", runDurationText(start, "", executing = true, nowMillis = startMillis + 3_600_000))
// A missing start is "no value": never a fabricated 0s and never a crash.
assertNull(runDurationText("", "", executing = true, nowMillis = startMillis))
// A future start (clock skew) clamps to 0s rather than going negative.
assertEquals("0s", runDurationText(start, "", executing = true, nowMillis = startMillis - 5_000))
// A finished run ignores the clock and keeps its stored total duration.
assertEquals(
"2m 5s",
runDurationText(
start,
"2026-10-15T02:02:05Z",
executing = false,
nowMillis = startMillis + 9_999_000,
),
)
// A finished run with no end timestamp has no duration, not an elapsed.
assertNull(runDurationText(start, "", executing = false, nowMillis = startMillis + 9_999_000))
}
@Test
fun fileChangesSummaryOmitsBlankParts() {
assertEquals("", fileChangesSummary(StageFileChanges()))
@@ -0,0 +1,66 @@
package net.awan.pipelines.ui.components
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* The list-scroll restore/clamp rule is pure, so it is checked here without a
* device: a saved position survives while its item is still in the list (the
* same index at the same offset), and a list that shrank underneath the operator
* clamps to the nearest valid item — the saved offset applies only to the saved
* item, an empty list stays at the top, and nothing throws.
*/
class ListScrollTest {
@Test
fun keepsTheSavedIndexAndOffsetWhenTheItemSurvived() {
assertEquals(
ListScrollAnchor(4, 37),
restoredScrollAnchor(ListScrollAnchor(4, 37), itemCount = 9),
)
}
@Test
fun keepsTheOffsetAtTheLastItem() {
assertEquals(
ListScrollAnchor(8, 12),
restoredScrollAnchor(ListScrollAnchor(8, 12), itemCount = 9),
)
}
@Test
fun clampsAShrunkenListToItsLastItemAndDropsTheOffset() {
assertEquals(
ListScrollAnchor(2, 0),
restoredScrollAnchor(ListScrollAnchor(7, 90), itemCount = 3),
)
}
@Test
fun clampsANegativeIndexToTheTopWithoutTheOffset() {
assertEquals(
ListScrollAnchor(0, 0),
restoredScrollAnchor(ListScrollAnchor(-3, 25), itemCount = 5),
)
}
@Test
fun anEmptyListStaysAtTheTop() {
assertEquals(
ListScrollAnchor(0, 0),
restoredScrollAnchor(ListScrollAnchor(6, 40), itemCount = 0),
)
}
@Test
fun aSingleItemListClampsButKeepsTheOffsetOnlyForThatItem() {
assertEquals(
ListScrollAnchor(0, 15),
restoredScrollAnchor(ListScrollAnchor(0, 15), itemCount = 1),
)
assertEquals(
ListScrollAnchor(0, 0),
restoredScrollAnchor(ListScrollAnchor(5, 15), itemCount = 1),
)
}
}
@@ -6,10 +6,11 @@ import org.junit.Test
/**
* The load-phase classification is pure, so the rules the cross-fading screens
* rely on are checked here without a device: a failed load with no data wins over
* loading, a load with no data is loading, an empty result is empty, and stale
* data always keeps the pane on content (the screen shows the error inline
* instead). Detail panes have no empty state, so absent data is an error or a
* load. The message-carrying phases keep the text captured at classification.
* loading, a list with no data yet (a load in flight, or one that has never
* loaded) is loading, an empty result is empty, and stale data always keeps the
* pane on content (the screen shows the error inline instead). Detail panes have
* no empty state, so absent data is an error or a load. The message-carrying
* phases keep the text captured at classification.
*/
class LoadPhaseTest {
@@ -60,16 +61,48 @@ class LoadPhaseTest {
)
}
@Test
fun listThatHasNeverLoadedReportsLoadingEvenBeforeTheRefreshStarts() {
// The runs pane has no pane-level empty state, so a data-less frame with
// no in-flight refresh would read as content unless the pane reports that
// it has never loaded. It must read as loading instead, so the restored
// scroll position is never clamped against the transient not-yet-loaded
// list (the empty line lives inside the loaded list).
assertEquals(
LoadPhase.Loading,
listLoadPhase(
loading = false,
error = null,
hasData = false,
emptyMessage = null,
loaded = false,
),
)
}
@Test
fun listWithoutAnySignalStaysOnContent() {
// A runs pane deliberately has no pane-level empty state, so its initial
// no-data/no-error frame is content (the empty line lives in the list).
// A screen with no "has loaded" signal (the default) keeps the old rule.
assertEquals(
LoadPhase.Content,
listLoadPhase(loading = false, error = null, hasData = false, emptyMessage = null),
)
}
@Test
fun aLoadedButDataLessListWithoutAnEmptyMessageIsStillContent() {
assertEquals(
LoadPhase.Content,
listLoadPhase(
loading = false,
error = null,
hasData = false,
emptyMessage = null,
loaded = true,
),
)
}
// ---- detail panes -------------------------------------------------------
@Test
@@ -0,0 +1,63 @@
package net.awan.pipelines.ui.components
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.MIN_COVERED_PANE_WIDTH_DP
import net.awan.pipelines.ui.theme.PEEK_WIDTH_DP
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The covered pane's statistics degrade by width through a pure decision, so
* which statistics show at which width is asserted here without a device: a thin
* strip keeps the title only, a medium strip the run counts, and a wide strip the
* full block. No tier ever shows a figure without its label.
*/
class PaneIdentityTest {
private val counts = listOf(
PaneStat("runs", "11"),
PaneStat("succeeded", "9"),
PaneStat("failed", "2"),
PaneStat("active", "1"),
)
private val details = listOf(
PaneStat("last", "succeeded · 2h ago", detail = true),
PaneStat("avg", "1m 5s", detail = true),
)
@Test
fun aStripThinnerThanOnePeekKeepsTheTitleOnly() {
assertEquals(PaneStatTier.Title, paneStatTier(PEEK_WIDTH_DP - 1.dp))
assertTrue(visiblePaneStats(counts + details, PaneStatTier.Title).isEmpty())
}
@Test
fun aMinimumCoveredStripShowsTheRunCounts() {
assertEquals(PaneStatTier.Counts, paneStatTier(MIN_COVERED_PANE_WIDTH_DP))
assertEquals(counts, visiblePaneStats(counts + details, PaneStatTier.Counts))
}
@Test
fun aStripWideEnoughForTheLongestLineShowsEveryStatistic() {
assertEquals(PaneStatTier.Full, paneStatTier(MIN_COVERED_PANE_WIDTH_DP + PEEK_WIDTH_DP))
assertEquals(counts + details, visiblePaneStats(counts + details, PaneStatTier.Full))
}
@Test
fun theTierBoundariesAreMonotonic() {
val widths = listOf(0.dp, PEEK_WIDTH_DP, MIN_COVERED_PANE_WIDTH_DP, 400.dp)
val tiers = widths.map(::paneStatTier)
assertEquals(listOf(PaneStatTier.Title, PaneStatTier.Counts, PaneStatTier.Counts, PaneStatTier.Full), tiers)
}
@Test
fun everyShownStatisticKeepsItsLabel() {
for (tier in PaneStatTier.entries) {
visiblePaneStats(counts + details, tier).forEach {
assertTrue("a statistic without a label at $tier: $it", it.label.isNotBlank())
assertTrue("a statistic without a value at $tier: $it", it.value.isNotBlank())
}
}
}
}
@@ -2,128 +2,119 @@ package net.awan.pipelines.ui.components
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.MIN_ACTIVE_PANE_WIDTH_DP
import net.awan.pipelines.ui.theme.MIN_COVERED_PANE_WIDTH_DP
import net.awan.pipelines.ui.theme.PEEK_BUDGET_DP
import net.awan.pipelines.ui.theme.PEEK_WIDTH_DP
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The pane geometry is pure, so the adaptive width and fold rules are checked
* here without a device: a narrow window spends no peek at all, a wide window
* spends one fixed budget shared between the covered panes however deep the
* stack gets, every shown peek keeps the named minimum covered width, and when
* the budget cannot give the whole stack that much the oldest levels fold into a
* single edge indicator rather than being squeezed.
* The pane geometry is pure, so the width invariant and the fold rules are
* checked here without a device: a narrow window spends no covered region at any
* depth, the covered region — and therefore the active pane's width — is the same
* at every depth, the nearest covered level keeps its identity edge, one older
* level is a thinner edge, and levels older than that fold into that edge's count
* rather than accumulating width. When the region cannot fit both a touch target
* for the thin edge and one for the nearest identity, the older levels fold into
* the nearest edge instead of being squeezed below the platform minimum.
*/
class SlidingPaneStackTest {
private fun assertDp(expected: Dp, actual: Dp, delta: Float = 0.01f) =
assertEquals(expected.value, actual.value, delta)
private fun totalWidth(strips: List<PeekStrip>): Dp =
strips.fold(0.dp) { acc, strip -> acc + strip.width }
private val minTouch = 48.dp
private fun totalWidth(edges: List<PaneEdge>): Dp =
edges.fold(0.dp) { acc, edge -> acc + edge.width }
@Test
fun narrowWindowSpendsNoPeekAtAnyDepth() {
// Budget 0 is the narrow model: no stack and no leftover strip, so there
// are no covered strips and every pane opens at the host's left edge.
fun narrowWindowSpendsNothingAtAnyDepth() {
// A region of 0 is the narrow model: no covered strip, so every pane opens
// at the host's left edge.
for (covered in 0..4) {
assertTrue(peekStripsDp(covered, 0.dp, 30.dp, PEEK_WIDTH_DP).isEmpty())
assertTrue(coveredEdgesDp(covered, 0.dp, minTouch, 30.dp).isEmpty())
}
}
@Test
fun wideActivePaneKeepsAConstantWidthAtEveryDepth() {
fun theCoveredRegionIsTheSameAtEveryDepthSoTheActiveWidthNeverChanges() {
val host = 800.dp
val budget = peekBudgetDp(host)
assertDp(PEEK_BUDGET_DP, budget)
// The covered strips always sum to exactly the budget, so the active
// (topmost) pane's left edge — and its width — never depend on depth.
for (covered in 1..4) {
val strips = peekStripsDp(covered, budget, startInset = 0.dp, minPeek = PEEK_WIDTH_DP)
assertDp(budget, totalWidth(strips))
assertDp(host - budget, paneWidthDp(host, totalWidth(strips)))
val region = 200.dp
// The edges always sum to exactly the region, so the active (topmost)
// pane's left edge — and its width — never depend on depth. That is the
// invariant: opening another level only adds an edge inside the region.
for (covered in 1..6) {
val edges = coveredEdgesDp(covered, region, minTouch, startInset = 30.dp)
assertDp(region, totalWidth(edges))
assertDp(host - region, paneWidthDp(host, totalWidth(edges)))
}
}
@Test
fun twoCoveredLevelsEachKeepTheMinimumCoveredWidth() {
val strips = peekStripsDp(2, PEEK_BUDGET_DP, startInset = 0.dp, minPeek = PEEK_WIDTH_DP)
// Three levels (list + detail + stage): two covered panes, no fold, and
// each has at least the named minimum so its compact identity reads.
assertEquals(2, strips.size)
assertEquals(listOf(0, 1), strips.map { it.level })
strips.forEach { assertTrue("peek below the minimum: $it", it.width >= MIN_COVERED_PANE_WIDTH_DP) }
assertTrue(strips.all { it.folded == 1 })
fun oneCoveredLevelKeepsTheWholeIdentityEdge() {
val edges = coveredEdgesDp(1, 200.dp, minTouch, startInset = 30.dp)
assertEquals(1, edges.size)
assertEquals(0, edges.first().level)
assertDp(200.dp, edges.first().width)
assertEquals(0, edges.first().folded)
}
@Test
fun aFourthLevelFoldsTheOldestIntoOneIndicator() {
// Four levels (three covered) with a budget of two minimums: the oldest
// levels collapse into one edge indicator carrying their count instead of
// squeezing all three, and one peek still shows the newest covered pane.
val strips = peekStripsDp(3, PEEK_BUDGET_DP, startInset = 0.dp, minPeek = PEEK_WIDTH_DP)
assertEquals(2, strips.size)
assertEquals(2, strips.first().folded)
assertEquals(1, strips.last().folded)
assertEquals(2, strips.last().level)
assertTrue(strips.all { it.width >= MIN_COVERED_PANE_WIDTH_DP })
assertDp(PEEK_BUDGET_DP, totalWidth(strips))
fun twoCoveredLevelsShowTheNearestIdentityAndOneThinnerOlderEdge() {
val edges = coveredEdgesDp(2, 200.dp, minTouch, startInset = 30.dp)
assertEquals(2, edges.size)
// The older level (0) is the thinner edge — one touch target after the
// leading gesture inset; the nearest level (1) keeps its identity and a
// full touch target of its own.
assertEquals(listOf(0, 1), edges.map { it.level })
assertDp(30.dp + minTouch, edges.first().width)
assertTrue("nearest identity below the touch target: $edges", edges.last().width >= minTouch)
assertEquals(0, edges.last().folded)
}
@Test
fun foldedLevelsAreTheOldestAndTheNewestStillPeeks() {
val covered = 4
val strips = peekStripsDp(covered, PEEK_BUDGET_DP, startInset = 0.dp, minPeek = PEEK_WIDTH_DP)
// The newest covered level keeps its own peek; all older ones fold.
assertEquals(covered - 1, strips.last().level)
assertEquals(3, strips.first().folded)
fun beyondTwoCoveredLevelsTheOlderOnesFoldIntoOneCountEdge() {
val edges = coveredEdgesDp(4, 260.dp, minTouch, startInset = 30.dp)
assertEquals(2, edges.size)
// Levels 0..2 collapse into the single older edge (showing its newest,
// level 2) carrying their count; the nearest level (3) keeps its identity.
assertEquals(listOf(2, 3), edges.map { it.level })
assertEquals(2, edges.first().folded)
assertEquals(0, edges.last().folded)
assertDp(260.dp, totalWidth(edges))
}
@Test
fun firstStripStaysTappableAfterTheGestureInset() {
val startInset = 30.dp
val strips = peekStripsDp(2, PEEK_BUDGET_DP, startInset, PEEK_WIDTH_DP)
// The leftmost strip is widened so the tappable part (after the inset)
// still measures at least the named minimum.
assertTrue(strips.first().width - startInset >= PEEK_WIDTH_DP)
// Even when the fold forces the smallest split, the widening holds.
val folded = peekStripsDp(4, PEEK_BUDGET_DP, 80.dp, PEEK_WIDTH_DP)
assertTrue(folded.first().width - 80.dp >= PEEK_WIDTH_DP)
fun whenThereIsNoRoomTheOlderLevelsFoldIntoTheNearestCount() {
// A region that cannot give the thin older edge and the nearest identity a
// touch target each collapses to a single edge carrying the count: nothing
// is squeezed below the platform minimum touch target.
val edges = coveredEdgesDp(3, 100.dp, minTouch, startInset = 30.dp)
assertEquals(1, edges.size)
assertEquals(2, edges.first().level)
assertEquals(2, edges.first().folded)
assertDp(100.dp, edges.first().width)
}
@Test
fun budgetShrinksSoTheActivePaneNeverCollapses() {
// A host narrower than the ideal leaves room for: the budget is clamped
// so the active pane keeps at least the named minimum width.
val host = 400.dp
val budget = peekBudgetDp(host)
assertTrue(budget >= 0.dp)
assertTrue(paneWidthDp(host, budget) >= MIN_ACTIVE_PANE_WIDTH_DP)
fun theNearestEdgeKeepsATouchTargetAfterTheGestureInset() {
val startInset = 40.dp
val region = 260.dp
for (covered in 1..5) {
val edges = coveredEdgesDp(covered, region, minTouch, startInset)
val nearest = edges.last()
// The first edge is inset past the left gesture area; any other edge
// is already clear of it.
val inset = if (edges.size == 1) startInset else 0.dp
assertTrue("nearest edge below the touch target: $edges", nearest.width - inset >= minTouch)
}
}
@Test
fun tinyHostNeverProducesNegativeGeometry() {
assertDp(0.dp, peekBudgetDp(100.dp))
val empty = peekStripsDp(3, peekBudgetDp(100.dp), 0.dp, PEEK_WIDTH_DP)
assertTrue(empty.isEmpty())
assertTrue(paneWidthDp(100.dp, 0.dp) >= 0.dp)
// A tiny non-zero budget still yields one usable strip, never negative.
val tiny = peekStripsDp(3, 40.dp, 0.dp, PEEK_WIDTH_DP)
assertEquals(1, tiny.size)
assertTrue(tiny.first().width >= 0.dp)
assertTrue(paneWidthDp(100.dp, totalWidth(tiny)) >= 0.dp)
}
@Test
fun stripsAreMonotonicAndDeterministic() {
// Same inputs give the same strips (opening and closing are mirrors),
// the strips never overlap, and they never run past the budget.
val a = peekStripsDp(3, PEEK_BUDGET_DP, 30.dp, PEEK_WIDTH_DP)
val b = peekStripsDp(3, PEEK_BUDGET_DP, 30.dp, PEEK_WIDTH_DP)
fun edgesAreMonotonicAndDeterministic() {
// Same inputs give the same edges (opening and closing are mirrors), the
// edges never overlap, and they never run past the region.
val a = coveredEdgesDp(4, 260.dp, minTouch, 30.dp)
val b = coveredEdgesDp(4, 260.dp, minTouch, 30.dp)
assertEquals(a, b)
a.zipWithNext { x, y -> assertTrue(y.start >= x.start + x.width) }
assertTrue(a.all { it.width >= 0.dp })
@@ -0,0 +1,225 @@
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
/**
* The covered-pane statistics are a pure fold of the run history the app already
* holds, so the counts, the last-run facts and the average duration are asserted
* here without a device: per-pipeline counts, a pipeline with no runs, an unknown
* pipeline id (which yields no lines, never the whole-history list summary),
* zero-duration runs and the whole-history list summary.
*/
class PaneStatsTest {
private val now = OffsetDateTime.parse("2026-10-16T12:00:00Z")
private fun run(
id: Long,
pipelineId: Long,
createdAt: String,
finishedAt: String = "",
status: String = "succeeded",
) = RunSummary(
id = id,
pipelineId = pipelineId,
createdAt = createdAt,
finishedAt = finishedAt,
status = status,
)
@Test
fun pipelineStatsCountOnlyThatPipelineByStatus() {
val stats = pipelinePeekStats(
listOf(
run(1, 10, "2026-10-16T09:00:00Z", "2026-10-16T09:01:00Z"),
run(2, 10, "2026-10-16T10:00:00Z", "2026-10-16T10:01:00Z", status = "failed"),
run(3, 10, "2026-10-16T11:00:00Z", status = "running"),
run(4, 11, "2026-10-16T09:30:00Z", "2026-10-16T09:31:00Z"),
),
pipelineId = 10,
now = now,
)
assertEquals(3, stats.total)
assertEquals(1, stats.succeeded)
assertEquals(1, stats.failed)
assertEquals(1, stats.active)
}
@Test
fun queuedRunsCountAsActive() {
val stats = pipelinePeekStats(
listOf(run(1, 10, "2026-10-16T11:00:00Z", status = "queued")),
pipelineId = 10,
now = now,
)
assertEquals(1, stats.active)
assertEquals(1, stats.total)
}
@Test
fun lastRunCarriesItsStateAndHowLongAgoItStarted() {
val stats = pipelinePeekStats(
listOf(
run(1, 10, "2026-10-16T09:00:00Z", "2026-10-16T09:01:00Z"),
run(2, 10, "2026-10-16T11:00:00Z", "2026-10-16T11:01:00Z", status = "failed"),
),
pipelineId = 10,
now = now,
)
// The newer run wins even though the input order is oldest-first.
assertEquals(RunState.Failed, stats.lastState)
assertEquals("1h ago", stats.lastAgo)
}
@Test
fun averageDurationIsOverTheRunsThatFinished() {
val stats = pipelinePeekStats(
listOf(
run(1, 10, "2026-10-16T09:00:00Z", "2026-10-16T09:01:00Z"),
run(2, 10, "2026-10-16T10:00:00Z", "2026-10-16T10:02:00Z"),
// A still-running run has no finished_at and must not drag the average.
run(3, 10, "2026-10-16T11:00:00Z", status = "running"),
),
pipelineId = 10,
now = now,
)
assertEquals(90L, stats.averageSeconds)
}
@Test
fun zeroDurationRunsAreRealMeasurementsInTheAverage() {
val stats = pipelinePeekStats(
listOf(
run(1, 10, "2026-10-16T09:00:00Z", "2026-10-16T09:00:00Z"),
run(2, 10, "2026-10-16T10:00:00Z", "2026-10-16T10:01:00Z"),
),
pipelineId = 10,
now = now,
)
// 0s and 60s average to 30s: the zero is counted, not skipped.
assertEquals(30L, stats.averageSeconds)
}
@Test
fun aPipelineWithNoRunsIsAllZerosAndNoLastRun() {
val stats = pipelinePeekStats(
listOf(run(1, 11, "2026-10-16T09:00:00Z", "2026-10-16T09:01:00Z")),
pipelineId = 10,
now = now,
)
assertEquals(0, stats.total)
assertEquals(0, stats.succeeded)
assertEquals(0, stats.failed)
assertEquals(0, stats.active)
assertNull(stats.lastState)
assertNull(stats.lastAgo)
assertNull(stats.averageSeconds)
}
@Test
fun unknownPipelineIdIsAllZerosAndNoLastRun() {
val stats = pipelinePeekStats(
listOf(run(1, 10, "2026-10-16T09:00:00Z", "2026-10-16T09:01:00Z")),
pipelineId = 99,
now = now,
)
assertEquals(0, stats.total)
assertNull(stats.lastState)
assertNull(stats.averageSeconds)
}
@Test
fun emptyHistoryIsAllZerosAndNoLastRun() {
val stats = pipelinePeekStats(emptyList(), pipelineId = 10, now = now)
assertEquals(0, stats.total)
assertNull(stats.lastState)
assertNull(stats.averageSeconds)
}
@Test
fun listStatsFoldTheWholeHistoryAndFindTheMostRecentRun() {
val stats = listPeekStats(
listOf(
run(1, 10, "2026-10-16T09:00:00Z", "2026-10-16T09:01:00Z"),
run(2, 11, "2026-10-16T11:30:00Z", status = "running"),
run(3, 11, "2026-10-16T08:00:00Z", status = "failed"),
),
now = now,
)
assertEquals(3, stats.total)
assertEquals(1, stats.succeeded)
assertEquals(1, stats.failed)
assertEquals(1, stats.active)
assertEquals(RunState.Running, stats.lastState)
assertEquals("30m ago", stats.lastAgo)
}
@Test
fun linesKeepALabelWithEveryNumberAndMarkTheDetailLines() {
val lines = pipelinePeekStats(
listOf(run(1, 10, "2026-10-16T11:00:00Z", "2026-10-16T11:01:00Z")),
pipelineId = 10,
now = now,
).lines()
assertEquals(listOf("runs", "succeeded", "failed", "active", "last", "avg"), lines.map { it.label })
assertEquals(listOf("1", "1", "0", "0"), lines.take(4).map { it.value })
assertTrue(lines.take(4).none { it.detail })
assertTrue(lines.drop(4).all { it.detail })
}
@Test
fun aPipelineWithNoRunsShowsCountsButNoLastRunOrAverageLines() {
val lines = pipelinePeekStats(emptyList(), pipelineId = 10, now = now).lines()
assertEquals(listOf("runs", "succeeded", "failed", "active"), lines.map { it.label })
}
@Test
fun listLinesCarryNoAverage() {
val lines = listPeekStats(emptyList(), now).lines()
assertEquals(listOf("runs", "succeeded", "failed", "active"), lines.map { it.label })
}
@Test
fun anUnknownPipelineYieldsNoLinesInsteadOfTheWholeHistorySummary() {
val history = listOf(
run(1, 10, "2026-10-16T09:00:00Z", "2026-10-16T09:01:00Z"),
run(2, 11, "2026-10-16T09:30:00Z", "2026-10-16T09:31:00Z"),
)
// A run pane whose pipeline is not known yet (the run has not loaded) must
// not borrow the server-wide list summary; it shows no statistics at all.
assertTrue(pipelineStatLines(history, null, now).isEmpty())
// Nor before the history has loaded, even for a known pipeline.
assertTrue(pipelineStatLines(null, 10, now).isEmpty())
}
@Test
fun pipelineStatLinesFoldOnlyTheNamedPipeline() {
val history = listOf(
run(1, 10, "2026-10-16T09:00:00Z", "2026-10-16T09:01:00Z"),
run(2, 11, "2026-10-16T09:30:00Z", "2026-10-16T09:31:00Z"),
)
val lines = pipelineStatLines(history, 10, now)
assertEquals(listOf("runs", "succeeded", "failed", "active", "last", "avg"), lines.map { it.label })
assertEquals("1", lines.first().value)
}
@Test
fun listStatLinesAreEmptyUntilLoadedThenFoldTheWholeHistory() {
assertTrue(listStatLines(null, now).isEmpty())
val lines = listStatLines(
listOf(
run(1, 10, "2026-10-16T09:00:00Z", "2026-10-16T09:01:00Z"),
run(2, 11, "2026-10-16T09:30:00Z", status = "running"),
),
now,
)
assertEquals(listOf("runs", "succeeded", "failed", "active", "last"), lines.map { it.label })
assertEquals("2", lines.first().value)
}
}
@@ -18,12 +18,14 @@ class PipelineLastRunTest {
createdAt: String,
finishedAt: String = createdAt,
status: String = "succeeded",
executing: Boolean = false,
) = RunSummary(
id = id,
pipelineId = pipelineId,
createdAt = createdAt,
finishedAt = finishedAt,
status = status,
executing = executing,
)
@Test
@@ -96,10 +98,30 @@ class PipelineLastRunTest {
}
@Test
fun metaLineOmitsAMissingDuration() {
// A running run has no finished_at, so the duration fragment is dropped.
fun metaLineShowsTheLiveElapsedOfARunningRun() {
// A running run has no finished_at, so its time fragment is the elapsed
// from its start to the anchor, recomputed as the shared clock advances.
val badge = pipelineRunBadges(
listOf(run(42, 10, "2026-10-16T11:00:00Z", finishedAt = "", status = "running")),
listOf(
run(
42,
10,
"2026-10-16T11:57:30Z",
finishedAt = "",
status = "running",
executing = true,
),
),
now,
).getValue(10L)
assertEquals("2m ago · 2m 30s · run 42", badge.metaLine())
}
@Test
fun metaLineOmitsAMissingDuration() {
// A finished run with no end timestamp has no duration fragment.
val badge = pipelineRunBadges(
listOf(run(42, 10, "2026-10-16T11:00:00Z", finishedAt = "")),
now,
).getValue(10L)
assertEquals("1h ago · run 42", badge.metaLine())
@@ -0,0 +1,90 @@
package net.awan.pipelines.ui.screens
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.data.protocol.UsageStats
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* The runs list's slots are built in one pure place, so the count a restored
* scroll position is clamped against is exactly what the LazyColumn draws: the
* usage block, the single empty-or-grouped body and the optional inline error
* row, in that order, with the stable keys the layout has always used.
*/
class RunListEntriesTest {
private fun run(id: Long) = RunSummary(id = id, name = "p$id")
@Test
fun usageThenDayGroupsThenRunsInOrder() {
val groups = listOf(
RunDayGroup("Today", listOf(run(2), run(1))),
RunDayGroup("Yesterday", listOf(run(3))),
)
val entries = runListEntries(
usage = UsageStats(total = 3),
nothingRecorded = false,
nothingMatched = false,
groups = groups,
error = null,
)
assertEquals(
listOf("usage", "day-Today", "run-2", "run-1", "day-Yesterday", "run-3"),
entries.map { it.key },
)
assertEquals(6, entries.size)
}
@Test
fun nothingRecordedIsOneEmptyLineWithoutAnAction() {
val entries = runListEntries(
usage = UsageStats(total = 0),
nothingRecorded = true,
nothingMatched = false,
groups = emptyList(),
error = null,
)
assertEquals(listOf("usage", "runs-empty"), entries.map { it.key })
val empty = entries.last() as RunListEntry.Empty
assertEquals("No runs have been recorded yet.", empty.message)
assertEquals(null, empty.actionLabel)
}
@Test
fun nothingMatchedIsOneEmptyLineWithTheClearAction() {
val entries = runListEntries(
usage = null,
nothingRecorded = false,
nothingMatched = true,
groups = emptyList(),
error = null,
)
assertEquals(listOf("runs-filtered-empty"), entries.map { it.key })
assertEquals("Clear filters", (entries.single() as RunListEntry.Empty).actionLabel)
}
@Test
fun theInlineErrorRowIsAppendedUnderTheRows() {
val entries = runListEntries(
usage = null,
nothingRecorded = false,
nothingMatched = false,
groups = listOf(RunDayGroup("Today", listOf(run(1)))),
error = "offline",
)
assertEquals(listOf("day-Today", "run-1", "runs-error"), entries.map { it.key })
assertEquals("offline", (entries.last() as RunListEntry.Error).message)
}
@Test
fun aNotYetRecordedHistoryWinsOverAFilteredEmptyOne() {
val entries = runListEntries(
usage = null,
nothingRecorded = true,
nothingMatched = true,
groups = emptyList(),
error = null,
)
assertEquals(listOf("runs-empty"), entries.map { it.key })
}
}