diff --git a/android/README.md b/android/README.md index 575ebd75..8ac79654 100644 --- a/android/README.md +++ b/android/README.md @@ -132,6 +132,10 @@ Verified on macOS with the host toolchain (JDK 17 from Android Studio, other runtime exception during the sweep. Known limitations of that run: pinch-zoom could not be driven through `adb` -(single-touch pan only), one portrait Fold viewport was used, and the graph is -not fit-to-content on first layout (pan to reach later columns); a panned graph -can still draw an edge curve across a neighbouring outcome label. +(single-touch pan only) and one portrait Fold viewport was used. A follow-up pass +fitted the graph to its viewport on first layout, clamped panning so the content +cannot leave the view, added a "Fit graph to view" action, connected on launch +when a server URL is already saved, and made the completed/recorded visit wording +and the outcome-label contrast consistent. The fitted graph still sits slightly +above the box's vertical centre, because the layout box includes padding that is +not drawn. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt index 9595c232..fa9b9f08 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt @@ -84,6 +84,18 @@ class AppViewModel( private val startKeys = ConcurrentHashMap() private val retryKeys = ConcurrentHashMap() + init { + // Connect on launch when a server URL is already saved, reusing the shared + // client and its bounded backoff (no new client, DI or polling). init runs + // once per ViewModel, so an explicit Disconnect (which sets Idle) is not + // immediately overridden and stays authoritative for the session. + if (settings.serverUrl.value.isNotBlank() && + repository.connectionState.value is ConnectionState.Idle + ) { + reconnect() + } + } + fun updateServerUrlDraft(value: String) { _serverUrlDraft.value = value _urlError.value = null diff --git a/android/app/src/main/java/net/awan/pipelines/ui/Format.kt b/android/app/src/main/java/net/awan/pipelines/ui/Format.kt index c954b0aa..efd6d846 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/Format.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/Format.kt @@ -31,3 +31,12 @@ fun JsonElement.displayText(): String = when (this) { fun Map?.displayMap(): String = this?.entries?.joinToString("\n") { "${it.key}: ${it.value.displayText()}" }.orEmpty() + +/** + * A run's step count in the server's own vocabulary, mirroring + * internal/tui/results.go ("%d completed visits") and internal/tui/run_graph.go + * ("%d recorded visits"), with a singular form for a single visit. The runs list + * and run detail share this so the same run is never described inconsistently. + */ +fun visitCount(count: Int, adjective: String): String = + "$count $adjective ${if (count == 1) "visit" else "visits"}" diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/WorkflowGraph.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/WorkflowGraph.kt index 063901fa..4f9ca5fc 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/WorkflowGraph.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/WorkflowGraph.kt @@ -5,13 +5,21 @@ import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.FitScreen +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember 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.Offset @@ -102,19 +110,59 @@ fun WorkflowGraph( success = scheme.tertiary, error = scheme.error, accent = listOf(scheme.primary, scheme.secondary, scheme.primaryContainer, scheme.secondaryContainer), + // Labels sit on a surface-coloured chip, so they must not reuse the + // container *fill* colours (primaryContainer/secondaryContainer), which + // are near-invisible as text on the surface. Draw those outcomes in + // their matching "on-container" colour instead; the other accents are + // already legible on the surface in both light and dark themes. + labelAccent = listOf( + scheme.primary, + scheme.secondary, + scheme.onPrimaryContainer, + scheme.onSecondaryContainer, + ), nodeFill = scheme.surfaceVariant, nodeFillActive = scheme.primaryContainer, nodeBorder = scheme.outline, nodeText = scheme.onSurface, terminalFill = scheme.secondaryContainer, labelBackground = scheme.surface, + labelText = scheme.onSurfaceVariant, ) } + val fitPaddingPx = with(density) { FIT_PADDING.toPx() } + val minVisiblePx = with(density) { MIN_VISIBLE.toPx() } + var scale by remember { mutableFloatStateOf(1f) } var offset by remember { mutableStateOf(Offset.Zero) } var canvasSize by remember { mutableStateOf(IntSize.Zero) } - var centered by remember { mutableStateOf(false) } + // Once the user pans or zooms, automatic re-fitting stops fighting them; the + // reset affordance below clears this and re-applies the fit transform. + var userAdjusted by remember { mutableStateOf(false) } + var fitRequest by remember { mutableIntStateOf(0) } + + // Fit the whole graph into the viewport on first layout and whenever the + // viewport itself changes size, unless the user has taken over the view. + LaunchedEffect(layout, canvasSize, fitRequest) { + if (userAdjusted) return@LaunchedEffect + val viewportWidth = canvasSize.width.toFloat() + val viewportHeight = canvasSize.height.toFloat() + if (viewportWidth <= 0f || viewportHeight <= 0f) return@LaunchedEffect + val viewport = Size(viewportWidth, viewportHeight) + val fitted = fitScale(viewport, Size(layout.width, layout.height), fitPaddingPx) + val scaled = Size(layout.width * fitted, layout.height * fitted) + scale = fitted + offset = clampOffset( + offset = Offset( + x = (viewport.width - scaled.width) / 2f, + y = (viewport.height - scaled.height) / 2f, + ), + content = scaled, + viewport = viewport, + minVisible = minVisiblePx, + ) + } Box( modifier = modifier @@ -124,20 +172,20 @@ fun WorkflowGraph( .clipToBounds() .background(MaterialTheme.colorScheme.surface) .semantics { contentDescription = description } - .onSizeChanged { size -> - canvasSize = size - if (!centered && layout.width > 0f && layout.height > 0f) { - offset = Offset( - x = (size.width - layout.width * scale) / 2f, - y = (size.height - layout.height * scale) / 2f, - ).coerceAtLeast(0f) - centered = true - } - } - .pointerInput(Unit) { + .onSizeChanged { canvasSize = it } + .pointerInput(layout) { detectTransformGestures { _, pan, zoom, _ -> - scale = (scale * zoom).coerceIn(MIN_SCALE, MAX_SCALE) - offset += pan + userAdjusted = true + val newScale = (scale * zoom).coerceIn(MIN_SCALE, MAX_SCALE) + scale = newScale + // Keep at least MIN_VISIBLE of the scaled content on screen so a + // drag can never leave an empty viewport. + offset = clampOffset( + offset = offset + pan, + content = Size(layout.width * newScale, layout.height * newScale), + viewport = Size(canvasSize.width.toFloat(), canvasSize.height.toFloat()), + minVisible = minVisiblePx, + ) } }, ) { @@ -147,28 +195,78 @@ fun WorkflowGraph( translate(offset.x, offset.y) scale(scale, scale, pivot = Offset.Zero) }) { - drawEdges(layout, colors, runState, textMeasurer) + // 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) + drawEdgeLabels(layout, colors, runState, textMeasurer) drawNodes(layout, colors, runState, selectedStage, textMeasurer) } } + IconButton( + onClick = { + userAdjusted = false + // Re-run the fit effect even when the viewport is unchanged. + fitRequest += 1 + }, + modifier = Modifier.align(Alignment.TopEnd).padding(4.dp), + ) { + Icon(Icons.Default.FitScreen, contentDescription = "Fit graph to view") + } } } -private fun Offset.coerceAtLeast(minimum: Float): Offset = - Offset(x.coerceAtLeast(minimum), y.coerceAtLeast(minimum)) - private class GraphColors( val success: Color, val error: Color, val accent: List, + val labelAccent: List, val nodeFill: Color, val nodeFillActive: Color, val nodeBorder: Color, val nodeText: Color, val terminalFill: Color, val labelBackground: Color, + val labelText: Color, ) +/** + * Uniform scale that fits [content] inside [viewport] with [padding] on every + * side, never upscaling above 1:1. Degenerate (zero/negative) content or + * viewport sizes return 1f rather than dividing by zero, so callers never see + * NaN or infinity. + */ +internal fun fitScale(viewport: Size, content: Size, padding: Float): Float { + val availableWidth = viewport.width - 2f * padding + val availableHeight = viewport.height - 2f * padding + if (content.width <= 0f || content.height <= 0f || + availableWidth <= 0f || availableHeight <= 0f + ) { + return 1f + } + return minOf(1f, availableWidth / content.width, availableHeight / content.height) + .coerceAtLeast(MIN_SCALE) +} + +/** + * Bounds a pan [offset] so at least [minVisible] pixels of the scaled [content] + * stay inside [viewport] on each axis, i.e. `offset.x` in + * `[minVisible - content.width, viewport.width - minVisible]` (same for y), so + * panning can never leave an empty viewport. A fitted/centred offset already + * inside those bounds is returned unchanged. Degenerate content or an empty + * bound range (a viewport smaller than twice [minVisible]) is returned + * unchanged so the caller never divides by zero or produces NaN. + */ +internal fun clampOffset(offset: Offset, content: Size, viewport: Size, minVisible: Float): Offset { + if (content.width <= 0f || content.height <= 0f) return offset + val minX = minVisible - content.width + val maxX = viewport.width - minVisible + val minY = minVisible - content.height + val maxY = viewport.height - minVisible + val x = if (minX <= maxX) offset.x.coerceIn(minX, maxX) else offset.x + val y = if (minY <= maxY) offset.y.coerceIn(minY, maxY) else offset.y + return Offset(x, y) +} + private fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density): GraphLayout { if (graph.stages.isEmpty()) return GraphLayout(emptyList(), emptyList(), 0f, 0f) @@ -274,15 +372,13 @@ private fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density) internal fun rankStages(graph: Graph): Map = graph.stages.withIndex().associate { (index, stage) -> stage.key to index } -private fun DrawScope.drawEdges( +private fun DrawScope.drawEdgePaths( layout: GraphLayout, colors: GraphColors, runState: RunGraphState?, - textMeasurer: TextMeasurer, ) { for (edge in layout.edges) { - val route = GraphRoute(edge.edge.source, edge.edge.outcome, edge.edge.target) - val executed = runState == null || route in runState.takenRoutes + val executed = edge.isExecuted(runState) val color = outcomeColor(edge.edge, colors) val alpha = if (executed) 1f else 0.25f val path = Path() @@ -296,14 +392,31 @@ private fun DrawScope.drawEdges( } drawPath(path, color = color.copy(alpha = alpha), style = Stroke(width = 3f)) drawArrowHead(edge.from, edge.to, color.copy(alpha = alpha)) + } +} - val label = edge.edge.label - val measured = textMeasurer.measure(label, TextStyle(fontSize = 11.sp, color = color.copy(alpha = alpha))) +/** + * 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. + */ +private fun DrawScope.drawEdgeLabels( + layout: GraphLayout, + colors: GraphColors, + runState: RunGraphState?, + textMeasurer: TextMeasurer, +) { + for (edge in layout.edges) { + 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 faint background so crossing edges stay legible. + // 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, @@ -311,7 +424,7 @@ private fun DrawScope.drawEdges( (edge.labelSlot - spread) * (measured.size.height + 2f), ) drawRect( - color = colors.labelBackground.copy(alpha = 0.82f * alpha), + 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), ) @@ -402,6 +515,22 @@ private fun outcomeColor(edge: GraphEdge, colors: GraphColors): Color = when (ed else -> colors.accent[abs(edge.outcome.hashCode()) % colors.accent.size] } +/** + * Legible label colour for an outcome, using [GraphColors.labelAccent] so + * container-filled accents are rendered as text in their on-container colour. + * Shares the outcome→index mapping with [outcomeColor] so a label always matches + * its curve's colour family. + */ +private fun outcomeLabelColor(edge: GraphEdge, colors: GraphColors): Color = when (edge.outcome) { + "error" -> colors.error + "success" -> colors.success + else -> colors.labelAccent[abs(edge.outcome.hashCode()) % colors.labelAccent.size] +} + +/** True when [runState] is null (definition view) or recorded this edge's route. */ +private fun EdgeLayout.isExecuted(runState: RunGraphState?): Boolean = + runState == null || GraphRoute(edge.source, edge.outcome, edge.target) in runState.takenRoutes + /** A screen-reader description so meaning is never conveyed by colour alone. */ private fun graphDescription(graph: Graph, runState: RunGraphState?): String { if (graph.stages.isEmpty()) return "Empty workflow graph" @@ -422,3 +551,7 @@ private fun graphDescription(graph: Graph, runState: RunGraphState?): String { private const val MIN_SCALE = 0.3f private const val MAX_SCALE = 3f + +/** 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 diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt index bded395d..01100c8d 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt @@ -53,6 +53,7 @@ import net.awan.pipelines.ui.components.LoadingState import net.awan.pipelines.ui.displayMap import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.graph.WorkflowGraph +import net.awan.pipelines.ui.visitCount @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -213,7 +214,10 @@ private fun RunDetailContent( append("run ${run.id} · ${run.status.ifBlank { "unknown" }}") if (run.outcome.isNotBlank()) append(" · outcome ${run.outcome}") if (run.executing) append(" · executing") - append(" · ${run.steps.size} recorded visits") + // Same vocabulary as the runs list and the server's own + // tui/results.go / run_graph.go: completed vs recorded visits. + append(" · ${visitCount(run.steps.size, "recorded")}") + append(" · ${visitCount(run.completedSteps, "completed")}") }, style = MaterialTheme.typography.bodyMedium, ) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt index 636942d2..7376df04 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt @@ -33,6 +33,7 @@ import net.awan.pipelines.ui.components.EmptyState import net.awan.pipelines.ui.components.ErrorState import net.awan.pipelines.ui.components.LoadingState import net.awan.pipelines.ui.formatDuration +import net.awan.pipelines.ui.visitCount @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -122,7 +123,10 @@ private fun RunRow(run: RunSummary, onClick: () -> Unit) { if (run.outcome.isNotBlank()) append(" · outcome ${run.outcome}") if (run.executing) append(" · executing") if (run.currentStage.isNotBlank()) append(" · stage ${run.currentStage}") - append(" · ${run.completedSteps} steps") + // Same vocabulary as run detail and the server's own + // tui/results.go: completed_steps counts completed visits. The + // summary carries no total, so "N of M steps" is not possible. + append(" · ${visitCount(run.completedSteps, "completed")}") }, style = MaterialTheme.typography.bodySmall, ) diff --git a/android/app/src/test/java/net/awan/pipelines/ui/graph/WorkflowGraphTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/graph/WorkflowGraphTest.kt index 9b39131c..8d20cd7d 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/graph/WorkflowGraphTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/graph/WorkflowGraphTest.kt @@ -1,8 +1,11 @@ package net.awan.pipelines.ui.graph +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size import net.awan.pipelines.data.protocol.Graph import net.awan.pipelines.data.protocol.Stage import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Test class WorkflowGraphTest { @@ -32,4 +35,84 @@ class WorkflowGraphTest { assertEquals(2, ranks["reviewer"]) assertEquals(3, ranks["ui_reviewer"]) } + + @Test + fun fitScaleShrinksContentWiderThanTheViewport() { + val scale = fitScale(viewport = Size(1000f, 400f), content = Size(2000f, 400f), padding = 0f) + assertEquals(0.5f, scale, 0.0001f) + } + + @Test + fun fitScaleUsesTheTighterAxis() { + // Width ratio 0.5, height ratio 0.4; the tighter axis must win. + val scale = fitScale(Size(1000f, 800f), Size(2000f, 2000f), padding = 0f) + assertEquals(0.4f, scale, 0.0001f) + } + + @Test + fun fitScaleNeverUpscalesContentSmallerThanTheViewport() { + val scale = fitScale(Size(1000f, 800f), Size(200f, 100f), padding = 0f) + assertEquals(1f, scale, 0.0001f) + } + + @Test + fun fitScaleAccountsForPaddingAndFloorsAboveZero() { + // (1000 - 200) / 2000 == 0.4. + assertEquals(0.4f, fitScale(Size(1000f, 400f), Size(2000f, 400f), padding = 100f), 0.0001f) + // Far smaller than the floor: still positive and never zero. + val floored = fitScale(Size(100f, 100f), Size(100_000f, 100_000f), padding = 0f) + assertEquals(0.3f, floored, 0.0001f) + } + + @Test + fun fitScaleIsFiniteForDegenerateSizes() { + assertTrue(fitScale(Size(0f, 0f), Size(100f, 100f), 0f).isFinite()) + assertTrue(fitScale(Size(100f, 100f), Size(0f, 0f), 0f).isFinite()) + assertTrue(fitScale(Size(100f, 100f), Size(-5f, 10f), 0f).isFinite()) + // Padding larger than the viewport must not divide by zero. + assertTrue(fitScale(Size(100f, 100f), Size(100f, 100f), padding = 60f).isFinite()) + } + + @Test + fun clampOffsetKeepsContentVisibleAtEveryExtreme() { + val viewport = Size(400f, 300f) + val content = Size(1000f, 500f) + val margin = 40f + + val farLeft = clampOffset(Offset(-10_000f, -10_000f), content, viewport, margin) + assertEquals(margin - content.width, farLeft.x, 0.001f) + assertEquals(margin - content.height, farLeft.y, 0.001f) + assertTrue(farLeft.x + content.width >= margin) + assertTrue(farLeft.y + content.height >= margin) + + val farRight = clampOffset(Offset(10_000f, 10_000f), content, viewport, margin) + assertEquals(viewport.width - margin, farRight.x, 0.001f) + assertEquals(viewport.height - margin, farRight.y, 0.001f) + assertTrue(farRight.x <= viewport.width - margin) + assertTrue(farRight.y <= viewport.height - margin) + } + + @Test + fun clampOffsetLeavesACentredSmallGraphUnchanged() { + val viewport = Size(400f, 300f) + val content = Size(200f, 100f) // fits on both axes + val centred = Offset( + x = (viewport.width - content.width) / 2f, + y = (viewport.height - content.height) / 2f, + ) + assertEquals(centred, clampOffset(centred, content, viewport, minVisible = 40f)) + } + + @Test + fun clampOffsetIsSymmetricAndSafeForSizes() { + val viewport = Size(400f, 300f) + val content = Size(1000f, 500f) + val left = clampOffset(Offset(-99_999f, 0f), content, viewport, 40f).x + val right = clampOffset(Offset(99_999f, 0f), content, viewport, 40f).x + // Bounds are symmetric about the viewport centre. + assertEquals(viewport.width - 40f + (40f - content.width), left + right, 0.001f) + // Degenerate content and an empty bound range are returned untouched, no NaN. + assertEquals(Offset.Zero, clampOffset(Offset.Zero, Size(0f, 0f), viewport, 40f)) + assertTrue(clampOffset(Offset(1f, 2f), content, Size(10f, 10f), 40f).x.isFinite()) + } }