Modernise the workflow graph's visual language

Replace the old terminal-diagram look on the Graph tab with a tonal
surface language, keeping the same information and every outcome hue.

- Nodes: stages are rounded rectangles from MaterialTheme.shapes.medium,
  terminals become pills (height/2). Fills are tonal surfaces via the new
  pure tonalFill(surface, accent, fraction) with a soft outlineVariant
  border instead of a flat fill plus hard outline.
- Type: node names use the cardTitle role and outcome labels the label
  role, with theme line height/letter spacing; the [brackets] and all-caps
  are gone (nodeDisplayLabel renders Success/Failure title-cased in colour).
- Edges: StrokeCap.Round/StrokeJoin.Round, bends rounded by one
  ROUTE_CORNER_RADIUS (cornerCutRadius clamps short segments), filled
  arrowheads scaled as edgeStrokeWidth * ARROW_HEAD_SCALE, and labels on
  a shared DrawScope tonal chip.
- Spacing: named dp tokens instead of ad-hoc literals.

Adds pure-logic unit tests (WorkflowGraphTest, GraphPaletteTest) and
documents the change in android/README.md.

Verified: :app:assembleDebug and :app:testDebugUnitTest both BUILD
SUCCESSFUL (207 tests, 0 failures) with no Kotlin warnings.
This commit is contained in:
2026-10-16 11:50:08 +01:00
parent 8b39c087fd
commit e5bde981ee
4 changed files with 644 additions and 84 deletions
@@ -51,6 +51,8 @@ import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
@@ -67,15 +69,12 @@ 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
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
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.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.currentStateAsState
@@ -93,6 +92,8 @@ 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
import net.awan.pipelines.ui.theme.PipelinesTextStyles
import net.awan.pipelines.ui.theme.pipelinesText
internal data class NodeLayout(
val key: String,
@@ -196,6 +197,13 @@ fun WorkflowGraph(
val scheme = MaterialTheme.colorScheme
val colors = remember(scheme) { graphColors(scheme) }
// The graph's type roles come from the app's one type scale (never ad-hoc
// sizes), and the corner radius from the app's shape scale rather than a raw
// literal; a terminal overrides it with a full pill in drawNodes.
val text = pipelinesText()
val nodeCornerPx = with(density) { MaterialTheme.shapes.medium.topStart.toPx(Size.Zero, this) }
val nodeBorderPx = with(density) { NODE_BORDER.toPx() }
val nodeBorderSelectedPx = with(density) { NODE_BORDER_SELECTED.toPx() }
// node key -> stage type, derived once per graph (never per frame) so node
// kind/colour and the spoken description share one lookup.
val stageTypeByKey = remember(graph) { graph.stages.associate { it.key to it.type } }
@@ -261,13 +269,13 @@ fun WorkflowGraph(
}
// Measured once per second (never per frame) so the canvas draw adds no
// allocation for the timer.
val elapsedLayout = remember(activeStartedAt, nowMillis, scheme, density) {
val elapsedLayout = remember(activeStartedAt, nowMillis, scheme, density, text) {
secondsSince(activeStartedAt.orEmpty(), nowMillis)
?.let(::formatDuration)
?.let {
textMeasurer.measure(
it,
TextStyle(fontSize = 11.sp, fontWeight = FontWeight.Medium, color = colors.nodeText),
text.label.copy(color = colors.nodeText),
)
}
}
@@ -335,7 +343,7 @@ 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, animate, phase)
drawEdgeLabels(layout, colors, runState, textMeasurer)
drawEdgeLabels(layout, colors, runState, textMeasurer, text)
drawNodes(
layout,
colors,
@@ -343,6 +351,10 @@ fun WorkflowGraph(
selectedStage,
stageTypeByKey,
textMeasurer,
text,
nodeCornerPx,
nodeBorderPx,
nodeBorderSelectedPx,
animate,
phase,
elapsedLayout,
@@ -478,6 +490,7 @@ private fun LegendSwatch(executed: Boolean, colors: GraphColors) {
start = from,
end = to,
strokeWidth = EDGE_STROKE,
cap = StrokeCap.Round,
pathEffect = if (executed) null else INACTIVE_DASH_EFFECT,
)
if (executed) drawArrowHead(listOf(from, to), color, ARROW_HEAD_SIZE)
@@ -508,6 +521,11 @@ internal class GraphColors(
* uses the same palette. The two terminal roles stay scheme roles so their
* meaning is kept; every other outcome uses the one curated, legible
* [GraphPalette] for both a stroke and its label text.
*
* Node and label surfaces are *tonal*: a raised surface tone ([scheme]'s
* `surfaceContainerHigh`/`surfaceContainerHighest`) blended with a subtle tint of
* the node's semantic colour (see [tonalFill]) rather than a flat fill, so a node
* reads as raised card, not a terminal cell.
*/
internal fun graphColors(scheme: ColorScheme): GraphColors = GraphColors(
// The two terminal roles stay scheme roles so their meaning is kept.
@@ -517,23 +535,60 @@ internal fun graphColors(scheme: ColorScheme): GraphColors = GraphColors(
// stroke and its label text, so a curve and its label always agree.
palette = GraphPalette.colors,
// Node fills differ by kind (see [GraphNodeKind]): model (neutral), ntfy
// (amber), other/custom (green), and the two terminals.
nodeFill = scheme.surfaceVariant,
nodeNtfyFill = scheme.tertiaryContainer,
nodeCustomFill = scheme.primaryContainer,
// A selected node inverts (light fill / dark text) plus a 4px border, so
// (amber), other/custom (green), and the two terminals (success/error). Each
// is a tonal surface carrying a subtle tint of that kind's semantic hue.
nodeFill = tonalFill(scheme.surfaceContainerHigh, scheme.onSurfaceVariant, NEUTRAL_TINT),
nodeNtfyFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, KIND_TINT),
nodeCustomFill = tonalFill(scheme.surfaceContainerHigh, scheme.primary, KIND_TINT),
// A selected node inverts (light fill / dark text) plus a stronger border, so
// selection reads in either appearance and never relies on colour.
nodeFillActive = scheme.inverseSurface,
nodeTextActive = scheme.inverseOnSurface,
nodeBorder = scheme.outline,
// The stage border is deliberately soft (a low-contrast outline variant), not
// the hard original outline; terminals carry their outcome hue instead.
nodeBorder = scheme.outlineVariant,
nodeBorderActive = scheme.primary,
nodeText = scheme.onSurface,
terminalFill = scheme.secondaryContainer,
terminalErrorFill = scheme.errorContainer,
labelBackground = scheme.surface,
terminalFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, TERMINAL_TINT),
terminalErrorFill = tonalFill(scheme.surfaceContainerHigh, scheme.error, TERMINAL_TINT),
// Edge outcome labels sit on a tonal chip (drawn as a rounded rect) rather than
// raw text over the canvas.
labelBackground = scheme.surfaceContainerHighest,
labelText = scheme.onSurfaceVariant,
)
/**
* [surface] blended with a [fraction] (0..1) of [accent], so a node/label fill
* carries a subtle tint of its semantic colour while staying a legible surface.
* Pure sRGB per-channel interpolation; a fraction outside `[0, 1]` is clamped so
* callers never overshoot the two colours.
*/
internal fun tonalFill(surface: Color, accent: Color, fraction: Float): Color {
val t = fraction.coerceIn(0f, 1f)
return Color(
red = surface.red + (accent.red - surface.red) * t,
green = surface.green + (accent.green - surface.green) * t,
blue = surface.blue + (accent.blue - surface.blue) * t,
alpha = surface.alpha + (accent.alpha - surface.alpha) * t,
)
}
/**
* The label a node shows in the graph: a stage keeps its declared key, while a
* terminal's all-caps `SUCCESS`/`FAILURE` becomes the readable `Success`/
* `Failure` (the graph type has no unnecessary all-caps). Pure, so the display
* form is unit-tested and the shared [GraphSemantics.nodeLabel] the
* TUI-mirroring panes still use is left untouched.
*/
internal fun nodeDisplayLabel(key: String): String {
val label = GraphSemantics.nodeLabel(key)
return if (Protocol.isTerminal(key)) {
label.lowercase().replaceFirstChar { it.uppercase() }
} else {
label
}
}
/** The accessibility label for one node, naming its type when it is a stage. */
private fun nodeDescription(node: NodeLayout, type: String?): String {
if (node.terminal) return "Terminal ${node.label}, tap for details"
@@ -714,14 +769,14 @@ private fun forwardAdjacent(edge: GraphEdge, rank: Map<String, Int>): Boolean =
internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density): GraphLayout {
if (graph.stages.isEmpty()) return GraphLayout(emptyList(), emptyList(), 0f, 0f)
val nodeWidth = with(density) { 132.dp.toPx() }
val portSpacing = with(density) { 12.dp.toPx() }
val hGap = with(density) { 132.dp.toPx() }
val pad = with(density) { 32.dp.toPx() }
val laneSpacing = with(density) { 26.dp.toPx() }
val terminalGap = with(density) { 64.dp.toPx() }
val trackStep = with(density) { 18.dp.toPx() }
val minNodeHeight = with(density) { 56.dp.toPx() }
val nodeWidth = with(density) { NODE_WIDTH.toPx() }
val portSpacing = with(density) { NODE_PORT_SPACING.toPx() }
val hGap = with(density) { NODE_H_GAP.toPx() }
val pad = with(density) { GRAPH_PAD.toPx() }
val laneSpacing = with(density) { EDGE_LANE_SPACING.toPx() }
val terminalGap = with(density) { TERMINAL_ROW_GAP.toPx() }
val trackStep = with(density) { EDGE_TRACK_STEP.toPx() }
val minNodeHeight = with(density) { NODE_MIN_HEIGHT.toPx() }
val ranks = rankStages(graph)
val edges = graph.edges()
@@ -770,7 +825,7 @@ internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density
graph.stages.forEachIndexed { index, stage ->
positions[stage.key] = NodeLayout(
key = stage.key,
label = GraphSemantics.nodeLabel(stage.key),
label = nodeDisplayLabel(stage.key),
x = stageX(index),
y = pad,
width = nodeWidth,
@@ -807,7 +862,7 @@ internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density
val successX = failureX + failureWidth + hGap
positions[Protocol.FAILURE_END] = NodeLayout(
key = Protocol.FAILURE_END,
label = GraphSemantics.nodeLabel(Protocol.FAILURE_END),
label = nodeDisplayLabel(Protocol.FAILURE_END),
x = failureX,
y = terminalY,
width = failureWidth,
@@ -816,7 +871,7 @@ internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density
)
positions[Protocol.SUCCESS_END] = NodeLayout(
key = Protocol.SUCCESS_END,
label = GraphSemantics.nodeLabel(Protocol.SUCCESS_END),
label = nodeDisplayLabel(Protocol.SUCCESS_END),
x = successX,
y = terminalY,
width = successWidth,
@@ -1118,6 +1173,56 @@ internal fun arrowDirection(points: List<Offset>): Offset {
return Offset.Zero
}
/**
* The clamped cut-back used at one bend of an axis-aligned route: the shared
* [radius], floored to half of the shorter adjacent segment ([inLength] into the
* corner, [outLength] out of it) so the two cut-backs can never meet or cross on
* a short run. It takes the lengths the caller already measured, so a bend's
* geometry is computed once. Pure, so the clamp is unit-tested without a Canvas.
*/
internal fun cornerCutRadius(inLength: Float, outLength: Float, radius: Float): Float =
minOf(radius, inLength / 2f, outLength / 2f).coerceAtLeast(0f)
/**
* The path an axis-aligned route [points] is drawn along: each interior right
* angle is replaced by a quadratic curve with the one consistent [radius] control
* offset (clamped per corner by [cornerCutRadius]), so the tracks read as smooth
* curves. The route's own endpoints and its stored polyline are unchanged, so
* hit-testing, the arrowheads and every layout test keep using the same geometry;
* only the rendered bends soften. Each corner's segment lengths are measured once
* and reused for both the clamp and the cut points; a degenerate route falls back
* to straight segments rather than dividing by zero.
*/
private fun roundedRoutePath(points: List<Offset>, radius: Float): Path {
val path = Path()
if (points.isEmpty()) return path
path.moveTo(points.first().x, points.first().y)
for (i in 1 until points.size - 1) {
val previous = points[i - 1]
val corner = points[i]
val next = points[i + 1]
val inLength = hypot(corner.x - previous.x, corner.y - previous.y)
val outLength = hypot(next.x - corner.x, next.y - corner.y)
val cut = cornerCutRadius(inLength, outLength, radius)
if (cut <= 0f) {
path.lineTo(corner.x, corner.y)
continue
}
val start = Offset(
corner.x + (previous.x - corner.x) / inLength * cut,
corner.y + (previous.y - corner.y) / inLength * cut,
)
val end = Offset(
corner.x + (next.x - corner.x) / outLength * cut,
corner.y + (next.y - corner.y) / outLength * cut,
)
path.lineTo(start.x, start.y)
path.quadraticTo(corner.x, corner.y, end.x, end.y)
}
path.lineTo(points.last().x, points.last().y)
return path
}
/**
* Column rank for every stage in declaration order, mirroring
* tui.layoutSingleRowGraph: `graph.Stages` is the source order, so stages keep
@@ -1143,23 +1248,29 @@ private fun DrawScope.drawEdgePaths(
// stored polyline, so there is no per-frame recompute.
val points = if (edge.points.isEmpty()) routePoints(edge) else edge.points
if (points.size < 2) continue
val path = Path()
path.moveTo(points.first().x, points.first().y)
for (i in 1 until points.size) {
path.lineTo(points[i].x, points[i].y)
}
// The stored route stays the axis-aligned polyline (the layout/tests
// contract); drawing only rounds its corners with the one shared
// [ROUTE_CORNER_RADIUS] control offset, so the tracks read as smooth curves
// without changing any routing.
val path = roundedRoutePath(points, ROUTE_CORNER_RADIUS.toPx())
// Executed = solid full-colour stroke plus an arrowhead; not executed =
// dashed muted stroke with no arrowhead. The difference is carried by line
// style and arrowhead presence, never by opacity alone, so it survives a
// 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.
// (same-hue) stroke and a matching arrowhead, so pass/fail dominates.
val motion = edgeMotion(edge.edge, runState)
if (motion != EdgeMotion.Unvisited) {
val color = edgeStrokeColor(edge.edge, runState, colors)
val width = edgeStrokeWidth(edge.edge, runState)
drawPath(path, color = color, style = Stroke(width = width))
drawArrowHead(points, color, edgeArrowHeadSize(edge.edge, runState))
drawPath(
path,
color = color,
style = Stroke(width = width, cap = StrokeCap.Round, join = StrokeJoin.Round),
)
// Reuse the width just computed for the stroke's own head (never
// re-deriving it), so the head always matches the line it terminates.
drawArrowHead(points, color, arrowHeadSizeFor(width))
// 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.
@@ -1172,6 +1283,8 @@ private fun DrawScope.drawEdgePaths(
color = colors.labelText,
style = Stroke(
width = edgeStrokeWidth(edge.edge, runState),
cap = StrokeCap.Round,
join = StrokeJoin.Round,
pathEffect = INACTIVE_DASH_EFFECT,
),
)
@@ -1224,33 +1337,57 @@ private fun pointAlong(points: List<Offset>, distance: Float): Offset? {
return points.lastOrNull()
}
/**
* Draws the rounded tonal chip behind a measured label: the shared chip paddings
* and corner ([EDGE_CHIP_PAD_X]/[EDGE_CHIP_PAD_Y]/[EDGE_CHIP_CORNER], dp tokens so
* they scale with the device), filled with [color]. Both the edge outcome labels
* and the active stage's elapsed badge use it, so the two chip call sites keep one
* geometry instead of repeating the same rounded rect. The caller draws the
* pre-measured text at [textTopLeft] afterwards.
*/
private fun DrawScope.drawTonalChip(textTopLeft: Offset, textSize: IntSize, color: Color) {
val padX = EDGE_CHIP_PAD_X.toPx()
val padY = EDGE_CHIP_PAD_Y.toPx()
val corner = EDGE_CHIP_CORNER.toPx()
drawRoundRect(
color = color,
topLeft = Offset(textTopLeft.x - padX, textTopLeft.y - padY),
size = Size(textSize.width + padX * 2f, textSize.height + padY * 2f),
cornerRadius = CornerRadius(corner, corner),
)
}
/**
* 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
* own edge's stored [EdgeLayout.labelPoint] (the edge's own lane/track), so
* distinct outcomes never overprint. An executed edge's label uses its legible
* outcome colour (see [outcomeColor]); a not-executed edge's label uses a muted
* colour on a near-opaque background, matching its dashed stroke rather than
* inheriting a faded curve alpha, which left the text unreadable.
* distinct outcomes never overprint. The label is drawn on a tonal rounded chip
* (not raw text over the canvas): the chip is the raised surface tone tinted with
* the label's own colour, so an executed edge's label keeps its legible outcome
* colour and a not-executed one stays muted but readable. The text uses the app's
* type scale ([text]'s label role), never an ad-hoc size.
*/
private fun DrawScope.drawEdgeLabels(
layout: GraphLayout,
colors: GraphColors,
runState: RunGraphState?,
textMeasurer: TextMeasurer,
text: PipelinesTextStyles,
) {
for (edge in layout.edges) {
val executed = edgeIsExecuted(edge.edge, runState)
val textColor = if (executed) outcomeColor(edge.edge.outcome, colors) else colors.labelText
val measured = textMeasurer.measure(edge.edge.label, TextStyle(fontSize = 11.sp, color = textColor))
// One colour serves both the label text and its chip tint: the outcome
// hue when the edge executed, otherwise the muted not-executed label tone.
val labelColor = if (executed) outcomeColor(edge.edge.outcome, colors) else colors.labelText
val measured = textMeasurer.measure(edge.edge.label, text.label.copy(color = labelColor))
val labelTopLeft = Offset(
x = edge.labelPoint.x - measured.size.width / 2f,
y = edge.labelPoint.y - measured.size.height - 2f,
)
drawRect(
color = colors.labelBackground.copy(alpha = if (executed) 0.92f else 0.86f),
topLeft = Offset(labelTopLeft.x - 3f, labelTopLeft.y - 1f),
size = Size(measured.size.width + 6f, measured.size.height + 2f),
drawTonalChip(
textTopLeft = labelTopLeft,
textSize = measured.size,
color = tonalFill(colors.labelBackground, labelColor, EDGE_CHIP_TINT),
)
// Draw the pre-measured layout: the string overload re-derives its width
// constraints from this DrawScope and throws when a label sits outside it
@@ -1299,6 +1436,10 @@ private fun DrawScope.drawNodes(
selectedStage: String?,
stageTypeByKey: Map<String, String?>,
textMeasurer: TextMeasurer,
text: PipelinesTextStyles,
nodeCornerPx: Float,
nodeBorderPx: Float,
nodeBorderSelectedPx: Float,
animate: Boolean,
phase: Float,
elapsedLayout: TextLayoutResult?,
@@ -1312,17 +1453,23 @@ private fun DrawScope.drawNodes(
val selected = node.key == selectedStage
val kind = graphNodeKind(node.terminal, node.key, stageTypeByKey[node.key])
val topLeft = Offset(node.x, node.y)
val corner = CornerRadius(NODE_CORNER_RADIUS, NODE_CORNER_RADIUS)
val borderWidth = if (selected && !node.terminal) 4f else 2f
// A stage is a rounded rectangle from the theme's shape scale; a terminal
// is a pill (fully rounded) so it is visibly not a stage.
val corner = if (node.terminal) {
CornerRadius(node.height / 2f, node.height / 2f)
} else {
CornerRadius(nodeCornerPx, nodeCornerPx)
}
val borderWidth = if (selected && !node.terminal) nodeBorderSelectedPx else nodeBorderPx
// 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.
// A tonal surface fill carrying a subtle tint of the node's semantic
// colour, plus a soft border (or the outcome hue for a terminal).
val fill = when {
kind == GraphNodeKind.TerminalFailure -> colors.terminalErrorFill
kind == GraphNodeKind.TerminalSuccess -> colors.terminalFill
@@ -1349,11 +1496,10 @@ private fun DrawScope.drawNodes(
cornerRadius = corner,
style = Stroke(width = borderWidth),
)
textColor = if (!node.terminal && selected) colors.nodeTextActive else colors.nodeText
} else {
// Hollow and outlined: no fill (the surface shows through), a dashed
// muted border and a muted but legible label, so "not executed" is a
// shape and border-style difference rather than a faded node. A
// Hollow and outlined: no fill (the tonal surface shows through), a
// dashed muted border and a muted but legible label, so "not executed"
// is a shape and border-style difference rather than a faded node. A
// selected not-executed node keeps the stronger border colour.
val border = if (selected && !node.terminal) colors.nodeBorderActive else colors.labelText
drawRoundRect(
@@ -1363,13 +1509,17 @@ private fun DrawScope.drawNodes(
cornerRadius = corner,
style = Stroke(width = borderWidth, pathEffect = INACTIVE_DASH_EFFECT),
)
textColor = colors.labelText
}
val label = "[" + node.label + "]"
val measured = textMeasurer.measure(
label,
TextStyle(fontSize = 13.sp, fontWeight = FontWeight.Medium, color = textColor),
)
// A terminal names its state in its own colour; a stage names itself in the
// node text colour (inverted when selected). No all-caps, no brackets.
val textColor: Color = when {
node.terminal && kind == GraphNodeKind.TerminalSuccess -> colors.success
node.terminal && kind == GraphNodeKind.TerminalFailure -> colors.error
selected && !node.terminal -> colors.nodeTextActive
executed -> colors.nodeText
else -> colors.labelText
}
val measured = textMeasurer.measure(node.label, text.cardTitle.copy(color = textColor))
// Pre-measured layout avoids the scope-relative width constraint crash and
// the redundant re-measure of the string overload.
drawText(
@@ -1381,7 +1531,7 @@ private fun DrawScope.drawNodes(
)
// 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
// an opaque tonal 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) {
@@ -1389,10 +1539,10 @@ private fun DrawScope.drawNodes(
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),
drawTonalChip(
textTopLeft = badgeTopLeft,
textSize = elapsedLayout.size,
color = tonalFill(colors.labelBackground, colors.nodeText, ELAPSED_CHIP_TINT),
)
drawText(textLayoutResult = elapsedLayout, topLeft = badgeTopLeft)
}
@@ -1489,9 +1639,22 @@ internal fun edgeStrokeWidth(edge: GraphEdge, runState: RunGraphState?): Float =
else -> EDGE_STROKE
}
/** The named arrowhead-size token for [edge], scaled to match [edgeStrokeWidth]. */
/**
* Arrowhead length for a stroke of [strokeWidth]: one [ARROW_HEAD_SCALE] multiple
* of the width. This is the single mapping both an edge and the legend share, and
* drawing passes the width it has just computed rather than re-deriving it, so a
* heavier line always carries a proportionally larger filled head.
*/
internal fun arrowHeadSizeFor(strokeWidth: Float): Float = strokeWidth * ARROW_HEAD_SCALE
/**
* The arrowhead length for [edge]: [arrowHeadSizeFor] of its own
* [edgeStrokeWidth], so a heavier line always carries a proportionally larger
* head and the two can never disagree. The pass/fail width is the heaviest, so
* its head is the largest; a not-executed edge draws no head at all.
*/
internal fun edgeArrowHeadSize(edge: GraphEdge, runState: RunGraphState?): Float =
if (isEmphasizedEdge(edge, runState)) PASSFAIL_ARROW_HEAD_SIZE else ARROW_HEAD_SIZE
arrowHeadSizeFor(edgeStrokeWidth(edge, runState))
/**
* The stroke colour for an executed [edge]: its outcome colour, made more
@@ -1522,7 +1685,7 @@ private fun graphDescription(graph: Graph, runState: RunGraphState?): String {
for (outcome in GraphSemantics.outcomes(stage)) {
val target = Protocol.resolveTarget(outcome, stage.edges[outcome] ?: continue)
val label = GraphSemantics.edgeLabel(stage, outcome)
builder.append("Outcome $label goes to ${GraphSemantics.nodeLabel(target)}. ")
builder.append("Outcome $label goes to ${nodeDisplayLabel(target)}. ")
}
}
builder.append("Stages can be tapped for details.")
@@ -1564,19 +1727,33 @@ 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.
* layout) so they scale with the device.
*/
private val ACTIVE_HALO_GAP = 6.dp
private val ACTIVE_HALO_STROKE = 4.dp
private const val ACTIVE_HALO_GLOW = 0.28f
/**
* Node geometry, spacing and border tokens. A node's corner radius comes from the
* app's shape scale (`MaterialTheme.shapes.medium`, read once in [WorkflowGraph]);
* a terminal overrides it with a full pill. Everything else is a named dp token so
* no call site writes a geometry literal, the gaps are deliberately generous so
* the graph breathes, and the values scale with the device.
*/
private val NODE_WIDTH = 150.dp
private val NODE_MIN_HEIGHT = 76.dp
private val NODE_PORT_SPACING = 14.dp
private val NODE_H_GAP = 168.dp
private val GRAPH_PAD = 40.dp
private val EDGE_LANE_SPACING = 34.dp
private val TERMINAL_ROW_GAP = 88.dp
private val EDGE_TRACK_STEP = 26.dp
private val NODE_BORDER = 1.dp
private val NODE_BORDER_SELECTED = 3.dp
/** Bottom inset of the active node's elapsed-time badge inside the node rect. */
private val ELAPSED_INSET = 4.dp
@@ -1591,10 +1768,11 @@ private const val FLOW_DOT_SCALE = 1.2f
* pixels, so the two states differ by shape, not by a faded tint.
*
* The two decisive outcomes (`success`/`error`) use the heavier
* [PASSFAIL_EDGE_STROKE] with the matching [PASSFAIL_ARROW_HEAD_SIZE] and a
* stronger [PASSFAIL_SATURATION] stroke, so pass/fail reads at a glance and from
* a distance, while every other outcome keeps the finer [EDGE_STROKE] and a
* not-executed route the finer still [INACTIVE_EDGE_STROKE].
* [PASSFAIL_EDGE_STROKE] with a proportionally larger arrowhead (see
* [edgeArrowHeadSize]) and a stronger [PASSFAIL_SATURATION] stroke, so pass/fail
* reads at a glance and from a distance, while every other outcome keeps the
* finer [EDGE_STROKE] and a not-executed route the finer still
* [INACTIVE_EDGE_STROKE].
*/
private const val EDGE_STROKE = 3f
@@ -1604,11 +1782,41 @@ private const val PASSFAIL_EDGE_STROKE = 7f
/** Stroke width for a not-executed edge; finer than either executed width. */
private const val INACTIVE_EDGE_STROKE = 2.5f
/** Arrowhead length for a normal executed edge. */
private const val ARROW_HEAD_SIZE = 12f
/**
* A route's corner radius, a dp token like the rest of the graph geometry: the
* one consistent control offset every right-angle bend of an orthogonal route is
* rounded by, so all tracks share a single curve language (and scale with the
* device) without changing the stored routing.
*/
private val ROUTE_CORNER_RADIUS = 7.dp
/** Arrowhead length for an executed pass/fail edge, scaled with its heavier stroke. */
private const val PASSFAIL_ARROW_HEAD_SIZE = 20f
/**
* Arrowhead length as a multiple of the edge's own stroke width, so a heavier line
* always carries a proportionally larger filled head (base `3 * 4 = 12`,
* pass/fail `7 * 4 = 28`). [ARROW_HEAD_SIZE] is the base length, used by the
* legend swatch, which names the generic executed state rather than pass/fail.
*/
private const val ARROW_HEAD_SCALE = 4f
private const val ARROW_HEAD_SIZE = EDGE_STROKE * ARROW_HEAD_SCALE
/**
* Tonal tints: the fraction of a node's/edge's semantic colour blended into the
* raised surface for its fill or chip. Small enough to read as a tint, large
* enough to tell the node kinds and outcome labels apart.
*/
private const val NEUTRAL_TINT = 0.10f
private const val KIND_TINT = 0.22f
private const val TERMINAL_TINT = 0.30f
private const val EDGE_CHIP_TINT = 0.20f
private const val ELAPSED_CHIP_TINT = 0.14f
/**
* The tonal chip's padding and corner, dp tokens like the other graph geometry
* (so a chip scales with the device rather than sitting at a raw pixel size).
*/
private val EDGE_CHIP_PAD_X = 2.dp
private val EDGE_CHIP_PAD_Y = 1.dp
private val EDGE_CHIP_CORNER = 2.dp
/**
* How much more saturated an executed pass/fail stroke is than its outcome
@@ -1634,7 +1842,7 @@ private val LEGEND_SWATCH_HEIGHT = 10.dp
* the former 360.dp / 340.dp literals). ~58% of the window height so the graph
* is a substantial share of the screen, floored at a height that still fits a
* 4-stage layout plus its lower terminal row: pad*2 + node + terminal gap + node
* = 32*2 + 56 + 72 + 56 = 248px at density 1.
* = 40*2 + 76 + 88 + 76 = 320px at density 1.
*/
internal fun collapsedGraphHeight(screenHeightDp: Int): Dp =
(screenHeightDp * 0.58f).dp.coerceAtLeast(GRAPH_PANEL_MIN_HEIGHT)
@@ -1643,4 +1851,4 @@ internal fun collapsedGraphHeight(screenHeightDp: Int): Dp =
internal fun expandedGraphHeight(screenHeightDp: Int): Dp = (screenHeightDp * 0.92f).dp
/** Floor that still fits a 4-stage graph with its terminal row (see above). */
internal val GRAPH_PANEL_MIN_HEIGHT = 260.dp
internal val GRAPH_PANEL_MIN_HEIGHT = 320.dp
@@ -182,6 +182,27 @@ class GraphPaletteTest {
private fun valueOf(color: Color): Float = maxOf(color.red, color.green, color.blue)
/**
* [tonalFill] blends a raised surface toward the accent by the given fraction,
* so a node/label fill carries a subtle tint of its semantic colour while
* staying a surface; the fraction is clamped so a caller never overshoots.
*/
@Test
fun tonalFillBlendsTowardTheAccentAndClampsTheFraction() {
val surface = darkSurface
val accent = Color(0xFFFF0000)
// Both endpoints are reproduced exactly on the channel.
assertEquals(surface.red, tonalFill(surface, accent, 0f).red, 0.0001f)
assertEquals(accent.red, tonalFill(surface, accent, 1f).red, 0.0001f)
// A mid tint sits strictly between the two and keeps the surface's alpha.
val mid = tonalFill(surface, accent, 0.2f)
assertTrue(mid.red > surface.red && mid.red < accent.red)
assertEquals(surface.alpha, mid.alpha, 0.0001f)
// Out-of-range fractions clamp to the endpoints instead of overshooting.
assertEquals(surface.red, tonalFill(surface, accent, -1f).red, 0.0001f)
assertEquals(accent.red, tonalFill(surface, accent, 2f).red, 0.0001f)
}
@Test
fun nodeKindIsDeterministicAndCoversEveryKind() {
assertEquals(GraphNodeKind.Model, graphNodeKind(false, "planner", null))
@@ -592,6 +592,62 @@ class WorkflowGraphTest {
assertEquals(1, GRAPH_LEGEND.count { it.executed })
}
/**
* The node label the graph shows is readable: a terminal's all-caps keyword
* becomes title case (no unnecessary all-caps), while a stage keeps its
* declared key.
*/
@Test
fun nodeDisplayLabelsAreReadableAndKeepStageKeys() {
assertEquals("Success", nodeDisplayLabel(Protocol.SUCCESS_END))
assertEquals("Failure", nodeDisplayLabel(Protocol.FAILURE_END))
assertEquals("ui_reviewer", nodeDisplayLabel("ui_reviewer"))
assertEquals("planner", nodeDisplayLabel("planner"))
}
/**
* A heavier line always carries a proportionally larger filled arrowhead: one
* consistent scale ties the head length to the stroke width, so the pass/fail
* head dominates exactly as its stroke does.
*/
@Test
fun arrowHeadScalesWithTheStrokeItTerminates() {
val graph = sampleGraph()
val success = graph.edges().first { it.outcome == "success" }
val other = graph.edges().first { it.outcome == "blocked" }
val runState = RunGraphState(
visitedStages = setOf(success.source, other.source),
takenRoutes = setOf(
GraphRoute(success.source, success.outcome, success.target),
GraphRoute(other.source, other.outcome, other.target),
),
currentStage = success.source,
)
val successRatio = edgeArrowHeadSize(success, runState) / edgeStrokeWidth(success, runState)
val otherRatio = edgeArrowHeadSize(other, runState) / edgeStrokeWidth(other, runState)
assertEquals(successRatio, otherRatio, 0.001f)
assertTrue(edgeArrowHeadSize(success, runState) > edgeArrowHeadSize(other, runState))
}
/**
* The rounded-corner cut at a route bend is the shared radius, floored to half
* the shorter adjacent segment so two cut-backs can never meet or cross; a
* degenerate adjacent segment yields no cut instead of dividing by zero. It
* works on the already-measured segment lengths, so a bend measures them once.
*/
@Test
fun cornerCutNeverExceedsHalfTheShorterSegment() {
val radius = 18f
// Both adjacent segments are long enough to take the full radius.
assertEquals(radius, cornerCutRadius(100f, 100f, radius), 0.001f)
// A short incoming segment halves the cut.
assertEquals(10f, cornerCutRadius(20f, 100f, radius), 0.001f)
// A short outgoing segment halves the cut.
assertEquals(15f, cornerCutRadius(100f, 30f, radius), 0.001f)
// A degenerate adjacent segment yields no cut.
assertEquals(0f, cornerCutRadius(0f, 100f, radius), 0.001f)
}
private fun assertNoSharedRuns(layout: GraphLayout) {
val edges = layout.edges
for (i in edges.indices) {