Animate the active stage and executed edges in the run graph

Show what is happening while a run is live. The executing stage now carries a
subtle pulsing halo (replacing the blink) and a live ticking elapsed badge
derived from the run's current visit start. Executed edges carry a directional
flow of light dots along the path; a finished stage settles into its static
colour. A finished run never animates, the animation pauses when the graph is
off screen, and with the system animation setting disabled it falls back to a
static but clearly marked running state.

The per-frame visual state and should-animate decision live in pure functions
(GraphMotion.kt, Format.kt secondsSince; GraphSemantics exposes executing and
currentStageStartedAt) with unit tests and no frame-timing assertions. Adds
GraphMotionTest and extends GraphSemanticsTest and FormatTest.
This commit is contained in:
2026-10-16 09:52:57 +01:00
parent 1e7862e7c9
commit 8b39c087fd
8 changed files with 581 additions and 14 deletions
@@ -75,6 +75,17 @@ data class RunGraphState(
val visitedStages: Set<String>,
val takenRoutes: Set<GraphRoute>,
val currentStage: String?,
/**
* True while the server still reports the run as executing. The graph only
* animates a live run; a finished one is drawn settled and static.
*/
val executing: Boolean = false,
/**
* RFC3339 start of the visit currently running for [currentStage], or null
* when the run is not live or that visit's start is unknown. The graph uses
* it for the live ticking elapsed time on the active node.
*/
val currentStageStartedAt: String? = null,
) {
companion object {
fun from(run: RunDetail): RunGraphState {
@@ -91,7 +102,17 @@ data class RunGraphState(
val current = run.currentStage.ifEmpty {
run.steps.lastOrNull()?.stage ?: ""
}
return RunGraphState(stages, routes, current.ifEmpty { null })
val stage = current.ifEmpty { null }
// Only a live run carries a ticking active stage; the matching running
// step's start keeps the timer on the same node as the halo.
val runningSince = if (run.executing && stage != null) {
run.steps.lastOrNull { it.stage == stage && it.status == "running" }
?.startedAt
?.takeIf { it.isNotBlank() }
} else {
null
}
return RunGraphState(stages, routes, stage, run.executing, runningSince)
}
}
}
@@ -38,6 +38,17 @@ internal fun durationSeconds(start: String, end: String): Long? {
fun formatDuration(start: String, end: String): String? =
durationSeconds(start, end)?.let(::formatDuration)
/**
* Non-negative whole seconds from a [start] RFC3339 timestamp to [nowMillis]
* (wall-clock epoch millis), or null when [start] is blank/unparseable. Clamps a
* future/unparseable elapsed to 0 so a live timer never prints a negative or a
* nonsensical value. The one derivation behind the run graph's ticking elapsed
* time, so it is pure and testable without the Compose runtime.
*/
internal fun secondsSince(start: String, nowMillis: Long): Long? =
parseInstant(start)?.let { ((nowMillis - it.toInstant().toEpochMilli()) / 1000).coerceAtLeast(0) }
/**
* Human duration for a whole number of seconds. The single formatting rule for
* every duration the UI shows (list meta, usage average, run summary, step
@@ -0,0 +1,99 @@
package net.awan.pipelines.ui.graph
import net.awan.pipelines.data.protocol.GraphEdge
import net.awan.pipelines.data.protocol.RunGraphState
import kotlin.math.PI
import kotlin.math.sin
/**
* How a stage node is drawn under a run:
*
* - [Active]: the stage the live run is executing right now; it carries a
* pulsing halo, and its live elapsed time is drawn under its label.
* - [Visited]: a stage the run already visited (or any stage in the
* definition-only view); it settles into its static fill/border.
* - [Unvisited]: a stage the run did not reach; drawn hollow, never animating.
*
* A finished run has no [Active] node, so nothing animates once it stops.
*/
internal enum class NodeMotion { Active, Visited, Unvisited }
/**
* How an edge is drawn under a run:
*
* - [Flowing]: an executed route while the run is live; its stroke carries a
* moving dot that reads the direction of travel.
* - [Settled]: an executed route under a finished run; a plain static stroke.
* - [Unvisited]: a route the run did not take; dashed and arrowless.
*/
internal enum class EdgeMotion { Flowing, Settled, Unvisited }
/**
* Whether the graph may animate at all, from the three independent gates:
* the run must still be executing (never animate a finished run), the system
* must have animations enabled (honour the OS/animation-scale setting), and the
* graph must be on screen (a backgrounded graph is paused). Pure, so the
* decision is asserted in a unit test rather than inferred from a frame clock.
*
* When this is false while the run is live, the graph still marks the active
* stage statically (see [ACTIVE_HALO_STATIC_ALPHA] and the drawn elapsed time),
* so "animations off" is a static but unmistakable running state, not a blank.
*/
internal fun graphShouldAnimate(
runState: RunGraphState?,
animationsEnabled: Boolean,
onScreen: Boolean,
): Boolean = runState?.executing == true && animationsEnabled && onScreen
/**
* The motion state of the stage [key] under [runState]. Pure and the single
* definition the drawing and the tests share: the definition-only view
* ([runState] == null) is entirely visited/static, an unvisited key is idle, and
* only the stage the live run is on is [NodeMotion.Active]. The live stage wins
* over the visited check, so it is unmistakably active even in the brief window
* before its step has been recorded in [RunGraphState.visitedStages].
*/
internal fun nodeMotion(key: String, runState: RunGraphState?): NodeMotion = when {
runState == null -> NodeMotion.Visited
runState.executing && key == runState.currentStage -> NodeMotion.Active
key !in runState.visitedStages -> NodeMotion.Unvisited
else -> NodeMotion.Visited
}
/**
* The motion state of [edge] under [runState]: an executed route flows while the
* run is live and settles once it finishes, and an untaken route is idle. The
* definition-only view ([runState] == null) is settled (static), as before.
*/
internal fun edgeMotion(edge: GraphEdge, runState: RunGraphState?): EdgeMotion = when {
!edgeIsExecuted(edge, runState) -> EdgeMotion.Unvisited
runState?.executing == true -> EdgeMotion.Flowing
else -> EdgeMotion.Settled
}
/**
* The active-node halo strength for a 0..1 animation [phase]: a smooth
* sinusoid that rises and falls once per cycle, never stepping between two
* values (a pulse, not a blink). Bounded to `[PULSE_MIN, PULSE_MAX]` so the
* halo is always visible and never fully transparent, and periodic in [phase]
* so it is seamless at the wrap. Pure, so the rhythm is asserted without any
* frame-timing.
*/
internal fun pulseAlpha(phase: Float): Float {
val t = ((phase % 1f) + 1f) % 1f
val wave = (sin(t * 2.0 * PI) + 1.0) / 2.0
return (PULSE_MIN + (PULSE_MAX - PULSE_MIN) * wave).toFloat()
}
/** Faintest the active halo ever gets; never invisible, never a blink-off. */
private const val PULSE_MIN = 0.35f
/** Strongest the active halo gets at the peak of a pulse. */
private const val PULSE_MAX = 0.9f
/**
* The fixed active-halo strength drawn when animation is off (the system
* setting, or a paused graph): clearly marked, just not moving. Within the
* [pulseAlpha] range so the static state looks like a frozen pulse.
*/
internal const val ACTIVE_HALO_STATIC_ALPHA = 0.85f
@@ -1,5 +1,12 @@
package net.awan.pipelines.ui.graph
import android.animation.ValueAnimator
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
@@ -29,6 +36,7 @@ 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
@@ -37,6 +45,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
@@ -56,6 +65,7 @@ import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
@@ -66,8 +76,13 @@ import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
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
@@ -76,6 +91,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.formatDuration
import net.awan.pipelines.ui.secondsSince
internal data class NodeLayout(
val key: String,
@@ -218,6 +235,48 @@ fun WorkflowGraph(
)
}
// Motion gates, all pure and testable (see GraphMotion.kt): only a live run,
// with animations enabled and the graph on screen, animates. Never animate a
// 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 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.
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)
}
}
// Measured once per second (never per frame) so the canvas draw adds no
// allocation for the timer.
val elapsedLayout = remember(activeStartedAt, nowMillis, scheme, density) {
secondsSince(activeStartedAt.orEmpty(), nowMillis)
?.let(::formatDuration)
?.let {
textMeasurer.measure(
it,
TextStyle(fontSize = 11.sp, fontWeight = FontWeight.Medium, color = colors.nodeText),
)
}
}
// Halo and badge geometry as dp tokens (like the node layout), so they scale
// with the device rather than sitting at a raw pixel size.
val haloGapPx = with(density) { ACTIVE_HALO_GAP.toPx() }
val haloStrokePx = with(density) { ACTIVE_HALO_STROKE.toPx() }
val elapsedInsetPx = with(density) { ELAPSED_INSET.toPx() }
Box(
modifier = modifier
// Let an expand scroll the (now taller) panel back into the visible
@@ -275,9 +334,22 @@ fun WorkflowGraph(
}) {
// Labels are drawn only after every curve so they always sit on
// top of a neighbouring edge instead of being crossed by it.
drawEdgePaths(layout, colors, runState)
drawEdgePaths(layout, colors, runState, animate, phase)
drawEdgeLabels(layout, colors, runState, textMeasurer)
drawNodes(layout, colors, runState, selectedStage, stageTypeByKey, textMeasurer)
drawNodes(
layout,
colors,
runState,
selectedStage,
stageTypeByKey,
textMeasurer,
animate,
phase,
elapsedLayout,
haloGapPx,
haloStrokePx,
elapsedInsetPx,
)
}
}
// Accessibility overlay: invisible nodes carrying a click action and a
@@ -1063,6 +1135,8 @@ private fun DrawScope.drawEdgePaths(
layout: GraphLayout,
colors: GraphColors,
runState: RunGraphState?,
animate: Boolean,
phase: Float,
) {
for (edge in layout.edges) {
// Routing already happened once in layoutGraph; drawing only replays the
@@ -1080,14 +1154,18 @@ private fun DrawScope.drawEdgePaths(
// screenshot, a dim screen and a colour-blind reader. An executed
// `success`/`error` edge uses the heavier pass/fail width, a stronger
// (same-hue) stroke and a matched arrowhead, so pass/fail dominates.
if (edgeIsExecuted(edge.edge, runState)) {
val motion = edgeMotion(edge.edge, runState)
if (motion != EdgeMotion.Unvisited) {
val color = edgeStrokeColor(edge.edge, runState, colors)
drawPath(
path,
color = color,
style = Stroke(width = edgeStrokeWidth(edge.edge, runState)),
)
val width = edgeStrokeWidth(edge.edge, runState)
drawPath(path, color = color, style = Stroke(width = width))
drawArrowHead(points, color, edgeArrowHeadSize(edge.edge, runState))
// While the run is live, an executed route carries a dot travelling
// source -> target so its direction reads at a glance. A settled or
// off-screen graph draws no dot.
if (animate && motion == EdgeMotion.Flowing) {
drawFlowDots(points, width, colors.nodeText, phase)
}
} else {
drawPath(
path,
@@ -1101,6 +1179,51 @@ private fun DrawScope.drawEdgePaths(
}
}
/**
* Draws [FLOW_DOT_COUNT] dots travelling along [points] from start to end,
* spaced evenly and advanced by [phase] (0..1), so the executed route reads its
* direction. Allocation-free: it walks the stored polyline with scalars only, so
* it is safe to call on every animation frame. The dot radius scales with the
* edge's own [strokeWidth] so it matches a pass/fail or normal route.
*/
private fun DrawScope.drawFlowDots(
points: List<Offset>,
strokeWidth: Float,
color: Color,
phase: Float,
) {
var total = 0f
for (i in 1 until points.size) {
total += hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y)
}
if (total <= 0f) return
val radius = strokeWidth * FLOW_DOT_SCALE
for (dot in 0 until FLOW_DOT_COUNT) {
val fraction = ((phase + dot.toFloat() / FLOW_DOT_COUNT) % 1f + 1f) % 1f
val center = pointAlong(points, fraction * total) ?: continue
drawCircle(color = color, radius = radius, center = center)
}
}
/**
* The point [distance] along the polyline [points], or null when there is no
* segment. Pure scalar interpolation with no allocation.
*/
private fun pointAlong(points: List<Offset>, distance: Float): Offset? {
var remaining = distance
for (i in 1 until points.size) {
val a = points[i - 1]
val b = points[i]
val length = hypot(b.x - a.x, b.y - a.y)
if (remaining <= length) {
val t = if (length <= 0f) 0f else remaining / length
return Offset(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)
}
remaining -= length
}
return points.lastOrNull()
}
/**
* Draws every outcome label in a second pass, after all curves, so a
* neighbouring edge can never be drawn across a label. Each label sits on its
@@ -1176,14 +1299,27 @@ private fun DrawScope.drawNodes(
selectedStage: String?,
stageTypeByKey: Map<String, String?>,
textMeasurer: TextMeasurer,
animate: Boolean,
phase: Float,
elapsedLayout: TextLayoutResult?,
haloGapPx: Float,
haloStrokePx: Float,
elapsedInsetPx: Float,
) {
for (node in layout.nodes) {
val executed = stageIsExecuted(node.key, runState)
val motion = nodeMotion(node.key, runState)
val executed = motion != NodeMotion.Unvisited
val selected = node.key == selectedStage
val kind = graphNodeKind(node.terminal, node.key, stageTypeByKey[node.key])
val topLeft = Offset(node.x, node.y)
val corner = androidx.compose.ui.geometry.CornerRadius(14f, 14f)
val corner = CornerRadius(NODE_CORNER_RADIUS, NODE_CORNER_RADIUS)
val borderWidth = if (selected && !node.terminal) 4f else 2f
// The active stage carries a halo behind its fill: a pulse while
// animating, a fixed but clearly visible ring otherwise, so a live run's
// current stage is unmistakable with or without animation.
if (motion == NodeMotion.Active) {
drawActiveHalo(node, colors, animate, phase, corner, haloGapPx, haloStrokePx)
}
val textColor: Color
if (executed) {
// Filled with a normal border, exactly as the definition-only view.
@@ -1243,9 +1379,62 @@ private fun DrawScope.drawNodes(
node.y + (node.height - measured.size.height) / 2f,
),
)
// The active stage's live elapsed time, drawn as a badge under its label
// from the pre-measured layout (so the draw pass adds no allocation), on
// a near-opaque surface chip so it stays legible over any node fill (the
// selected active node is filled light in the dark theme). Only the
// active node has one, and only while the run is live.
if (motion == NodeMotion.Active && elapsedLayout != null) {
val badgeTopLeft = Offset(
x = node.x + (node.width - elapsedLayout.size.width) / 2f,
y = node.y + node.height - elapsedLayout.size.height - elapsedInsetPx,
)
drawRect(
color = colors.labelBackground.copy(alpha = 0.92f),
topLeft = Offset(badgeTopLeft.x - 3f, badgeTopLeft.y - 1f),
size = Size(elapsedLayout.size.width + 6f, elapsedLayout.size.height + 2f),
)
drawText(textLayoutResult = elapsedLayout, topLeft = badgeTopLeft)
}
}
}
/**
* The halo that makes the active stage unmistakable: a rounded-rect ring drawn a
* little outside the node, behind its fill, plus a soft glow filling the ring so
* it reads even at a small fit scale. Its strength is the smooth [pulseAlpha]
* while animating and [ACTIVE_HALO_STATIC_ALPHA] when the graph is static
* (animations disabled or paused), so the active stage is clearly marked in both
* cases. Drawing it uses only primitives, so it allocates nothing.
*/
private fun DrawScope.drawActiveHalo(
node: NodeLayout,
colors: GraphColors,
animate: Boolean,
phase: Float,
corner: CornerRadius,
gap: Float,
strokeWidth: Float,
) {
val strength = if (animate) pulseAlpha(phase) else ACTIVE_HALO_STATIC_ALPHA
val topLeft = Offset(node.x - gap, node.y - gap)
val size = Size(node.width + gap * 2f, node.height + gap * 2f)
val haloCorner = CornerRadius(corner.x + gap, corner.y + gap)
drawRoundRect(
color = colors.nodeBorderActive.copy(alpha = strength * ACTIVE_HALO_GLOW),
topLeft = topLeft,
size = size,
cornerRadius = haloCorner,
)
drawRoundRect(
color = colors.nodeBorderActive.copy(alpha = strength),
topLeft = topLeft,
size = size,
cornerRadius = haloCorner,
style = Stroke(width = strokeWidth),
)
}
/**
* The colour for an outcome: the theme error role for `error`, a clearly
* positive theme colour for `success`, and the curated [GraphPalette] entry for
@@ -1323,7 +1512,12 @@ private fun graphDescription(graph: Graph, runState: RunGraphState?): String {
for (stage in graph.stages) {
val executed = stageIsExecuted(stage.key, runState)
builder.append("Stage ${stage.key}")
if (runState != null) builder.append(if (executed) ", executed" else ", not executed")
if (runState != null) {
builder.append(if (executed) ", executed" else ", not executed")
if (runState.executing && stage.key == runState.currentStage) {
builder.append(", currently running")
}
}
builder.append(". ")
for (outcome in GraphSemantics.outcomes(stage)) {
val target = Protocol.resolveTarget(outcome, stage.edges[outcome] ?: continue)
@@ -1342,6 +1536,54 @@ private const val MAX_SCALE = 3f
private val FIT_PADDING = 16.dp
private val MIN_VISIBLE = 48.dp
/**
* The active-node pulse: one full cycle per [PULSE_PERIOD_MILLIS], driven by a
* linear 0..1 phase and mapped to a smooth strength by [pulseAlpha]. A slow sine
* is a halo, never a blink. Only composed while [graphShouldAnimate] is true, so
* a finished, off-screen or animations-disabled graph has no animation clock.
*/
@Composable
private fun rememberPulsePhase(animate: Boolean): Float {
if (!animate) return 0f
val transition = rememberInfiniteTransition(label = "graph-pulse")
val phase by transition.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = PULSE_PERIOD_MILLIS, easing = LinearEasing),
repeatMode = RepeatMode.Restart,
),
label = "graph-pulse-phase",
)
return phase
}
/** 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
/** Corner radius of a node rect, shared by the fill/border and the active halo. */
private const val NODE_CORNER_RADIUS = 14f
/**
* The active halo: how far outside the node it sits, how thick its ring is, and
* how much of the pulse strength its soft glow carries. dp tokens (like the node
* layout) so they scale with the device; the raw node border/corner literals are
* pre-existing graph geometry.
*/
private val ACTIVE_HALO_GAP = 6.dp
private val ACTIVE_HALO_STROKE = 4.dp
private const val ACTIVE_HALO_GLOW = 0.28f
/** Bottom inset of the active node's elapsed-time badge inside the node rect. */
private val ELAPSED_INSET = 4.dp
/** Executed-edge flow: this many dots per route, sized against the edge stroke. */
private const val FLOW_DOT_COUNT = 2
private const val FLOW_DOT_SCALE = 1.2f
/**
* Line-style tokens shared by the graph and its legend. Widths and the arrowhead
* size are named here so no call site writes a stroke literal. An executed route
@@ -368,7 +368,11 @@ private fun RunGraphTab(
onStageTap: (String, Int) -> Unit,
) {
val text = pipelinesText()
val runState = remember(run.id, run.steps) { RunGraphState.from(run) }
// Keyed on the fields RunGraphState.from reads (steps, executing, current
// stage) so a run that finishes without a new step still stops animating.
val runState = remember(run.id, run.steps, run.executing, run.currentStage) {
RunGraphState.from(run)
}
// Grouped once per step-list change; the sheet opened from the graph starts on
// the most recent visit of the tapped stage.
val timeline = remember(run.steps) { runTimeline(run.steps) }
@@ -385,7 +389,7 @@ private fun RunGraphTab(
Text("This server did not include the run graph.", style = text.meta)
} else {
Text(
"Executed stages and routes are solid; not-executed ones are dashed and outlined. Executed success and failure routes are drawn thickest. Pinch to zoom, drag to pan, tap a stage for details.",
"The running stage pulses with its elapsed time and executed routes flow; a finished run settles, and with animations off the running stage stays marked. Solid means executed, dashed and outlined not executed; executed success and failure routes are drawn thickest. Pinch to zoom, drag to pan, tap a stage for details.",
style = text.meta,
)
WorkflowGraph(
@@ -2,6 +2,7 @@ package net.awan.pipelines.data.protocol
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -77,5 +78,34 @@ class GraphSemanticsTest {
assertEquals(setOf("a", "b", "#failure", "#success"), state.visitedStages)
assertTrue(GraphRoute("a", "error", "#failure") in state.takenRoutes)
assertEquals("b", state.currentStage)
// A finished run animates nothing: no executing flag, no live start.
assertFalse(state.executing)
assertNull(state.currentStageStartedAt)
}
@Test
fun runGraphStateCarriesTheLiveStageAndItsStart() {
val run = RunDetail(
id = 2,
name = "demo",
status = "running",
executing = true,
currentStage = "b",
steps = listOf(
RunStep(
sequence = 1,
stage = "a",
status = "succeeded",
startedAt = "2026-10-16T07:00:00Z",
finishedAt = "2026-10-16T07:01:00Z",
),
RunStep(sequence = 2, stage = "b", status = "running", startedAt = "2026-10-16T07:01:00Z"),
),
)
val state = RunGraphState.from(run)
assertTrue(state.executing)
assertEquals("b", state.currentStage)
// The timer rides on the stage the run is on, from that visit's start.
assertEquals("2026-10-16T07:01:00Z", state.currentStageStartedAt)
}
}
@@ -33,6 +33,19 @@ class FormatTest {
assertNull(formatDuration("2026-10-15T02:05:00Z", "2026-10-15T02:00:00Z"))
}
@Test
fun secondsSinceCountsFromTheStartAndIsSafe() {
// 2026-10-15T02:00:00Z in epoch millis, plus a minute and a bit.
val startMillis = parseInstant("2026-10-15T02:00:00Z")!!.toInstant().toEpochMilli()
assertEquals(0L, secondsSince("2026-10-15T02:00:00Z", startMillis))
assertEquals(125L, secondsSince("2026-10-15T02:00:00Z", startMillis + 125_000))
// A start in the future clamps to 0 rather than going negative.
assertEquals(0L, secondsSince("2026-10-15T02:00:00Z", startMillis - 5_000))
// Blank or unparseable starts are "no elapsed", never a fabricated value.
assertNull(secondsSince("", startMillis))
assertNull(secondsSince("not a timestamp", startMillis))
}
@Test
fun fileChangesSummaryOmitsBlankParts() {
assertEquals("", fileChangesSummary(StageFileChanges()))
@@ -0,0 +1,147 @@
package net.awan.pipelines.ui.graph
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.GraphRoute
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.data.protocol.Stage
import net.awan.pipelines.data.protocol.edges
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.abs
/**
* The graph's motion is a pure decision: which node/edge is in which visual
* state, and whether the graph animates at all, are functions of the run state
* only. These tests assert that policy directly, with no frame clock, so a
* finished run, a paused graph and the animations-off setting are all covered
* without timing a single frame.
*/
class GraphMotionTest {
private fun stage(key: String, edges: Map<String, String>) = Stage(key = key, edges = edges)
private fun graph() = Graph(
stages = listOf(
stage("planner", mapOf("success" to "implementer", "error" to "#failure")),
stage("implementer", mapOf("success" to "reviewer", "error" to "#failure")),
stage("reviewer", mapOf("success" to "#success", "error" to "#failure")),
),
)
private fun takenRoute() = graph().edges().first { it.source == "planner" && it.outcome == "success" }
private fun untakenRoute() = graph().edges().first { it.source == "planner" && it.outcome == "error" }
/** A live run paused on `implementer`, with a recorded start for the tick. */
private fun liveRun(): RunGraphState {
val taken = takenRoute()
return RunGraphState(
visitedStages = setOf("planner", "implementer"),
takenRoutes = setOf(GraphRoute(taken.source, taken.outcome, taken.target)),
currentStage = "implementer",
executing = true,
currentStageStartedAt = "2026-10-16T07:36:56+01:00",
)
}
private fun finishedRun(): RunGraphState =
liveRun().copy(executing = false, currentStageStartedAt = null)
@Test
fun graphAnimatesOnlyForALiveRunOnScreenWithAnimationsEnabled() {
val live = liveRun()
assertTrue(graphShouldAnimate(live, animationsEnabled = true, onScreen = true))
// None of the three gates alone is enough.
assertFalse("finished runs never animate", graphShouldAnimate(finishedRun(), true, true))
assertFalse("animations disabled", graphShouldAnimate(live, animationsEnabled = false, onScreen = true))
assertFalse("off screen", graphShouldAnimate(live, animationsEnabled = true, onScreen = false))
assertFalse("definition view", graphShouldAnimate(null, animationsEnabled = true, onScreen = true))
}
@Test
fun theRunningStageIsTheOnlyActiveNode() {
val live = liveRun()
assertEquals(NodeMotion.Active, nodeMotion("implementer", live))
assertEquals(NodeMotion.Visited, nodeMotion("planner", live))
assertEquals(NodeMotion.Unvisited, nodeMotion("reviewer", live))
assertEquals(NodeMotion.Unvisited, nodeMotion("#success", live))
}
/**
* The live stage is active even before its step is recorded: [visitedStages]
* comes from the recorded steps, so a just-started stage can lag it. The halo
* must not depend on that ordering.
*/
@Test
fun theExecutingStageIsActiveEvenBeforeItsStepIsRecorded() {
val noStepsYet = RunGraphState(
visitedStages = emptySet(),
takenRoutes = emptySet(),
currentStage = "implementer",
executing = true,
currentStageStartedAt = "2026-10-16T07:36:56+01:00",
)
assertEquals(NodeMotion.Active, nodeMotion("implementer", noStepsYet))
}
@Test
fun aFinishedRunHasNoActiveNode() {
val finished = finishedRun()
assertEquals(NodeMotion.Visited, nodeMotion("implementer", finished))
assertEquals(NodeMotion.Visited, nodeMotion("planner", finished))
assertEquals(NodeMotion.Unvisited, nodeMotion("reviewer", finished))
}
@Test
fun theDefinitionViewIsEntirelySettledAndStatic() {
for (key in listOf("planner", "implementer", "reviewer", "#success", "#failure")) {
assertEquals(key, NodeMotion.Visited, nodeMotion(key, null))
}
}
@Test
fun takenRoutesFlowOnlyWhileTheRunIsLive() {
assertEquals(EdgeMotion.Flowing, edgeMotion(takenRoute(), liveRun()))
assertEquals(EdgeMotion.Settled, edgeMotion(takenRoute(), finishedRun()))
assertEquals(EdgeMotion.Unvisited, edgeMotion(untakenRoute(), liveRun()))
assertEquals(EdgeMotion.Unvisited, edgeMotion(untakenRoute(), finishedRun()))
// Definition view: every route is executed, so settled/static (as before).
assertEquals(EdgeMotion.Settled, edgeMotion(takenRoute(), null))
assertEquals(EdgeMotion.Settled, edgeMotion(untakenRoute(), null))
}
/**
* The active halo is a smooth pulse, not a blink: it stays visible, changes
* gradually between samples, both rises and falls, wraps seamlessly, and has
* a clear peak (not two alternating values).
*/
@Test
fun pulseAlphaIsABoundedSmoothNonBinaryRhythm() {
var previous = pulseAlpha(0f)
var sawIncrease = false
var sawDecrease = false
for (i in 1..100) {
val value = pulseAlpha(i / 100f)
assertTrue("in (0,1]: $value", value > 0f && value <= 1f)
assertTrue("always visible: $value", value > 0.2f)
if (value > previous) sawIncrease = true
if (value < previous) sawDecrease = true
assertTrue("continuous at $i ($value vs $previous)", abs(value - previous) < 0.1f)
previous = value
}
assertTrue("rises then falls", sawIncrease && sawDecrease)
// Periodic: the cycle wraps without a jump.
assertEquals(pulseAlpha(0f), pulseAlpha(1f), 0.0001f)
// A clear peak early in the cycle and a trough later; not a two-value blink.
assertTrue(pulseAlpha(0.25f) > pulseAlpha(0.75f))
assertTrue(pulseAlpha(0.25f) - pulseAlpha(0.75f) > 0.2f)
}
@Test
fun staticHaloIsClearlyVisible() {
assertTrue(ACTIVE_HALO_STATIC_ALPHA in 0.5f..1f)
assertTrue(ACTIVE_HALO_STATIC_ALPHA > 0f)
}
}