Give every graph edge its own track and open a stage detail sheet on tap

Allocate a distinct source port, target port, across-run lane and vertical
track per edge in the pure layoutGraph (stable edge-id order), mirroring the
TUI's per-edge routing, so no two routes share a row or column; each outcome
label follows its own edge's track. Rewrite routePoints to build every
polyline from those precomputed ports/lanes/tracks instead of shared corridor
constants, keeping runs axis-aligned and the layout deterministic.

Add pure hitTest/toGraphPoint plus a tap detector that maps taps back through
the current transform: tapping a node calls onStageTap, tapping empty space
does nothing, and pan/zoom keep working. Add StageDetailSheet, a Material 3
ModalBottomSheet overlay (near full height, scrollable, responsive on wide
windows) showing the stage definition and, on a run graph, that run's step;
wire it into the pipeline and run graph tabs.

Extend WorkflowGraphTest with the no-shared-collinear-run invariant, distinct
port, determinism and hit-test cases.
This commit is contained in:
2026-10-15 16:46:40 +01:00
parent e6d00d4ee5
commit 238f3fbdd8
5 changed files with 944 additions and 106 deletions
@@ -0,0 +1,270 @@
package net.awan.pipelines.ui.graph
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.GraphSemantics
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.Stage
import net.awan.pipelines.data.protocol.edges
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.components.DETAIL_MAX_WIDTH_DP
import net.awan.pipelines.ui.components.KeyValueRow
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The effective stage type, mirroring internal/stage.EffectiveType: a blank type
* is the model stage. Kept pure so the sheet chip and the node description share
* one derivation.
*/
internal fun effectiveStageType(type: String?): String =
if (type.isNullOrBlank()) "model" else type
/** One labelled row/block of stage detail, rendered by the sheet. */
internal data class StageField(
val label: String,
val value: String,
val mono: Boolean = false,
val block: Boolean = false,
)
/**
* The pure definition view of a [stage]: key + type title, prompt, output, edges
* with their outcomes and resolved terminals, configs, tools, limits and memory
* sources. Only non-blank fields are emitted, so the sheet never shows an empty
* row and no protocol field is invented.
*/
internal fun stageDefinitionFields(stage: Stage): List<StageField> {
val fields = ArrayList<StageField>()
fields += StageField("Type", effectiveStageType(stage.type))
if (stage.prompt.isNotBlank()) fields += StageField("Prompt", stage.prompt, block = true)
if (stage.output.isNotBlank()) fields += StageField("Output", stage.output, block = true)
val outcomes = GraphSemantics.outcomes(stage).map { outcome ->
val target = Protocol.resolveTarget(outcome, stage.edges[outcome] ?: "")
val label = GraphSemantics.nodeLabel(target)
val suffix = if (Protocol.isTerminal(target)) " (terminal)" else ""
"$outcome → $label$suffix"
}
if (outcomes.isNotEmpty()) {
fields += StageField("Outcomes", outcomes.joinToString("\n"), block = true)
}
stage.configs.keys.sorted().forEach { key ->
val value = stage.configs.getValue(key)
if (value.isNotBlank()) fields += StageField(configLabel(key), value)
}
stage.blocks?.get("tools")?.takeIf { it.isNotBlank() }?.let {
fields += StageField("Tools", it, block = true)
}
stage.limits?.let { limits ->
if (limits.maxVisits > 0) fields += StageField("Max visits", limits.maxVisits.toString())
val on = limits.on.orEmpty()
if (on.isNotEmpty()) fields += StageField("Limit on", on.joinToString(", "))
}
stage.memory?.takeIf { it.isNotEmpty() }?.let { memory ->
fields += StageField(
"Memory",
memory.entries.joinToString("\n") { "${it.key}: ${it.value}" },
block = true,
)
}
stage.notify?.let { policy ->
if (policy.on.isNotEmpty()) fields += StageField("Notify on", policy.on.joinToString(", "))
if (policy.destination.isNotBlank()) fields += StageField("Notify destination", policy.destination)
val artifacts = policy.artifacts.orEmpty()
if (artifacts.isNotEmpty()) fields += StageField("Notify artifacts", artifacts.joinToString(", "))
}
return fields
}
/**
* The pure run view of one [RunStep] for the selected stage: status, outcome,
* duration, visit against the control's max_visits, target, session id,
* diagnostic, transcript, a file-change summary and notification receipts. Blank
* fields are skipped.
*/
internal fun runStepFields(step: RunStep): List<StageField> {
val fields = ArrayList<StageField>()
if (step.status.isNotBlank()) fields += StageField("Status", step.status)
if (step.outcome.isNotBlank()) fields += StageField("Outcome", step.outcome)
formatDuration(step.startedAt, step.finishedAt)?.let { fields += StageField("Duration", it) }
step.control?.let { control ->
val suffix = if (control.limitReached) " (limit reached)" else ""
when {
control.maxVisits > 0 -> fields += StageField("Visit", "${control.visit} / ${control.maxVisits}$suffix")
control.visit > 0 -> fields += StageField("Visit", control.visit.toString())
}
control.modelTarget?.takeIf { it.isNotBlank() }?.let { fields += StageField("Model target", it) }
}
if (step.target.isNotBlank()) fields += StageField("Target", step.target)
if (step.sessionId.isNotBlank()) fields += StageField("Session", step.sessionId, mono = true)
if (step.agentActive) fields += StageField("Agent", "active")
if (step.diagnostic.isNotBlank()) fields += StageField("Diagnostic", step.diagnostic, block = true)
if (step.transcript.isNotBlank()) fields += StageField("Transcript", step.transcript, block = true)
step.fileChanges?.let { changes ->
val summary = buildString {
append(changes.status)
if (changes.files.isNotEmpty()) append(" (${changes.files.size} files)")
if (changes.skipped > 0) append(", ${changes.skipped} skipped")
}.trim().trimStart(',')
if (summary.isNotBlank()) fields += StageField("File changes", summary)
if (changes.files.isNotEmpty()) {
fields += StageField(
"Changed files",
changes.files.joinToString("\n") { file ->
"${file.kind} ${file.path}" +
(if (file.binary) " (binary)" else "") +
(if (file.truncated) " (truncated)" else "")
},
block = true,
)
}
}
step.notifications.orEmpty().forEach { receipt ->
if (receipt.status.isNotBlank() || receipt.destination.isNotBlank()) {
fields += StageField(
"Notification",
"${receipt.status} → ${receipt.destination}" +
(receipt.diagnostic?.takeIf { it.isNotBlank() }?.let { " · $it" } ?: ""),
)
}
}
return fields
}
/** Incoming routes into a terminal node, for the sheet opened on a terminal. */
internal fun terminalFields(graph: Graph, key: String): List<StageField> {
val lines = graph.edges()
.filter { it.target == key }
.map { "${it.source} · ${it.label} → ${GraphSemantics.nodeLabel(key)}" }
return if (lines.isEmpty()) {
emptyList()
} else {
listOf(StageField("Incoming routes", lines.joinToString("\n"), block = true))
}
}
private fun configLabel(key: String): String = when (key) {
"provider" -> "Provider"
"model" -> "Model"
"retries" -> "Retries"
"timeout" -> "Timeout"
"budget_usd" -> "Budget (USD)"
"budget_tokens" -> "Budget (tokens)"
"harness" -> "Harness"
else -> key
}
/**
* The one reusable stage-detail overlay, opened when a node in [WorkflowGraph] is
* tapped. It is a Material 3 [ModalBottomSheet] that opens near full height
* (`skipPartiallyExpanded`), is scrollable, and dismisses by swipe, back or
* tapping outside. On a wide window it reuses the screens' responsive centring
* (the shared [DETAIL_MAX_WIDTH_DP]) instead of stretching one narrow column. It
* is an overlay on the current screen; no navigation route is added.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StageDetailSheet(
stageKey: String,
graph: Graph,
runStep: RunStep?,
onDismiss: () -> Unit,
) {
val text = pipelinesText()
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val stage = graph.stages.firstOrNull { it.key == stageKey }
val definition = stage?.let(::stageDefinitionFields) ?: terminalFields(graph, stageKey)
val run = runStep?.let(::runStepFields).orEmpty()
val typeLabel = if (stage != null) effectiveStageType(stage.type) else "terminal"
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
dragHandle = { BottomSheetDefaults.DragHandle() },
) {
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.TopCenter) {
Column(
modifier = Modifier
.widthIn(max = DETAIL_MAX_WIDTH_DP.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text(
GraphSemantics.nodeLabel(stageKey),
style = text.screenTitle,
modifier = Modifier.semantics { heading() },
)
TypeChip(typeLabel)
if (definition.isNotEmpty()) {
Text("Definition", style = text.sectionHeader, modifier = Modifier.padding(top = 8.dp))
definition.forEach { field -> FieldRow(field) }
}
if (run.isNotEmpty()) {
Text("This run", style = text.sectionHeader, modifier = Modifier.padding(top = 8.dp))
run.forEach { field -> FieldRow(field) }
}
if (definition.isEmpty() && run.isEmpty()) {
Text("No details recorded for this node.", style = text.meta)
}
}
}
}
}
/** One field as either the shared code card (blocks) or a key/value row. */
@Composable
private fun FieldRow(field: StageField) {
if (field.block) {
CodeBlock(field.label, field.value)
} else {
KeyValueRow(field.label, field.value, monospace = field.mono)
}
}
/** A small rounded chip naming the stage type (model / ntfy / …). */
@Composable
private fun TypeChip(label: String) {
Surface(
shape = RoundedCornerShape(50),
color = MaterialTheme.colorScheme.secondaryContainer,
) {
Text(
text = label,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
)
}
}
@@ -3,12 +3,15 @@ package net.awan.pipelines.ui.graph
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.material.icons.Icons
@@ -35,14 +38,19 @@ import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.Role
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.TextMeasurer
import androidx.compose.ui.text.TextStyle
@@ -50,10 +58,12 @@ 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 kotlin.math.abs
import kotlin.math.roundToInt
import kotlinx.coroutines.launch
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.GraphEdge
@@ -71,7 +81,11 @@ internal data class NodeLayout(
val width: Float,
val height: Float,
val terminal: Boolean,
)
) {
/** The graph-space rect hit when a tap lands inside this node. */
fun contains(point: Offset): Boolean =
point.x >= x && point.x <= x + width && point.y >= y && point.y <= y + height
}
internal data class EdgeLayout(
val edge: GraphEdge,
@@ -85,10 +99,18 @@ internal data class EdgeLayout(
val bottomExit: Boolean,
val sourceRank: Int,
val targetRank: Int,
// Index of this edge among the outgoing edges of its source plus how many
// there are, so each label can get its own row instead of overprinting.
val labelSlot: Int,
val labelCount: Int,
// True for a non-adjacent non-terminal route (a feedback or jump edge): it
// leaves the source, drops to its own lane, travels across and rises into the
// target's left edge, mirroring the TUI's arc/multi-run tracks.
val across: Boolean,
// The edge's own horizontal lane and the vertical track columns it uses, all
// allocated once by [layoutGraph] (stable edge-id order) so drawing and
// hit-testing share exactly one allocation and no two routes share a track.
val lane: Float,
val trackX: Float,
val leadX: Float,
// Where this edge's outcome label is drawn (on the edge's own lane/track).
val labelPoint: Offset,
// The axis-aligned polyline this edge is drawn along, computed once by
// [routePoints] during layout so drawing never re-routes per frame.
val points: List<Offset> = emptyList(),
@@ -116,6 +138,10 @@ internal data class ZoomResult(val offset: Offset, val scale: Float)
* the `error*` fallback marker, `#success`/`#failure` terminals and loop routes.
* When [runState] is supplied, executed stages/routes are highlighted and the
* rest dimmed; when it is null the full definition is shown.
*
* A tap that lands inside a node (stage or terminal) calls [onStageTap] with the
* node key; tapping empty space does nothing. Pan/zoom keep working because the
* tap detector is separate from the transform detector.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
@@ -124,6 +150,7 @@ fun WorkflowGraph(
modifier: Modifier = Modifier,
runState: RunGraphState? = null,
selectedStage: String? = null,
onStageTap: (String) -> Unit = {},
) {
val density = LocalDensity.current
val configuration = LocalConfiguration.current
@@ -222,6 +249,16 @@ fun WorkflowGraph(
.background(MaterialTheme.colorScheme.surface)
.semantics { contentDescription = description }
.onSizeChanged { canvasSize = it }
// A tap is mapped through the current transform to graph space and
// hit-tested against the (single) layout allocation. It runs only on a
// tap, never per frame; empty space does nothing and pan/zoom are
// untouched because this is a separate detector.
.pointerInput(layout) {
detectTapGestures { position ->
val graphPoint = toGraphPoint(position, offset, scale)
hitTest(layout, graphPoint)?.let(onStageTap)
}
}
.pointerInput(layout) {
detectTransformGestures { centroid, pan, zoom, _ ->
userAdjusted = true
@@ -253,6 +290,39 @@ fun WorkflowGraph(
drawNodes(layout, colors, runState, selectedStage, textMeasurer)
}
}
// Accessibility overlay: invisible nodes carrying a click action and a
// spoken label. It shares the canvas transform (graphicsLayer) and the
// layout's coordinates, so a screen reader reaches exactly the nodes that
// hit-testing reaches. It has no pointer handler, so it never steals the
// pan/zoom gestures from the Canvas below.
Box(
Modifier
.fillMaxSize()
.graphicsLayer(
translationX = offset.x,
translationY = offset.y,
scaleX = scale,
scaleY = scale,
transformOrigin = TransformOrigin(0f, 0f),
),
) {
layout.nodes.forEach { node ->
val nodeType = graph.stages.firstOrNull { it.key == node.key }?.type
Box(
Modifier
.offset { IntOffset(node.x.roundToInt(), node.y.roundToInt()) }
.size(with(density) { node.width.toDp() }, with(density) { node.height.toDp() })
.semantics {
contentDescription = nodeDescription(node, nodeType)
role = Role.Button
onClick(label = "Open details for ${node.label}") {
onStageTap(node.key)
true
}
},
)
}
}
Row(
modifier = Modifier.align(Alignment.TopEnd).padding(4.dp),
) {
@@ -305,6 +375,13 @@ private class GraphColors(
val labelText: Color,
)
/** 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"
val typeLabel = effectiveStageType(type)
return "Stage ${node.label}, $typeLabel, tap for details"
}
/**
* Uniform scale that fits [content] inside [viewport] with [padding] on every
* side, never upscaling above 1:1. Degenerate (zero/negative) content or
@@ -373,29 +450,169 @@ internal fun zoomAbout(
return ZoomResult(anchored, newScale)
}
/**
* The draw transform is `p * scale + offset`, so a tap in viewport space maps to
* graph space as `(tap - offset) / scale`. Pure, so hit-test mapping is unit
* tested without Compose; a degenerate scale returns [Offset.Zero] instead of
* dividing by zero.
*/
internal fun toGraphPoint(tap: Offset, offset: Offset, scale: Float): Offset {
if (!scale.isFinite() || scale == 0f) return Offset.Zero
return (tap - offset) / scale
}
/** The key of the stage/terminal whose rect contains [graphPoint], else null. */
internal fun hitTest(layout: GraphLayout, graphPoint: Offset): String? =
layout.nodes.firstOrNull { it.contains(graphPoint) }?.key
/**
* A tiny one-dimensional allocator that places a run at the first position,
* starting from [desired] and stepping outward by `step`, that is at least `step`
* away from every already-placed run whose cross-interval overlaps. It is the
* single mechanism that keeps two edges off the same row/column: horizontal runs
* pass their x-interval, vertical runs their y-interval. Deterministic because
* callers allocate in stable edge-id order.
*/
private class SegmentAllocator(private val eps: Float) {
private val pos = ArrayList<Float>()
private val lo = ArrayList<Float>()
private val hi = ArrayList<Float>()
fun allocate(desired: Float, from: Float, to: Float, min: Float, max: Float, step: Float): Float {
val start = desired.coerceIn(min, max)
val a = minOf(from, to)
val b = maxOf(from, to)
var k = 0
while (k <= 512) {
val candidates = if (k == 0) listOf(start) else listOf(start + k * step, start - k * step)
for (candidate in candidates) {
if (candidate < min || candidate > max) continue
if (isFree(candidate, a, b)) {
record(candidate, a, b)
return candidate
}
}
k++
}
record(start, a, b)
return start
}
private fun isFree(candidate: Float, a: Float, b: Float): Boolean {
for (i in pos.indices) {
if (abs(pos[i] - candidate) < eps && lo[i] <= b && a <= hi[i]) return false
}
return true
}
private fun record(candidate: Float, a: Float, b: Float) {
pos.add(candidate)
lo.add(a)
hi.add(b)
}
}
/**
* A partially-routed edge. Routing runs in passes over these holders so the gap
* tracks are all placed before any under-node/terminal port vertical, which is
* what stops a later route being starved into sharing a column (the original
* overlap defect). Mutable only during layout.
*/
private class RouteParts(
val edge: GraphEdge,
val source: NodeLayout,
val target: NodeLayout,
val sourceRank: Int,
val targetRank: Int,
val forward: Boolean,
val bottomExit: Boolean,
val topEntry: Boolean,
val backEdge: Boolean,
val across: Boolean,
val lane: Float,
) {
var fromX = 0f
var fromY = 0f
var toX = 0f
var toY = 0f
var trackX = 0f
var leadX = 0f
}
/** Centred fan for the k-th of n ports: 0, +s, -s, +2s, -2s, ... around centre. */
private fun portOffset(index: Int, spacing: Float): Float {
if (index == 0) return 0f
val magnitude = ((index + 1) / 2).toFloat()
val sign = if (index % 2 == 1) 1f else -1f
return sign * magnitude * spacing
}
/** True for an edge that goes to the immediately following stage. */
private fun forwardAdjacent(edge: GraphEdge, rank: Map<String, Int>): Boolean =
!Protocol.isTerminal(edge.target) &&
(rank[edge.target] ?: 0) == (rank[edge.source] ?: 0) + 1
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 nodeHeight = with(density) { 56.dp.toPx() }
val hGap = with(density) { 88.dp.toPx() }
val portSpacing = with(density) { 12.dp.toPx() }
val hGap = with(density) { 132.dp.toPx() }
val pad = with(density) { 32.dp.toPx() }
val terminalRowGap = with(density) { 72.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 ranks = rankStages(graph)
val edges = graph.edges()
val hasTerminal = graph.stages.any { stage ->
stage.edges.values.any { Protocol.isTerminal(it) || it == "#" }
}
// Stages occupy a single top row in declaration order, exactly like
// tui.layoutSingleRowGraph: x grows with the declared stage index and every
// stage shares the same y.
// Port demand per node, so the node grows tall enough to host one port per
// distinct edge leaving/entering it (the distinct-port requirement).
val outCount = HashMap<String, Int>()
val inCount = HashMap<String, Int>()
val bottomCount = HashMap<String, Int>()
for (edge in edges) {
val bottom = edge.outcome == "error" && edge.target == Protocol.FAILURE_END
val forward = forwardAdjacent(edge, ranks)
if (!bottom && !forward) outCount[edge.source] = (outCount[edge.source] ?: 0) + 1
if (bottom) bottomCount[edge.source] = (bottomCount[edge.source] ?: 0) + 1
if (!Protocol.isTerminal(edge.target) && !forward) {
inCount[edge.target] = (inCount[edge.target] ?: 0) + 1
}
}
val terminalIn = HashMap<String, Int>()
if (hasTerminal) {
terminalIn[Protocol.FAILURE_END] = edges.count { it.target == Protocol.FAILURE_END }
terminalIn[Protocol.SUCCESS_END] = edges.count { it.target == Protocol.SUCCESS_END }
}
var maxPorts = 1
(outCount.values + inCount.values + bottomCount.values + terminalIn.values).forEach {
maxPorts = maxOf(maxPorts, it)
}
val nodeHeight = maxOf(minNodeHeight, (maxPorts + 1) * portSpacing)
val portLo = pad + portSpacing * 0.5f
val portHi = pad + nodeHeight - portSpacing * 0.5f
val stageCount = graph.stages.size
val contentLeft = pad + hGap
fun stageX(index: Int) = contentLeft + index * (nodeWidth + hGap)
fun gapBounds(gap: Int): Pair<Float, Float> = when {
gap <= 0 -> pad to contentLeft
gap >= stageCount -> (stageX(stageCount - 1) + nodeWidth) to
(stageX(stageCount - 1) + nodeWidth + hGap)
else -> (stageX(gap - 1) + nodeWidth) to stageX(gap)
}
val positions = HashMap<String, NodeLayout>()
graph.stages.forEachIndexed { index, stage ->
positions[stage.key] = NodeLayout(
key = stage.key,
label = GraphSemantics.nodeLabel(stage.key),
x = pad + index * (nodeWidth + hGap),
x = stageX(index),
y = pad,
width = nodeWidth,
height = nodeHeight,
@@ -403,24 +620,38 @@ internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density
)
}
val stageRowInner = graph.stages.size * nodeWidth +
(graph.stages.size - 1).coerceAtLeast(0) * hGap
val terminalPairInner = 2 * nodeWidth + hGap
val contentInner = if (hasTerminal) maxOf(stageRowInner, terminalPairInner) else stageRowInner
val width = pad * 2 + contentInner
val stageRowRight = stageX(stageCount - 1) + nodeWidth
val stageBottom = pad + nodeHeight
// Every non-forward edge needs its own cross lane, stacked below the stage
// row in stable edge-id order; the terminal row sits below all of them.
val laneIds = edges.filterNot { forwardAdjacent(it, ranks) }
val laneIndexById = HashMap<Int, Int>()
laneIds.forEachIndexed { index, edge -> laneIndexById[edge.id] = index }
fun laneY(edge: GraphEdge) = stageBottom + ((laneIndexById[edge.id] ?: 0) + 1) * laneSpacing
val terminalY = stageBottom + (laneIds.size + 1) * laneSpacing + terminalGap
// Terminal widths grow with their incoming-edge count so every incoming route
// gets its own top port without crowding (mirroring the TUI's per-incoming
// terminal width).
val terminalWidthFor = { incoming: Int -> maxOf(nodeWidth, incoming * trackStep + 4 * portSpacing) }
val failureWidth = if (hasTerminal) terminalWidthFor(terminalIn[Protocol.FAILURE_END] ?: 0) else nodeWidth
val successWidth = if (hasTerminal) terminalWidthFor(terminalIn[Protocol.SUCCESS_END] ?: 0) else nodeWidth
val terminalPairInner = failureWidth + successWidth + hGap
val width = maxOf(stageRowRight + hGap + pad, terminalPairInner + 2 * pad)
if (hasTerminal) {
// Both terminals share one lower row, FAILURE left of SUCCESS, the pair
// centred on the content width, so incoming arrows enter their top border.
val terminalY = pad + nodeHeight + terminalRowGap
val failureX = pad + (contentInner - terminalPairInner) / 2f
val successX = failureX + nodeWidth + hGap
val centre = width / 2f
val failureX = centre - terminalPairInner / 2f
val successX = failureX + failureWidth + hGap
positions[Protocol.FAILURE_END] = NodeLayout(
key = Protocol.FAILURE_END,
label = GraphSemantics.nodeLabel(Protocol.FAILURE_END),
x = failureX,
y = terminalY,
width = nodeWidth,
width = failureWidth,
height = nodeHeight,
terminal = true,
)
@@ -429,93 +660,282 @@ internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density
label = GraphSemantics.nodeLabel(Protocol.SUCCESS_END),
x = successX,
y = terminalY,
width = nodeWidth,
width = successWidth,
height = nodeHeight,
terminal = true,
)
}
val edges = graph.edges()
val countsBySource = edges.groupingBy { it.source }.eachCount()
val slotsBySource = HashMap<String, Int>()
val edgeLayouts = edges.mapNotNull { edge ->
// One shared allocator per axis so no two collinear runs overlap. Horizontal
// runs pass their x-interval, vertical runs their y-interval.
val horizontals = SegmentAllocator(eps = portSpacing)
val verticals = SegmentAllocator(eps = trackStep / 3f)
// Forward edges are allocated first: a straight forward route keeps a single
// horizontal segment by sharing one y between its source and target ports.
val forwardEdges = edges.filter { forwardAdjacent(it, ranks) }
val forwardY = HashMap<Int, Float>()
forwardEdges.forEachIndexed { index, edge ->
val source = positions[edge.source] ?: return@forEachIndexed
val target = positions[edge.target] ?: return@forEachIndexed
val y = source.y + source.height / 2f -
(forwardEdges.size - 1) / 2f * portSpacing + index * portSpacing
forwardY[edge.id] = horizontals.allocate(
desired = y,
from = source.x + source.width,
to = target.x,
min = portLo,
max = portHi,
step = portSpacing,
)
}
// Routing happens in three passes so a later allocation can never be starved
// by an earlier one: (1) horizontal port anchors, (2) the gap tracks, then
// (3) the bottom/terminal port verticals that live under the nodes.
val parts = edges.mapNotNull { edge ->
val source = positions[edge.source] ?: return@mapNotNull null
val target = positions[edge.target] ?: return@mapNotNull null
val sourceRank = ranks[edge.source] ?: 0
val targetIsTerminal = Protocol.isTerminal(edge.target)
val targetRank = if (targetIsTerminal) graph.stages.size else (ranks[edge.target] ?: 0)
val bottomExit = edge.outcome == "error" && edge.target == Protocol.FAILURE_END
val labelSlot = slotsBySource.getOrDefault(edge.source, 0)
slotsBySource[edge.source] = labelSlot + 1
EdgeLayout(
val forward = forwardAdjacent(edge, ranks)
// A terminal target is entered from the top (mirroring tui.graphEdge.topEntry),
// including an error->#failure route that leaves the source bottom.
val topEntry = targetIsTerminal
val backEdge = !targetIsTerminal && targetRank <= sourceRank
val across = !targetIsTerminal && !forward
val part = RouteParts(
edge = edge,
from = if (bottomExit) {
Offset(source.x + source.width / 2f, source.y + source.height)
} else {
Offset(source.x + source.width, source.y + source.height / 2f)
},
to = if (targetIsTerminal) {
Offset(target.x + target.width / 2f, target.y)
} else {
Offset(target.x, target.y + target.height / 2f)
},
backEdge = !targetIsTerminal && targetRank <= sourceRank,
topEntry = targetIsTerminal,
bottomExit = bottomExit,
source = source,
target = target,
sourceRank = sourceRank,
targetRank = targetRank,
labelSlot = labelSlot,
labelCount = countsBySource[edge.source] ?: 1,
).let { it.copy(points = routePoints(it)) }
forward = forward,
bottomExit = bottomExit,
topEntry = topEntry,
backEdge = backEdge,
across = across,
lane = laneY(edge),
)
// Pass 1: horizontal anchors.
when {
bottomExit -> {
part.fromX = Float.NaN
part.fromY = source.y + source.height
}
forward -> {
part.fromX = source.x + source.width
part.fromY = forwardY[edge.id] ?: (source.y + source.height / 2f)
}
else -> {
val slot = edges.filter {
it.source == edge.source && !forwardAdjacent(it, ranks) &&
!(it.outcome == "error" && it.target == Protocol.FAILURE_END)
}.indexOfFirst { it.id == edge.id }
part.fromX = source.x + source.width
part.fromY = horizontals.allocate(
desired = source.y + source.height / 2f + portOffset(slot, portSpacing),
from = source.x + source.width,
to = source.x + source.width + hGap,
min = portLo,
max = portHi,
step = portSpacing,
)
}
}
when {
forward -> {
part.toX = target.x
part.toY = forwardY[edge.id] ?: (target.y + target.height / 2f)
}
targetIsTerminal -> {
part.toX = Float.NaN
part.toY = target.y
}
else -> {
val slot = edges.filter {
it.target == edge.target && !Protocol.isTerminal(it.target) &&
!forwardAdjacent(it, ranks)
}.indexOfFirst { it.id == edge.id }
part.toX = target.x
part.toY = horizontals.allocate(
desired = target.y + target.height / 2f + portOffset(slot, portSpacing),
from = target.x - hGap,
to = target.x,
min = portLo,
max = portHi,
step = portSpacing,
)
}
}
part
}
val height = pad * 2 + nodeHeight + (if (hasTerminal) terminalRowGap + nodeHeight else 0f)
// Pass 2: the vertical tracks in the gaps.
for (part in parts) {
if (part.topEntry && !part.bottomExit) {
val (gapLo, gapHi) = gapBounds(part.sourceRank + 1)
part.trackX = verticals.allocate(
desired = gapLo + trackStep,
from = minOf(part.fromY, part.lane),
to = maxOf(part.fromY, part.lane),
min = gapLo + trackStep / 2f,
max = gapHi - trackStep / 2f,
step = trackStep,
)
} else if (part.across) {
val (sourceGapLo, sourceGapHi) = gapBounds(part.sourceRank + 1)
part.trackX = verticals.allocate(
desired = sourceGapLo + trackStep,
from = minOf(part.fromY, part.lane),
to = maxOf(part.fromY, part.lane),
min = sourceGapLo + trackStep / 2f,
max = sourceGapHi - trackStep / 2f,
step = trackStep,
)
val (targetGapLo, targetGapHi) = gapBounds(part.targetRank)
part.leadX = verticals.allocate(
desired = targetGapHi - trackStep,
from = minOf(part.lane, part.toY),
to = maxOf(part.lane, part.toY),
min = targetGapLo + trackStep / 2f,
max = targetGapHi - trackStep / 2f,
step = trackStep,
)
}
}
// Pass 3: the bottom-exit drop and the terminal top-drop.
for (part in parts) {
if (part.bottomExit) {
val bottomIndex = edges.filter {
it.outcome == "error" && it.target == Protocol.FAILURE_END && it.source == part.edge.source
}.indexOfFirst { it.id == part.edge.id }
part.fromX = verticals.allocate(
desired = part.source.x + part.source.width / 2f + portOffset(bottomIndex, portSpacing),
from = part.source.y + part.source.height,
to = part.lane,
min = part.source.x + portSpacing,
max = part.source.x + part.source.width - portSpacing,
step = trackStep,
)
}
if (part.topEntry) {
val slot = edges.filter { it.target == part.edge.target }.indexOfFirst { it.id == part.edge.id }
part.toX = verticals.allocate(
desired = part.target.x + part.target.width / 2f + portOffset(slot, portSpacing),
from = part.lane,
to = part.target.y,
min = part.target.x + portSpacing,
max = part.target.x + part.target.width - portSpacing,
step = trackStep,
)
}
}
val edgeLayouts = parts.map { part ->
val layout = EdgeLayout(
edge = part.edge,
from = Offset(part.fromX, part.fromY),
to = Offset(part.toX, part.toY),
backEdge = part.backEdge,
topEntry = part.topEntry,
bottomExit = part.bottomExit,
sourceRank = part.sourceRank,
targetRank = part.targetRank,
across = part.across,
lane = part.lane,
trackX = part.trackX,
leadX = part.leadX,
labelPoint = Offset.Zero,
)
val points = routePoints(layout)
layout.copy(points = points, labelPoint = labelPointFor(layout, points))
}
val height = pad * 2 + nodeHeight + (if (hasTerminal) {
(laneIds.size + 1) * laneSpacing + terminalGap + nodeHeight
} else {
0f
})
return GraphLayout(positions.values.toList(), edgeLayouts, width, height)
}
/**
* Where this edge's outcome label is drawn: the midpoint of its own lane run (or
* its single straight segment for a forward edge), so each label travels on that
* edge's own track instead of overprinting a neighbouring route. Pure, and the
* point is stored on [EdgeLayout] so drawing never recomputes it.
*/
private fun labelPointFor(edge: EdgeLayout, points: List<Offset>): Offset {
if (points.size < 2) return edge.from
if (!edge.bottomExit && !edge.topEntry && !edge.across) {
return (points.first() + points.last()) / 2f
}
// The lane run is the widest horizontal segment of the route.
var best: Pair<Offset, Offset>? = null
var bestWidth = -1f
for (i in 1 until points.size) {
val a = points[i - 1]
val b = points[i]
if (a.y == b.y && abs(b.x - a.x) > bestWidth) {
bestWidth = abs(b.x - a.x)
best = a to b
}
}
val (a, b) = best ?: return points.first()
return Offset((a.x + b.x) / 2f, a.y)
}
/**
* The axis-aligned polyline an edge is drawn along: horizontal and vertical runs
* joined at right angles, mirroring internal/tui/graph_layout.go (source track ->
* lane -> target track). Pure and independent of drawing so tests can assert it
* and layout can precompute it once per edge.
* and layout can precompute it once per edge; it only reads the ports/lanes the
* allocator already fixed on [edge].
*
* - `bottomExit` (error -> #failure) drops out of the source's bottom, runs
* across above the terminal and drops into its top border.
* - `topEntry` (any other terminal) leaves the source's right edge, drops into a
* lane just above the lower terminal row, then drops into the terminal top.
* - `backEdge` (loop) dips below the stages, runs back horizontally and enters
* the target's left edge.
* - a forward edge is a single horizontal segment when source and target share a
* y, otherwise an L across a shared mid-x.
* - `bottomExit` (error -> #failure) drops out of the source's bottom port into
* its own lane and down into the terminal's own top port.
* - `topEntry` (any other terminal) leaves the source's right-edge port, uses
* its own vertical track and lane and drops into the terminal's own top port.
* - `across` (a loop or jump) uses its own bottom dip lane and its own lead
* column into the target's own left port.
* - a forward edge is a single horizontal segment when its ports share a y.
*
* Consecutive equal points are collapsed so no zero-length segment is produced.
*/
internal fun routePoints(edge: EdgeLayout): List<Offset> {
val raw = when {
edge.bottomExit -> {
val approachY = edge.to.y - BOTTOM_EXIT_APPROACH
listOf(edge.from, Offset(edge.from.x, approachY), Offset(edge.to.x, approachY), edge.to)
}
edge.topEntry -> {
val laneY = edge.to.y - LANE_APPROACH
listOf(edge.from, Offset(edge.from.x, laneY), Offset(edge.to.x, laneY), edge.to)
}
edge.backEdge -> {
val dipY = maxOf(edge.from.y, edge.to.y) + BACK_EDGE_DIP
val leadX = edge.to.x - BACK_EDGE_LEAD
listOf(
edge.from,
Offset(edge.from.x, dipY),
Offset(leadX, dipY),
Offset(leadX, edge.to.y),
edge.to,
)
}
edge.bottomExit -> listOf(
edge.from,
Offset(edge.from.x, edge.lane),
Offset(edge.to.x, edge.lane),
edge.to,
)
edge.topEntry -> listOf(
edge.from,
Offset(edge.trackX, edge.from.y),
Offset(edge.trackX, edge.lane),
Offset(edge.to.x, edge.lane),
edge.to,
)
edge.across -> listOf(
edge.from,
Offset(edge.trackX, edge.from.y),
Offset(edge.trackX, edge.lane),
Offset(edge.leadX, edge.lane),
Offset(edge.leadX, edge.to.y),
edge.to,
)
edge.from.y == edge.to.y -> listOf(edge.from, edge.to)
else -> {
val midX = (edge.from.x + edge.to.x) / 2f
listOf(edge.from, Offset(midX, edge.from.y), Offset(midX, edge.to.y), edge.to)
}
else -> listOf(
edge.from,
Offset(edge.trackX, edge.from.y),
Offset(edge.trackX, edge.to.y),
edge.to,
)
}
val points = ArrayList<Offset>(raw.size)
for (point in raw) {
@@ -577,10 +997,12 @@ private fun DrawScope.drawEdgePaths(
/**
* Draws every outcome label in a second pass, after all curves, so a
* neighbouring edge can never be drawn across a label. Executed edges use a
* legible on-surface variant of their outcome colour (see [outcomeLabelColor]);
* dimmed edges use a muted colour on a near-opaque background instead of
* inheriting the curve's 0.25 alpha, which left the text unreadable.
* 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. Executed edges use a legible on-surface
* variant of their outcome colour (see [outcomeLabelColor]); dimmed edges use a
* muted colour on a near-opaque background instead of inheriting the curve's
* 0.25 alpha, which left the text unreadable.
*/
private fun DrawScope.drawEdgeLabels(
layout: GraphLayout,
@@ -592,16 +1014,9 @@ private fun DrawScope.drawEdgeLabels(
val executed = edge.isExecuted(runState)
val textColor = if (executed) outcomeLabelColor(edge.edge, colors) else colors.labelText
val measured = textMeasurer.measure(edge.edge.label, TextStyle(fontSize = 11.sp, color = textColor))
// Every outgoing edge of a stage shares the same `from` anchor, so drawing
// each label at a fixed offset overprints distinct outcomes (success/error,
// blocked/skipped). Give each label its own row in a per-source stack,
// mirroring the independent ports/tracks of internal/tui/graph_layout.go,
// and draw a near-opaque background so crossing edges stay legible.
val spread = (edge.labelCount - 1) / 2f
val labelTopLeft = Offset(
x = edge.from.x + 8f,
y = edge.from.y - measured.size.height / 2f +
(edge.labelSlot - spread) * (measured.size.height + 2f),
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),
@@ -738,24 +1153,13 @@ private fun graphDescription(graph: Graph, runState: RunGraphState?): String {
builder.append("Outcome $label goes to ${GraphSemantics.nodeLabel(target)}. ")
}
}
builder.append("Stages can be tapped for details.")
return builder.toString()
}
private const val MIN_SCALE = 0.3f
private const val MAX_SCALE = 3f
/** How far below the stage row a loop route dips before curving back. */
private const val BACK_EDGE_DIP = 64f
/** How far above a terminal's top border the bottom-exit route levels off. */
private const val BOTTOM_EXIT_APPROACH = 32f
/** How far above the target's left edge a loop route levels off before entering. */
private const val BACK_EDGE_LEAD = 24f
/** How far above the terminal row a top-entry route runs before dropping in. */
private const val LANE_APPROACH = 32f
/** Breathing room left around a fitted graph, and the least content kept visible. */
private val FIT_PADDING = 16.dp
private val MIN_VISIBLE = 48.dp
@@ -47,6 +47,7 @@ import net.awan.pipelines.ui.components.KeyValueRow
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.collapsibleSection
import net.awan.pipelines.ui.components.pipelineDetailTabs
import net.awan.pipelines.ui.graph.StageDetailSheet
import net.awan.pipelines.ui.graph.WorkflowGraph
import net.awan.pipelines.ui.theme.pipelinesText
@@ -189,6 +190,9 @@ private fun PipelineSummaryTab(detail: PipelineDetail, wide: Boolean, modifier:
@Composable
private fun PipelineGraphTab(detail: PipelineDetail, modifier: Modifier) {
val text = pipelinesText()
// The stage whose detail sheet is open; survives configuration changes. The
// sheet is an overlay on this screen (no navigation route).
var selectedStage by rememberSaveable { mutableStateOf<String?>(null) }
LazyColumn(
modifier = modifier,
contentPadding = PaddingValues(vertical = 16.dp),
@@ -199,13 +203,25 @@ private fun PipelineGraphTab(detail: PipelineDetail, modifier: Modifier) {
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
"Pinch to zoom, drag to pan. Edges are labelled with their outcome; error* is the implicit fallback.",
"Pinch to zoom, drag to pan, tap a stage for details. Edges are labelled with their outcome; error* is the implicit fallback.",
style = text.meta,
)
WorkflowGraph(graph = detail.graph, modifier = Modifier.fillMaxWidth())
WorkflowGraph(
graph = detail.graph,
modifier = Modifier.fillMaxWidth(),
onStageTap = { selectedStage = it },
)
}
}
}
selectedStage?.let { key ->
StageDetailSheet(
stageKey = key,
graph = detail.graph,
runStep = null,
onDismiss = { selectedStage = null },
)
}
}
@Composable
@@ -76,6 +76,7 @@ import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.displayMap
import net.awan.pipelines.ui.displayText
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.graph.StageDetailSheet
import net.awan.pipelines.ui.graph.WorkflowGraph
import net.awan.pipelines.ui.theme.pipelinesText
import net.awan.pipelines.ui.visitCount
@@ -313,6 +314,8 @@ private fun RunSummaryTab(run: RunDetail, wide: Boolean, modifier: Modifier) {
private fun RunGraphTab(run: RunDetail, modifier: Modifier) {
val text = pipelinesText()
val runState = remember(run.id, run.steps) { RunGraphState.from(run) }
// The stage whose detail sheet is open; the sheet overlays this screen.
var selectedStage by rememberSaveable { mutableStateOf<String?>(null) }
LazyColumn(
modifier = modifier,
contentPadding = PaddingValues(vertical = 16.dp),
@@ -326,7 +329,7 @@ private fun RunGraphTab(run: RunDetail, modifier: Modifier) {
Text("This server did not include the run graph.", style = text.meta)
} else {
Text(
"Executed stages and routes are highlighted; the rest are dimmed. Pinch to zoom, drag to pan.",
"Executed stages and routes are highlighted; the rest are dimmed. Pinch to zoom, drag to pan, tap a stage for details.",
style = text.meta,
)
WorkflowGraph(
@@ -334,11 +337,22 @@ private fun RunGraphTab(run: RunDetail, modifier: Modifier) {
modifier = Modifier.fillMaxWidth(),
runState = runState,
selectedStage = runState.currentStage,
onStageTap = { selectedStage = it },
)
}
}
}
}
selectedStage?.let { key ->
StageDetailSheet(
stageKey = key,
graph = run.graph,
// This run's latest step for the stage (a stage can be visited more
// than once); null when the run never reached it.
runStep = run.steps.lastOrNull { it.stage == key },
onDismiss = { selectedStage = null },
)
}
}
/**
@@ -7,6 +7,7 @@ import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.Stage
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.hypot
@@ -24,6 +25,30 @@ class WorkflowGraphTest {
),
)
/**
* A denser graph than [sampleGraph]: many multi-outcome nodes, several edges
* into each terminal, two routes to the same next stage, a forward jump and
* further back edges. The per-edge track invariant must hold here too.
*/
private fun denseGraph() = Graph(
stages = listOf(
stage("a", mapOf("success" to "b", "fast" to "c", "error" to "#failure", "abort" to "#failure")),
stage("b", mapOf("success" to "c", "retry" to "a", "blocked" to "#failure", "error" to "#failure")),
stage("c", mapOf("success" to "d", "skip" to "d", "error" to "#failure")),
stage("d", mapOf("success" to "e", "error" to "#failure")),
stage(
"e",
mapOf(
"success" to "#success",
"done" to "#success",
"missing" to "#failure",
"revisit" to "b",
"stay" to "e",
),
),
),
)
/**
* Regression for the back-edge ordering defect: `reviewer rejected -> implementer`
* used to feed the longest-path relaxation and push `implementer` past
@@ -392,4 +417,113 @@ class WorkflowGraphTest {
val negative = zoomAbout(offset, 0.5f, Offset(80f, 60f), zoom = -2f, 0.3f, 3f)
assertEquals(offset, negative.offset)
}
/**
* The fix: no two edges may share a collinear run. For every unordered pair
* of edges, no horizontal segment shares a y over an overlapping x range and
* no vertical segment shares an x over an overlapping y range. Verified on the
* sample graph and a denser multi-outcome / multi-terminal graph; crossings
* are still allowed, only overlaps are not.
*/
@Test
fun noTwoEdgesShareACollinearRun() {
for (graph in listOf(sampleGraph(), denseGraph())) {
assertNoSharedRuns(layoutGraph(graph, Density(1f)))
}
}
/** Distinct edges leaving/entering one node must use distinct ports. */
@Test
fun distinctEdgesUseDistinctPorts() {
for (graph in listOf(sampleGraph(), denseGraph())) {
val layout = layoutGraph(graph, Density(1f))
layout.edges.groupBy { it.edge.source }.forEach { (source, list) ->
assertEquals("ports leaving $source", list.size, list.map { it.from }.toSet().size)
}
layout.edges.groupBy { it.edge.target }.forEach { (target, list) ->
assertEquals("ports entering $target", list.size, list.map { it.to }.toSet().size)
}
}
}
/** Layout is pure and deterministic: two calls give equal routes. */
@Test
fun layoutIsDeterministic() {
val first = layoutGraph(sampleGraph(), Density(1f))
val second = layoutGraph(sampleGraph(), Density(1f))
assertEquals(first.edges.map { it.points }, second.edges.map { it.points })
}
/**
* Hit-testing and the tap→graph transform are pure: a tap inside a stage
* returns that stage, a tap on a terminal returns the terminal and a tap on
* empty space returns null, at several pan and zoom values. Hit-testing uses
* the same layout (ports/tracks) as drawing.
*/
@Test
fun hitTestFindsNodesAtSeveralPansAndZooms() {
val layout = layoutGraph(sampleGraph(), Density(1f))
val transforms = listOf(
Offset.Zero to 1f,
Offset(-140f, 60f) to 1.5f,
Offset(90f, -30f) to 0.5f,
)
for ((offset, scale) in transforms) {
for (key in listOf("planner", "ui_reviewer", Protocol.FAILURE_END, Protocol.SUCCESS_END)) {
val node = layout.nodes.single { it.key == key }
val centre = Offset(node.x + node.width / 2f, node.y + node.height / 2f)
val tap = centre * scale + offset
assertEquals(
"tap on $key at scale $scale",
key,
hitTest(layout, toGraphPoint(tap, offset, scale)),
)
}
val empty = Offset(layout.width + 500f, layout.height + 500f)
assertNull(hitTest(layout, toGraphPoint(empty * scale + offset, offset, scale)))
}
}
private fun assertNoSharedRuns(layout: GraphLayout) {
val edges = layout.edges
for (i in edges.indices) {
for (j in i + 1 until edges.size) {
assertNoSharedRuns(edges[i], edges[j])
}
}
}
private fun assertNoSharedRuns(a: EdgeLayout, b: EdgeLayout) {
val message = "routes ${a.edge} and ${b.edge}"
for (i in 1 until a.points.size) {
val a0 = a.points[i - 1]
val a1 = a.points[i]
if (a0.y != a1.y) continue
val aMin = minOf(a0.x, a1.x)
val aMax = maxOf(a0.x, a1.x)
for (k in 1 until b.points.size) {
val b0 = b.points[k - 1]
val b1 = b.points[k]
if (b0.y != b1.y || b0.y != a0.y) continue
val bMin = minOf(b0.x, b1.x)
val bMax = maxOf(b0.x, b1.x)
assertTrue("$message share a horizontal run at y=${a0.y}", !(aMin < bMax && bMin < aMax))
}
}
for (i in 1 until a.points.size) {
val a0 = a.points[i - 1]
val a1 = a.points[i]
if (a0.x != a1.x) continue
val aMin = minOf(a0.y, a1.y)
val aMax = maxOf(a0.y, a1.y)
for (k in 1 until b.points.size) {
val b0 = b.points[k - 1]
val b1 = b.points[k]
if (b0.x != b1.x || b0.x != a0.x) continue
val bMin = minOf(b0.y, b1.y)
val bMax = maxOf(b0.y, b1.y)
assertTrue("$message share a vertical run at x=${a0.x}", !(aMin < bMax && bMin < aMax))
}
}
}
}