From 9f7c4a8c77ac9f2f1b3d9683d9206d9b56f32224 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 17 Oct 2026 17:10:10 +0100 Subject: [PATCH] Split the run view and the app shell into files by concern Pure move of two oversized Android UI files into smaller files by concern, with no behaviour change: - RunDetailScreen.kt 847 -> 342: the run header and ConfirmDialog stay; the five run tabs move out to RunSummaryTab.kt, RunGraphTab.kt, RunFieldSectionsTab.kt, RunEvidenceTab.kt and RunTimelineTab.kt. - PipelinesApp.kt 1003 -> 405: the shell/scaffold, NavHost and hoisted state stay; the destination pill and the three destinations move out to DestinationBar.kt, PipelineDestination.kt, RunsDestination.kt and TemplatesDestination.kt. Same package, same composable names and signatures, same call graph and rendering. The only textual edits are eleven private -> internal visibility widenings on declarations now called across the new file boundaries. No strings, colours, spacing tokens, tests or entry points changed. Verified with `gradle :app:assembleDebug --no-daemon` (BUILD SUCCESSFUL) and `gradle :app:testDebugUnitTest --no-daemon` (545 tests, 0 failures, 0 errors, 0 skipped). Checked packaging that could go stale with this change: - internal/author/skill/references/ (the packaged authoring skill references): none mention these files or any Android UI symbol, so nothing to update. - packaged templates: not touched and none reference the split files. - android/README.md: its historical prose still names some now-stale file locations; left unedited because the shared documentation is folded by a single writer and this commit's job is the move itself. --- .../net/awan/pipelines/ui/DestinationBar.kt | 294 +++++++++ .../awan/pipelines/ui/PipelineDestination.kt | 141 ++++ .../net/awan/pipelines/ui/PipelinesApp.kt | 604 +----------------- .../net/awan/pipelines/ui/RunsDestination.kt | 150 +++++ .../awan/pipelines/ui/TemplatesDestination.kt | 70 ++ .../pipelines/ui/screens/RunDetailScreen.kt | 507 +-------------- .../pipelines/ui/screens/RunEvidenceTab.kt | 135 ++++ .../ui/screens/RunFieldSectionsTab.kt | 74 +++ .../awan/pipelines/ui/screens/RunGraphTab.kt | 70 ++ .../pipelines/ui/screens/RunSummaryTab.kt | 164 +++++ .../pipelines/ui/screens/RunTimelineTab.kt | 155 +++++ 11 files changed, 1257 insertions(+), 1107 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/DestinationBar.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/PipelineDestination.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/RunsDestination.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/TemplatesDestination.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/RunEvidenceTab.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/RunFieldSectionsTab.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/RunGraphTab.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/RunTimelineTab.kt diff --git a/android/app/src/main/java/net/awan/pipelines/ui/DestinationBar.kt b/android/app/src/main/java/net/awan/pipelines/ui/DestinationBar.kt new file mode 100644 index 00000000..32188ba1 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/DestinationBar.kt @@ -0,0 +1,294 @@ +package net.awan.pipelines.ui + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.SizeTransform +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsFocusedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Search +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +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.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import net.awan.pipelines.ui.components.MotionStandard +import net.awan.pipelines.ui.components.spec +import net.awan.pipelines.ui.theme.SPACING_M +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XS + +/** + * The horizontal offset of the pill's travelling selection indicator for the + * destination at [index]: the pill's inner padding plus [index] item slots + * ([itemSize] + [gap]). Pure and in one place, so the indicator lines up exactly + * with the icon it selects and the geometry is unit-testable without a device. + * A missing selection (-1) pins to the first slot and the caller draws nothing. + */ +internal fun destinationIndicatorOffsetDp(index: Int, itemSize: Dp, gap: Dp): Dp = + gap + (itemSize + gap) * index.coerceAtLeast(0) + +/** + * The bottom container: the destination pill that morphs into the omni-search + * field. It is one [Surface] so the morph reads as the same container changing + * role, not two surfaces swapping. Neither opening nor dismissing navigates, so + * the destination the pill had selected is untouched and the reverse restores + * exactly that pill. + */ +@Composable +internal fun DestinationBar( + destinations: List, + currentRoute: String?, + state: OmniSearchState, + onSelect: (TopDestination) -> Unit, + onOpenSearch: () -> Unit, + onDismissSearch: () -> Unit, + onQueryChange: (String) -> Unit, + onFocusChange: (Boolean) -> Unit, + onSubmitSearch: () -> Unit, + modifier: Modifier = Modifier, +) { + val scheme = MaterialTheme.colorScheme + Surface( + modifier = modifier, + shape = RoundedCornerShape(50), + color = scheme.surfaceContainerHigh, + tonalElevation = 3.dp, + shadowElevation = 6.dp, + ) { + // The icons fade out while the field fades in, and the container takes the + // new content's size. The field fills the width the caller's inset padding + // leaves, so the grown size derives from that plus the field's own layout, + // and the position from the container's right-anchored alignment; no pill + // size is copied. + AnimatedContent( + targetState = state.open, + transitionSpec = { + (fadeIn(animationSpec = MotionStandard.spec()) togetherWith + fadeOut(animationSpec = MotionStandard.spec())) + .using(SizeTransform(clip = false) { _, _ -> MotionStandard.spec() }) + }, + contentAlignment = Alignment.CenterEnd, + label = "omni-search-morph", + ) { open -> + if (open) { + OmniSearchField( + query = state.query, + onQueryChange = onQueryChange, + onFocusChange = onFocusChange, + onSubmit = onSubmitSearch, + onDismiss = onDismissSearch, + ) + } else { + DestinationIcons( + destinations = destinations, + currentRoute = currentRoute, + onSelect = onSelect, + onOpenSearch = onOpenSearch, + ) + } + } + } +} + +/** + * The resting destination pill: the Pipelines/Runs/Settings destinations plus the + * omni-search entry point, each a [DESTINATION_ITEM_SIZE] touch target. Selection + * is one tonal indicator that travels between the icons ([MotionStandard], so it + * slides rather than jumping) plus the icon's fading tint, while the `Role.Tab` + * selected accessibility state is never conveyed by colour alone. Tapping a + * destination switches through the caller's existing navigate/popUpTo logic; the + * icons own the taps, so a tap registers even while the indicator is still + * travelling, and the settled pill equals the old one. + * + * The fourth control (Search) does not navigate: it is a plain [Role.Button] + * action that morphs this container into the search field. + */ +@Composable +private fun DestinationIcons( + destinations: List, + currentRoute: String?, + onSelect: (TopDestination) -> Unit, + onOpenSearch: () -> Unit, +) { + val scheme = MaterialTheme.colorScheme + val selectedIndex = destinations.indexOfFirst { destinationSelected(currentRoute, it.route) } + // One long-lived animator, so a rapid run of taps only retargets it (never + // half-way) and the first composition starts already settled at the target. + val indicatorOffset by animateDpAsState( + targetValue = destinationIndicatorOffsetDp( + selectedIndex, + DESTINATION_ITEM_SIZE, + DESTINATION_ITEM_GAP, + ), + animationSpec = MotionStandard.spec(), + label = "destination-indicator", + ) + Box { + // Drawn behind the icons, so the highlight slides under whichever is + // selected; before the nav graph settles there is no selection and + // nothing is drawn. + if (selectedIndex >= 0) { + Box( + Modifier + .offset(x = indicatorOffset, y = DESTINATION_ITEM_GAP) + .size(DESTINATION_ITEM_SIZE) + .clip(CircleShape) + .background(scheme.secondaryContainer), + ) + } + Row( + modifier = Modifier.padding(DESTINATION_ITEM_GAP), + horizontalArrangement = Arrangement.spacedBy(DESTINATION_ITEM_GAP), + verticalAlignment = Alignment.CenterVertically, + ) { + destinations.forEach { destination -> + val selected = destinationSelected(currentRoute, destination.route) + // The glyph tint fades in step with the travelling indicator. + val iconColor by animateColorAsState( + targetValue = if (selected) scheme.onSecondaryContainer else scheme.onSurfaceVariant, + animationSpec = MotionStandard.spec(), + label = "destination-icon", + ) + Box( + modifier = Modifier + .size(DESTINATION_ITEM_SIZE) + .clip(CircleShape) + .selectable( + selected = selected, + role = Role.Tab, + onClick = { onSelect(destination) }, + ), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = destination.icon, + contentDescription = destination.label, + tint = iconColor, + ) + } + } + Box( + modifier = Modifier + .size(DESTINATION_ITEM_SIZE) + .clip(CircleShape) + .clickable( + role = Role.Button, + onClickLabel = "Search", + onClick = onOpenSearch, + ), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Default.Search, + contentDescription = "Search", + tint = scheme.onSurfaceVariant, + ) + } + } + } +} + +/** + * The search field the pill morphs into: a single-line input focused as it opens + * (so the keyboard is up), a leading search glyph and a trailing close action. It + * reports focus changes into [OmniSearchState] and every keystroke to the caller, + * which debounces the query and drives the results panel above it. + */ +@Composable +private fun OmniSearchField( + query: String, + onQueryChange: (String) -> Unit, + onFocusChange: (Boolean) -> Unit, + onSubmit: () -> Unit, + onDismiss: () -> Unit, +) { + val scheme = MaterialTheme.colorScheme + val interaction = remember { MutableInteractionSource() } + val focused by interaction.collectIsFocusedAsState() + val focusRequester = remember { FocusRequester() } + LaunchedEffect(focused) { onFocusChange(focused) } + // Focus as the field opens so the keyboard is up; an open field restored after + // a process death re-focuses the same way. + LaunchedEffect(Unit) { focusRequester.requestFocus() } + + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = SPACING_M, vertical = SPACING_XS), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + imageVector = Icons.Default.Search, + contentDescription = null, + tint = scheme.onSurfaceVariant, + ) + BasicTextField( + value = query, + onValueChange = onQueryChange, + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge.copy(color = scheme.onSurface), + cursorBrush = SolidColor(scheme.primary), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { onSubmit() }), + interactionSource = interaction, + modifier = Modifier + .weight(1f) + .padding(horizontal = SPACING_S) + .focusRequester(focusRequester), + decorationBox = { innerTextField -> + if (query.isEmpty()) { + Text( + text = "Search pipelines, runs and artifacts", + style = MaterialTheme.typography.bodyLarge, + color = scheme.onSurfaceVariant, + ) + } + innerTextField() + }, + ) + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Close search") + } + } +} + +/** The destination pill's icon touch target and the size of its selection indicator. */ +internal val DESTINATION_ITEM_SIZE = 48.dp + +/** The gap between destinations, also the pill's inner padding. */ +internal val DESTINATION_ITEM_GAP = 4.dp diff --git a/android/app/src/main/java/net/awan/pipelines/ui/PipelineDestination.kt b/android/app/src/main/java/net/awan/pipelines/ui/PipelineDestination.kt new file mode 100644 index 00000000..74aaffd1 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/PipelineDestination.kt @@ -0,0 +1,141 @@ +package net.awan.pipelines.ui + +import androidx.activity.compose.PredictiveBackHandler +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountTree +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import kotlinx.coroutines.flow.collect +import net.awan.pipelines.ui.components.SlidingPaneStack +import net.awan.pipelines.ui.components.clampTabIndex +import net.awan.pipelines.ui.components.pipelineDetailTabs +import net.awan.pipelines.ui.components.rememberPaneContent +import net.awan.pipelines.ui.graph.PipelineStagePane +import net.awan.pipelines.ui.screens.PipelineDetailScreen +import net.awan.pipelines.ui.screens.PipelineListScreen + +/** + * The Pipelines destination: one sliding pane stack whose pane 0 is the pipeline + * list, pane 1 is the selected pipeline (Summary/Graph/Source) and pane 2 is the + * stage pane for a graph node. The saved [PaneSelection] survives rotation, + * configuration change and process death. Back (gesture/button) and the nearest + * peek tap both step back exactly one level via [backFrom]; tapping a lower peek + * closes every pane to its right via [popTo]. + */ +@Composable +internal fun PipelineDestination( + vm: AppViewModel, + wide: Boolean, + selection: PaneSelection, + onSelectionChange: (PaneSelection) -> Unit, + listState: LazyListState, + onOpenRun: (Long) -> Unit, +) { + val depth = selection.depth + val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) } + + PredictiveBackHandler(enabled = depth >= 1) { progress -> + // Consume the gesture; on completion perform exactly one Back step. + progress.collect { } + onBack() + } + + SlidingPaneStack( + depth = depth, + wide = wide, + onPopTo = { level -> onSelectionChange(popTo(selection, level)) }, + compactLabel = "Pipelines", + compactIcon = Icons.Filled.AccountTree, + // Every covered pane in this stack (the list, or a pipeline's detail) carries + // a statistics block, so the region is sized for it and a single covered + // pane can show the last-run and average lines rather than only counts. + compactStats = true, + backContentDescription = { level -> + when (level) { + 0 -> "Back to pipelines" + 1 -> "Back to pipeline" + else -> "Back to stage" + } + }, + pane = { level, covered, paneModifier -> + when (level) { + 0 -> PipelineListScreen( + vm = vm, + onOpen = { id, version -> + onSelectionChange(PaneSelection(MasterPane.Detail, id, version)) + }, + modifier = paneModifier, + selectedId = selection.itemId.takeIf { depth >= 1 }, + covered = covered, + listState = listState, + ) + 1 -> rememberPaneContent( + selection.itemId.takeIf { it != 0L }?.let { + Triple(it, selection.itemVersion, selection.sectionIndex) + }, + )?.let { (itemId, version, sectionIndex) -> + PipelineDetailScreen( + vm = vm, + pipelineId = itemId, + version = version, + onBack = onBack, + onOpenRun = onOpenRun, + selectedSection = clampTabIndex(sectionIndex, pipelineDetailTabs.size), + onSelectSection = { onSelectionChange(selection.copy(sectionIndex = it)) }, + modifier = paneModifier, + wide = wide, + onOpenStage = { key -> + onSelectionChange( + selection.copy(pane = MasterPane.Stage, stageKey = key, stageVisit = 0), + ) + }, + covered = covered, + ) + } + 2 -> rememberPaneContent( + selection.stageKey?.let { + Triple(selection.itemId, selection.itemVersion, it) + }, + )?.let { (itemId, version, key) -> + PipelineStagePane( + vm = vm, + pipelineId = itemId, + version = version, + stageKey = key, + openSection = null, + onOpenSection = { sectionKey -> + onSelectionChange( + selection.copy(pane = MasterPane.Section, sectionKey = sectionKey), + ) + }, + onBack = onBack, + wide = wide, + modifier = paneModifier, + covered = covered, + ) + } + 3 -> rememberPaneContent( + selection.sectionKey?.let { + Triple(selection.itemId, it, selection.stageKey) + }, + )?.let { (itemId, sectionKey, key) -> + // A closing section pane keeps the identity that opened it, so + // it renders its content until it is fully off-screen. + PipelineStagePane( + vm = vm, + pipelineId = itemId, + version = selection.itemVersion, + stageKey = key.orEmpty(), + openSection = sectionKey, + onOpenSection = {}, + onBack = onBack, + wide = wide, + modifier = paneModifier, + covered = covered, + ) + } + } + }, + ) +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt index df7dce80..22b680c7 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt @@ -1,54 +1,30 @@ package net.awan.pipelines.ui import androidx.activity.compose.BackHandler -import androidx.activity.compose.PredictiveBackHandler -import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.SizeTransform -import androidx.compose.animation.animateColorAsState -import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut -import androidx.compose.animation.togetherWith import androidx.compose.foundation.background -import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures -import androidx.compose.foundation.interaction.MutableInteractionSource -import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.foundation.selection.selectable -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.BasicTextField -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.Chat import androidx.compose.material.icons.filled.AccountTree -import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.History -import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -58,15 +34,9 @@ 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.draw.clip -import androidx.compose.ui.focus.FocusRequester -import androidx.compose.ui.focus.focusRequester -import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalConfiguration -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle @@ -74,36 +44,20 @@ import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController -import kotlinx.coroutines.flow.collect import net.awan.pipelines.data.protocol.SearchResult import net.awan.pipelines.data.transport.ConnectionState +import net.awan.pipelines.ui.chat.ChatScreen import net.awan.pipelines.ui.components.AttentionIndicator import net.awan.pipelines.ui.components.AttentionSheet import net.awan.pipelines.ui.components.ConnectionBanner import net.awan.pipelines.ui.components.MotionStandard -import net.awan.pipelines.ui.components.SlidingPaneStack -import net.awan.pipelines.ui.components.clampTabIndex import net.awan.pipelines.ui.components.paneSafeArea -import net.awan.pipelines.ui.components.pipelineDetailTabs -import net.awan.pipelines.ui.components.rememberPaneContent -import net.awan.pipelines.ui.components.runDetailTabs import net.awan.pipelines.ui.components.spec -import net.awan.pipelines.ui.graph.PipelineStagePane -import net.awan.pipelines.ui.graph.RunStagePane -import net.awan.pipelines.ui.screens.PipelineDetailScreen -import net.awan.pipelines.ui.screens.PipelineListScreen -import net.awan.pipelines.ui.screens.RunDetailScreen -import net.awan.pipelines.ui.screens.RunHistoryScreen import net.awan.pipelines.ui.screens.SettingsScreen -import net.awan.pipelines.ui.screens.TemplateDetailScreen -import net.awan.pipelines.ui.screens.TemplateGalleryScreen import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE -import net.awan.pipelines.ui.theme.SPACING_M import net.awan.pipelines.ui.theme.SPACING_S -import net.awan.pipelines.ui.theme.SPACING_XS -import net.awan.pipelines.ui.chat.ChatScreen -private data class TopDestination(val route: String, val label: String, val icon: ImageVector) +internal data class TopDestination(val route: String, val label: String, val icon: ImageVector) private val destinations = listOf( TopDestination("pipelines", "Pipelines", Icons.Default.AccountTree), @@ -126,7 +80,7 @@ internal fun destinationSelected(currentRoute: String?, route: String): Boolean * button and the system Back button/gesture all call through here, so a section * never disagrees with the pane. */ -private fun backFrom(selection: PaneSelection): PaneSelection = +internal fun backFrom(selection: PaneSelection): PaneSelection = when (val result = backStep(selection)) { is BackResult.Show -> result.selection BackResult.Exit -> selection @@ -422,327 +376,6 @@ fun PipelinesApp( /** How dark the scrim behind the open search field is. */ private const val SEARCH_SCRIM_ALPHA = 0.5f -/** - * The Pipelines destination: one sliding pane stack whose pane 0 is the pipeline - * list, pane 1 is the selected pipeline (Summary/Graph/Source) and pane 2 is the - * stage pane for a graph node. The saved [PaneSelection] survives rotation, - * configuration change and process death. Back (gesture/button) and the nearest - * peek tap both step back exactly one level via [backFrom]; tapping a lower peek - * closes every pane to its right via [popTo]. - */ -@Composable -private fun PipelineDestination( - vm: AppViewModel, - wide: Boolean, - selection: PaneSelection, - onSelectionChange: (PaneSelection) -> Unit, - listState: LazyListState, - onOpenRun: (Long) -> Unit, -) { - val depth = selection.depth - val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) } - - PredictiveBackHandler(enabled = depth >= 1) { progress -> - // Consume the gesture; on completion perform exactly one Back step. - progress.collect { } - onBack() - } - - SlidingPaneStack( - depth = depth, - wide = wide, - onPopTo = { level -> onSelectionChange(popTo(selection, level)) }, - compactLabel = "Pipelines", - compactIcon = Icons.Filled.AccountTree, - // Every covered pane in this stack (the list, or a pipeline's detail) carries - // a statistics block, so the region is sized for it and a single covered - // pane can show the last-run and average lines rather than only counts. - compactStats = true, - backContentDescription = { level -> - when (level) { - 0 -> "Back to pipelines" - 1 -> "Back to pipeline" - else -> "Back to stage" - } - }, - pane = { level, covered, paneModifier -> - when (level) { - 0 -> PipelineListScreen( - vm = vm, - onOpen = { id, version -> - onSelectionChange(PaneSelection(MasterPane.Detail, id, version)) - }, - modifier = paneModifier, - selectedId = selection.itemId.takeIf { depth >= 1 }, - covered = covered, - listState = listState, - ) - 1 -> rememberPaneContent( - selection.itemId.takeIf { it != 0L }?.let { - Triple(it, selection.itemVersion, selection.sectionIndex) - }, - )?.let { (itemId, version, sectionIndex) -> - PipelineDetailScreen( - vm = vm, - pipelineId = itemId, - version = version, - onBack = onBack, - onOpenRun = onOpenRun, - selectedSection = clampTabIndex(sectionIndex, pipelineDetailTabs.size), - onSelectSection = { onSelectionChange(selection.copy(sectionIndex = it)) }, - modifier = paneModifier, - wide = wide, - onOpenStage = { key -> - onSelectionChange( - selection.copy(pane = MasterPane.Stage, stageKey = key, stageVisit = 0), - ) - }, - covered = covered, - ) - } - 2 -> rememberPaneContent( - selection.stageKey?.let { - Triple(selection.itemId, selection.itemVersion, it) - }, - )?.let { (itemId, version, key) -> - PipelineStagePane( - vm = vm, - pipelineId = itemId, - version = version, - stageKey = key, - openSection = null, - onOpenSection = { sectionKey -> - onSelectionChange( - selection.copy(pane = MasterPane.Section, sectionKey = sectionKey), - ) - }, - onBack = onBack, - wide = wide, - modifier = paneModifier, - covered = covered, - ) - } - 3 -> rememberPaneContent( - selection.sectionKey?.let { - Triple(selection.itemId, it, selection.stageKey) - }, - )?.let { (itemId, sectionKey, key) -> - // A closing section pane keeps the identity that opened it, so - // it renders its content until it is fully off-screen. - PipelineStagePane( - vm = vm, - pipelineId = itemId, - version = selection.itemVersion, - stageKey = key.orEmpty(), - openSection = sectionKey, - onOpenSection = {}, - onBack = onBack, - wide = wide, - modifier = paneModifier, - covered = covered, - ) - } - } - }, - ) -} - -/** - * The Runs destination: the same shared pane stack with the run list, the - * selected run's tabs and the stage pane. Its selection is owned by - * [PipelinesApp] so the Pipelines detail can open a run it just started. - */ -@Composable -private fun RunsDestination( - vm: AppViewModel, - wide: Boolean, - selection: PaneSelection, - onSelectionChange: (PaneSelection) -> Unit, - pendingNav: SearchTarget.Run?, - onPendingNavResolved: () -> Unit, - listState: LazyListState, -) { - val depth = selection.depth - val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) } - - // A run search hit that names a recorded visit is applied once the run's steps - // have loaded: the visit's stage pane (or the matched section) replaces the - // plain run detail. A target for another run waits for its own detail. - val runState by vm.runDetail.collectAsStateWithLifecycle() - LaunchedEffect(pendingNav, runState.data) { - val target = pendingNav ?: return@LaunchedEffect - val run = runState.data ?: return@LaunchedEffect - if (run.id != target.runId) return@LaunchedEffect - onSelectionChange(resolveRunTarget(target, run.id, run.steps)) - onPendingNavResolved() - } - - PredictiveBackHandler(enabled = depth >= 1) { progress -> - progress.collect { } - onBack() - } - - SlidingPaneStack( - depth = depth, - wide = wide, - onPopTo = { level -> onSelectionChange(popTo(selection, level)) }, - compactLabel = "Runs", - compactIcon = Icons.Filled.History, - // Every covered pane in this stack (the runs list, or a run's detail) carries - // a statistics block, so the region is sized for it and the runs list's - // counts and most-recent run are actually shown rather than dropped by the - // title-only tier. - compactStats = true, - backContentDescription = { level -> - when (level) { - 0 -> "Back to runs" - 1 -> "Back to run" - else -> "Back to stage" - } - }, - pane = { level, covered, paneModifier -> - when (level) { - 0 -> RunHistoryScreen( - vm = vm, - onOpenRun = { runId -> onSelectionChange(PaneSelection(MasterPane.Detail, runId)) }, - modifier = paneModifier, - selectedRunId = selection.itemId.takeIf { depth >= 1 }, - covered = covered, - listState = listState, - ) - 1 -> rememberPaneContent( - selection.itemId.takeIf { it != 0L }?.let { it to selection.sectionIndex }, - )?.let { (itemId, sectionIndex) -> - RunDetailScreen( - vm = vm, - runId = itemId, - onBack = onBack, - selectedSection = clampTabIndex(sectionIndex, runDetailTabs.size), - onSelectSection = { onSelectionChange(selection.copy(sectionIndex = it)) }, - modifier = paneModifier, - wide = wide, - onOpenStage = { key, visit -> - onSelectionChange( - selection.copy(pane = MasterPane.Stage, stageKey = key, stageVisit = visit), - ) - }, - covered = covered, - ) - } - 2 -> rememberPaneContent( - selection.stageKey?.let { - Triple(selection.itemId, it, selection.stageVisit) - }, - )?.let { (itemId, key, visit) -> - RunStagePane( - vm = vm, - runId = itemId, - stageKey = key, - visitIndex = visit, - openSection = null, - onOpenSection = { sectionKey -> - onSelectionChange( - selection.copy(pane = MasterPane.Section, sectionKey = sectionKey), - ) - }, - onVisitChange = { onSelectionChange(selection.copy(stageVisit = it)) }, - onBack = onBack, - wide = wide, - modifier = paneModifier, - covered = covered, - ) - } - 3 -> rememberPaneContent( - selection.sectionKey?.let { - Triple(selection.itemId, it, selection.stageKey) - }, - )?.let { (itemId, sectionKey, key) -> - // A closing section pane keeps the identity that opened it, so - // it renders its content until it is fully off-screen. - RunStagePane( - vm = vm, - runId = itemId, - stageKey = key.orEmpty(), - visitIndex = selection.stageVisit, - openSection = sectionKey, - onOpenSection = {}, - onVisitChange = { onSelectionChange(selection.copy(stageVisit = it)) }, - onBack = onBack, - wide = wide, - modifier = paneModifier, - covered = covered, - ) - } - } - }, - ) -} - -/** - * The Templates destination: the same shared pane stack, with the template - * gallery as pane 0 and the selected template's detail as pane 1. The selected - * template key is the saved state, so it survives rotation, configuration change - * and process death; Back/the peek pop one level. Nothing here starts a run. - */ -@Composable -private fun TemplatesDestination( - vm: AppViewModel, - wide: Boolean, - listState: LazyListState, -) { - var selectedKey by rememberSaveable { mutableStateOf(null) } - val depth = if (selectedKey == null) 0 else 1 - val onBack: () -> Unit = { selectedKey = null } - - PredictiveBackHandler(enabled = depth >= 1) { progress -> - progress.collect { } - onBack() - } - - SlidingPaneStack( - depth = depth, - wide = wide, - onPopTo = { level -> if (level <= 0) selectedKey = null }, - compactLabel = "Templates", - compactIcon = TemplatesIcon, - backContentDescription = { level -> - if (level == 0) "Back to templates" else "Back to template" - }, - pane = { level, covered, paneModifier -> - when (level) { - 0 -> TemplateGalleryScreen( - vm = vm, - wide = wide, - onOpen = { key -> selectedKey = key }, - listState = listState, - modifier = paneModifier, - covered = covered, - ) - 1 -> rememberPaneContent(selectedKey)?.let { key -> - TemplateDetailScreen( - vm = vm, - templateKey = key, - onBack = onBack, - wide = wide, - modifier = paneModifier, - covered = covered, - ) - } - } - }, - ) -} - -/** - * The horizontal offset of the pill's travelling selection indicator for the - * destination at [index]: the pill's inner padding plus [index] item slots - * ([itemSize] + [gap]). Pure and in one place, so the indicator lines up exactly - * with the icon it selects and the geometry is unit-testable without a device. - * A missing selection (-1) pins to the first slot and the caller draws nothing. - */ -internal fun destinationIndicatorOffsetDp(index: Int, itemSize: Dp, gap: Dp): Dp = - gap + (itemSize + gap) * index.coerceAtLeast(0) - /** The Chat destination's navigation route. */ private const val CHAT_ROUTE = "chat" @@ -770,234 +403,3 @@ internal fun destinationPillVisible(currentRoute: String?, conversationOpen: Boo */ internal fun destinationPillReserve(pillVisible: Boolean): Dp = if (pillVisible) DESTINATION_PILL_RESERVE else 0.dp - -/** - * The bottom container: the destination pill that morphs into the omni-search - * field. It is one [Surface] so the morph reads as the same container changing - * role, not two surfaces swapping. Neither opening nor dismissing navigates, so - * the destination the pill had selected is untouched and the reverse restores - * exactly that pill. - */ -@Composable -private fun DestinationBar( - destinations: List, - currentRoute: String?, - state: OmniSearchState, - onSelect: (TopDestination) -> Unit, - onOpenSearch: () -> Unit, - onDismissSearch: () -> Unit, - onQueryChange: (String) -> Unit, - onFocusChange: (Boolean) -> Unit, - onSubmitSearch: () -> Unit, - modifier: Modifier = Modifier, -) { - val scheme = MaterialTheme.colorScheme - Surface( - modifier = modifier, - shape = RoundedCornerShape(50), - color = scheme.surfaceContainerHigh, - tonalElevation = 3.dp, - shadowElevation = 6.dp, - ) { - // The icons fade out while the field fades in, and the container takes the - // new content's size. The field fills the width the caller's inset padding - // leaves, so the grown size derives from that plus the field's own layout, - // and the position from the container's right-anchored alignment; no pill - // size is copied. - AnimatedContent( - targetState = state.open, - transitionSpec = { - (fadeIn(animationSpec = MotionStandard.spec()) togetherWith - fadeOut(animationSpec = MotionStandard.spec())) - .using(SizeTransform(clip = false) { _, _ -> MotionStandard.spec() }) - }, - contentAlignment = Alignment.CenterEnd, - label = "omni-search-morph", - ) { open -> - if (open) { - OmniSearchField( - query = state.query, - onQueryChange = onQueryChange, - onFocusChange = onFocusChange, - onSubmit = onSubmitSearch, - onDismiss = onDismissSearch, - ) - } else { - DestinationIcons( - destinations = destinations, - currentRoute = currentRoute, - onSelect = onSelect, - onOpenSearch = onOpenSearch, - ) - } - } - } -} - -/** - * The resting destination pill: the Pipelines/Runs/Settings destinations plus the - * omni-search entry point, each a [DESTINATION_ITEM_SIZE] touch target. Selection - * is one tonal indicator that travels between the icons ([MotionStandard], so it - * slides rather than jumping) plus the icon's fading tint, while the `Role.Tab` - * selected accessibility state is never conveyed by colour alone. Tapping a - * destination switches through the caller's existing navigate/popUpTo logic; the - * icons own the taps, so a tap registers even while the indicator is still - * travelling, and the settled pill equals the old one. - * - * The fourth control (Search) does not navigate: it is a plain [Role.Button] - * action that morphs this container into the search field. - */ -@Composable -private fun DestinationIcons( - destinations: List, - currentRoute: String?, - onSelect: (TopDestination) -> Unit, - onOpenSearch: () -> Unit, -) { - val scheme = MaterialTheme.colorScheme - val selectedIndex = destinations.indexOfFirst { destinationSelected(currentRoute, it.route) } - // One long-lived animator, so a rapid run of taps only retargets it (never - // half-way) and the first composition starts already settled at the target. - val indicatorOffset by animateDpAsState( - targetValue = destinationIndicatorOffsetDp( - selectedIndex, - DESTINATION_ITEM_SIZE, - DESTINATION_ITEM_GAP, - ), - animationSpec = MotionStandard.spec(), - label = "destination-indicator", - ) - Box { - // Drawn behind the icons, so the highlight slides under whichever is - // selected; before the nav graph settles there is no selection and - // nothing is drawn. - if (selectedIndex >= 0) { - Box( - Modifier - .offset(x = indicatorOffset, y = DESTINATION_ITEM_GAP) - .size(DESTINATION_ITEM_SIZE) - .clip(CircleShape) - .background(scheme.secondaryContainer), - ) - } - Row( - modifier = Modifier.padding(DESTINATION_ITEM_GAP), - horizontalArrangement = Arrangement.spacedBy(DESTINATION_ITEM_GAP), - verticalAlignment = Alignment.CenterVertically, - ) { - destinations.forEach { destination -> - val selected = destinationSelected(currentRoute, destination.route) - // The glyph tint fades in step with the travelling indicator. - val iconColor by animateColorAsState( - targetValue = if (selected) scheme.onSecondaryContainer else scheme.onSurfaceVariant, - animationSpec = MotionStandard.spec(), - label = "destination-icon", - ) - Box( - modifier = Modifier - .size(DESTINATION_ITEM_SIZE) - .clip(CircleShape) - .selectable( - selected = selected, - role = Role.Tab, - onClick = { onSelect(destination) }, - ), - contentAlignment = Alignment.Center, - ) { - Icon( - imageVector = destination.icon, - contentDescription = destination.label, - tint = iconColor, - ) - } - } - Box( - modifier = Modifier - .size(DESTINATION_ITEM_SIZE) - .clip(CircleShape) - .clickable( - role = Role.Button, - onClickLabel = "Search", - onClick = onOpenSearch, - ), - contentAlignment = Alignment.Center, - ) { - Icon( - imageVector = Icons.Default.Search, - contentDescription = "Search", - tint = scheme.onSurfaceVariant, - ) - } - } - } -} - -/** - * The search field the pill morphs into: a single-line input focused as it opens - * (so the keyboard is up), a leading search glyph and a trailing close action. It - * reports focus changes into [OmniSearchState] and every keystroke to the caller, - * which debounces the query and drives the results panel above it. - */ -@Composable -private fun OmniSearchField( - query: String, - onQueryChange: (String) -> Unit, - onFocusChange: (Boolean) -> Unit, - onSubmit: () -> Unit, - onDismiss: () -> Unit, -) { - val scheme = MaterialTheme.colorScheme - val interaction = remember { MutableInteractionSource() } - val focused by interaction.collectIsFocusedAsState() - val focusRequester = remember { FocusRequester() } - LaunchedEffect(focused) { onFocusChange(focused) } - // Focus as the field opens so the keyboard is up; an open field restored after - // a process death re-focuses the same way. - LaunchedEffect(Unit) { focusRequester.requestFocus() } - - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = SPACING_M, vertical = SPACING_XS), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - imageVector = Icons.Default.Search, - contentDescription = null, - tint = scheme.onSurfaceVariant, - ) - BasicTextField( - value = query, - onValueChange = onQueryChange, - singleLine = true, - textStyle = MaterialTheme.typography.bodyLarge.copy(color = scheme.onSurface), - cursorBrush = SolidColor(scheme.primary), - keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), - keyboardActions = KeyboardActions(onSearch = { onSubmit() }), - interactionSource = interaction, - modifier = Modifier - .weight(1f) - .padding(horizontal = SPACING_S) - .focusRequester(focusRequester), - decorationBox = { innerTextField -> - if (query.isEmpty()) { - Text( - text = "Search pipelines, runs and artifacts", - style = MaterialTheme.typography.bodyLarge, - color = scheme.onSurfaceVariant, - ) - } - innerTextField() - }, - ) - IconButton(onClick = onDismiss) { - Icon(Icons.Default.Close, contentDescription = "Close search") - } - } -} - -/** The destination pill's icon touch target and the size of its selection indicator. */ -internal val DESTINATION_ITEM_SIZE = 48.dp - -/** The gap between destinations, also the pill's inner padding. */ -internal val DESTINATION_ITEM_GAP = 4.dp diff --git a/android/app/src/main/java/net/awan/pipelines/ui/RunsDestination.kt b/android/app/src/main/java/net/awan/pipelines/ui/RunsDestination.kt new file mode 100644 index 00000000..9fded90d --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/RunsDestination.kt @@ -0,0 +1,150 @@ +package net.awan.pipelines.ui + +import androidx.activity.compose.PredictiveBackHandler +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.History +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import kotlinx.coroutines.flow.collect +import net.awan.pipelines.ui.components.SlidingPaneStack +import net.awan.pipelines.ui.components.clampTabIndex +import net.awan.pipelines.ui.components.rememberPaneContent +import net.awan.pipelines.ui.components.runDetailTabs +import net.awan.pipelines.ui.graph.RunStagePane +import net.awan.pipelines.ui.screens.RunDetailScreen +import net.awan.pipelines.ui.screens.RunHistoryScreen + +/** + * The Runs destination: the same shared pane stack with the run list, the + * selected run's tabs and the stage pane. Its selection is owned by + * [PipelinesApp] so the Pipelines detail can open a run it just started. + */ +@Composable +internal fun RunsDestination( + vm: AppViewModel, + wide: Boolean, + selection: PaneSelection, + onSelectionChange: (PaneSelection) -> Unit, + pendingNav: SearchTarget.Run?, + onPendingNavResolved: () -> Unit, + listState: LazyListState, +) { + val depth = selection.depth + val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) } + + // A run search hit that names a recorded visit is applied once the run's steps + // have loaded: the visit's stage pane (or the matched section) replaces the + // plain run detail. A target for another run waits for its own detail. + val runState by vm.runDetail.collectAsStateWithLifecycle() + LaunchedEffect(pendingNav, runState.data) { + val target = pendingNav ?: return@LaunchedEffect + val run = runState.data ?: return@LaunchedEffect + if (run.id != target.runId) return@LaunchedEffect + onSelectionChange(resolveRunTarget(target, run.id, run.steps)) + onPendingNavResolved() + } + + PredictiveBackHandler(enabled = depth >= 1) { progress -> + progress.collect { } + onBack() + } + + SlidingPaneStack( + depth = depth, + wide = wide, + onPopTo = { level -> onSelectionChange(popTo(selection, level)) }, + compactLabel = "Runs", + compactIcon = Icons.Filled.History, + // Every covered pane in this stack (the runs list, or a run's detail) carries + // a statistics block, so the region is sized for it and the runs list's + // counts and most-recent run are actually shown rather than dropped by the + // title-only tier. + compactStats = true, + backContentDescription = { level -> + when (level) { + 0 -> "Back to runs" + 1 -> "Back to run" + else -> "Back to stage" + } + }, + pane = { level, covered, paneModifier -> + when (level) { + 0 -> RunHistoryScreen( + vm = vm, + onOpenRun = { runId -> onSelectionChange(PaneSelection(MasterPane.Detail, runId)) }, + modifier = paneModifier, + selectedRunId = selection.itemId.takeIf { depth >= 1 }, + covered = covered, + listState = listState, + ) + 1 -> rememberPaneContent( + selection.itemId.takeIf { it != 0L }?.let { it to selection.sectionIndex }, + )?.let { (itemId, sectionIndex) -> + RunDetailScreen( + vm = vm, + runId = itemId, + onBack = onBack, + selectedSection = clampTabIndex(sectionIndex, runDetailTabs.size), + onSelectSection = { onSelectionChange(selection.copy(sectionIndex = it)) }, + modifier = paneModifier, + wide = wide, + onOpenStage = { key, visit -> + onSelectionChange( + selection.copy(pane = MasterPane.Stage, stageKey = key, stageVisit = visit), + ) + }, + covered = covered, + ) + } + 2 -> rememberPaneContent( + selection.stageKey?.let { + Triple(selection.itemId, it, selection.stageVisit) + }, + )?.let { (itemId, key, visit) -> + RunStagePane( + vm = vm, + runId = itemId, + stageKey = key, + visitIndex = visit, + openSection = null, + onOpenSection = { sectionKey -> + onSelectionChange( + selection.copy(pane = MasterPane.Section, sectionKey = sectionKey), + ) + }, + onVisitChange = { onSelectionChange(selection.copy(stageVisit = it)) }, + onBack = onBack, + wide = wide, + modifier = paneModifier, + covered = covered, + ) + } + 3 -> rememberPaneContent( + selection.sectionKey?.let { + Triple(selection.itemId, it, selection.stageKey) + }, + )?.let { (itemId, sectionKey, key) -> + // A closing section pane keeps the identity that opened it, so + // it renders its content until it is fully off-screen. + RunStagePane( + vm = vm, + runId = itemId, + stageKey = key.orEmpty(), + visitIndex = selection.stageVisit, + openSection = sectionKey, + onOpenSection = {}, + onVisitChange = { onSelectionChange(selection.copy(stageVisit = it)) }, + onBack = onBack, + wide = wide, + modifier = paneModifier, + covered = covered, + ) + } + } + }, + ) +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/TemplatesDestination.kt b/android/app/src/main/java/net/awan/pipelines/ui/TemplatesDestination.kt new file mode 100644 index 00000000..6b97587d --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/TemplatesDestination.kt @@ -0,0 +1,70 @@ +package net.awan.pipelines.ui + +import androidx.activity.compose.PredictiveBackHandler +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import kotlinx.coroutines.flow.collect +import net.awan.pipelines.ui.components.SlidingPaneStack +import net.awan.pipelines.ui.components.rememberPaneContent +import net.awan.pipelines.ui.screens.TemplateDetailScreen +import net.awan.pipelines.ui.screens.TemplateGalleryScreen + +/** + * The Templates destination: the same shared pane stack, with the template + * gallery as pane 0 and the selected template's detail as pane 1. The selected + * template key is the saved state, so it survives rotation, configuration change + * and process death; Back/the peek pop one level. Nothing here starts a run. + */ +@Composable +internal fun TemplatesDestination( + vm: AppViewModel, + wide: Boolean, + listState: LazyListState, +) { + var selectedKey by rememberSaveable { mutableStateOf(null) } + val depth = if (selectedKey == null) 0 else 1 + val onBack: () -> Unit = { selectedKey = null } + + PredictiveBackHandler(enabled = depth >= 1) { progress -> + progress.collect { } + onBack() + } + + SlidingPaneStack( + depth = depth, + wide = wide, + onPopTo = { level -> if (level <= 0) selectedKey = null }, + compactLabel = "Templates", + compactIcon = TemplatesIcon, + backContentDescription = { level -> + if (level == 0) "Back to templates" else "Back to template" + }, + pane = { level, covered, paneModifier -> + when (level) { + 0 -> TemplateGalleryScreen( + vm = vm, + wide = wide, + onOpen = { key -> selectedKey = key }, + listState = listState, + modifier = paneModifier, + covered = covered, + ) + 1 -> rememberPaneContent(selectedKey)?.let { key -> + TemplateDetailScreen( + vm = vm, + templateKey = key, + onBack = onBack, + wide = wide, + modifier = paneModifier, + covered = covered, + ) + } + } + }, + ) +} 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 adc2d623..6e4997f1 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,34 +1,22 @@ package net.awan.pipelines.ui.screens -import androidx.compose.foundation.ExperimentalFoundationApi -import androidx.compose.foundation.clickable -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.WindowInsetsSides import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth 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.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.DirectionsRun -import androidx.compose.material.icons.filled.AttachFile import androidx.compose.material.icons.filled.Cancel 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.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar @@ -38,69 +26,34 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle -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 -import net.awan.pipelines.data.protocol.RunStep -import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.ui.AppViewModel -import net.awan.pipelines.ui.ArtifactGroup -import net.awan.pipelines.ui.LoadState -import net.awan.pipelines.ui.components.CodeBlock -import net.awan.pipelines.ui.components.ColoredChip import net.awan.pipelines.ui.components.DecisionPrompt -import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.DetailTabs import net.awan.pipelines.ui.components.ErrorState -import net.awan.pipelines.ui.components.KeyValueRow import net.awan.pipelines.ui.components.LiveBadge 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.RunStatusIcon import net.awan.pipelines.ui.components.StateCrossfade -import net.awan.pipelines.ui.components.StatusChip 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.pendingDecision -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 -import net.awan.pipelines.ui.graph.WorkflowGraph -import net.awan.pipelines.ui.graph.graphColors -import net.awan.pipelines.ui.graph.outcomeColor import net.awan.pipelines.ui.graph.rememberArtifactSelection +import net.awan.pipelines.ui.pendingDecision import net.awan.pipelines.ui.runArtifactGroups -import net.awan.pipelines.ui.runArtifactsHeader import net.awan.pipelines.ui.runIdentity import net.awan.pipelines.ui.runLabel -import net.awan.pipelines.ui.RUN_VIEW_TITLE_LINES -import net.awan.pipelines.ui.theme.ICON_INLINE_DP -import net.awan.pipelines.ui.theme.ICON_STATUS_DP import net.awan.pipelines.ui.theme.SPACING_L -import net.awan.pipelines.ui.theme.SPACING_M import net.awan.pipelines.ui.theme.SPACING_S -import net.awan.pipelines.ui.theme.SPACING_XS -import net.awan.pipelines.ui.theme.SPACING_XXS import net.awan.pipelines.ui.theme.pipelinesText -import net.awan.pipelines.ui.visitCount @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -387,461 +340,3 @@ private fun ConfirmDialog( dismissButton = { TextButton(onClick = onDismiss) { Text("Keep") } }, ) } - -/** - * Summary carries everything the old page header carried: the run name, a - * status/outcome/executing chip row, recorded + completed visits, the pipeline - * id/version, current stage, workspace, content hash, start/finish/duration and - * the failure diagnostic. - */ -@OptIn(ExperimentalFoundationApi::class) -@Composable -private fun RunSummaryTab( - run: RunDetail, - wide: Boolean, - modifier: Modifier, - configuredServerUrl: String, - fetchArtifactBytes: suspend (String) -> ByteArray?, - artifactGroups: List, - selection: ArtifactSelection, - onSelectionChange: (ArtifactSelection) -> Unit, -) { - val text = pipelinesText() - val state = runStateOf(run.status) - // The artifacts section starts collapsed and its expand/collapse choice is - // remembered/saved per run id, so a different run reseeds it and a run opened - // fresh starts collapsed. Both the header and the gallery read the same - // snapshot, so they can never disagree. - val artifactsExpansion = rememberSectionExpansion(run.id) - val artifactsHeader = remember(run.steps, run.executing) { - runArtifactsHeader(run.steps, run.executing) - } - DetailTabBody(wide, modifier) { columnModifier -> - LazyColumn( - modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), - ) { - // The artifacts gallery still leads the summary, but inside one - // collapsed section: its header alone carries the run's capture - // wording until the operator expands it, and expanding reveals the - // unchanged gallery (nothing when no artifacts were recorded). - collapsibleSection( - title = artifactsHeader, - key = SUMMARY_ARTIFACTS_KEY, - expanded = artifactsExpansion.isExpanded(SUMMARY_ARTIFACTS_KEY), - onToggle = { artifactsExpansion.toggle(SUMMARY_ARTIFACTS_KEY) }, - ) { - if (artifactGroups.isNotEmpty()) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = SPACING_L, vertical = SPACING_S), - ) { - ArtifactGallery( - groups = artifactGroups, - configuredServerUrl = configuredServerUrl, - fetchArtifactBytes = fetchArtifactBytes, - selection = selection, - onSelectionChange = onSelectionChange, - ) - } - } - } - item(key = "run-summary") { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L), - verticalArrangement = Arrangement.spacedBy(SPACING_XS), - ) { - // The run view's own copy of the title: the operator must be - // able to read what the run is called, so it is never elided - - // it wraps over as many lines as it needs. The compact app-bar - // copy above stays a one-line label for context while this - // scrollable, complete one is what the operator reads. - Text( - runLabel(run.title, run.name), - style = text.screenTitle, - maxLines = RUN_VIEW_TITLE_LINES, - overflow = TextOverflow.Clip, - ) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(SPACING_S), - ) { - StatusChip(label = run.status.ifBlank { state.label }, state = state) - if (run.outcome.isNotBlank()) Text("outcome ${run.outcome}", style = text.meta) - if (run.executing) Text("executing", style = text.meta) - } - Text( - buildString { - append("run ${run.id}") - // 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("Stage", run.currentStage) - KeyValueRow("Workspace", run.workspace) - KeyValueRow("Content hash", run.contentHash, monospace = true) - KeyValueRow("Started", run.createdAt) - KeyValueRow("Finished", run.finishedAt) - RunDurationRow(run) - KeyValueRow("Retry of", if (run.retryOf > 0) "run ${run.retryOf}" else "") - CodeBlock("Diagnostic", run.diagnostic, Modifier.padding(top = SPACING_S)) - } - } - } - } -} - -/** - * 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 - * is the scroll container, so an expanded panel scrolls instead of clipping. - */ -@Composable -private fun RunGraphTab( - run: RunDetail, - modifier: Modifier, - onStageTap: (String, Int) -> Unit, -) { - val text = pipelinesText() - // Keyed on the fields RunGraphState.from reads (steps, executing, current - // stage) so a run that finishes without a new step still stops animating. - val runState = remember(run.id, run.steps, run.executing, run.currentStage) { - RunGraphState.from(run) - } - // Grouped once per step-list change; the sheet opened from the graph starts on - // the most recent visit of the tapped stage. - val timeline = remember(run.steps) { runTimeline(run.steps) } - LazyColumn( - modifier = modifier, - contentPadding = PaddingValues(vertical = SPACING_L), - ) { - item(key = "run-graph") { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L), - verticalArrangement = Arrangement.spacedBy(SPACING_S), - ) { - if (run.graph.stages.isEmpty()) { - Text("This server did not include the run graph.", style = text.meta) - } else { - Text( - "The running stage pulses with its elapsed time and executed routes flow; a finished run settles, and with animations off the running stage stays marked. Solid means executed, dashed and outlined not executed; executed success and failure routes are drawn thickest. Pinch to zoom, drag to pan, tap a stage for details.", - style = text.meta, - ) - WorkflowGraph( - graph = run.graph, - modifier = Modifier.fillMaxWidth(), - runState = runState, - selectedStage = runState.currentStage, - onStageTap = { key -> - val visits = timeline.visitsByStage[key].orEmpty() - onStageTap(key, (visits.size - 1).coerceAtLeast(0)) - }, - ) - } - } - } - } -} - -/** - * One inner collapsible section per input/output result field, each holding the - * field's value as a themed [CodeBlock]. Grouping is derived once per data - * change with `remember`, and the expansion state is remembered/saved. - */ -@Composable -private fun RunFieldSectionsTab( - emptyMessage: String, - keyPrefix: String, - entries: List>, - wide: Boolean, - modifier: Modifier, -) { - val text = pipelinesText() - val expansion = rememberSectionExpansion(entries) - DetailTabBody(wide, modifier) { columnModifier -> - LazyColumn( - modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), - ) { - if (entries.isEmpty()) { - item(key = "$keyPrefix-empty") { - Text( - emptyMessage, - style = text.meta, - modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), - ) - } - } else { - entries.forEach { (key, value) -> - val label = fieldSectionTitle(key, keyPrefix) - val sectionKey = "$keyPrefix-$key" - collapsibleSection( - title = label, - key = sectionKey, - expanded = expansion.isExpanded(sectionKey), - onToggle = { expansion.toggle(sectionKey) }, - ) { - CodeBlock( - label = label, - text = value.displayText(), - modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_XS), - ) - } - } - } - } - } -} - -/** One inner collapsible section per session-evidence entry (data block inside). */ -@OptIn(ExperimentalFoundationApi::class) -@Composable -private fun RunEvidenceTab( - evidenceState: LoadState>, - steps: List, - onLoadEvidence: () -> Unit, - wide: Boolean, - modifier: Modifier, -) { - val text = pipelinesText() - val evidence = evidenceState.data.orEmpty() - val expansion = rememberSectionExpansion(evidence) - // Correlate each evidence record with its step once per data change, by the - // protocol's shared sequence, never per recomposition. - val stepBySequence = remember(steps) { steps.associateBy { it.sequence } } - DetailTabBody(wide, modifier) { columnModifier -> - LazyColumn( - modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), - ) { - item(key = "evidence-reload") { - Row( - modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L), - horizontalArrangement = Arrangement.spacedBy(SPACING_S), - ) { - 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 = SPACING_L, vertical = SPACING_S), - ) - } - evidenceState.error != null -> item(key = "evidence-error") { - Text( - evidenceState.error!!, - color = MaterialTheme.colorScheme.error, - style = text.meta, - modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), - ) - } - evidenceState.loaded && evidence.isEmpty() -> item(key = "evidence-empty") { - Text( - "No session evidence recorded.", - style = text.meta, - modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), - ) - } - else -> evidence.forEach { record -> - val sectionKey = "evidence-${record.sequence}-${record.sessionId}" - collapsibleSection( - title = evidenceSectionTitle(record, stepBySequence[record.sequence]), - key = sectionKey, - expanded = expansion.isExpanded(sectionKey), - onToggle = { expansion.toggle(sectionKey) }, - ) { - EvidenceDetails(record, Modifier.padding(horizontal = SPACING_L, vertical = SPACING_XS)) - } - } - } - } - } -} - -/** - * A field section's title: the field's own name, falling back to the section - * prefix (input/output) so a blank or missing key never yields an empty title. - */ -internal fun fieldSectionTitle(key: String, keyPrefix: String): String = key.ifBlank { keyPrefix } - -/** - * A self-describing evidence-section title: the step, and when the matching - * step is known the stage and visit, plus the backend (or, when absent, the - * session id) identity. Never a bare index; falls back gracefully when the - * record cannot be correlated with a step. - */ -internal fun evidenceSectionTitle(record: SessionEvidence, step: RunStep?): String { - val parts = ArrayList() - if (record.sequence > 0) parts += "step ${record.sequence}" - if (step != null) { - val visit = step.control?.visit?.takeIf { it > 0 } - val stage = buildString { - if (step.stage.isNotBlank()) append(step.stage) - if (visit != null) { - if (isNotEmpty()) append(' ') - append("visit $visit") - } - } - if (stage.isNotBlank()) parts += stage - } - val identity = record.backend.ifBlank { record.sessionId } - if (identity.isNotBlank()) parts += identity - return if (parts.isEmpty()) "Evidence" else "Evidence - " + parts.joinToString(", ") -} - -/** - * The Timeline tab: one compact line per recorded visit (stage name, visit - * number, outcome chip and duration plus a brief description) and nothing else. - * The heavy per-step evidence lives only in the stage pane opened by - * tapping an entry. The steps are grouped once per step-list change, not per - * recomposition, and rendered in this single LazyColumn. - */ -@OptIn(ExperimentalFoundationApi::class) -@Composable -private fun RunTimelineTab( - run: RunDetail, - wide: Boolean, - modifier: Modifier, - onStageTap: (String, Int) -> Unit, -) { - val text = pipelinesText() - // Grouped once per step-list change, not per recomposition. - val timeline = remember(run.steps) { runTimeline(run.steps) } - DetailTabBody(wide, modifier) { columnModifier -> - LazyColumn( - modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), - ) { - if (timeline.entries.isEmpty()) { - item(key = "timeline-empty") { - Text( - "No visits recorded.", - style = text.meta, - modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), - ) - } - } else { - items( - timeline.entries, - key = { "timeline-${it.stageKey}-${it.step.sequence}" }, - ) { entry -> - TimelineRow(entry) { - onStageTap(entry.stageKey, entry.visitIndex) - } - HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) - } - } - } - } -} - -/** - * One compact timeline line: a leading status glyph, the stage name and visit - * number, the outcome chip and duration, then a single-line description. No - * inline code block, metadata grid, transcript, file-changes or notifications - * evidence is rendered here; that all lives in the stage detail sheet. - */ -@Composable -private fun TimelineRow(entry: TimelineEntry, onClick: () -> Unit) { - val text = pipelinesText() - val state = runStateOf(entry.step.outcome.ifBlank { entry.step.status }) - val chipLabel = entry.outcomeLabel.ifBlank { state.label } - // A visit's chip and glyph are a *stage outcome*, not the run status, so they - // take the graph's outcome palette and agree with the workflow graph instead - // of being mapped through the run-status colours (the two are different - // vocabularies). Built once per scheme, from the same factory the graph uses. - val scheme = MaterialTheme.colorScheme - val outcomeColors = remember(scheme) { graphColors(scheme) } - val outcomeTint = outcomeColor(entry.step.outcome.ifBlank { entry.step.status }, outcomeColors) - Row( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick) - .padding(horizontal = SPACING_L, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(SPACING_M), - ) { - RunStatusIcon( - state = state, - contentDescription = "Visit ${entry.visit} ${entry.stageKey}: ${state.label}", - modifier = Modifier.size(ICON_INLINE_DP), - tint = outcomeTint, - ) - Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(SPACING_XXS)) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(SPACING_S), - ) { - Text( - "${entry.stageKey} · visit ${entry.visit}", - style = text.cardTitle, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - ColoredChip(label = chipLabel, color = outcomeTint, icon = runStateIcon(state)) - if (hasArtifacts(entry.step)) { - Icon( - imageVector = Icons.Default.AttachFile, - contentDescription = "Visit ${entry.visit} has recorded artifacts", - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(ICON_STATUS_DP), - ) - } - if (entry.duration != null) { - Text(entry.duration, style = text.meta, maxLines = 1) - } - } - if (entry.description.isNotBlank()) { - Text( - entry.description, - style = text.meta, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - } -} - -/** A session-evidence entry's fields plus its data/diagnostic code blocks. */ -@Composable -private fun EvidenceDetails(evidence: SessionEvidence, modifier: Modifier = Modifier) { - val text = pipelinesText() - Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(SPACING_XS)) { - 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) - CodeBlock("Diagnostic", evidence.diagnostic.orEmpty()) - CodeBlock("Data", evidence.data.orEmpty()) - } -} - -// The run summary's artifacts section key: stable so its expand/collapse choice -// is remembered consistently (it is namespaced under the summary tab's saved -// state and reseeded by run id). -private const val SUMMARY_ARTIFACTS_KEY = "artifacts" diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunEvidenceTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunEvidenceTab.kt new file mode 100644 index 00000000..2dda6065 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunEvidenceTab.kt @@ -0,0 +1,135 @@ +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.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.SessionEvidence +import net.awan.pipelines.ui.LoadState +import net.awan.pipelines.ui.components.CodeBlock +import net.awan.pipelines.ui.components.DetailTabBody +import net.awan.pipelines.ui.components.collapsibleSection +import net.awan.pipelines.ui.components.rememberSectionExpansion +import net.awan.pipelines.ui.theme.SPACING_L +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XS +import net.awan.pipelines.ui.theme.pipelinesText + +/** One inner collapsible section per session-evidence entry (data block inside). */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +internal fun RunEvidenceTab( + evidenceState: LoadState>, + steps: List, + onLoadEvidence: () -> Unit, + wide: Boolean, + modifier: Modifier, +) { + val text = pipelinesText() + val evidence = evidenceState.data.orEmpty() + val expansion = rememberSectionExpansion(evidence) + // Correlate each evidence record with its step once per data change, by the + // protocol's shared sequence, never per recomposition. + val stepBySequence = remember(steps) { steps.associateBy { it.sequence } } + DetailTabBody(wide, modifier) { columnModifier -> + LazyColumn( + modifier = columnModifier, + contentPadding = PaddingValues(vertical = SPACING_L), + ) { + item(key = "evidence-reload") { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L), + horizontalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + 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 = SPACING_L, vertical = SPACING_S), + ) + } + evidenceState.error != null -> item(key = "evidence-error") { + Text( + evidenceState.error!!, + color = MaterialTheme.colorScheme.error, + style = text.meta, + modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), + ) + } + evidenceState.loaded && evidence.isEmpty() -> item(key = "evidence-empty") { + Text( + "No session evidence recorded.", + style = text.meta, + modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), + ) + } + else -> evidence.forEach { record -> + val sectionKey = "evidence-${record.sequence}-${record.sessionId}" + collapsibleSection( + title = evidenceSectionTitle(record, stepBySequence[record.sequence]), + key = sectionKey, + expanded = expansion.isExpanded(sectionKey), + onToggle = { expansion.toggle(sectionKey) }, + ) { + EvidenceDetails(record, Modifier.padding(horizontal = SPACING_L, vertical = SPACING_XS)) + } + } + } + } + } +} + +/** + * A self-describing evidence-section title: the step, and when the matching + * step is known the stage and visit, plus the backend (or, when absent, the + * session id) identity. Never a bare index; falls back gracefully when the + * record cannot be correlated with a step. + */ +internal fun evidenceSectionTitle(record: SessionEvidence, step: RunStep?): String { + val parts = ArrayList() + if (record.sequence > 0) parts += "step ${record.sequence}" + if (step != null) { + val visit = step.control?.visit?.takeIf { it > 0 } + val stage = buildString { + if (step.stage.isNotBlank()) append(step.stage) + if (visit != null) { + if (isNotEmpty()) append(' ') + append("visit $visit") + } + } + if (stage.isNotBlank()) parts += stage + } + val identity = record.backend.ifBlank { record.sessionId } + if (identity.isNotBlank()) parts += identity + return if (parts.isEmpty()) "Evidence" else "Evidence - " + parts.joinToString(", ") +} + +/** A session-evidence entry's fields plus its data/diagnostic code blocks. */ +@Composable +private fun EvidenceDetails(evidence: SessionEvidence, modifier: Modifier = Modifier) { + val text = pipelinesText() + Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(SPACING_XS)) { + 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) + CodeBlock("Diagnostic", evidence.diagnostic.orEmpty()) + CodeBlock("Data", evidence.data.orEmpty()) + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunFieldSectionsTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunFieldSectionsTab.kt new file mode 100644 index 00000000..be3e685a --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunFieldSectionsTab.kt @@ -0,0 +1,74 @@ +package net.awan.pipelines.ui.screens + +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import kotlinx.serialization.json.JsonElement +import net.awan.pipelines.ui.components.CodeBlock +import net.awan.pipelines.ui.components.DetailTabBody +import net.awan.pipelines.ui.components.collapsibleSection +import net.awan.pipelines.ui.components.rememberSectionExpansion +import net.awan.pipelines.ui.displayText +import net.awan.pipelines.ui.theme.SPACING_L +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XS +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * One inner collapsible section per input/output result field, each holding the + * field's value as a themed [CodeBlock]. Grouping is derived once per data + * change with `remember`, and the expansion state is remembered/saved. + */ +@Composable +internal fun RunFieldSectionsTab( + emptyMessage: String, + keyPrefix: String, + entries: List>, + wide: Boolean, + modifier: Modifier, +) { + val text = pipelinesText() + val expansion = rememberSectionExpansion(entries) + DetailTabBody(wide, modifier) { columnModifier -> + LazyColumn( + modifier = columnModifier, + contentPadding = PaddingValues(vertical = SPACING_L), + ) { + if (entries.isEmpty()) { + item(key = "$keyPrefix-empty") { + Text( + emptyMessage, + style = text.meta, + modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), + ) + } + } else { + entries.forEach { (key, value) -> + val label = fieldSectionTitle(key, keyPrefix) + val sectionKey = "$keyPrefix-$key" + collapsibleSection( + title = label, + key = sectionKey, + expanded = expansion.isExpanded(sectionKey), + onToggle = { expansion.toggle(sectionKey) }, + ) { + CodeBlock( + label = label, + text = value.displayText(), + modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_XS), + ) + } + } + } + } + } +} + +/** + * A field section's title: the field's own name, falling back to the section + * prefix (input/output) so a blank or missing key never yields an empty title. + */ +internal fun fieldSectionTitle(key: String, keyPrefix: String): String = key.ifBlank { keyPrefix } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunGraphTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunGraphTab.kt new file mode 100644 index 00000000..faea05ac --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunGraphTab.kt @@ -0,0 +1,70 @@ +package net.awan.pipelines.ui.screens + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.data.protocol.RunGraphState +import net.awan.pipelines.ui.graph.WorkflowGraph +import net.awan.pipelines.ui.theme.SPACING_L +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * 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 + * is the scroll container, so an expanded panel scrolls instead of clipping. + */ +@Composable +internal fun RunGraphTab( + run: RunDetail, + modifier: Modifier, + onStageTap: (String, Int) -> Unit, +) { + val text = pipelinesText() + // Keyed on the fields RunGraphState.from reads (steps, executing, current + // stage) so a run that finishes without a new step still stops animating. + val runState = remember(run.id, run.steps, run.executing, run.currentStage) { + RunGraphState.from(run) + } + // Grouped once per step-list change; the sheet opened from the graph starts on + // the most recent visit of the tapped stage. + val timeline = remember(run.steps) { runTimeline(run.steps) } + LazyColumn( + modifier = modifier, + contentPadding = PaddingValues(vertical = SPACING_L), + ) { + item(key = "run-graph") { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L), + verticalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + if (run.graph.stages.isEmpty()) { + Text("This server did not include the run graph.", style = text.meta) + } else { + Text( + "The running stage pulses with its elapsed time and executed routes flow; a finished run settles, and with animations off the running stage stays marked. Solid means executed, dashed and outlined not executed; executed success and failure routes are drawn thickest. Pinch to zoom, drag to pan, tap a stage for details.", + style = text.meta, + ) + WorkflowGraph( + graph = run.graph, + modifier = Modifier.fillMaxWidth(), + runState = runState, + selectedStage = runState.currentStage, + onStageTap = { key -> + val visits = timeline.visitsByStage[key].orEmpty() + onStageTap(key, (visits.size - 1).coerceAtLeast(0)) + }, + ) + } + } + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt new file mode 100644 index 00000000..e6f7b631 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt @@ -0,0 +1,164 @@ +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.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.ui.ArtifactGroup +import net.awan.pipelines.ui.RUN_VIEW_TITLE_LINES +import net.awan.pipelines.ui.components.CodeBlock +import net.awan.pipelines.ui.components.DetailTabBody +import net.awan.pipelines.ui.components.KeyValueRow +import net.awan.pipelines.ui.components.StatusChip +import net.awan.pipelines.ui.components.collapsibleSection +import net.awan.pipelines.ui.components.rememberLiveNowMillis +import net.awan.pipelines.ui.components.rememberSectionExpansion +import net.awan.pipelines.ui.components.runStateOf +import net.awan.pipelines.ui.graph.ArtifactGallery +import net.awan.pipelines.ui.graph.ArtifactSelection +import net.awan.pipelines.ui.runArtifactsHeader +import net.awan.pipelines.ui.runDurationText +import net.awan.pipelines.ui.runLabel +import net.awan.pipelines.ui.theme.SPACING_L +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XS +import net.awan.pipelines.ui.theme.pipelinesText +import net.awan.pipelines.ui.visitCount + +/** + * Summary carries everything the old page header carried: the run name, a + * status/outcome/executing chip row, recorded + completed visits, the pipeline + * id/version, current stage, workspace, content hash, start/finish/duration and + * the failure diagnostic. + */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +internal fun RunSummaryTab( + run: RunDetail, + wide: Boolean, + modifier: Modifier, + configuredServerUrl: String, + fetchArtifactBytes: suspend (String) -> ByteArray?, + artifactGroups: List, + selection: ArtifactSelection, + onSelectionChange: (ArtifactSelection) -> Unit, +) { + val text = pipelinesText() + val state = runStateOf(run.status) + // The artifacts section starts collapsed and its expand/collapse choice is + // remembered/saved per run id, so a different run reseeds it and a run opened + // fresh starts collapsed. Both the header and the gallery read the same + // snapshot, so they can never disagree. + val artifactsExpansion = rememberSectionExpansion(run.id) + val artifactsHeader = remember(run.steps, run.executing) { + runArtifactsHeader(run.steps, run.executing) + } + DetailTabBody(wide, modifier) { columnModifier -> + LazyColumn( + modifier = columnModifier, + contentPadding = PaddingValues(vertical = SPACING_L), + ) { + // The artifacts gallery still leads the summary, but inside one + // collapsed section: its header alone carries the run's capture + // wording until the operator expands it, and expanding reveals the + // unchanged gallery (nothing when no artifacts were recorded). + collapsibleSection( + title = artifactsHeader, + key = SUMMARY_ARTIFACTS_KEY, + expanded = artifactsExpansion.isExpanded(SUMMARY_ARTIFACTS_KEY), + onToggle = { artifactsExpansion.toggle(SUMMARY_ARTIFACTS_KEY) }, + ) { + if (artifactGroups.isNotEmpty()) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = SPACING_L, vertical = SPACING_S), + ) { + ArtifactGallery( + groups = artifactGroups, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, + selection = selection, + onSelectionChange = onSelectionChange, + ) + } + } + } + item(key = "run-summary") { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L), + verticalArrangement = Arrangement.spacedBy(SPACING_XS), + ) { + // The run view's own copy of the title: the operator must be + // able to read what the run is called, so it is never elided - + // it wraps over as many lines as it needs. The compact app-bar + // copy above stays a one-line label for context while this + // scrollable, complete one is what the operator reads. + Text( + runLabel(run.title, run.name), + style = text.screenTitle, + maxLines = RUN_VIEW_TITLE_LINES, + overflow = TextOverflow.Clip, + ) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + StatusChip(label = run.status.ifBlank { state.label }, state = state) + if (run.outcome.isNotBlank()) Text("outcome ${run.outcome}", style = text.meta) + if (run.executing) Text("executing", style = text.meta) + } + Text( + buildString { + append("run ${run.id}") + // 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("Stage", run.currentStage) + KeyValueRow("Workspace", run.workspace) + KeyValueRow("Content hash", run.contentHash, monospace = true) + KeyValueRow("Started", run.createdAt) + KeyValueRow("Finished", run.finishedAt) + RunDurationRow(run) + KeyValueRow("Retry of", if (run.retryOf > 0) "run ${run.retryOf}" else "") + CodeBlock("Diagnostic", run.diagnostic, Modifier.padding(top = SPACING_S)) + } + } + } + } +} + +/** + * 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 run summary's artifacts section key: stable so its expand/collapse choice +// is remembered consistently (it is namespaced under the summary tab's saved +// state and reseeded by run id). +private const val SUMMARY_ARTIFACTS_KEY = "artifacts" diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunTimelineTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunTimelineTab.kt new file mode 100644 index 00000000..2b06b6b2 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunTimelineTab.kt @@ -0,0 +1,155 @@ +package net.awan.pipelines.ui.screens + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.clickable +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.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.material.icons.Icons +import androidx.compose.material.icons.filled.AttachFile +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.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.ui.components.ColoredChip +import net.awan.pipelines.ui.components.DetailTabBody +import net.awan.pipelines.ui.components.RunStatusIcon +import net.awan.pipelines.ui.components.runStateIcon +import net.awan.pipelines.ui.components.runStateOf +import net.awan.pipelines.ui.graph.graphColors +import net.awan.pipelines.ui.graph.outcomeColor +import net.awan.pipelines.ui.theme.ICON_INLINE_DP +import net.awan.pipelines.ui.theme.ICON_STATUS_DP +import net.awan.pipelines.ui.theme.SPACING_L +import net.awan.pipelines.ui.theme.SPACING_M +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XXS +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * The Timeline tab: one compact line per recorded visit (stage name, visit + * number, outcome chip and duration plus a brief description) and nothing else. + * The heavy per-step evidence lives only in the stage pane opened by + * tapping an entry. The steps are grouped once per step-list change, not per + * recomposition, and rendered in this single LazyColumn. + */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +internal fun RunTimelineTab( + run: RunDetail, + wide: Boolean, + modifier: Modifier, + onStageTap: (String, Int) -> Unit, +) { + val text = pipelinesText() + // Grouped once per step-list change, not per recomposition. + val timeline = remember(run.steps) { runTimeline(run.steps) } + DetailTabBody(wide, modifier) { columnModifier -> + LazyColumn( + modifier = columnModifier, + contentPadding = PaddingValues(vertical = SPACING_L), + ) { + if (timeline.entries.isEmpty()) { + item(key = "timeline-empty") { + Text( + "No visits recorded.", + style = text.meta, + modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), + ) + } + } else { + items( + timeline.entries, + key = { "timeline-${it.stageKey}-${it.step.sequence}" }, + ) { entry -> + TimelineRow(entry) { + onStageTap(entry.stageKey, entry.visitIndex) + } + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + } + } + } + } +} + +/** + * One compact timeline line: a leading status glyph, the stage name and visit + * number, the outcome chip and duration, then a single-line description. No + * inline code block, metadata grid, transcript, file-changes or notifications + * evidence is rendered here; that all lives in the stage detail sheet. + */ +@Composable +private fun TimelineRow(entry: TimelineEntry, onClick: () -> Unit) { + val text = pipelinesText() + val state = runStateOf(entry.step.outcome.ifBlank { entry.step.status }) + val chipLabel = entry.outcomeLabel.ifBlank { state.label } + // A visit's chip and glyph are a *stage outcome*, not the run status, so they + // take the graph's outcome palette and agree with the workflow graph instead + // of being mapped through the run-status colours (the two are different + // vocabularies). Built once per scheme, from the same factory the graph uses. + val scheme = MaterialTheme.colorScheme + val outcomeColors = remember(scheme) { graphColors(scheme) } + val outcomeTint = outcomeColor(entry.step.outcome.ifBlank { entry.step.status }, outcomeColors) + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = SPACING_L, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_M), + ) { + RunStatusIcon( + state = state, + contentDescription = "Visit ${entry.visit} ${entry.stageKey}: ${state.label}", + modifier = Modifier.size(ICON_INLINE_DP), + tint = outcomeTint, + ) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(SPACING_XXS)) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + Text( + "${entry.stageKey} · visit ${entry.visit}", + style = text.cardTitle, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + ColoredChip(label = chipLabel, color = outcomeTint, icon = runStateIcon(state)) + if (hasArtifacts(entry.step)) { + Icon( + imageVector = Icons.Default.AttachFile, + contentDescription = "Visit ${entry.visit} has recorded artifacts", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(ICON_STATUS_DP), + ) + } + if (entry.duration != null) { + Text(entry.duration, style = text.meta, maxLines = 1) + } + } + if (entry.description.isNotBlank()) { + Text( + entry.description, + style = text.meta, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } +}