From e843aa08a8f8d764c5c526451812f77d21c49110 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 15 Oct 2026 03:46:06 +0100 Subject: [PATCH] Restructure the Runs area and add collapsible sticky sections Four related UI changes, all requested after using the app on a phone. - Graph pinch zoom is now anchored to the gesture centroid. The handler dropped the centroid and the canvas scaled about the content origin, so a pinch slid the graph away from the fingers. zoomAbout() keeps the content point under the fingers fixed, applies the pan and then clampOffset, with unit tests proving the centroid point is unchanged and the scale and bounds are respected. - Pipeline detail and run detail now use a LazyColumn of collapsible sections (shared Sections.kt header, rotating chevron, animateContentSize) whose titles stick to the top while their content scrolls beneath, with per-section state remembered and exposed to accessibility. Steps and session evidence stay lazy list items instead of nested scrollables. - The Runs list is rebuilt: the raw result preview is gone, failures show a two-line diagnostic in the error colour, each run has a colour-coded status chip with a matching icon per state (RunStatus.kt, core Material icons - no new dependency), the usage aggregates render as a metrics block with a formatted average instead of a run-on line of seconds, and runs are grouped by day under sticky date headers. - Run detail steps are a timeline: a status dot joined to the next step, the stage and visit number, an outcome chip and the duration, with input, output, transcript, file changes and notifications behind a per-step 'Show details'. - One centralised type hierarchy (Typography.kt) for screen title, section header, card title, subtitle, body and monospace data, applied across the list, the cards and both detail screens. Verified: :app:assembleDebug and :app:testDebugUnitTest succeed offline with 53 tests and 0 failures (new FormatTest, RunStatusTest and RunGroupingTest; WorkflowGraphTest 23 to 27), and the app was driven on the emulator with screenshots of the runs list states, the sticky date header, the steps timeline, an expanded step, a collapsed section and the sticky section header. --- android/README.md | 59 ++- .../main/java/net/awan/pipelines/ui/Format.kt | 23 +- .../awan/pipelines/ui/components/RunStatus.kt | 202 ++++++++ .../awan/pipelines/ui/components/Sections.kt | 113 +++++ .../awan/pipelines/ui/graph/WorkflowGraph.kt | 53 ++- .../ui/screens/PipelineDetailScreen.kt | 144 ++++-- .../pipelines/ui/screens/RunDetailScreen.kt | 431 +++++++++++++----- .../pipelines/ui/screens/RunHistoryScreen.kt | 319 ++++++++++--- .../java/net/awan/pipelines/ui/theme/Theme.kt | 17 +- .../net/awan/pipelines/ui/theme/Typography.kt | 74 +++ .../java/net/awan/pipelines/ui/FormatTest.kt | 28 ++ .../pipelines/ui/components/RunStatusTest.kt | 37 ++ .../pipelines/ui/graph/WorkflowGraphTest.kt | 67 +++ .../pipelines/ui/screens/RunGroupingTest.kt | 46 ++ 14 files changed, 1376 insertions(+), 237 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/components/RunStatus.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/components/Sections.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/theme/Typography.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/components/RunStatusTest.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/screens/RunGroupingTest.kt diff --git a/android/README.md b/android/README.md index 32900f21..9bd3bf2c 100644 --- a/android/README.md +++ b/android/README.md @@ -89,7 +89,11 @@ stops it. highlighted, others dimmed) plus a screen-reader description. Edges are drawn as axis-aligned orthogonal polylines like the TUI (`routePoints` computes the path once per layout and stores it on `EdgeLayout.points`), and each arrowhead - points along its route's final segment rather than the from-to chord. + points along its route's final segment rather than the from-to chord. Pinch + zoom is anchored to the gesture centroid: the pure `zoomAbout` keeps the + content point under the fingers fixed (clamped to `MIN_SCALE`/`MAX_SCALE`) and + the existing pan clamp is applied afterwards, so the content no longer slides + away from the fingers. - One shared graph-panel height (`collapsedGraphHeight`/`expandedGraphHeight`) replaces the former 360.dp and 340.dp literals, so both detail screens render the graph at the same size: about 58% of the window height floored at a height @@ -107,6 +111,34 @@ stops it. is retained for when it is explicitly requested. - Consistent Material 3 top app bars on Pipelines, Runs and Settings (and the existing back/refresh/start/cancel/retry bars on the detail screens). +- Both detail screens render a single `LazyColumn` whose sections ("Versions", + "Workflow graph", "Source" on a pipeline; "Run graph", "Input", "Output", + "Session evidence", "Steps" on a run) are collapsible via a shared + `SectionHeader`: tapping a header toggles it, an animated chevron rotates with + the state, the header sticks to the top of the list while its content scrolls + under an opaque background, and the state is exposed to accessibility + (`"Steps, expanded"`). Expanded state is `rememberSaveable`, per section and + per screen, defaulting to expanded. Real lists (versions, steps, session + evidence) are items of the one outer list, so nothing nests a scrollable. +- Steps render as a timeline in run detail: a leading status glyph connected to + the next step by an outcome-coloured line, the stage with its sequence/visit + number, an outcome chip and the duration, with every retained piece of evidence + (input, output, transcript, file changes, notifications, control evidence) + behind a collapsible, collapsed-by-default detail in monospace. +- The runs list is grouped by day (`Today`/`Yesterday`/date, newest first) under + sticky headers, with the usage aggregates as a metrics block (total, average + via `formatDuration`, and colour-coded succeeded/failed/canceled/interrupted/ + active counts). Each card shows the pipeline name with a version chip, a + colour-coded status chip with a distinct icon per state + (running/queued/succeeded/failed/canceled/interrupted/active/unknown), a meta + row (run id, start time, duration) and the diagnostic only when non-blank, + clamped to two lines. The raw `resultPreview` is no longer printed, and + progress is shown honestly (completed visits + current stage, with an + indeterminate indicator while executing; no invented total). +- One centralised type scale (`ui/theme/Typography.kt`, passed to + `MaterialTheme` and exposed as named roles) defines the screen/app-bar title, + section header, card title, subtitle/meta, body and monospace data, applied on + the list and both detail screens. - Run history with server `usage` aggregates, and run details with steps (status/outcome/diagnostic/session/transcript/file changes/notifications/ control evidence). Session evidence is scoped to the selected run and each @@ -143,10 +175,12 @@ Verified on macOS with the host toolchain (JDK 17 from Android Studio, `ANDROID_HOME=/Users/alan/Library/Android/sdk`, Gradle 8.11.1 `--offline`): - `:app:compileDebugKotlin`, `:app:assembleDebug` and `:app:testDebugUnitTest` - all succeed; **42 unit tests, 0 failures** (protocol model, graph semantics, + all succeed; **53 unit tests, 0 failures** (protocol model, graph semantics, server URL, workflow-graph layout including the terminal row, bottom exits, - back edges, orthogonal routing/axis alignment, arrowhead direction and the - shared panel height). Re-run with `--rerun-tasks` to confirm. + back edges, orthogonal routing/axis alignment, arrowhead direction, the + shared panel height and the new `zoomAbout` anchor/clamp cases, plus duration + formatting, run-state mapping and run day-grouping). Re-run with + `--rerun-tasks` to confirm. - The debug APK was installed and driven on the `Pixel_Fold_API_36` emulator (Android 16, `adb shell cmd uimode night yes`) against a live server at `ws://10.0.2.2:8080/connect` with workspace `/Users/alan/repos/pipelines`. @@ -181,3 +215,20 @@ launch window/bar colours match it) and moved the `#failure`/`#success` terminal to a lower row beneath the stage row; before/after captures for the theme, graph and app bar/style are under `captures/style_pass/` (`*_before.png` are the pre-change baseline referenced by the task, `*_after.png` are the new build). + +The Runs-area pass (centroid zoom, collapsible sticky sections, runs list, steps +timeline, type hierarchy) was verified the same way on the `Pixel_Fold_API_36` +emulator (dark mode, `adb shell cmd uimode night yes`) against the live server: +the debug APK was installed, the list/detail/step flows were driven with +`adb shell input` and `uiautomator dump`, and captures were written to +`captures/runs_pass/` (git-ignored): `runs_list_top`, +`runs_list_scrolled_sticky` (a `13 Oct 2026` header pinned under the app bar), +`runs_list_states`, `runs_card_interrupted`, `run_detail_top`, +`run_detail_graph_collapsed`, `run_detail_steps`, `run_detail_step_expanded`, +`run_detail_sticky_section` (a `Steps, expanded` header pinned mid-list), +`pipeline_detail_sections`, `pipeline_detail_section_collapsed`, +`pipeline_graph_panned` and `pipeline_graph_fit`. `adb logcat` for the app +package contained no `FATAL EXCEPTION` or Compose/other runtime exception during +the sweep. As before, `adb` cannot synthesise a two-finger pinch, so the +centroid-anchored zoom is verified primarily by the `zoomAbout` unit tests and +the on-device graph was exercised with pan + "Fit graph to view" only. 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 efd6d846..a11cc2e2 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 @@ -12,15 +12,26 @@ fun formatDuration(start: String, end: String): String? { if (start.isBlank() || end.isBlank()) return null return runCatching { val seconds = Duration.between(OffsetDateTime.parse(start), OffsetDateTime.parse(end)).seconds - when { - seconds < 0 -> null - seconds < 60 -> "${seconds}s" - seconds < 3600 -> "${seconds / 60}m ${seconds % 60}s" - else -> "${seconds / 3600}h ${(seconds % 3600) / 60}m" - } + if (seconds < 0) null else formatDuration(seconds) }.getOrNull() } +/** + * Human duration for a whole number of seconds. The single formatting rule for + * every duration the UI shows (list meta, usage average, run summary, step + * duration); the timestamp overload above delegates here so the two never drift. + * A negative total is rendered as "0s" so a caller with a clamped/rounded + * average never prints a negative duration. + */ +fun formatDuration(totalSeconds: Long): String { + val seconds = totalSeconds.coerceAtLeast(0) + return when { + seconds < 60 -> "${seconds}s" + seconds < 3600 -> "${seconds / 60}m ${seconds % 60}s" + else -> "${seconds / 3600}h ${(seconds % 3600) / 60}m" + } +} + /** Compact rendering of arbitrary protocol JSON values for read-only display. */ fun JsonElement.displayText(): String = when (this) { is JsonPrimitive -> content diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatus.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatus.kt new file mode 100644 index 00000000..8430010b --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatus.kt @@ -0,0 +1,202 @@ +package net.awan.pipelines.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.Warning +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.path +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * The run states the server can report, mirroring the vocabulary in + * internal/tui/run_progress.go and internal/protocol/stats.go + * (`running`/`queued`/`succeeded`/`failed`/`canceled`/`interrupted`, plus the + * `active` usage bucket). [Unknown] is the safe fallback for a blank or + * unrecognised status so a bad value never crashes the UI. + */ +enum class RunState(val label: String) { + Running("running"), + Queued("queued"), + Succeeded("succeeded"), + Failed("failed"), + Canceled("canceled"), + Interrupted("interrupted"), + Active("active"), + Unknown("unknown"), +} + +/** + * Maps a server status or outcome word to a [RunState], accepting the server's + * own vocabulary only. The step/outcome words (`success`/`completed`/`error`) + * map onto the same states so the list, detail summary and steps timeline all + * render one shared chip and icon set. + */ +fun runStateOf(status: String): RunState = when (status.trim().lowercase()) { + "running" -> RunState.Running + "queued" -> RunState.Queued + "active" -> RunState.Active + "succeeded", "success", "completed", "done" -> RunState.Succeeded + "failed", "error" -> RunState.Failed + "canceled", "cancelled" -> RunState.Canceled + "interrupted" -> RunState.Interrupted + else -> RunState.Unknown +} + +/** Colour family for a state, sourced from the app-owned scheme (never colour-only). */ +@Composable +fun runStateColor(state: RunState): Color = when (state) { + RunState.Running, RunState.Active -> MaterialTheme.colorScheme.primary + RunState.Queued -> MaterialTheme.colorScheme.secondary + RunState.Succeeded -> MaterialTheme.colorScheme.tertiary + RunState.Failed, RunState.Interrupted -> MaterialTheme.colorScheme.error + RunState.Canceled, RunState.Unknown -> MaterialTheme.colorScheme.onSurfaceVariant +} + +/** A distinct glyph per state so the state is readable without the words. */ +fun runStateIcon(state: RunState): ImageVector = when (state) { + RunState.Running -> RunningIcon + RunState.Queued -> QueuedIcon + RunState.Succeeded -> Icons.Default.CheckCircle + RunState.Failed -> Icons.Default.Warning + RunState.Canceled -> Icons.Default.Close + RunState.Interrupted -> InterruptedIcon + RunState.Active -> Icons.Default.PlayArrow + RunState.Unknown -> Icons.Default.Info +} + +/** + * A state glyph with an accurate [contentDescription]. The glyphs come from the + * core icon set or the small local [ImageVector]s below; the extended icon pack + * is not used, so state is never conveyed by colour alone. + */ +@Composable +fun RunStatusIcon( + state: RunState, + contentDescription: String? = state.label, + modifier: Modifier = Modifier, + tint: Color = runStateColor(state), +) { + Icon( + imageVector = runStateIcon(state), + contentDescription = contentDescription, + tint = tint, + modifier = modifier, + ) +} + +/** A colour-coded chip pairing a state glyph with its text label. */ +@Composable +fun StatusChip( + label: String, + state: RunState, + modifier: Modifier = Modifier, +) { + val color = runStateColor(state) + Row( + modifier = modifier + .clip(RoundedCornerShape(50)) + .background(color.copy(alpha = 0.16f)) + .padding(horizontal = 8.dp, vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + RunStatusIcon(state, contentDescription = label, modifier = Modifier.size(14.dp), tint = color) + Text( + text = label, + color = color, + fontWeight = FontWeight.Medium, + style = pipelinesText().label, + ) + } +} + +/** Convenience: the run's own status word plus its colour-coded chip. */ +@Composable +fun RunStatusChip(state: RunState, modifier: Modifier = Modifier) { + StatusChip(label = state.label, state = state, modifier = modifier) +} + +// --- Local glyphs (core set has no equivalent) --------------------------------- + +/** A live "activity" pulse, used for a running run/step. */ +private val RunningIcon: ImageVector = strokeIcon("Running") { + moveTo(3f, 12f) + lineTo(7f, 12f) + lineTo(9.5f, 6f) + lineTo(13f, 18f) + lineTo(15.5f, 12f) + lineTo(21f, 12f) +} + +/** A clock, used for a queued run. */ +private val QueuedIcon: ImageVector = strokeIcon("Queued") { + moveTo(12f, 3f) + curveTo(16.97f, 3f, 21f, 7.03f, 21f, 12f) + curveTo(21f, 16.97f, 16.97f, 21f, 12f, 21f) + curveTo(7.03f, 21f, 3f, 16.97f, 3f, 12f) + curveTo(3f, 7.03f, 7.03f, 3f, 12f, 3f) + close() + moveTo(12f, 7f) + lineTo(12f, 12f) + lineTo(16f, 14f) +} + +/** Pause bars, used for an interrupted run (distinct from the failed warning). */ +private val InterruptedIcon: ImageVector = ImageVector.Builder( + name = "Interrupted", + defaultWidth = 24.dp, + defaultHeight = 24.dp, + viewportWidth = 24f, + viewportHeight = 24f, +).path(fill = SolidColor(Color.Black)) { + moveTo(8f, 5f) + lineTo(8f, 19f) + lineTo(11f, 19f) + lineTo(11f, 5f) + close() + moveTo(13f, 5f) + lineTo(13f, 19f) + lineTo(16f, 19f) + lineTo(16f, 5f) + close() +}.build() + +/** Builds a stroke-only 24dp glyph from a path block. */ +private fun strokeIcon(name: String, block: androidx.compose.ui.graphics.vector.PathBuilder.() -> Unit): ImageVector = + ImageVector.Builder( + name = name, + defaultWidth = 24.dp, + defaultHeight = 24.dp, + viewportWidth = 24f, + viewportHeight = 24f, + ).path( + fill = null, + stroke = SolidColor(Color.Black), + strokeLineWidth = 1.8f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) { + this.block() + }.build() diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/Sections.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/Sections.kt new file mode 100644 index 00000000..9eb05aa7 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/Sections.kt @@ -0,0 +1,113 @@ +package net.awan.pipelines.ui.components + +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.role +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * The one collapsible section header shared by both detail screens: the section + * title in the theme's section-header style, a trailing chevron that rotates + * with the state (animated, no jump cut), an opaque background matching the + * screen so content passing underneath a stuck header stays readable, and a + * subtle divider. + * + * Accessibility is exposed without relying on the chevron: the header is a + * single button node described as e.g. "Steps, expanded" and carries the + * `expanded`/`collapsed` state. + */ +@Composable +fun SectionHeader( + title: String, + expanded: Boolean, + onToggle: () -> Unit, + modifier: Modifier = Modifier, +) { + val rotation by animateFloatAsState( + targetValue = if (expanded) 0f else -90f, + label = "section-chevron", + ) + Column( + modifier = modifier + .fillMaxWidth() + // Opaque: the header is sticky, so content scrolls under it. + .background(MaterialTheme.colorScheme.background) + .clickable(role = Role.Button, onClick = onToggle) + .clearAndSetSemantics { + contentDescription = "$title, ${if (expanded) "expanded" else "collapsed"}" + role = Role.Button + onClick(label = if (expanded) "Collapse $title" else "Expand $title") { + onToggle() + true + } + }, + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = title, + style = pipelinesText().sectionHeader, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Icon( + imageVector = Icons.Default.KeyboardArrowDown, + contentDescription = null, + modifier = Modifier.rotate(rotation), + ) + } + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + } +} + +/** + * Emits a collapsible [section] into a [LazyListScope]: a sticky header for the + * title and, only while [expanded], the content as items of the *same* outer + * list. Nothing ever nests a scrollable, so real laziness is preserved. + */ +@OptIn(ExperimentalFoundationApi::class) +fun LazyListScope.collapsibleSection( + title: String, + key: Any, + expanded: Boolean, + onToggle: () -> Unit, + content: LazyListScope.() -> Unit, +) { + stickyHeader(key = "section-$key") { + SectionHeader(title = title, expanded = expanded, onToggle = onToggle) + } + if (expanded) { + content() + } +} 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 5017343f..48eef38b 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 @@ -101,6 +101,13 @@ internal data class GraphLayout( val height: Float, ) +/** + * Result of anchoring a zoom gesture at a content point: the new pan [offset] + * and the clamped [scale] to apply. Kept as a small pure value so the zoom maths + * can be unit-tested without the Compose runtime. See [zoomAbout]. + */ +internal data class ZoomResult(val offset: Offset, val scale: Float) + /** * Renders a workflow [Graph] as a pannable, zoomable node-and-arrow diagram. * @@ -216,15 +223,17 @@ fun WorkflowGraph( .semantics { contentDescription = description } .onSizeChanged { canvasSize = it } .pointerInput(layout) { - detectTransformGestures { _, pan, zoom, _ -> + detectTransformGestures { centroid, pan, zoom, _ -> 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. + // Anchor the zoom at the gesture centroid so the content under + // the fingers stays put, then apply the gesture pan and keep at + // least MIN_VISIBLE of the scaled content on screen so a drag can + // never leave an empty viewport. + val zoomed = zoomAbout(offset, scale, centroid, zoom, MIN_SCALE, MAX_SCALE) + scale = zoomed.scale offset = clampOffset( - offset = offset + pan, - content = Size(layout.width * newScale, layout.height * newScale), + offset = zoomed.offset + pan, + content = Size(layout.width * zoomed.scale, layout.height * zoomed.scale), viewport = Size(canvasSize.width.toFloat(), canvasSize.height.toFloat()), minVisible = minVisiblePx, ) @@ -334,6 +343,36 @@ internal fun clampOffset(offset: Offset, content: Size, viewport: Size, minVisib return Offset(x, y) } +/** + * Anchors a zoom gesture at the [centroid] (the point between the fingers) so the + * content point under the fingers stays under the fingers. The draw transform is + * `offset + p * scale`, so the content point under the centroid is + * `(centroid - offset) / scale`; keeping it fixed while the scale becomes + * `newScale` gives `centroid - (centroid - offset) * (newScale / scale)`. + * + * [zoom] is the gesture's relative scale factor and the result scale is clamped + * to `[minScale, maxScale]`. A non-finite or non-positive [scale]/[zoom] returns + * the input unchanged, so no NaN/infinity ever reaches the draw transform. + * The gesture pan is applied by the caller after this, before [clampOffset]. + */ +internal fun zoomAbout( + offset: Offset, + scale: Float, + centroid: Offset, + zoom: Float, + minScale: Float = MIN_SCALE, + maxScale: Float = MAX_SCALE, +): ZoomResult { + if (!scale.isFinite() || scale <= 0f || !zoom.isFinite() || zoom <= 0f) { + return ZoomResult(offset, scale) + } + val newScale = (scale * zoom).coerceIn(minScale, maxScale) + val ratio = newScale / scale + val anchored = centroid - (centroid - offset) * ratio + if (!anchored.x.isFinite() || !anchored.y.isFinite()) return ZoomResult(offset, scale) + return ZoomResult(anchored, newScale) +} + internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density): GraphLayout { if (graph.stages.isEmpty()) return GraphLayout(emptyList(), emptyList(), 0f, 0f) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt index a13805cc..358f44f9 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt @@ -1,13 +1,15 @@ package net.awan.pipelines.ui.screens +import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.PlayArrow @@ -29,6 +31,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontFamily @@ -36,11 +39,14 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import net.awan.pipelines.data.ErrorMessages import net.awan.pipelines.data.protocol.PipelineDetail +import net.awan.pipelines.data.protocol.VersionSummary import net.awan.pipelines.ui.AppViewModel import net.awan.pipelines.ui.components.ErrorState 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.graph.WorkflowGraph +import net.awan.pipelines.ui.theme.pipelinesText @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -104,61 +110,113 @@ fun PipelineDetailScreen( } } +@OptIn(ExperimentalFoundationApi::class) @Composable private fun PipelineDetailContent(detail: PipelineDetail, modifier: Modifier = Modifier) { - Column( - modifier = modifier - .fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - Text("${detail.name}", style = MaterialTheme.typography.headlineSmall) - Text( - "id ${detail.id} · v${detail.version} · ${detail.graph.stages.size} stages", - style = MaterialTheme.typography.bodyMedium, - ) - KeyValueRow("Content hash", detail.contentHash, monospace = true) - KeyValueRow("Latest version", if (detail.latestVersion > 0) "v${detail.latestVersion}" else "") - KeyValueRow("Version created", detail.versionCreatedAt) - KeyValueRow("Pipeline created", detail.createdAt) - KeyValueRow("Pipeline updated", detail.updatedAt) + val text = pipelinesText() + // Per-section expanded state, defaulting to expanded and surviving + // recomposition and configuration changes (each call site is stable). + var versionsExpanded by rememberSaveable { mutableStateOf(true) } + var graphExpanded by rememberSaveable { mutableStateOf(true) } + var sourceExpanded by rememberSaveable { mutableStateOf(true) } - if (detail.versions.isNotEmpty()) { - Text("Versions", style = MaterialTheme.typography.titleMedium) - detail.versions.forEach { v -> - Card(Modifier.fillMaxWidth()) { - Row(Modifier.padding(12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Text("v${v.version}", style = MaterialTheme.typography.titleSmall) - Text("${v.stages} stages", style = MaterialTheme.typography.bodySmall) - Text(v.createdAt, style = MaterialTheme.typography.bodySmall) - } + LazyColumn( + modifier = modifier.fillMaxSize(), + contentPadding = PaddingValues(vertical = 16.dp), + ) { + item(key = "summary") { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text(detail.name, style = text.screenTitle) + Text( + "id ${detail.id} · v${detail.version} · ${detail.graph.stages.size} stages", + style = text.meta, + ) + KeyValueRow("Content hash", detail.contentHash, monospace = true) + KeyValueRow("Latest version", if (detail.latestVersion > 0) "v${detail.latestVersion}" else "") + KeyValueRow("Version created", detail.versionCreatedAt) + KeyValueRow("Pipeline created", detail.createdAt) + KeyValueRow("Pipeline updated", detail.updatedAt) + } + } + + collapsibleSection( + title = "Versions", + key = "versions", + expanded = versionsExpanded, + onToggle = { versionsExpanded = !versionsExpanded }, + ) { + if (detail.versions.isEmpty()) { + item(key = "versions-empty") { + Text( + "No versions recorded.", + style = text.meta, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + } else { + items(detail.versions, key = { "version-${it.version}" }) { v -> + VersionRow(v, Modifier.padding(horizontal = 16.dp, vertical = 4.dp).animateItem()) } } } - Text("Workflow graph", style = MaterialTheme.typography.titleMedium) - Text( - "Pinch to zoom, drag to pan. Edges are labelled with their outcome; error* is the implicit fallback.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - WorkflowGraph(graph = detail.graph, modifier = Modifier.fillMaxWidth()) + collapsibleSection( + title = "Workflow graph", + key = "graph", + expanded = graphExpanded, + onToggle = { graphExpanded = !graphExpanded }, + ) { + item(key = "graph") { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + "Pinch to zoom, drag to pan. Edges are labelled with their outcome; error* is the implicit fallback.", + style = text.meta, + ) + WorkflowGraph(graph = detail.graph, modifier = Modifier.fillMaxWidth()) + } + } + } if (detail.source.isNotBlank()) { - Text("Source", style = MaterialTheme.typography.titleMedium) - Card(Modifier.fillMaxWidth()) { - Text( - text = detail.source, - fontFamily = FontFamily.Monospace, - style = MaterialTheme.typography.bodySmall, - modifier = Modifier.padding(12.dp), - ) + collapsibleSection( + title = "Source", + key = "source", + expanded = sourceExpanded, + onToggle = { sourceExpanded = !sourceExpanded }, + ) { + item(key = "source") { + Card(Modifier.fillMaxWidth().padding(horizontal = 16.dp).animateItem()) { + Text( + text = detail.source, + fontFamily = FontFamily.Monospace, + style = text.mono, + modifier = Modifier.padding(12.dp), + ) + } + } } } } } +@Composable +private fun VersionRow(v: VersionSummary, modifier: Modifier = Modifier) { + val text = pipelinesText() + Card(modifier.fillMaxWidth()) { + Row(Modifier.padding(12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text("v${v.version}", style = text.cardTitle) + Text("${v.stages} stages", style = text.meta) + Text(v.createdAt, style = text.meta) + } + } +} + @Composable private fun StartRunDialog( vm: AppViewModel, 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 fe85e808..33ea0853 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 @@ -1,22 +1,36 @@ package net.awan.pipelines.ui.screens +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Cancel +import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Replay import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme @@ -30,9 +44,12 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.delay @@ -48,9 +65,15 @@ import net.awan.pipelines.ui.LoadState import net.awan.pipelines.ui.components.ErrorState import net.awan.pipelines.ui.components.KeyValueRow import net.awan.pipelines.ui.components.LoadingState +import net.awan.pipelines.ui.components.RunStatusIcon +import net.awan.pipelines.ui.components.StatusChip +import net.awan.pipelines.ui.components.collapsibleSection +import net.awan.pipelines.ui.components.runStateColor +import net.awan.pipelines.ui.components.runStateOf import net.awan.pipelines.ui.displayMap import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.graph.WorkflowGraph +import net.awan.pipelines.ui.theme.pipelinesText import net.awan.pipelines.ui.visitCount @OptIn(ExperimentalMaterial3Api::class) @@ -191,6 +214,7 @@ private fun ConfirmDialog( ) } +@OptIn(ExperimentalFoundationApi::class) @Composable private fun RunDetailContent( run: RunDetail, @@ -198,173 +222,352 @@ private fun RunDetailContent( evidenceState: LoadState>, modifier: Modifier = Modifier, ) { + val text = pipelinesText() val runState = remember(run.id, run.steps) { RunGraphState.from(run) } - Column( - modifier = modifier - .fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), + // Per-section expanded state; defaults to expanded and remembered across + // recomposition and configuration changes. + var graphExpanded by rememberSaveable { mutableStateOf(true) } + var inputExpanded by rememberSaveable { mutableStateOf(true) } + var outputExpanded by rememberSaveable { mutableStateOf(true) } + var evidenceExpanded by rememberSaveable { mutableStateOf(true) } + var stepsExpanded by rememberSaveable { mutableStateOf(true) } + + val input = run.input.displayMap() + val output = run.output.displayMap() + val evidence = evidenceState.data.orEmpty() + + LazyColumn( + modifier = modifier.fillMaxSize(), + contentPadding = PaddingValues(vertical = 16.dp), ) { - Text(run.name, style = MaterialTheme.typography.headlineSmall) - Text( - buildString { - append("run ${run.id} · ${run.status.ifBlank { "unknown" }}") - if (run.outcome.isNotBlank()) append(" · outcome ${run.outcome}") - if (run.executing) append(" · executing") - // 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, - ) - KeyValueRow("Pipeline", "id ${run.pipelineId} · v${run.version}") - KeyValueRow("Workspace", run.workspace) - KeyValueRow("Content hash", run.contentHash, monospace = true) - KeyValueRow("Started", run.createdAt) - KeyValueRow("Finished", run.finishedAt) - KeyValueRow("Duration", formatDuration(run.createdAt, run.finishedAt) ?: "") - if (run.diagnostic.isNotBlank()) { - Text(run.diagnostic, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium) + item(key = "summary") { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text(run.name, style = text.screenTitle) + Text( + buildString { + append("run ${run.id} · ${run.status.ifBlank { "unknown" }}") + if (run.outcome.isNotBlank()) append(" · outcome ${run.outcome}") + if (run.executing) append(" · executing") + // 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 = text.meta, + ) + KeyValueRow("Pipeline", "id ${run.pipelineId} · v${run.version}") + KeyValueRow("Workspace", run.workspace) + KeyValueRow("Content hash", run.contentHash, monospace = true) + KeyValueRow("Started", run.createdAt) + KeyValueRow("Finished", run.finishedAt) + KeyValueRow("Duration", formatDuration(run.createdAt, run.finishedAt) ?: "") + if (run.diagnostic.isNotBlank()) { + Text(run.diagnostic, color = MaterialTheme.colorScheme.error, style = text.body) + } + } } - if (run.graph.stages.isNotEmpty()) { - Text("Run graph", style = MaterialTheme.typography.titleMedium) - Text( - "Executed stages and routes are highlighted; the rest are dimmed. Pinch to zoom, drag to pan.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - WorkflowGraph( - graph = run.graph, - modifier = Modifier.fillMaxWidth(), - runState = runState, - selectedStage = runState.currentStage, - ) - } else { - Text("This server did not include the run graph.", style = MaterialTheme.typography.bodySmall) + collapsibleSection( + title = "Run graph", + key = "graph", + expanded = graphExpanded, + onToggle = { graphExpanded = !graphExpanded }, + ) { + item(key = "graph") { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (run.graph.stages.isEmpty()) { + 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.", + style = text.meta, + ) + WorkflowGraph( + graph = run.graph, + modifier = Modifier.fillMaxWidth(), + runState = runState, + selectedStage = runState.currentStage, + ) + } + } + } } - val input = run.input.displayMap() if (input.isNotBlank()) { - Text("Input", style = MaterialTheme.typography.titleMedium) - Card(Modifier.fillMaxWidth()) { - Text(input, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(12.dp)) + collapsibleSection( + title = "Input", + key = "input", + expanded = inputExpanded, + onToggle = { inputExpanded = !inputExpanded }, + ) { + item(key = "input") { + Card(Modifier.fillMaxWidth().padding(horizontal = 16.dp).animateItem()) { + Text(input, style = text.mono, modifier = Modifier.padding(12.dp)) + } + } } } - val output = run.output.displayMap() + if (output.isNotBlank()) { - Text("Output", style = MaterialTheme.typography.titleMedium) - Card(Modifier.fillMaxWidth()) { - Text(output, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(12.dp)) + collapsibleSection( + title = "Output", + key = "output", + expanded = outputExpanded, + onToggle = { outputExpanded = !outputExpanded }, + ) { + item(key = "output") { + Card(Modifier.fillMaxWidth().padding(horizontal = 16.dp).animateItem()) { + Text(output, style = text.mono, modifier = Modifier.padding(12.dp)) + } + } } } - Text("Session evidence", style = MaterialTheme.typography.titleMedium) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedButton(onClick = onLoadEvidence, enabled = !evidenceState.loading) { - Text(if (evidenceState.loading) "Loading…" else "Reload session evidence") + collapsibleSection( + title = "Session evidence", + key = "evidence", + expanded = evidenceExpanded, + onToggle = { evidenceExpanded = !evidenceExpanded }, + ) { + item(key = "evidence-reload") { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedButton(onClick = onLoadEvidence, enabled = !evidenceState.loading) { + Text(if (evidenceState.loading) "Loading…" else "Reload session evidence") + } + } + } + when { + evidenceState.loading && evidenceState.data == null -> item(key = "evidence-loading") { + Text( + "Loading session evidence…", + style = text.meta, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + evidenceState.error != null -> item(key = "evidence-error") { + Text( + evidenceState.error!!, + color = MaterialTheme.colorScheme.error, + style = text.meta, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + evidenceState.loaded && evidence.isEmpty() -> item(key = "evidence-empty") { + Text( + "No session evidence recorded.", + style = text.meta, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + else -> items(evidence, key = { "evidence-${it.sequence}-${it.sessionId}" }) { record -> + EvidenceCard(record, Modifier.padding(horizontal = 16.dp, vertical = 4.dp).animateItem()) + } } } - when { - evidenceState.loading && evidenceState.data == null -> - Text("Loading session evidence…", style = MaterialTheme.typography.bodySmall) - evidenceState.error != null -> - Text(evidenceState.error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) - evidenceState.loaded && evidenceState.data.isNullOrEmpty() -> - Text("No session evidence recorded.", style = MaterialTheme.typography.bodySmall) - else -> evidenceState.data.orEmpty().forEach { EvidenceCard(it) } - } - Text("Steps", style = MaterialTheme.typography.titleMedium) - if (run.steps.isEmpty()) { - Text("No steps recorded.", style = MaterialTheme.typography.bodySmall) - } else { - run.steps.forEach { StepCard(it) } + collapsibleSection( + title = "Steps", + key = "steps", + expanded = stepsExpanded, + onToggle = { stepsExpanded = !stepsExpanded }, + ) { + if (run.steps.isEmpty()) { + item(key = "steps-empty") { + Text( + "No steps recorded.", + style = text.meta, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + } else { + itemsIndexed( + run.steps, + key = { _, step -> "step-${step.sequence}-${step.stage}" }, + ) { index, step -> + StepCard( + step = step, + isLast = index == run.steps.lastIndex, + modifier = Modifier.padding(horizontal = 16.dp).animateItem(), + ) + } + } } } } +/** + * One step as a timeline entry: a leading status glyph in a gutter connected to + * the next entry by a line coloured by this step's outcome, the stage name with + * its sequence and visit number, an outcome chip and the duration. Every retained + * piece of evidence lives behind a collapsible detail, collapsed by default. + */ @Composable -private fun StepCard(step: RunStep) { - Card(Modifier.fillMaxWidth()) { - Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text("${step.sequence}. ${step.stage}", style = MaterialTheme.typography.titleSmall) - Text(step.status, style = MaterialTheme.typography.bodySmall) - if (step.outcome.isNotBlank()) Text("outcome ${step.outcome}", style = MaterialTheme.typography.bodySmall) - if (step.agentActive) Text("agent active", style = MaterialTheme.typography.bodySmall) +private fun StepCard(step: RunStep, isLast: Boolean, modifier: Modifier = Modifier) { + val text = pipelinesText() + val state = runStateOf(step.outcome.ifBlank { step.status }) + val color = runStateColor(state) + var detailsExpanded by rememberSaveable { mutableStateOf(false) } + val chevron by animateFloatAsState( + targetValue = if (detailsExpanded) 0f else -90f, + label = "step-chevron", + ) + val chipLabel = step.outcome.ifBlank { step.status }.ifBlank { state.label } + + Row(modifier = modifier.fillMaxWidth().height(IntrinsicSize.Min)) { + // Timeline gutter: the status glyph, then a connector line to the next + // step (coloured by this step's outcome). + Column( + modifier = Modifier.fillMaxHeight().width(36.dp).padding(top = 2.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + RunStatusIcon( + state = state, + contentDescription = "Step ${step.sequence} ${step.stage}: ${state.label}", + tint = color, + modifier = Modifier.size(20.dp), + ) + if (!isLast) { + Box( + Modifier + .padding(top = 4.dp) + .weight(1f) + .width(2.dp) + .background(color.copy(alpha = 0.5f)), + ) } - if (step.target.isNotBlank()) Text("target ${step.target}", style = MaterialTheme.typography.bodySmall) - val duration = formatDuration(step.startedAt, step.finishedAt) - if (duration != null) Text("took $duration", style = MaterialTheme.typography.bodySmall) - if (step.sessionId.isNotBlank()) Text("session ${step.sessionId}", style = MaterialTheme.typography.bodySmall) - if (step.diagnostic.isNotBlank()) { - Text(step.diagnostic, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) + } + + Column( + modifier = Modifier.weight(1f).padding(start = 8.dp, bottom = 12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + "${step.sequence}. ${step.stage}", + style = text.cardTitle, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + StatusChip(label = chipLabel, state = state) + } + + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text(step.status, style = text.meta) + val duration = formatDuration(step.startedAt, step.finishedAt) + if (duration != null) Text("took $duration", style = text.meta) + if (step.agentActive) Text("agent active", style = text.meta) } step.control?.let { control -> Text( "visit ${control.visit}/${control.maxVisits}" + (if (control.limitReached) " · limit reached" else "") + (control.modelTarget?.let { " · model $it" } ?: ""), - style = MaterialTheme.typography.bodySmall, + style = text.meta, ) } - val input = step.input.displayMap() - if (input.isNotBlank()) Text("input:\n$input", fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall) - val output = step.output.displayMap() - if (output.isNotBlank()) Text("output:\n$output", fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall) - step.fileChanges?.let { changes -> - Text( - "file changes: ${changes.status}" + - (if (changes.files.isNotEmpty()) " (${changes.files.size})" else "") + - (if (changes.skipped > 0) " · ${changes.skipped} skipped" else ""), - style = MaterialTheme.typography.bodySmall, - ) - changes.files.take(MAX_LISTED_FILES).forEach { file -> FileChangeRow(file) } + if (step.target.isNotBlank()) Text("target ${step.target}", style = text.meta) + if (step.sessionId.isNotBlank()) Text("session ${step.sessionId}", style = text.mono) + if (step.diagnostic.isNotBlank()) { + Text(step.diagnostic, color = MaterialTheme.colorScheme.error, style = text.meta) } - step.notifications.orEmpty().forEach { notification -> NotificationRow(notification) } - if (step.transcript.isNotBlank()) { - Text("transcript", style = MaterialTheme.typography.labelMedium) - Text(step.transcript, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall) + + // Evidence is collapsed by default so the timeline stays scannable. + Row( + modifier = Modifier + .clickable { detailsExpanded = !detailsExpanded } + .padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Icon( + imageVector = Icons.Default.KeyboardArrowDown, + contentDescription = null, + modifier = Modifier.size(16.dp).rotate(chevron), + ) + Text(if (detailsExpanded) "Hide details" else "Show details", style = text.meta) + } + + if (detailsExpanded) { + StepEvidence(step, text) } } } } @Composable -private fun FileChangeRow(file: FileChange) { +private fun StepEvidence(step: RunStep, text: net.awan.pipelines.ui.theme.PipelinesTextStyles) { + val input = step.input.displayMap() + if (input.isNotBlank()) EvidenceBlock("input", input, text) + val output = step.output.displayMap() + if (output.isNotBlank()) EvidenceBlock("output", output, text) + step.fileChanges?.let { changes -> + Text( + "file changes: ${changes.status}" + + (if (changes.files.isNotEmpty()) " (${changes.files.size})" else "") + + (if (changes.skipped > 0) " · ${changes.skipped} skipped" else ""), + style = text.label, + ) + changes.files.take(MAX_LISTED_FILES).forEach { file -> FileChangeRow(file, text) } + } + step.notifications.orEmpty().forEach { notification -> NotificationRow(notification, text) } + if (step.transcript.isNotBlank()) EvidenceBlock("transcript", step.transcript, text) +} + +@Composable +private fun EvidenceBlock(label: String, value: String, text: net.awan.pipelines.ui.theme.PipelinesTextStyles) { + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(label, style = text.label) + Text(value, style = text.mono) + } +} + +@Composable +private fun FileChangeRow(file: FileChange, text: net.awan.pipelines.ui.theme.PipelinesTextStyles) { Text( "· ${file.kind} ${file.path}" + (if (file.binary) " (binary)" else "") + (if (file.truncated) " (truncated)" else ""), - style = MaterialTheme.typography.bodySmall, + style = text.mono, ) } @Composable -private fun NotificationRow(receipt: NotificationReceipt) { +private fun NotificationRow(receipt: NotificationReceipt, text: net.awan.pipelines.ui.theme.PipelinesTextStyles) { Text( "notification ${receipt.status} → ${receipt.destination}" + (receipt.diagnostic?.let { " · $it" } ?: ""), - style = MaterialTheme.typography.bodySmall, + style = text.mono, ) } @Composable -private fun EvidenceCard(evidence: SessionEvidence) { - Card(Modifier.fillMaxWidth()) { +private fun EvidenceCard(evidence: SessionEvidence, modifier: Modifier = Modifier) { + val text = pipelinesText() + Card(modifier.fillMaxWidth()) { Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text("Evidence ${evidence.sequence}", style = MaterialTheme.typography.titleSmall) - if (evidence.sessionId.isNotBlank()) Text("session ${evidence.sessionId}", style = MaterialTheme.typography.bodySmall) - if (evidence.backend.isNotBlank()) Text("backend ${evidence.backend}", style = MaterialTheme.typography.bodySmall) - if (evidence.directory.isNotBlank()) Text("directory ${evidence.directory}", style = MaterialTheme.typography.bodySmall) + Text("Evidence ${evidence.sequence}", style = text.cardTitle) + if (evidence.sessionId.isNotBlank()) Text("session ${evidence.sessionId}", style = text.mono) + if (evidence.backend.isNotBlank()) Text("backend ${evidence.backend}", style = text.meta) + if (evidence.directory.isNotBlank()) Text("directory ${evidence.directory}", style = text.meta) if (!evidence.diagnostic.isNullOrBlank()) { - Text(evidence.diagnostic, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) + Text(evidence.diagnostic, color = MaterialTheme.colorScheme.error, style = text.meta) } if (!evidence.data.isNullOrBlank()) { - Text(evidence.data, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall) + HorizontalDivider() + Text(evidence.data, style = text.mono) } } } 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 7376df04..7b234443 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 @@ -1,18 +1,26 @@ package net.awan.pipelines.ui.screens +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Refresh import androidx.compose.material3.Card +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -23,19 +31,33 @@ import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle +import java.time.LocalDate +import java.time.OffsetDateTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter import net.awan.pipelines.data.protocol.RunSummary import net.awan.pipelines.data.protocol.UsageStats import net.awan.pipelines.ui.AppViewModel -import net.awan.pipelines.ui.components.EmptyState +import net.awan.pipelines.ui.components.RunState +import net.awan.pipelines.ui.components.RunStatusChip import net.awan.pipelines.ui.components.ErrorState import net.awan.pipelines.ui.components.LoadingState +import net.awan.pipelines.ui.components.runStateColor +import net.awan.pipelines.ui.components.runStateOf import net.awan.pipelines.ui.formatDuration +import net.awan.pipelines.ui.theme.PipelinesTextStyles +import net.awan.pipelines.ui.theme.pipelinesText import net.awan.pipelines.ui.visitCount -@OptIn(ExperimentalMaterial3Api::class) +@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable fun RunHistoryScreen( vm: AppViewModel, @@ -66,82 +88,257 @@ fun RunHistoryScreen( onRetry = vm::refreshRuns, modifier = Modifier.padding(padding), ) - else -> { - val history = state.data - val runs = history?.runs.orEmpty() - .filter { filterPipelineId == null || it.pipelineId == filterPipelineId } - Column(Modifier.fillMaxSize().padding(padding)) { - history?.usage?.let { UsageCard(it) } - if (runs.isEmpty()) { - EmptyState("No runs have been recorded yet.") - } else { - LazyColumn( - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - items(runs, key = { it.id }) { run -> RunRow(run) { onOpenRun(run.id) } } - } - } - if (state.error != null) { - Text(state.error!!, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) - } + else -> RunHistoryContent( + usage = state.data?.usage, + runs = state.data?.runs.orEmpty(), + filterPipelineId = filterPipelineId, + error = state.error, + onOpenRun = onOpenRun, + modifier = Modifier.padding(padding), + ) + } + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun RunHistoryContent( + usage: UsageStats?, + runs: List, + filterPipelineId: Long?, + error: String?, + onOpenRun: (Long) -> Unit, + modifier: Modifier = Modifier, +) { + // Day-grouping is derived once per data change (single pass, keyed on the + // stable source list), not per recomposition. + val groups = remember(runs, filterPipelineId) { + val filtered = if (filterPipelineId == null) { + runs + } else { + runs.filter { it.pipelineId == filterPipelineId } + } + val zone = ZoneId.systemDefault() + groupRunsByDay(filtered, LocalDate.now(zone), zone) + } + + LazyColumn( + modifier = modifier.fillMaxSize(), + contentPadding = PaddingValues(bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + if (usage != null) { + item(key = "usage") { + UsageMetrics(usage, Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) + } + } + if (groups.isEmpty()) { + item(key = "runs-empty") { + Text( + "No runs have been recorded yet.", + style = pipelinesText().body, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(24.dp), + ) + } + } else { + groups.forEach { group -> + stickyHeader(key = "day-${group.label}") { DayHeader(group.label) } + items(group.runs, key = { "run-${it.id}" }) { run -> + RunRow( + run = run, + modifier = Modifier.padding(horizontal = 16.dp).animateItem(), + onClick = { onOpenRun(run.id) }, + ) } } } + if (error != null) { + item(key = "runs-error") { + Text( + error, + color = MaterialTheme.colorScheme.error, + style = pipelinesText().body, + modifier = Modifier.padding(16.dp), + ) + } + } } } +/** A sticky day header ("Today"/"Yesterday"/date) above each group of runs. */ @Composable -private fun UsageCard(usage: UsageStats) { - Card(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) { - Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text("Usage", style = MaterialTheme.typography.titleMedium) - Text( - "total ${usage.total} · succeeded ${usage.succeeded} · failed ${usage.failed} · " + - "canceled ${usage.canceled} · interrupted ${usage.interrupted} · active ${usage.active}", - style = MaterialTheme.typography.bodySmall, - ) - if (usage.averageSeconds > 0) { - Text("average ${"%.1f".format(usage.averageSeconds)}s", style = MaterialTheme.typography.bodySmall) +private fun DayHeader(label: String) { + Text( + text = label, + style = pipelinesText().sectionHeader, + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.background) + .padding(horizontal = 16.dp, vertical = 8.dp), + ) +} + +/** + * The usage aggregates as a metrics block (not one run-on line): total and the + * average duration, then the colour-coded per-status counts. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun UsageMetrics(usage: UsageStats, modifier: Modifier = Modifier) { + val text = pipelinesText() + Card(modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.Bottom, + ) { + Metric("Total", usage.total.toString(), MaterialTheme.colorScheme.onSurface, text) + if (usage.averageSeconds > 0) { + Metric("Average", formatDuration(usage.averageSeconds.toLong()), MaterialTheme.colorScheme.onSurfaceVariant, text) + } + } + FlowRow( + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Metric("Succeeded", usage.succeeded.toString(), runStateColor(RunState.Succeeded), text) + Metric("Failed", usage.failed.toString(), runStateColor(RunState.Failed), text) + Metric("Canceled", usage.canceled.toString(), runStateColor(RunState.Canceled), text) + Metric("Interrupted", usage.interrupted.toString(), runStateColor(RunState.Interrupted), text) + Metric("Active", usage.active.toString(), runStateColor(RunState.Active), text) } } } } @Composable -private fun RunRow(run: RunSummary, onClick: () -> Unit) { - Card(Modifier.fillMaxWidth().clickable(onClick = onClick)) { - Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text(run.name, style = MaterialTheme.typography.titleMedium) - Text("v${run.version}", style = MaterialTheme.typography.bodySmall) +private fun Metric(label: String, value: String, color: Color, text: PipelinesTextStyles) { + Column { + Text(value, style = text.screenTitle, color = color) + Text(label, style = text.meta) + } +} + +@Composable +private fun RunRow(run: RunSummary, modifier: Modifier = Modifier, onClick: () -> Unit) { + val text = pipelinesText() + val state = runStateOf(run.status) + Card(modifier.fillMaxWidth().clickable(onClick = onClick)) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + run.name, + style = text.cardTitle, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + VersionChip("v${run.version}") } - Text( - buildString { - append("run ${run.id} · ${run.status.ifBlank { "unknown" }}") - if (run.outcome.isNotBlank()) append(" · outcome ${run.outcome}") - if (run.executing) append(" · executing") - if (run.currentStage.isNotBlank()) append(" · stage ${run.currentStage}") - // 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, - ) - val duration = formatDuration(run.createdAt, run.finishedAt) - val timing = buildString { - append("started ${run.createdAt}") - if (duration != null) append(" · took $duration") + + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + RunStatusChip(state) + if (run.executing) { + // The summary carries no total step count, so progress is shown + // honestly as an indeterminate indicator plus completed visits. + CircularProgressIndicator(modifier = Modifier.size(14.dp), strokeWidth = 2.dp) + } + Spacer(Modifier.weight(1f)) + Text(progressText(run), style = text.meta, maxLines = 1, overflow = TextOverflow.Ellipsis) } - if (run.createdAt.isNotBlank()) Text(timing, style = MaterialTheme.typography.bodySmall) + + Text(metaText(run), style = text.meta, maxLines = 1, overflow = TextOverflow.Ellipsis) + if (run.diagnostic.isNotBlank()) { - Text(run.diagnostic, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) - } - if (!run.resultPreview.isNullOrBlank()) { - Text(run.resultPreview, style = MaterialTheme.typography.bodySmall) + Text( + run.diagnostic, + style = text.meta, + color = if (state == RunState.Failed) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) } } } } + +@Composable +private fun VersionChip(version: String) { + Text( + version, + style = pipelinesText().label, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .clip(RoundedCornerShape(50)) + .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)) + .padding(horizontal = 8.dp, vertical = 2.dp), + ) +} + +/** Progress from the fields a summary actually has: completed visits + stage. */ +private fun progressText(run: RunSummary): String = buildString { + append(visitCount(run.completedSteps, "completed")) + if (run.currentStage.isNotBlank()) append(" · stage ${run.currentStage}") +} + +/** Run id, start time and duration, all via formatDuration for the duration. */ +private fun metaText(run: RunSummary): String = buildString { + append("run ${run.id}") + val start = formatRunStart(run.createdAt) + if (start != null) append(" · $start") + val duration = formatDuration(run.createdAt, run.finishedAt) + if (duration != null) append(" · $duration") +} + +private fun formatRunStart(createdAt: String): String? { + if (createdAt.isBlank()) return null + return runCatching { + OffsetDateTime.parse(createdAt) + .atZoneSameInstant(ZoneId.systemDefault()) + .format(START_FORMAT) + }.getOrNull() +} + +internal data class RunDayGroup(val label: String, val runs: List) + +/** + * Groups runs by calendar day in the device timezone, newest first, preserving + * the order within a day. A blank/unparseable timestamp gets a safe "Unknown + * date" group instead of crashing. + */ +internal fun groupRunsByDay(runs: List, today: LocalDate, zone: ZoneId): List { + val ordered = runs.sortedWith( + compareByDescending { runDate(it.createdAt, zone) } + .thenByDescending { it.createdAt }, + ) + val groups = LinkedHashMap>() + for (run in ordered) { + groups.getOrPut(dayLabel(run.createdAt, today, zone)) { mutableListOf() } += run + } + return groups.map { (label, list) -> RunDayGroup(label, list) } +} + +internal fun dayLabel(createdAt: String, today: LocalDate, zone: ZoneId): String { + val date = runDate(createdAt, zone) ?: return "Unknown date" + return when (date) { + today -> "Today" + today.minusDays(1) -> "Yesterday" + else -> date.format(DAY_FORMAT) + } +} + +private fun runDate(createdAt: String, zone: ZoneId): LocalDate? { + if (createdAt.isBlank()) return null + return runCatching { + OffsetDateTime.parse(createdAt).atZoneSameInstant(zone).toLocalDate() + }.getOrNull() +} + +private val DAY_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM yyyy") +private val START_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM HH:mm") diff --git a/android/app/src/main/java/net/awan/pipelines/ui/theme/Theme.kt b/android/app/src/main/java/net/awan/pipelines/ui/theme/Theme.kt index ee866ca1..c98b0960 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/theme/Theme.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/theme/Theme.kt @@ -4,12 +4,17 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider /** * Material 3 theming. Dark is the default appearance so the app matches the dark * Pipelines TUI on launch; the light scheme is retained for when it is * explicitly requested. Dynamic (wallpaper) colour is deliberately not used so * the app keeps its own identity. + * + * The app's one type scale ([PipelinesTypography]) is installed here and the + * named type roles are exposed through [LocalPipelinesText] so no screen repeats + * ad-hoc `MaterialTheme.typography.*` + colour combinations. */ @Composable fun PipelinesTheme( @@ -18,8 +23,16 @@ fun PipelinesTheme( ) { MaterialTheme( colorScheme = if (darkTheme) PipelinesDarkColors else PipelinesLightColors, - content = content, - ) + typography = PipelinesTypography, + ) { + val textStyles = rememberPipelinesTextStyles( + MaterialTheme.typography, + MaterialTheme.colorScheme.onSurfaceVariant, + ) + CompositionLocalProvider(LocalPipelinesText provides textStyles) { + content() + } + } } internal val PipelinesDarkColors = darkColorScheme( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/theme/Typography.kt b/android/app/src/main/java/net/awan/pipelines/ui/theme/Typography.kt new file mode 100644 index 00000000..fc1054cb --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/theme/Typography.kt @@ -0,0 +1,74 @@ +package net.awan.pipelines.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +/** + * The app's one type scale. It is passed to [androidx.compose.material3.MaterialTheme] + * so every screen, card and section stops picking its own sizes ad hoc: the + * app-bar/screen title, section header, card title, body and label roles all come + * from here. + */ +internal val PipelinesTypography = Typography( + titleLarge = TextStyle(fontWeight = FontWeight.SemiBold, fontSize = 22.sp, lineHeight = 28.sp), + titleMedium = TextStyle(fontWeight = FontWeight.SemiBold, fontSize = 16.sp, lineHeight = 22.sp, letterSpacing = 0.15.sp), + titleSmall = TextStyle(fontWeight = FontWeight.Medium, fontSize = 15.sp, lineHeight = 20.sp), + bodyLarge = TextStyle(fontSize = 16.sp, lineHeight = 24.sp), + bodyMedium = TextStyle(fontSize = 14.sp, lineHeight = 20.sp), + bodySmall = TextStyle(fontSize = 12.sp, lineHeight = 16.sp), + labelMedium = TextStyle(fontWeight = FontWeight.Medium, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp), +) + +/** + * The centralised type hierarchy as named roles. Material typography carries the + * size/weight; the roles Material cannot carry (secondary/meta colour and + * monospace data) are decided here once instead of in every file. + * + * - [screenTitle] — the screen / app-bar title. + * - [sectionHeader] — a collapsible section title. + * - [cardTitle] — a card's leading title (pipeline name, stage name). + * - [meta] — a subtitle/meta line in the secondary colour. + * - [body] — ordinary body copy. + * - [label] — a small key/value label. + * - [mono] — monospace data (source, hashes, sessions, run input/output). + */ +data class PipelinesTextStyles( + val screenTitle: TextStyle, + val sectionHeader: TextStyle, + val cardTitle: TextStyle, + val meta: TextStyle, + val body: TextStyle, + val label: TextStyle, + val mono: TextStyle, +) + +internal val LocalPipelinesText = staticCompositionLocalOf { + error("PipelinesTextStyles is only available inside PipelinesTheme") +} + +/** Resolves the shared type roles against the current Material colour scheme. */ +@Composable +internal fun rememberPipelinesTextStyles( + typography: Typography, + secondary: androidx.compose.ui.graphics.Color, +): PipelinesTextStyles = remember(typography, secondary) { + PipelinesTextStyles( + screenTitle = typography.titleLarge, + sectionHeader = typography.titleMedium, + cardTitle = typography.titleSmall, + meta = typography.bodySmall.copy(color = secondary), + body = typography.bodyMedium, + label = typography.labelMedium, + mono = typography.bodySmall.copy(fontFamily = FontFamily.Monospace), + ) +} + +/** Convenience accessor so screens read the shared roles from one place. */ +@Composable +internal fun pipelinesText(): PipelinesTextStyles = LocalPipelinesText.current diff --git a/android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt new file mode 100644 index 00000000..53046605 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt @@ -0,0 +1,28 @@ +package net.awan.pipelines.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class FormatTest { + + @Test + fun formatDurationSecondsUsesTheSharedRule() { + assertEquals("0s", formatDuration(0L)) + assertEquals("59s", formatDuration(59L)) + assertEquals("1m 0s", formatDuration(60L)) + assertEquals("2m 5s", formatDuration(125L)) + assertEquals("1h 1m", formatDuration(3661L)) + // A negative total (e.g. a rounded average) never prints a negative duration. + assertEquals("0s", formatDuration(-5L)) + } + + @Test + fun formatDurationBetweenTimestampsDelegatesToTheSecondsRule() { + assertEquals("2m 5s", formatDuration("2026-10-15T02:00:00Z", "2026-10-15T02:02:05Z")) + // Blank or reversed boundaries are "no duration", not a crash or "null". + assertNull(formatDuration("", "2026-10-15T02:02:05Z")) + assertNull(formatDuration("2026-10-15T02:00:00Z", "")) + assertNull(formatDuration("2026-10-15T02:05:00Z", "2026-10-15T02:00:00Z")) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/components/RunStatusTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/components/RunStatusTest.kt new file mode 100644 index 00000000..bb6d6a74 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/components/RunStatusTest.kt @@ -0,0 +1,37 @@ +package net.awan.pipelines.ui.components + +import org.junit.Assert.assertEquals +import org.junit.Test + +class RunStatusTest { + + @Test + fun runStateOfMirrorsTheServerVocabulary() { + assertEquals(RunState.Running, runStateOf("running")) + assertEquals(RunState.Queued, runStateOf("queued")) + assertEquals(RunState.Active, runStateOf("active")) + assertEquals(RunState.Succeeded, runStateOf("succeeded")) + // Step/outcome words map onto the same states. + assertEquals(RunState.Succeeded, runStateOf("completed")) + assertEquals(RunState.Succeeded, runStateOf("success")) + assertEquals(RunState.Failed, runStateOf("failed")) + assertEquals(RunState.Failed, runStateOf("error")) + assertEquals(RunState.Canceled, runStateOf("canceled")) + assertEquals(RunState.Interrupted, runStateOf("interrupted")) + } + + @Test + fun runStateOfIsSafeForBlankAndUnknownValues() { + assertEquals(RunState.Unknown, runStateOf("")) + assertEquals(RunState.Unknown, runStateOf(" ")) + assertEquals(RunState.Unknown, runStateOf("something-new")) + // Case/whitespace tolerant. + assertEquals(RunState.Running, runStateOf(" Running ")) + } + + @Test + fun everyStateHasADistinctGlyph() { + val glyphs = RunState.entries.map { runStateIcon(it) } + assertEquals(RunState.entries.size, glyphs.toSet().size) + } +} 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 ce1d4fd6..1e865eec 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 @@ -325,4 +325,71 @@ class WorkflowGraphTest { assertTrue(expandedGraphHeight(1000).value > collapsedGraphHeight(1000).value) assertEquals(920f, expandedGraphHeight(1000).value, 0.01f) } + + /** + * The whole point of the fix: the content point under the gesture centroid + * must not move, i.e. `(centroid - offset) / scale` is invariant. The draw + * transform is `offset + p * scale`, so this is exactly the point measured + * before and after. + */ + @Test + fun zoomAboutKeepsTheContentPointUnderTheCentroidFixed() { + val offset = Offset(-24f, 18f) + val scale = 0.75f + val centroid = Offset(210f, 130f) + val contentBefore = (centroid - offset) / scale + val result = zoomAbout(offset, scale, centroid, zoom = 1.6f, 0.3f, 3f) + val contentAfter = (centroid - result.offset) / result.scale + assertEquals(contentBefore.x, contentAfter.x, 0.001f) + assertEquals(contentBefore.y, contentAfter.y, 0.001f) + } + + @Test + fun zoomAboutClampsTheScaleAtBothExtremes() { + val zoomedIn = zoomAbout(Offset.Zero, 1f, Offset(50f, 50f), zoom = 9f, 0.3f, 3f) + assertEquals(3f, zoomedIn.scale, 0.0001f) + val zoomedOut = zoomAbout(Offset.Zero, 1f, Offset(50f, 50f), zoom = 0.01f, 0.3f, 3f) + assertEquals(0.3f, zoomedOut.scale, 0.0001f) + } + + /** + * After the caller applies the pan and re-clamps, the anchored offset must + * stay inside clampOffset's bounds on both axes. + */ + @Test + fun zoomAboutResultStaysWithinClampOffsetBounds() { + val viewport = Size(400f, 300f) + val content = Size(1000f, 500f) + val minVisible = 40f + val centroid = Offset(300f, 80f) + val result = zoomAbout(Offset(-100f, -50f), 0.8f, centroid, zoom = 1.4f, 0.3f, 3f) + val clamped = clampOffset( + offset = result.offset, + content = Size(content.width * result.scale, content.height * result.scale), + viewport = viewport, + minVisible = minVisible, + ) + val scaled = Size(content.width * result.scale, content.height * result.scale) + assertTrue(clamped.x >= minVisible - scaled.width && clamped.x <= viewport.width - minVisible) + assertTrue(clamped.y >= minVisible - scaled.height && clamped.y <= viewport.height - minVisible) + } + + /** A degenerate scale (0) and a pure pan (zoom == 1) stay finite and sensible. */ + @Test + fun zoomAboutIsFiniteForDegenerateScaleAndPurePan() { + val offset = Offset(12f, -7f) + val degenerate = zoomAbout(offset, scale = 0f, Offset(100f, 100f), zoom = 1.5f, 0.3f, 3f) + assertEquals(offset, degenerate.offset) + assertEquals(0f, degenerate.scale, 0.0001f) + + val purePan = zoomAbout(offset, 0.5f, Offset(80f, 60f), zoom = 1f, 0.3f, 3f) + assertEquals(0.5f, purePan.scale, 0.0001f) + assertEquals(offset.x, purePan.offset.x, 0.001f) + assertEquals(offset.y, purePan.offset.y, 0.001f) + assertTrue(purePan.offset.x.isFinite() && purePan.offset.y.isFinite()) + + // A negative zoom is ignored rather than flipping content. + val negative = zoomAbout(offset, 0.5f, Offset(80f, 60f), zoom = -2f, 0.3f, 3f) + assertEquals(offset, negative.offset) + } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/screens/RunGroupingTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/screens/RunGroupingTest.kt new file mode 100644 index 00000000..c735f742 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/screens/RunGroupingTest.kt @@ -0,0 +1,46 @@ +package net.awan.pipelines.ui.screens + +import java.time.LocalDate +import java.time.ZoneOffset +import net.awan.pipelines.data.protocol.RunSummary +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class RunGroupingTest { + + private fun run(id: Long, createdAt: String) = RunSummary(id = id, name = "p$id", createdAt = createdAt) + + @Test + fun groupsRunsByDayNewestFirstWithStickyLabels() { + val today = LocalDate.of(2026, 10, 15) + val zone = ZoneOffset.UTC + // Deliberately unsorted input. + val runs = listOf( + run(3, "2026-10-10T09:00:00Z"), + run(1, "2026-10-15T10:00:00Z"), + run(2, "2026-10-14T09:00:00Z"), + ) + val groups = groupRunsByDay(runs, today, zone) + assertEquals(listOf("Today", "Yesterday"), groups.take(2).map { it.label }) + assertEquals(listOf(1L), groups[0].runs.map { it.id }) + assertEquals(listOf(2L), groups[1].runs.map { it.id }) + // The older group is neither "Today" nor "Yesterday" and keeps its run. + assertTrue(groups[2].label != "Today" && groups[2].label != "Yesterday") + assertEquals(listOf(3L), groups[2].runs.map { it.id }) + } + + @Test + fun blankOrUnparseableCreatedAtFallsBackToASaneLabel() { + val today = LocalDate.of(2026, 10, 15) + val zone = ZoneOffset.UTC + val groups = groupRunsByDay( + listOf(run(1, ""), run(2, "not-a-date"), run(3, "2026-10-15T10:00:00Z")), + today, + zone, + ) + assertEquals("Today", groups.first().label) + val unknown = groups.first { it.label == "Unknown date" } + assertEquals(setOf(1L, 2L), unknown.runs.map { it.id }.toSet()) + } +}