Show live elapsed time for running runs

A running run now shows how long it has taken so far instead of its start
time, kept live: the runs-list meta row, the pipeline list's last-run line
and the run detail summary's Duration row all read one shared rule,
runDurationText (ui/Format.kt), which reports the elapsed while executing and
keeps the stored total once the run has finished.

The elapsed is derived from the server's own start timestamp against a single
shared clock, rememberLiveNowMillis/hostResumed (ui/components/LiveTime.kt),
so it stays correct after a reconnect and never ticks while the app is
backgrounded or while no shown run is executing. WorkflowGraph's private
lifecycle read and once-a-second loop are replaced by that same shared pair.
A missing start omits the value and a future start (clock skew) reads as 0s.

Unit tests (FormatTest, PipelineLastRunTest) cover a run that has just
started, the minute and hour boundaries, a missing and a future start, and a
finished run keeping its stored total duration.
This commit is contained in:
2026-10-16 18:13:50 +01:00
parent c700b28e6a
commit b003872032
10 changed files with 645 additions and 121 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
@@ -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
}
@@ -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
@@ -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,39 @@ 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,
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 +139,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 +214,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 +229,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(),
)
}
}
}
}
@@ -44,6 +44,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 +70,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 +110,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 +159,20 @@ 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,
modifier = modifier.fillMaxSize(),
)
return
@@ -408,7 +420,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 +429,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,7 +15,7 @@ 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.filled.Refresh
@@ -56,6 +56,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 +65,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 +89,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 +111,25 @@ 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,
modifier = modifier.fillMaxSize(),
)
return
@@ -159,6 +175,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 +200,7 @@ fun RunHistoryScreen(
error = state.error,
onOpenRun = onOpenRun,
onClearFilters = onClearFilters,
listState = listState,
modifier = Modifier.padding(padding),
)
}
@@ -247,6 +269,7 @@ private fun RunHistoryContent(
error: String?,
onOpenRun: (Long) -> Unit,
onClearFilters: () -> Unit,
listState: LazyListState,
modifier: Modifier = Modifier,
) {
val zone = ZoneId.systemDefault()
@@ -265,59 +288,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 +486,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 +539,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 +576,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? {
@@ -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()))
@@ -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())