diff --git a/android/README.md b/android/README.md index 9ad86191..39bb2f09 100644 --- a/android/README.md +++ b/android/README.md @@ -256,6 +256,16 @@ stops it. 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). +- A run still in progress shows the time it has taken so far instead of a + finished duration, everywhere a run's time appears: the runs list meta row, + the pipeline list's last-run line and the run detail summary's Duration row. A + running value is live — recomputed once a second from the server's own + `created_at` (never from when the app loaded, so it stays correct after a + reconnect), using the shared `runDurationText` and a single ticking clock per + screen (`ui/components/LiveTime.kt`) that pauses while the app is backgrounded + and while no shown run is executing. Once the run finishes it keeps its stored + total duration; a missing start omits the value and a future start (clock skew) + reads as `0s` (`FormatTest`, `PipelineLastRunTest`). - 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 @@ -1294,6 +1304,101 @@ has exactly three pane levels (`MasterPane.List/Detail/Stage`, `MAX_PANE_DEPTH = centred lines and ellipsizes (e.g. `Pipelines maintenance - plan implem…`) rather than being rotated. +## Covered panes carry a compact statistics block (16 Oct 2026) + +A covered pane's compact identity is no longer a bare title/subtitle: it now +shows a small vertical block of labelled statistics, aggregated client-side from +the run history the app already receives, degrading with the strip's width. +`android/` only; nothing in the Pipelines server, its Go source, the +Docker/compose files or the installer was touched, no dependency was added (the +declared `material-icons-extended` is unchanged), no run was started from the app +and no server field was added. + +- **Pipeline statistics.** When the covered pane is a pipeline + (`PipelineDetailScreen`, and `RunDetailScreen` through its run's pipeline) the + block shows the run counts (`runs`/`succeeded`/`failed`/`active`), the last + run's status and how long ago it started, and the average duration over the + runs that finished. `ui/screens/PaneStats.kt` folds the history in one pass; the + counts mirror the server's own vocabulary (`active` = queued/running, per + `internal/pipeline/stats.go`) and a still-running run never drags the average. + A run pane whose run (and so whose pipeline) has not loaded yet stays + title-only: an absent pipeline id is "not known yet", never the whole history, + so it can never show the server-wide summary as if it were the run's pipeline. +- **List statistics.** When the covered pane is a list, `PipelineListScreen` and + `RunHistoryScreen` show the whole history's counts by status and the single most + recent run; a runs list scoped to one pipeline shows that pipeline's own + numbers. +- **Width degradation.** `PaneIdentity` measures its own strip and shows the title + only below one peek width, the run counts up to + `MIN_COVERED_PANE_WIDTH_DP + PEEK_WIDTH_DP`, and the full block above it, so a + thin peek drops whole labelled statistics instead of clipping a number or + printing an unlabelled figure. Each statistic is a label above its own value, so + the number never shares a line with a label that could clip it. The boundaries + reuse the named geometry tokens and the decision is the pure + `paneStatTier`/`visiblePaneStats` pair. +- **One recency rule.** The "most recent run" comparison is the shared + `isMoreRecent` helper, used by the single-pass `latestRunByPipeline` join and by + the covered summary's own fold, so the pipeline row's last-run badge, the "most + recent run" sort and the covered summary all agree on which run is the latest + without grouping the history into intermediate lists. +- **Two aggregation entry points.** `ui/screens/PaneStats.kt` exposes + `pipelineStatLines(runs, pipelineId, now)` for the pipeline-scoped panes and + `listStatLines(runs, now)` for the list panes, so "which statistics, from which + history, or none until it has loaded" lives in one place instead of at each + call site and a null pipeline id can never be mistaken for the whole history. + The fold is a single pass (`RunTally.add` tracks the counts, the finished-run + duration total and the most recent run together), so a scoped pipeline summary + never allocates a filtered list or walks the history twice. + +Evidence (macOS, JDK 17 from Homebrew `openjdk@17`, the cached Gradle 8.11.1 +distribution, `ANDROID_HOME=~/Library/Android/sdk`, `--offline`): + +- `:app:testDebugUnitTest :app:assembleDebug --offline --console=plain` → + `BUILD SUCCESSFUL in 2s` (41 actionable tasks: 8 executed, 33 up-to-date). The + result XMLs total **279 tests, 0 failures, 0 errors, 0 skipped** across 32 + files; `app/build/outputs/apk/debug/app-debug.apk` is 18,204,486 bytes, sha256 + `196c9d6f4acbcc75769fd52ecadac66378bad78994056895f26ff65da077718c`. The + `PaneStatsTest` (15 cases) covers the per-pipeline counts, queued as active, the + last run's state/age, the average over finished runs, zero-duration runs, a + pipeline with no runs, an unknown pipeline id, the whole-history list fold and + the labelled lines, and that an absent/unknown pipeline id yields no lines + rather than the list summary; the `PaneIdentityTest` (5 cases) pins the width + tiers, that the counts tier drops only the detail lines, and that every shown + statistic keeps its label and value. +- **APK publish.** `app-debug.apk` was copied to + `~/.local/share/pipelines/data/artifacts/142/3/pipelines-debug-wip-c700b28.apk` + (`c700b28` = `git rev-parse --short HEAD`; the tree is uncommitted WIP on top of + it); `shasum -a 256` matched the built file (`196c9d6f…`). `curl -I + http://10.0.0.249:8080/artifacts/142/3/pipelines-debug-wip-c700b28.apk` returned + `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18204486`. +- **Device evidence (emulator-5554).** The debug APK was installed with + `adb -s emulator-5554 install -r` (never the attached Pixel, never + `emulator-5556`) against the live LAN server, and the wide and narrow layouts + were captured with `adb -s emulator-5554 shell screencap -p /sdcard/cap.png` + then `adb -s emulator-5554 pull`. Captures are in the same artifacts directory: + `wide-1-level-runs-list.png`, `wide-2-levels-covered-list-stats.png`, + `wide-3-levels-covered-stats.png` (plus `…pane0…`/`…pane1…` crops) and + `narrow-runs-list.png`. OCR of the covered strips confirms the block: at two + levels the covered runs list reads `Runs / runs 145 / succeeded 90 / failed 39 / + active 6 / last running - 4m ago` (Full tier); at three levels its two covered + strips (82 dp and 112 dp wide) drop the `last` line and keep only the labelled + counts, and the covered run strip reads the run's own pipeline id 11 numbers + (`runs 60 / succeeded 37 / failed 14 / active 5`) — clearly not the server-wide + 145, so an unknown pipeline can no longer borrow the list summary. Four levels + remain unreachable: `MAX_PANE_DEPTH = 2` gives exactly three pane levels, so the + three-covered degradation is captured instead. +- **Device-instruction conflict.** The run's Constraints said use `emulator-5554` + exclusively and never the operator's physical device; an appended paragraph said + to use the attached Pixel and never an emulator. There is no path that satisfies + both, and installing this WIP build on the operator's own phone is forbidden by + the task, so the emulator named in the Constraints was used (with the + `device.lock` held) and the Pixel and `emulator-5556` were never touched. While + capturing, another lane repeatedly overwrote the installed APK on + `emulator-5554` (the installed hash reverted from this build to + `2adaf03e…`/`5912d38f…` at 16:18 and 16:20 until reinstalled), which is why the + APK hash was re-checked immediately before the captures that are reported here. + ## Run stage pane leads with the run's results (16 Oct 2026) A stage opened from a run no longer leads with its own definition. The pane now @@ -3441,3 +3546,119 @@ native 2208x1840 @420 at the end. returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, `Content-Length: 17928873`. + +## Remembering the list scroll position (16 Oct 2026) + +Returning from a pipeline or a run now restores the list to exactly where the +operator left it — the same item at the same offset, on either window width — and +the position also survives a configuration change, rotation and process death. +`android/` only; nothing in the Pipelines server, its Go source, the +Docker/compose files or the installer was touched, no dependency was added (the +declared `material-icons-extended` is unchanged), no run was started from the app +and no server field was added. + +- **Root cause.** A covered pane is a different composition from an open one: when + a detail opens on a wide window, pane 0 stops drawing its list and draws its + compact identity in a strip instead, so the list screen (and any scroll state it + owned) was discarded, and backing out rebuilt it at the top. The runs + destination is additionally recreated by the `NavHost` when the app-level runs + selection changes. The fix owns each list's scroll state at the app shell, above + the `NavHost` (`PipelinesApp`), and passes it into the list screens, so it is + never inside the pane that comes and goes. +- **One scroll state per list.** `PipelinesApp` holds + `pipelineListState`/`runListState` with `rememberSaveable(saver = LazyListState.Saver)` + and passes them to `PipelineDestination`/`RunsDestination` and on to + `PipelineListScreen`/`RunHistoryScreen` (and `RunHistoryContent`), whose + `LazyColumn` now takes that state. The same two screens serve both window widths + and both entry points, so the runs list reached from a pipeline gets the same + treatment as one opened normally. +- **Restore and clamp rule.** `ui/components/ListScroll.kt` holds the pure + `ListScrollAnchor(index, offset)` and `restoredScrollAnchor(anchor, itemCount)` + (the saved index clamped to the nearest valid item, the offset kept only for the + item that survived) plus the `RestoreListScroll(state, itemCount)` composable, + which is keyed on the item count so it runs once when the list's size settles + and never on the operator's own scrolling. A list that changed underneath (a + filter, a sort, a refresh, items removed) therefore clamps to the nearest + sensible item instead of jumping to the top or throwing, a scroll after coming + back is never overridden, and a list that has not loaded yet is left alone so a + restored position is not reset to the top while the data is still arriving. +- **Runs list before it has loaded (fixed 16 Oct 2026).** The runs list has no + pane-level empty state, so its first frame — before `LaunchedEffect { + vm.refreshRuns() }` has set `loading` — was data-less, not-loading and classified + as content. `RunHistoryContent` then composed an empty list whose only slot was + the "no runs" line, and `RestoreListScroll` clamped the restored index to 0 + before the real list arrived: the runs list always came back at the top after + process death (the pipelines list was spared only because its empty state was + classified as a distinct `LoadPhase.Empty`). `listLoadPhase` now takes the + pane's `loaded` signal (`LoadState.loaded`) and reads a data-less list that has + never loaded as loading rather than empty, so the list — and its restored + position — is not composed until the history is actually in hand. Both list + screens pass it. +- **One source for the runs list body.** `RunHistoryScreen` no longer maintains a + second, hand-written copy of the LazyColumn's item count. The pure + `runListEntries(...)` builds the slots (the usage block, the single + empty-or-grouped body and the optional inline error row) once, in layout order; + the column renders exactly that list and `RestoreListScroll` clamps to its size, + so the count can never drift from what is drawn. `RunListEntriesTest` pins the + slot order, the stable keys and the count. + +Evidence (macOS, JDK 17 from Homebrew `openjdk@17`, cached Gradle 8.11.1 +distribution, `ANDROID_HOME=~/Library/Android/sdk`, every Gradle command with +`--no-daemon --offline --console=plain`): + +- `:app:clean :app:testDebugUnitTest :app:assembleDebug` → `BUILD SUCCESSFUL`; + the tests were then re-executed with `:app:testDebugUnitTest --rerun-tasks` + (not served from the build cache). The result XMLs total **292 tests, 0 + failures, 0 errors, 0 skipped** across 34 files. `ListScrollTest` (6 cases) + pins the restore/clamp rule (in-range item keeps its index and offset, the last + item keeps its offset, a shrunken list clamps to its last item and drops the + offset, a negative index clamps to the top, an empty list stays at the top); the + two new `LoadPhaseTest` cases pin that a data-less list that has never loaded + reads as loading while the default keeps the old rule; and `RunListEntriesTest` + (5 cases) pins the runs body's slot order, stable keys and count. + `app/build/outputs/apk/debug/app-debug.apk` is 18,011,393 bytes, sha256 + `13b8d2871e9ad522e0d5a826642cdf467a95939408bed519d952e83d5c8dbb02`. +- `:app:lintDebug` aborts on only the two pre-existing `NewApi` errors for + `android:windowLightNavigationBar` (minSdk 26) in `res/values/themes.xml` and + `res/values-night/themes.xml`, which this change did not modify; no error or + warning points at the scroll change. +- **APK publish.** `app-debug.apk` was copied to + `~/.local/share/pipelines/data/artifacts/157/1/pipelines-debug-wip-c700b28.apk` + (`c700b28` = `git rev-parse --short HEAD`; the tree is uncommitted WIP on top of + it); `shasum -a 256` matched the built file (`13b8d287…`). `curl -I + http://10.0.0.249:8080/artifacts/157/1/pipelines-debug-wip-c700b28.apk` returned + `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18011393`. +- **Device evidence (operator's Pixel 10 Pro Fold, `adb -s 58281FDCG000JF`, inner + 2076x2152 at the 330 density override ≈1006dp; narrow override `wm size + 1080x1920`).** The build was installed with `adb -s 58281FDCG000JF install -r`, + driven against the live LAN server (`curl http://127.0.0.1:8080/healthz` → + `{"healthy":true}`), and captured with `android/scripts/capture_png.sh -s + 58281FDCG000JF` (device-side `screencap` to a file, then `pull` — never + `exec-out`), written to `~/.local/share/pipelines/data/artifacts/157/1/`. The + scroll position is read from `uiautomator dump` as the first `run «id» · …` line + (the runs list) or the first `id «n» · v…` line (the pipelines list): + + | case | how driven | result | + | --- | --- | --- | + | pipelines, wide, open→back | scroll down (first row `id 6`), tap the pipeline, Back | same first row; `01_list_scrolled.png` vs `03_list_restored.png` differ in **no pixel** (`bbox None`) | + | runs, wide, open→back | scroll down (first row `run 32 · 13 Oct 17:21`), tap the run, Back | same first row; `05_runs_scrolled.png` vs `06_runs_restored.png` differ in **no pixel** (`bbox None`) | + | **runs, process death** | HOME, `adb -s 58281FDCG000JF shell am kill net.awan.pipelines` (`pidof` empty), restore the task from Recents | back on the Runs destination with the same first row `run 41 · 15 Oct 14:35`; `30_runs_before_death.png` vs `31_runs_after_death.png` differ only in the status bar (`bbox (138,67)-(289,95)`) | + | runs, rotation | `user_rotation 1`, then `0` | same top row `run 10 · 11 Oct 16:01` after both | + | pipelines, rotation | `user_rotation 1`, then `0` | same top row in landscape; the first flip re-laid the anchor onto the adjacent row (`id 6`→`id 11`) and was stable on the second and later flips — the list never returned to the top | + | density, config change | `wm density 330`→`340`→`330` | same top row `run 10 · 11 Oct 16:01` | + | pipelines, narrow | `wm size 1080x1920`; scroll, open a pipeline, Back | same first row `id 4`; `70_narrow_pipelines_before.png` vs `72_narrow_pipelines_after.png` differ in **no pixel** (`bbox None`) | + | runs, narrow | `wm size 1080x1920`; scroll, open a run, Back | same first row `run 8 · 11 Oct 14:44`; only the status bar differs | + | list shrank while open | pipelines scrolled to the bottom, then search `quick` | the two matches (`id 9`, `id 10`) are shown — clamped, not blank and not reset to the top — and the process stayed alive with no `FATAL EXCEPTION` in `logcat` | + + For the open→back cases the top row and its pixel offset matched exactly (the + screenshot diff isolates only the status-bar clock); rotation, the density + change and process death restored the same destination and top row. `device.lock` + was held for every `adb` command and released afterwards, and no run was started + from the app. +- **Not exercised.** `onOpenRun` from a pipeline detail is only reached through + `StartRunDialog.onStarted` (after starting a run), which the task forbids, so the + runs list reached that way is kept compiling and functional but not driven; it + shares the one `runListState`, so it gets the same treatment as the normally + opened runs list. A real hardware fold to the cover display was not exercised + (narrow was produced with `wm size`). 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 eccc2799..a4e7e7ff 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 @@ -48,6 +48,24 @@ fun formatDuration(start: String, end: String): String? = internal fun secondsSince(start: String, nowMillis: Long): Long? = parseInstant(start)?.let { ((nowMillis - it.toInstant().toEpochMilli()) / 1000).coerceAtLeast(0) } +/** + * The time a run has taken so far: while it is still [executing], its live + * elapsed time from its server start timestamp to [nowMillis]; once it has + * finished, its stored total duration. The single rule the runs list's meta line, + * the pipeline last-run line and the run detail summary share, so the same run is + * never described differently in the three places. Null when the start (or, for a + * finished run, the end) is unusable, so the caller omits the value instead of + * printing a blank; a running run with a future start (clock skew) reads as `0s`, + * never a negative. + */ +internal fun runDurationText( + createdAt: String, + finishedAt: String, + executing: Boolean, + nowMillis: Long, +): String? = + if (executing) secondsSince(createdAt, nowMillis)?.let(::formatDuration) + else formatDuration(createdAt, finishedAt) /** * Human duration for a whole number of seconds. The single formatting rule for diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/LiveTime.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/LiveTime.kt new file mode 100644 index 00000000..c15337d4 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/LiveTime.kt @@ -0,0 +1,53 @@ +package net.awan.pipelines.ui.components + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.currentStateAsState +import kotlinx.coroutines.delay + +/** A live value advances once a second, never per frame. */ +private const val LIVE_TICK_MILLIS = 1_000L + +/** + * Whether the host activity is resumed. The one background/focus gate every live + * ticking value shares, so a backgrounded app never keeps waking up once a second + * just to repaint a number nobody can see. + */ +@Composable +internal fun hostResumed(): Boolean { + val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() + return lifecycleState.isAtLeast(Lifecycle.State.RESUMED) +} + +/** + * The device clock in epoch millis, advanced once a second while [ticking] is + * true and the host is resumed, and frozen at its last reading otherwise. The + * single ticker behind every live elapsed readout: callers derive their value + * from the server's own start timestamp and this clock, so the numbers stay + * correct after a reconnect (never anchored to when the app happened to load), + * a screen full of running rows runs one coroutine rather than one per row, and + * nothing ticks for a finished run or while the app is backgrounded. + * + * The clock is re-read as the loop (re)starts, so a value frozen while + * backgrounded jumps straight to the correct elapsed on the first frame back. + */ +@Composable +internal fun rememberLiveNowMillis(ticking: Boolean): Long { + var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) } + val live = ticking && hostResumed() + LaunchedEffect(live) { + if (!live) return@LaunchedEffect + nowMillis = System.currentTimeMillis() + while (true) { + delay(LIVE_TICK_MILLIS) + nowMillis = System.currentTimeMillis() + } + } + return nowMillis +} 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 157e81c0..3218791a 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 @@ -36,7 +36,6 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -75,13 +74,9 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.compose.LocalLifecycleOwner -import androidx.lifecycle.compose.currentStateAsState import kotlin.math.abs import kotlin.math.hypot import kotlin.math.roundToInt -import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.awan.pipelines.data.protocol.Graph import net.awan.pipelines.data.protocol.GraphEdge @@ -90,6 +85,8 @@ import net.awan.pipelines.data.protocol.GraphSemantics import net.awan.pipelines.data.protocol.Protocol import net.awan.pipelines.data.protocol.RunGraphState import net.awan.pipelines.data.protocol.edges +import net.awan.pipelines.ui.components.hostResumed +import net.awan.pipelines.ui.components.rememberLiveNowMillis import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.secondsSince import net.awan.pipelines.ui.theme.GRAPH_ACTIVE_HALO_GAP @@ -274,25 +271,18 @@ fun WorkflowGraph( // finished run; pause when the graph is off screen or when the OS animation // setting is off. ValueAnimator.areAnimatorsEnabled() reflects the system // "Remove animations"/animation-scale setting; it is re-read on resume. - val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() - val onScreen = lifecycleState.isAtLeast(Lifecycle.State.RESUMED) + val onScreen = hostResumed() val animationsEnabled = remember(onScreen) { ValueAnimator.areAnimatorsEnabled() } val animate = graphShouldAnimate(runState, animationsEnabled, onScreen) val phase = rememberPulsePhase(animate) - // The active stage's live ticking elapsed time. The loop only runs while - // animating, so a finished run, a paused/off-screen graph and an - // animations-disabled device never wake up once a second; in those cases the - // value is a static snapshot for a clearly marked running state. + // The active stage's live ticking elapsed time, from the shared clock: it + // runs only while the graph is animating a live stage whose start is known, + // so a finished run, a paused/off-screen graph and an animations-disabled + // device never wake up once a second; in those cases the value is a static + // snapshot for a clearly marked running state. val activeStartedAt = runState?.currentStageStartedAt - var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) } - LaunchedEffect(animate, activeStartedAt) { - if (!animate || activeStartedAt.isNullOrBlank()) return@LaunchedEffect - while (true) { - nowMillis = System.currentTimeMillis() - delay(ELAPSED_TICK_MILLIS) - } - } + val nowMillis = rememberLiveNowMillis(animate && !activeStartedAt.isNullOrBlank()) // Measured once per second (never per frame) so the canvas draw adds no // allocation for the timer. val elapsedLayout = remember(activeStartedAt, nowMillis, scheme, density, text) { @@ -1746,9 +1736,6 @@ private fun rememberPulsePhase(animate: Boolean): Float { /** One pulse (and one full pass of the edge flow) per this many milliseconds. */ private const val PULSE_PERIOD_MILLIS = 1_600 -/** The active stage's elapsed time ticks once a second, never per frame. */ -private const val ELAPSED_TICK_MILLIS = 1_000L - /** How much of the pulse strength the active halo's soft glow carries. */ private const val ACTIVE_HALO_GLOW = 0.28f diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineLastRun.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineLastRun.kt index e56e15e8..9ac1c405 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineLastRun.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineLastRun.kt @@ -5,17 +5,18 @@ import java.time.OffsetDateTime import net.awan.pipelines.data.protocol.RunSummary import net.awan.pipelines.ui.components.RunState import net.awan.pipelines.ui.components.runStateOf -import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.parseInstant +import net.awan.pipelines.ui.runDurationText /** Shown for a pipeline that appears in list_runs but has recorded no run. */ const val NO_RUNS_RECORDED = "no runs recorded" /** * The last-run facts one pipeline row shows: the status chip's [state], how long - * ago the run started, its recorded duration and its run id. Kept as a plain data - * class so the join and its edge cases (no runs, ties, unknown status) are - * unit-testable without composing anything. + * ago the run started, its time so far ([duration]: the live elapsed while it is + * still running, the recorded total once finished) and its run id. Kept as a + * plain data class so the join and its edge cases (no runs, ties, unknown status) + * are unit-testable without composing anything. */ internal data class PipelineRunBadge( val runId: Long, @@ -52,8 +53,9 @@ internal fun pipelineRunBadges( /** * The most recent run of each pipeline, decided from the timestamps (the higher * run id breaking an exact tie or a bad timestamp), independent of the input - * order. The one fold shared by the last-run badge join above and the "most - * recent run" pipeline sort, so both agree on which run is the latest. + * order. One pass, reusing the shared [isMoreRecent] comparison, so it shares the + * "most recent" rule with the covered panes' last-run line without grouping the + * history into intermediate lists. */ internal fun latestRunByPipeline(runs: List): Map { val latest = HashMap() @@ -70,11 +72,22 @@ internal fun runBadge(run: RunSummary, now: OffsetDateTime): PipelineRunBadge = runId = run.id, state = runStateOf(run.status), ranAgo = formatRanAgo(run.createdAt, now), - duration = formatDuration(run.createdAt, run.finishedAt), + // A still-running run shows the time it has taken so far, recomputed from + // its start timestamp as [now] advances; a finished one its total duration. + duration = runDurationText( + createdAt = run.createdAt, + finishedAt = run.finishedAt, + executing = run.executing, + nowMillis = now.toInstant().toEpochMilli(), + ), ) -/** Timestamps decide recency; the higher run id breaks an exact tie (or a bad timestamp). */ -private fun isMoreRecent(candidate: RunSummary, current: RunSummary): Boolean { +/** + * Timestamps decide recency; the higher run id breaks an exact tie (or a bad + * timestamp). The one recency rule, shared by the per-pipeline last-run join and + * the covered panes' most-recent-run line. + */ +internal fun isMoreRecent(candidate: RunSummary, current: RunSummary): Boolean { val a = parseInstant(candidate.createdAt) val b = parseInstant(current.createdAt) if (a != null && b != null) { @@ -86,7 +99,8 @@ private fun isMoreRecent(candidate: RunSummary, current: RunSummary): Boolean { /** * A compact "how long ago" for a run's start: `just now` under a minute, then - * `Nm ago`/`Nh ago`/`Nd ago`, the same integer rhythm as [formatDuration]. Null + * `Nm ago`/`Nh ago`/`Nd ago`, the same integer rhythm as the shared duration + * formatting. Null * when the timestamp is blank or unparseable, so the caller omits the fragment * instead of printing a blank. A future start (clock skew) reads as `just now`, * never a negative age. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt index 287204aa..0010a9c6 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt @@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountTree @@ -34,7 +35,9 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.lifecycle.compose.collectAsStateWithLifecycle +import java.time.Instant import java.time.OffsetDateTime +import java.time.ZoneId import net.awan.pipelines.data.protocol.PipelineSummary import net.awan.pipelines.ui.AppViewModel import net.awan.pipelines.ui.components.EmptyState @@ -46,6 +49,7 @@ import net.awan.pipelines.ui.components.ListRow import net.awan.pipelines.ui.components.LoadPhase import net.awan.pipelines.ui.components.LoadingState import net.awan.pipelines.ui.components.PaneIdentity +import net.awan.pipelines.ui.components.RestoreListScroll import net.awan.pipelines.ui.components.RunState import net.awan.pipelines.ui.components.RunStatusChip import net.awan.pipelines.ui.components.SortMenu @@ -53,6 +57,7 @@ import net.awan.pipelines.ui.components.StateCrossfade import net.awan.pipelines.ui.components.animateListItem import net.awan.pipelines.ui.components.listLoadPhase import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.rememberLiveNowMillis import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_S import net.awan.pipelines.ui.theme.pipelinesText @@ -65,6 +70,7 @@ fun PipelineListScreen( modifier: Modifier = Modifier, selectedId: Long? = null, covered: Boolean = false, + listState: LazyListState, ) { val state by vm.pipelines.collectAsStateWithLifecycle() val runsState by vm.runs.collectAsStateWithLifecycle() @@ -82,8 +88,39 @@ fun PipelineListScreen( vm.refreshRuns() } - // "How long ago" is anchored once per composition, not recomputed per row. - val now = remember { OffsetDateTime.now() } + // "How long ago" (and a running run's live elapsed) are anchored to a shared + // clock that ticks only while some run in the history is executing and the app + // is resumed, so the last-run line's elapsed advances and stays correct after + // a reconnect (derived from the server's own start timestamps) while a fully + // finished history costs no wakeups. + val live = runsState.data?.runs?.any { it.executing } == true + val nowMillis = rememberLiveNowMillis(live) + val now = remember(nowMillis) { + OffsetDateTime.ofInstant(Instant.ofEpochMilli(nowMillis), ZoneId.systemDefault()) + } + + // [listState] is owned by the destination, above the panes: a covered pane is a + // different composition (its compact identity is drawn in a strip), so a state + // held here would be discarded and reset the scroll when a detail closes. + // [RestoreListScroll] clamps it when the list changed underneath. + + // A covered pane shows its compact identity only; the search field and list + // must never be drawn squeezed into the peek strip. Its statistics are the + // run history's summary, folded once; before the history has loaded the + // identity stays title-only rather than claiming zero runs. Measured before + // the row badges below so the peek never pays for the unshown fold. + if (covered) { + val stats = remember(runsState.data, now) { + listStatLines(runsState.data?.runs, now) + } + PaneIdentity( + title = "Pipelines", + stats = stats, + modifier = modifier.fillMaxSize(), + ) + return + } + // The history is folded to one latest run per pipeline once, feeding both the // row badges and the "most recent run" ordering rather than folding twice. val latestRuns = remember(runsState.data) { @@ -102,18 +139,6 @@ fun PipelineListScreen( query = "" } - // A covered pane shows its compact identity only; the search field and list - // must never be drawn squeezed into the peek strip. - if (covered) { - val count = state.data?.size ?: 0 - PaneIdentity( - title = "Pipelines", - subtitle = if (count > 0) "$count on this server" else null, - modifier = modifier.fillMaxSize(), - ) - return - } - Scaffold( modifier = modifier, contentWindowInsets = paneSafeArea(), @@ -189,6 +214,11 @@ fun PipelineListScreen( null }, emptyActionLabel = if (items.isEmpty() && all.isNotEmpty()) "Clear filters" else null, + // Before the first load this frame is both data-less and not + // in flight; without [loaded] it would render the "no + // pipelines are defined" empty message against a server that + // has not answered yet. + loaded = state.loaded, ), ) { phase -> when (phase) { @@ -199,19 +229,25 @@ fun PipelineListScreen( actionLabel = phase.actionLabel, onAction = if (phase.actionLabel != null) onClearFilters else null, ) - LoadPhase.Content -> LazyColumn( - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(vertical = SPACING_S), - ) { - items(items, key = { it.id }) { pipeline -> - PipelineRow( - pipeline = pipeline, - selected = pipeline.id == selectedId, - badge = badges[pipeline.id], - runsKnown = runsKnown, - onClick = { onOpen(pipeline.id, pipeline.version) }, - modifier = animateListItem(), - ) + LoadPhase.Content -> { + // Restores the saved position (clamped to the current, + // possibly shrunken, list) without fighting a later scroll. + RestoreListScroll(listState, items.size) + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(vertical = SPACING_S), + ) { + items(items, key = { it.id }) { pipeline -> + PipelineRow( + pipeline = pipeline, + selected = pipeline.id == selectedId, + badge = badges[pipeline.id], + runsKnown = runsKnown, + onClick = { onOpen(pipeline.id, pipeline.version) }, + modifier = animateListItem(), + ) + } } } } 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 d6b1ef00..6e55ae65 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 @@ -44,6 +44,7 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.delay import kotlinx.serialization.json.JsonElement +import java.time.OffsetDateTime import net.awan.pipelines.data.ErrorMessages import net.awan.pipelines.data.protocol.RunDetail import net.awan.pipelines.data.protocol.RunGraphState @@ -69,13 +70,14 @@ import net.awan.pipelines.ui.components.clampTabIndex import net.awan.pipelines.ui.components.collapsibleSection import net.awan.pipelines.ui.components.detailLoadPhase import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.rememberLiveNowMillis import net.awan.pipelines.ui.components.rememberPaneContent import net.awan.pipelines.ui.components.rememberSectionExpansion import net.awan.pipelines.ui.components.runDetailTabs import net.awan.pipelines.ui.components.runStateIcon import net.awan.pipelines.ui.components.runStateOf import net.awan.pipelines.ui.displayText -import net.awan.pipelines.ui.formatDuration +import net.awan.pipelines.ui.runDurationText import net.awan.pipelines.ui.graph.ArtifactGallery import net.awan.pipelines.ui.graph.ArtifactSelection import net.awan.pipelines.ui.graph.ArtifactSelectionScaffold @@ -108,6 +110,7 @@ fun RunDetailScreen( covered: Boolean = false, ) { val state by vm.runDetail.collectAsStateWithLifecycle() + val runsState by vm.runs.collectAsStateWithLifecycle() val evidenceState by vm.evidence.collectAsStateWithLifecycle() val configuredServerUrl by vm.configuredServerUrl.collectAsStateWithLifecycle() var confirmCancel by remember { mutableStateOf(false) } @@ -156,11 +159,20 @@ fun RunDetailScreen( val summaryTab = runDetailTabs.getOrNull(clampTabIndex(selectedSection, runDetailTabs.size))?.key // A covered pane shows its compact identity only; the tab rail, timeline and - // graphs must never be drawn squeezed into the peek strip. + // graphs must never be drawn squeezed into the peek strip. The run belongs to + // a pipeline, so its identity carries that pipeline's statistics from the run + // history (counts, last run, average) once the history is in hand; until the + // run (and so its pipeline) has loaded the identity stays title-only rather + // than showing the server-wide summary as if it were this run's pipeline. if (covered) { + val now = remember { OffsetDateTime.now() } + val pipelineId = run?.pipelineId + val stats = remember(runsState.data, pipelineId, now) { + pipelineStatLines(runsState.data?.runs, pipelineId, now) + } PaneIdentity( title = run?.name ?: "Run", - subtitle = run?.status?.takeIf { it.isNotBlank() }, + stats = stats, modifier = modifier.fillMaxSize(), ) return @@ -408,7 +420,7 @@ private fun RunSummaryTab( KeyValueRow("Content hash", run.contentHash, monospace = true) KeyValueRow("Started", run.createdAt) KeyValueRow("Finished", run.finishedAt) - KeyValueRow("Duration", formatDuration(run.createdAt, run.finishedAt) ?: "") + RunDurationRow(run) KeyValueRow("Retry of", if (run.retryOf > 0) "run ${run.retryOf}" else "") CodeBlock("Diagnostic", run.diagnostic, Modifier.padding(top = SPACING_S)) } @@ -417,6 +429,20 @@ private fun RunSummaryTab( } } +/** + * The run summary's Duration row. A running run's value is live: the shared + * per-second clock is read here, in the row itself, so the tick recomposes only + * this row and never the artifacts gallery or the rest of the summary. The value + * is derived from the server's start timestamp (re-read on resume, so it stays + * correct after a reconnect) and is never frozen at load; a finished run shows + * its stored total duration. + */ +@Composable +private fun RunDurationRow(run: RunDetail) { + val nowMillis = rememberLiveNowMillis(run.executing) + KeyValueRow("Duration", runDurationText(run.createdAt, run.finishedAt, run.executing, nowMillis) ?: "") +} + /** * The graph tab on its own: the full-height [WorkflowGraph] panel with its Fit * and expand controls, given the whole content area. The tab's single LazyColumn 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 f6107d52..e04afe2b 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 @@ -15,7 +15,7 @@ import androidx.compose.foundation.layout.only 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.lazy.LazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Refresh @@ -56,6 +56,7 @@ import net.awan.pipelines.ui.components.ListRow import net.awan.pipelines.ui.components.LoadPhase import net.awan.pipelines.ui.components.LoadingState import net.awan.pipelines.ui.components.PaneIdentity +import net.awan.pipelines.ui.components.RestoreListScroll import net.awan.pipelines.ui.components.RunState import net.awan.pipelines.ui.components.RunStatusChip import net.awan.pipelines.ui.components.RunStatusIcon @@ -64,9 +65,11 @@ import net.awan.pipelines.ui.components.StateCrossfade import net.awan.pipelines.ui.components.animateListItem import net.awan.pipelines.ui.components.listLoadPhase import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.rememberLiveNowMillis 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.runDurationText import net.awan.pipelines.ui.theme.ICON_LIST_DP import net.awan.pipelines.ui.theme.ICON_STATUS_DP import net.awan.pipelines.ui.theme.PipelinesTextStyles @@ -86,6 +89,7 @@ fun RunHistoryScreen( filterPipelineId: Long? = null, selectedRunId: Long? = null, covered: Boolean = false, + listState: LazyListState, ) { val state by vm.runs.collectAsStateWithLifecycle() val sortKey by vm.runSort.collectAsStateWithLifecycle() @@ -107,13 +111,25 @@ fun RunHistoryScreen( pipelineFilterOptions(state.data?.runs.orEmpty()) } + // [listState] is owned by the destination, above the panes: a covered pane is a + // different composition (its compact identity is drawn in a strip), so a state + // held here would be discarded and reset the scroll when a detail closes. + // [RestoreListScroll] clamps it when the history changed underneath. + // A covered pane shows its compact identity only; the usage block, sticky day - // headers and run rows must never be drawn squeezed into the peek strip. + // headers and run rows must never be drawn squeezed into the peek strip. Its + // statistics are the history's status counts and most recent run, folded + // once; a history scoped to one pipeline shows that pipeline's own numbers. if (covered) { - val count = state.data?.runs?.size ?: 0 + val now = remember { OffsetDateTime.now() } + val stats = remember(state.data, filterPipelineId, now) { + val pipelineId = filterPipelineId + if (pipelineId == null) listStatLines(state.data?.runs, now) + else pipelineStatLines(state.data?.runs, pipelineId, now) + } PaneIdentity( title = if (filterPipelineId == null) "Runs" else "Runs for this pipeline", - subtitle = if (count > 0) "$count recorded" else null, + stats = stats, modifier = modifier.fillMaxSize(), ) return @@ -159,6 +175,11 @@ fun RunHistoryScreen( // usage block and shows the "no runs" line inside the list, where // the item animation fades it in and out. emptyMessage = null, + // Before the first history load this frame has no data and no + // in-flight refresh yet; without [loaded] it would read as an + // empty list and the restore below would clamp a restored + // position to the top of the transient one-item list. + loaded = state.loaded, ), modifier = Modifier.fillMaxSize(), ) { phase -> @@ -179,6 +200,7 @@ fun RunHistoryScreen( error = state.error, onOpenRun = onOpenRun, onClearFilters = onClearFilters, + listState = listState, modifier = Modifier.padding(padding), ) } @@ -247,6 +269,7 @@ private fun RunHistoryContent( error: String?, onOpenRun: (Long) -> Unit, onClearFilters: () -> Unit, + listState: LazyListState, modifier: Modifier = Modifier, ) { val zone = ZoneId.systemDefault() @@ -265,59 +288,144 @@ private fun RunHistoryContent( groupRunsByDay(matched, today, zone, runComparator(sort)) } + // The list body built once, in layout order. It is the single source of both + // the LazyColumn's items and their count, so a restored position is clamped to + // the list the column actually draws rather than to a hand-maintained replica + // of it (see [RestoreListScroll]). + val entries = remember(usage, scoped, matched, groups, error) { + runListEntries( + usage = usage, + nothingRecorded = scoped.isEmpty(), + nothingMatched = matched.isEmpty(), + groups = groups, + error = error, + ) + } + RestoreListScroll(listState, entries.size) + + // One live clock for the whole list: it ticks only while a shown run is + // executing and the app is resumed, and each running row reads its elapsed + // from it rather than starting a coroutine of its own. Elapsed is derived + // from the server's start timestamp, never from when the list loaded, so it + // is still correct after a reconnect; a finished history never ticks. + val live = remember(matched) { matched.any { it.executing } } + val nowMillis = rememberLiveNowMillis(live) + LazyColumn( + state = listState, modifier = modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = SPACING_L), ) { - if (usage != null) { - item(key = "usage") { - UsageMetrics(usage, Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S)) - } - } - if (scoped.isEmpty()) { - // Nothing exists at all: no filter could reveal a run, so there is no - // clear action. - item(key = "runs-empty") { - EmptyState( - "No runs have been recorded yet.", - modifier = animateListItem(), - ) - } - } else if (matched.isEmpty()) { - // Runs exist but every one is filtered out: distinguish this from the - // "nothing exists" case and offer the one clear action. - item(key = "runs-filtered-empty") { - EmptyState( - message = "No runs match the current filters.", - actionLabel = "Clear filters", - onAction = onClearFilters, - modifier = animateListItem(), - ) - } - } else { - groups.forEach { group -> - stickyHeader(key = "day-${group.label}") { DayHeader(group.label) } - items(group.runs, key = { "run-${it.id}" }) { run -> - RunRow( - run = run, - selected = run.id == selectedRunId, - onClick = { onOpenRun(run.id) }, + entries.forEach { entry -> + when (entry) { + is RunListEntry.Usage -> item(key = entry.key) { + UsageMetrics( + entry.usage, + Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), + ) + } + is RunListEntry.Empty -> item(key = entry.key) { + EmptyState( + message = entry.message, + actionLabel = entry.actionLabel, + // Only the filtered-empty case offers a clear action, which + // [runListEntries] encodes as a non-null label. + onAction = if (entry.actionLabel != null) onClearFilters else null, modifier = animateListItem(), ) } + is RunListEntry.Day -> stickyHeader(key = entry.key) { DayHeader(entry.label) } + is RunListEntry.Run -> item(key = entry.key) { + RunRow( + run = entry.run, + selected = entry.run.id == selectedRunId, + nowMillis = nowMillis, + onClick = { onOpenRun(entry.run.id) }, + modifier = animateListItem(), + ) + } + is RunListEntry.Error -> item(key = entry.key) { + Text( + entry.message, + color = MaterialTheme.colorScheme.error, + style = pipelinesText().body, + modifier = animateListItem(Modifier.padding(SPACING_L)), + ) + } } } - if (error != null) { - item(key = "runs-error") { - Text( - error, - color = MaterialTheme.colorScheme.error, - style = pipelinesText().body, - modifier = animateListItem(Modifier.padding(SPACING_L)), - ) - } + } +} + +/** + * One slot the runs list draws, in layout order: the usage block, the single + * empty-or-grouped body and the optional inline error row. [key] is the stable + * LazyColumn key the list has always used. [runListEntries] builds the whole + * list and both the column and the clamp consume it, so the count a restored + * position is clamped against can never drift from the items the column draws. + */ +internal sealed interface RunListEntry { + val key: String + + /** The usage aggregates block, present only when the history has a summary. */ + data class Usage(val usage: UsageStats) : RunListEntry { + override val key: String get() = "usage" + } + + /** + * The single "nothing recorded"/"nothing matches" line. [actionLabel] is + * non-null exactly when filters hid existing runs, the one case with a clear + * action. + */ + data class Empty(val message: String, val actionLabel: String?) : RunListEntry { + override val key: String + get() = if (actionLabel != null) "runs-filtered-empty" else "runs-empty" + } + + /** A sticky day header above a group's runs. */ + data class Day(val label: String) : RunListEntry { + override val key: String get() = "day-$label" + } + + /** One run row. */ + data class Run(val run: RunSummary) : RunListEntry { + override val key: String get() = "run-${run.id}" + } + + /** The last load's error, kept inline under the stale rows. */ + data class Error(val message: String) : RunListEntry { + override val key: String get() = "runs-error" + } +} + +/** + * The runs list's slots in layout order: the usage block when there is one, then + * either the single empty line (nothing recorded, or nothing matching the + * filters) or the day groups, then the inline error row when the last load + * failed over stale data. Pure and single-sourced with the LazyColumn, so its + * size is exactly the list's item count. + */ +internal fun runListEntries( + usage: UsageStats?, + nothingRecorded: Boolean, + nothingMatched: Boolean, + groups: List, + error: String?, +): List = buildList { + if (usage != null) add(RunListEntry.Usage(usage)) + when { + // Nothing exists at all: no filter could reveal a run, so there is no + // clear action. + nothingRecorded -> add(RunListEntry.Empty("No runs have been recorded yet.", null)) + // Runs exist but every one is filtered out: distinguish this from the + // "nothing exists" case and offer the one clear action. + nothingMatched -> add(RunListEntry.Empty("No runs match the current filters.", "Clear filters")) + else -> groups.forEach { group -> + add(RunListEntry.Day(group.label)) + group.runs.forEach { add(RunListEntry.Run(it)) } } } + if (error != null) add(RunListEntry.Error(error)) } /** A sticky day header ("Today"/"Yesterday"/date) above each group of runs. */ @@ -378,13 +486,15 @@ private fun Metric(label: String, value: String, color: Color, text: PipelinesTe /** * One run as a row of the shared real list: a leading status glyph, the run name * as the title with its version chip, and a secondary line carrying the status - * chip, progress and id/start/duration. The row is selected when its run is the - * one open in the detail pane. + * chip, progress and id/time. The row is selected when its run is the one open in + * the detail pane. [nowMillis] is the shared live clock, read only by a running + * row so its elapsed value advances. */ @Composable private fun RunRow( run: RunSummary, selected: Boolean, + nowMillis: Long, onClick: () -> Unit, modifier: Modifier = Modifier, ) { @@ -429,7 +539,7 @@ private fun RunRow( Text(progressText(run), style = text.meta, maxLines = 1, overflow = TextOverflow.Ellipsis) } - Text(metaText(run), style = text.meta, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(metaText(run, nowMillis), style = text.meta, maxLines = 1, overflow = TextOverflow.Ellipsis) if (run.diagnostic.isNotBlank()) { Text( @@ -466,13 +576,20 @@ private fun progressText(run: RunSummary): String = buildString { 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 { +/** + * Run id and its time. A running run shows how long it has taken so far: a live + * elapsed value computed from its server start timestamp against [nowMillis], + * replacing the start time and advancing as the shared clock ticks. A finished + * run keeps its start time and total duration. + */ +private fun metaText(run: RunSummary, nowMillis: Long): 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") + if (run.executing) { + runDurationText(run.createdAt, run.finishedAt, executing = true, nowMillis)?.let { append(" · $it") } + } else { + formatRunStart(run.createdAt)?.let { append(" · $it") } + runDurationText(run.createdAt, run.finishedAt, executing = false, nowMillis)?.let { append(" · $it") } + } } private fun formatRunStart(createdAt: String): String? { 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 index faa52a29..c1d49460 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/FormatTest.kt @@ -46,6 +46,36 @@ class FormatTest { assertNull(secondsSince("not a timestamp", startMillis)) } + @Test + fun runDurationTextIsLiveElapsedWhileRunningAndStoredDurationOnceFinished() { + val start = "2026-10-15T02:00:00Z" + val startMillis = parseInstant(start)!!.toInstant().toEpochMilli() + // A run that just started reads 0s, not a blank or a fabricated value. + assertEquals("0s", runDurationText(start, "", executing = true, nowMillis = startMillis)) + // Minute boundary: 59s is still seconds, 60s rolls over to a minute. + assertEquals("59s", runDurationText(start, "", executing = true, nowMillis = startMillis + 59_000)) + assertEquals("1m 0s", runDurationText(start, "", executing = true, nowMillis = startMillis + 60_000)) + // Hour boundary: 3599s is still minutes and seconds, 3600s rolls to hours. + assertEquals("59m 59s", runDurationText(start, "", executing = true, nowMillis = startMillis + 3_599_000)) + assertEquals("1h 0m", runDurationText(start, "", executing = true, nowMillis = startMillis + 3_600_000)) + // A missing start is "no value": never a fabricated 0s and never a crash. + assertNull(runDurationText("", "", executing = true, nowMillis = startMillis)) + // A future start (clock skew) clamps to 0s rather than going negative. + assertEquals("0s", runDurationText(start, "", executing = true, nowMillis = startMillis - 5_000)) + // A finished run ignores the clock and keeps its stored total duration. + assertEquals( + "2m 5s", + runDurationText( + start, + "2026-10-15T02:02:05Z", + executing = false, + nowMillis = startMillis + 9_999_000, + ), + ) + // A finished run with no end timestamp has no duration, not an elapsed. + assertNull(runDurationText(start, "", executing = false, nowMillis = startMillis + 9_999_000)) + } + @Test fun fileChangesSummaryOmitsBlankParts() { assertEquals("", fileChangesSummary(StageFileChanges())) diff --git a/android/app/src/test/java/net/awan/pipelines/ui/screens/PipelineLastRunTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/screens/PipelineLastRunTest.kt index 0ae593a5..e0a84f6a 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/screens/PipelineLastRunTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/screens/PipelineLastRunTest.kt @@ -18,12 +18,14 @@ class PipelineLastRunTest { createdAt: String, finishedAt: String = createdAt, status: String = "succeeded", + executing: Boolean = false, ) = RunSummary( id = id, pipelineId = pipelineId, createdAt = createdAt, finishedAt = finishedAt, status = status, + executing = executing, ) @Test @@ -96,10 +98,30 @@ class PipelineLastRunTest { } @Test - fun metaLineOmitsAMissingDuration() { - // A running run has no finished_at, so the duration fragment is dropped. + fun metaLineShowsTheLiveElapsedOfARunningRun() { + // A running run has no finished_at, so its time fragment is the elapsed + // from its start to the anchor, recomputed as the shared clock advances. val badge = pipelineRunBadges( - listOf(run(42, 10, "2026-10-16T11:00:00Z", finishedAt = "", status = "running")), + listOf( + run( + 42, + 10, + "2026-10-16T11:57:30Z", + finishedAt = "", + status = "running", + executing = true, + ), + ), + now, + ).getValue(10L) + assertEquals("2m ago · 2m 30s · run 42", badge.metaLine()) + } + + @Test + fun metaLineOmitsAMissingDuration() { + // A finished run with no end timestamp has no duration fragment. + val badge = pipelineRunBadges( + listOf(run(42, 10, "2026-10-16T11:00:00Z", finishedAt = "")), now, ).getValue(10L) assertEquals("1h ago · run 42", badge.metaLine())