Add remembered filters to the runs and pipelines lists

Give each list a filter control, remembered per list across restarts like
the sort, combined with AND. Filters narrow; the (later) omni search will
find, so they are kept distinct.

- ui/screens/ListFilter.kt: RunTimeRange (AnyTime default, Today, Last7Days,
  Last30Days), RunPresence (Any default, HasRuns, NoRuns) and the
  RunFilters/PipelineFilters data classes, with one pure predicate per facet
  (runMatchesStatuses, runMatchesPipeline, runMatchesTimeRange,
  pipelineMatchesPresence, pipelineMatchesLastRunStatus) and the AND-combining
  filterRuns/filterPipelines. A default narrows nothing; an empty status set
  means "any"; the time windows are inclusive calendar days; a blank,
  unparseable or future timestamp never matches a finite window; a runless
  pipeline has no last-run status; fromStorage tolerates stale/unknown/blank
  values; encodeRunStates/decodeRunStates round-trip the status set.
- ui/components/FilterMenu.kt: the shared top-bar control both screens use -
  an IconButton with a numeric active-filter count badge opening the caller's
  sections plus one Clear filters action (disabled when nothing is active),
  the count folded into the icon description, and a menu capped to the window
  and clear of the navigation inset so it stays scrollable rather than
  clipping.
- PipelineListScreen.kt/RunHistoryScreen.kt wire the control and predicates;
  the existing name search on pipelines stays a separate field, and the new
  pipeline facets depend on the run history.
- ui/components/States.kt: EmptyState gains optional actionLabel/onAction so
  both lists distinguish "nothing exists" from "nothing matches the current
  filters" and offer Clear filters only in the latter.
- data/SettingsRepository.kt + ui/AppViewModel.kt: store each facet under its
  own stable key as a StateFlow, exactly like the sort keys; the screens
  resolve the stored strings so the repository stays unaware of the UI enums.

Verified on this tree with :app:testDebugUnitTest, assembleDebug, and
emulator-5556 persistence and captures; recorded in android/README.md.
This commit is contained in:
2026-10-16 06:01:18 +01:00
parent 1c925d72f7
commit 54af4535d7
10 changed files with 1152 additions and 30 deletions
+199
View File
@@ -1558,3 +1558,202 @@ a real hardware fold to the cover display was not exercised (narrow was produced
with `wm size`); no before/after baseline build was captured, since the change is
additive and the default orders are asserted unchanged by the `ServerOrder`/
`NewestFirst` unit tests.
## Filters for the runs and pipelines lists (16 Oct 2026)
Both list top bars gained a filter control, remembered per list across restarts
like the sort. `android/` only; nothing in the Pipelines server, its Go source,
the Docker/compose files or the installer was touched, no dependency was added
(the one new glyph, `Icons.Default.FilterList`, is from the already-declared
`material-icons-extended`), no run was started from the app, and the attached
Pixel 10 Pro Fold was never installed on or driven (every `adb`/emulator command
targeted `emulator-5556`).
- **Pure predicates.** `ui/screens/ListFilter.kt` defines `RunTimeRange`
(`AnyTime` default, `Today`, `Last7Days`, `Last30Days`), `RunPresence`
(`Any` default, `HasRuns`, `NoRuns`) and the `RunFilters`/`PipelineFilters`
data classes plus one pure predicate per facet (`runMatchesStatuses`,
`runMatchesPipeline`, `runMatchesTimeRange`, `pipelineMatchesPresence`,
`pipelineMatchesLastRunStatus`) and the AND-combining `filterRuns`/
`filterPipelines`. A default filter narrows nothing; an empty status set means
"any status". The status options are the server's own run vocabulary
(queued/running/succeeded/failed/canceled/interrupted), not the app-only
`active`/`unknown` buckets. A time window is inclusive calendar days ending
today (last 7 = today + the six days before), and a blank, unparseable or
future-dated timestamp never matches a finite window. A pipeline with no run
has no last-run status, so a selected status never matches it. `fromStorage`
tolerates stale/unknown/blank values by returning the default, and
`encodeRunStates`/`decodeRunStates` round-trip the status set as the server
status words in ordinal order.
- **Runs list.** Status (multi-select), pipeline (single-select from the
distinct pipelines already present in the run history, named by their runs, so
no extra fetch) and the time range, combined with AND.
- **Pipelines list.** The existing name search stays a separate field; the new
filter adds has-runs / no-runs and the most-recent run's status (multi-select).
Both pipeline facets depend on the run history, so `filterPipelines` leaves the
list unfiltered until that history is known rather than briefly hiding every
row.
- **Shared control.** `ui/components/FilterMenu.kt` is the one top-bar control
both screens use: an `IconButton` carrying a numeric active-filter count badge
(so "filters active" is never colour alone) opening the caller's sections plus
a divider and one Clear filters action (disabled when nothing is active). Its
`optionContent` slot receives a `dismiss` callback, so single-select entries
close the menu while multi-select toggles keep it open; `FilterCheckItem` is
the shared leading-check row. It has no geometry literals and anchors
correctly at both window widths.
- **Empty states.** `ui/components/States.kt`'s `EmptyState` gained optional
`actionLabel`/`onAction`. Both lists now distinguish "nothing exists" (no
action) from "nothing matches the current filters" (a Clear filters action);
the pipelines list also says when the name search and the filters together
match nothing. The clear action resets that list's filters (and, on Pipelines,
the search) without touching the other list.
- **Persistence.** `data/SettingsRepository.kt` stores each facet under its own
stable key (`run_filter_statuses`, `run_filter_pipeline`,
`run_filter_time_range`, `pipeline_filter_presence`,
`pipeline_filter_run_statuses`) with a `StateFlow`, exactly like the sorts;
`AppViewModel` exposes them and their setters. The screens resolve the stored
strings with `RunFilters.fromStorage`/`PipelineFilters.fromStorage` (the
repository stays unaware of the UI enums).
- **Shared time helper.** The run screen's file-private `runDate` was removed in
favour of `ListFilter.kt`'s `runLocalDate`, so the day-grouping label and the
time-range predicate share one parse. `groupRunsByDay` is unchanged.
Verified on this tree (macOS, Homebrew JDK 25 (`openjdk@25`), Gradle 9.7.1,
`ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--offline`):
- `gradle --offline :app:testDebugUnitTest --rerun-tasks` → the 22 test-result
XMLs aggregate to **183 tests, 0 failures, 0 errors, 0 skipped** (up from 167;
the new `ListFilterTest` has 16 cases covering stored-value parsing/fallback,
encode/decode round-trip and garbage tolerance, empty-status "any", the status
union, pipeline id vs any, the inclusive time windows and blank/future
timestamps, the AND combination of every facet, presence has/no-runs, last-run
status excluding runless pipelines, the `runsKnown` guard, and the
distinct/sorted pipeline options).
- `gradle --offline :app:assembleDebug --rerun-tasks --no-build-cache` (a full
rebuild, so the published binary is exactly this tree) succeeded →
`app-debug.apk` **17,912,489 bytes**, sha256
`eaa34c0b030511c2e4de1964dc4e905e62e822e876b5c0128bfff4d918933fc5`.
- On `emulator-5556` (`sdk_gphone16k_arm64`, 2208x1840, dark mode) against the
live server `ws://10.0.2.2:8080/connect`, driven with `adb shell input` and
`uiautomator dump`; every capture below was written with
`android/scripts/capture_png.sh -s emulator-5556` (validated PNG, named display
id) into `…/artifacts/89/1/`:
- Selecting status `failed` narrowed the runs list to the failed runs and
showed the badge `1` (`01_runs_filtered_failed.png`), read back from the
accessibility tree.
- The runs `Filter runs` menu opened with its Status, Pipeline and Time range
sections, the active-count badge and `Clear filters`
(`02_runs_filter_menu_open.png`).
- **Filtered-empty state.** Adding pipeline `Complete a Task` to the `failed`
status matched run 43, but the contradictory `running` status (no `Complete
a Task` run is running) yielded no match: the list showed `No runs match the
current filters.` with a `Clear filters` button and badge `2`
(`03_runs_filtered_empty.png`); the button restored the full list and removed
the badge.
- The pipelines `Filter pipelines` menu carries the Runs (Any/Has runs/No runs)
and Last run status sections, the badge and `Clear filters`
(`05_pipelines_filter_menu_open.png`). `Has runs` + last-run status
`succeeded` narrowed the list to its succeeded-last-run pipelines
(`04_pipelines_filtered_has_runs_succeeded.png`); `No runs` + last-run status
`succeeded` is contradictory and showed `No pipelines match the current
filters.` with `Clear filters` and badge `2`
(`06_pipelines_filtered_empty.png`); the button restored the list and cleared
only the pipelines filter (the runs filter was left intact).
- **Persistence proof.** With runs status `failed` and pipelines `has_runs` +
last-run status `succeeded`, `run-as net.awan.pipelines cat
shared_prefs/pipelines_settings.xml` showed `run_filter_statuses=failed`,
`pipeline_filter_presence=has_runs`, `pipeline_filter_run_statuses=succeeded`.
`am force-stop net.awan.pipelines` (verified `pidof` empty) then `am start`
and a fresh `uiautomator dump` showed the pipelines list still narrowed with
badge `2` (`07_pipelines_filtered_after_relaunch.png`) and the runs list still
filtered to `failed` with badge `1`
(`08_runs_filtered_after_relaunch.png`), with no interaction.
- `adb -s emulator-5556 logcat -d | grep -c 'FATAL EXCEPTION'` and `… | grep -c
'E AndroidRuntime'` each returned 0; no run was started from the app.
- **APK publish.** `app-debug.apk` was copied to
`~/.local/share/pipelines/data/artifacts/89/1/pipelines-debug-wip-1c925d7.apk`
(`1c925d7` = `git rev-parse --short HEAD`); `shasum -a 256` matched. `curl -I
http://10.0.0.249:8080/artifacts/89/1/pipelines-debug-wip-1c925d7.apk`
returned `HTTP/1.1 200 OK`, `Content-Type:
application/vnd.android.package-archive`, `Content-Length: 17912489`, and a
streamed `GET | shasum -a 256` returned the same `eaa34c0b…` as the local file.
The deterministic full-rebuild APK was installed on `emulator-5556`
(`adb -s emulator-5556 install -r`) and the pulled installed `base.apk` hashed
to `eaa34c0b…`, so the reviewed source is what was actually rendered. At
17.1 MiB it exceeds the server's 8 MiB per-file inventory cap, so it is served
by direct URL only.
Not verified in this pass: `:app:lintDebug` was not run; a real hardware fold to
the cover display was not exercised (all captures were at the inner panel's
2208x1840 width, so no narrow-width capture of the filter menu was taken); the
time-range facet was unit-tested but not exercised on device, and no before/after
baseline build was captured, since the change is additive and the default filters
are asserted to narrow nothing by the unit tests.
### Filter menu overflow and accessibility (16 Oct 2026)
A UI review of the pass above found the runs `DropdownMenu` grew unbounded with
the distinct-pipeline count (N=8 made it fill the whole window), clipping the
`Clear filters` item under the bottom gesture inset, and that neither the
active-filter count nor the checked facets were exposed to accessibility. Fixed
in `ui/components/FilterMenu.kt` only (`android/`, no new dependency):
- **Bounded menu.** `filterMenuMaxHeight(screenHeightDp)` caps the menu at
`0.85 ×` the window height (window-derived, like the graph's height helpers, so
no new geometry literal), so the menu scrolls internally instead of growing
past the window as `N` rises.
- **Reset always visible.** The single `Clear filters` action is now a leading
header row (`Filters` + the reset `TextButton`, disabled when nothing is
active), so it is fully in view on open and never below the fold or clipped.
- **Above the navigation inset.** A trailing spacer of
`WindowInsets.navigationBars` bottom padding keeps the last option clear of the
gesture area at maximum scroll.
- **Accessible state.** The icon's description now folds in the count
(`filterMenuDescription`, e.g. "Filter runs, 2 filters active"), and
`FilterCheckItem` exposes `toggleableState` plus `Role.Checkbox`, so TalkBack
announces the count and which facet is checked.
Re-verified on this tree (Homebrew JDK 25, Gradle 9.7.1,
`ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--offline`):
- `gradle --offline :app:testDebugUnitTest --rerun-tasks` → **185 tests, 0
failures** (new `FilterMenuTest`: the height helper's proportional/positive
growth and the description's 0/1/2/negative wording).
- `gradle --offline :app:assembleDebug` succeeded → `app-debug.apk` **18,005,500
bytes**, sha256 `7351c13b…`.
- On `emulator-5556` (2208x1840, density 420, dark mode) against
`ws://10.0.2.2:8080/connect`, captured with `android/scripts/capture_png.sh -s
emulator-5556` into `…/artifacts/89/4/`:
- The runs menu now has window `[1210,75]–[1945,1639]` (1564px = the 596dp cap),
ending ~138px above the gesture exclusion (y=1777); `Filters`/`Clear filters`
sit at the top (y=133–186) and after four swipes the last item `Last 30 days`
is at y=1466–1519, fully visible with the nav spacer below it
(`02_runs_filter_menu.png`).
- `uiautomator dump` reports the runs filter rows `checkable=true` with the
selected row `checked=true` (`Any time`), and the icon `content-desc` is
`Filter runs, 2 filters active` / `Filter runs, 1 filter active` matching
the badge (`03_runs_filtered_failed.png`, `01_runs_filtered_empty.png`).
- The pipelines menu (`Filters`/`Clear filters` at the top, `Runs` and `Last run
status` sections) is `[1542,93]–[1945,1622]`, also above the inset
(`04_pipelines_filter_menu.png`); `Has runs` + last-run `succeeded` filtered
the list (`05_…png`), `No runs` + `succeeded` showed `No pipelines match the
current filters.` with `Clear filters` (`06_…png`).
- **Persistence proof.** `am force-stop net.awan.pipelines` (verified `pidof`
empty) then `am start` and a fresh dump showed the pipelines screen still
filtered (badge `2`) and the runs list still `Filter runs, 1 filter active`
(`07_…png`, `08_…png`), with no interaction.
- `adb -s emulator-5556 logcat -d | grep -c 'FATAL EXCEPTION'` and `… | grep -c
'E AndroidRuntime'` each returned 0.
- **APK publish.** `app-debug.apk` copied to
`…/artifacts/89/4/pipelines-debug-wip-1c925d7.apk` (`1c925d7` = `git rev-parse
--short HEAD`); `shasum -a 256` matched. `curl` against
`http://10.0.0.75:8080/artifacts/89/4/pipelines-debug-wip-1c925d7.apk` returned
`HTTP 200`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 18005500`.
Not verified: the **"nothing exists"** variants (`No pipelines are defined on this
server.` / `No runs have been recorded yet.`) were not captured — the live server
has both pipelines and runs, `list_runs` is not workspace-scoped, and the task
forbids touching the server's data, so there was no empty source to render them
against; the branch is unit-covered only indirectly. A real hardware fold and
`:app:lintDebug` were again not exercised.
@@ -30,6 +30,25 @@ class SettingsRepository(context: Context) {
private val _runSort = MutableStateFlow(prefs.getString(KEY_RUN_SORT, "").orEmpty())
val runSort: StateFlow<String> = _runSort.asStateFlow()
// The chosen list filters, stored as their stable storage keys/encodings and
// resolved (with a default fallback for a stale/unknown value) by the list
// screens, so this repository stays unaware of the UI's filter enums.
private val _runFilterStatuses = MutableStateFlow(prefs.getString(KEY_RUN_FILTER_STATUSES, "").orEmpty())
val runFilterStatuses: StateFlow<String> = _runFilterStatuses.asStateFlow()
private val _runFilterPipeline = MutableStateFlow(prefs.getString(KEY_RUN_FILTER_PIPELINE, "").orEmpty())
val runFilterPipeline: StateFlow<String> = _runFilterPipeline.asStateFlow()
private val _runFilterTimeRange = MutableStateFlow(prefs.getString(KEY_RUN_FILTER_TIME_RANGE, "").orEmpty())
val runFilterTimeRange: StateFlow<String> = _runFilterTimeRange.asStateFlow()
private val _pipelineFilterPresence = MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_PRESENCE, "").orEmpty())
val pipelineFilterPresence: StateFlow<String> = _pipelineFilterPresence.asStateFlow()
private val _pipelineFilterRunStatuses =
MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_RUN_STATUSES, "").orEmpty())
val pipelineFilterRunStatuses: StateFlow<String> = _pipelineFilterRunStatuses.asStateFlow()
fun setServerUrl(value: String) {
val trimmed = value.trim()
_serverUrl.value = trimmed
@@ -52,6 +71,31 @@ class SettingsRepository(context: Context) {
prefs.edit().putString(KEY_RUN_SORT, value).apply()
}
fun setRunFilterStatuses(value: String) {
_runFilterStatuses.value = value
prefs.edit().putString(KEY_RUN_FILTER_STATUSES, value).apply()
}
fun setRunFilterPipeline(value: String) {
_runFilterPipeline.value = value
prefs.edit().putString(KEY_RUN_FILTER_PIPELINE, value).apply()
}
fun setRunFilterTimeRange(value: String) {
_runFilterTimeRange.value = value
prefs.edit().putString(KEY_RUN_FILTER_TIME_RANGE, value).apply()
}
fun setPipelineFilterPresence(value: String) {
_pipelineFilterPresence.value = value
prefs.edit().putString(KEY_PIPELINE_FILTER_PRESENCE, value).apply()
}
fun setPipelineFilterRunStatuses(value: String) {
_pipelineFilterRunStatuses.value = value
prefs.edit().putString(KEY_PIPELINE_FILTER_RUN_STATUSES, value).apply()
}
/** True only when the user has explicitly supplied both required values. */
fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank()
@@ -60,5 +104,10 @@ class SettingsRepository(context: Context) {
const val KEY_WORKSPACE = "workspace"
const val KEY_PIPELINE_SORT = "pipeline_sort"
const val KEY_RUN_SORT = "run_sort"
const val KEY_RUN_FILTER_STATUSES = "run_filter_statuses"
const val KEY_RUN_FILTER_PIPELINE = "run_filter_pipeline"
const val KEY_RUN_FILTER_TIME_RANGE = "run_filter_time_range"
const val KEY_PIPELINE_FILTER_PRESENCE = "pipeline_filter_presence"
const val KEY_PIPELINE_FILTER_RUN_STATUSES = "pipeline_filter_run_statuses"
}
}
@@ -52,6 +52,13 @@ class AppViewModel(
val pipelineSort: StateFlow<String> = settings.pipelineSort
val runSort: StateFlow<String> = settings.runSort
/** The stored pipeline/run filter keys; the list screens resolve them to filters. */
val runFilterStatuses: StateFlow<String> = settings.runFilterStatuses
val runFilterPipeline: StateFlow<String> = settings.runFilterPipeline
val runFilterTimeRange: StateFlow<String> = settings.runFilterTimeRange
val pipelineFilterPresence: StateFlow<String> = settings.pipelineFilterPresence
val pipelineFilterRunStatuses: StateFlow<String> = settings.pipelineFilterRunStatuses
private val _serverUrlDraft = MutableStateFlow(settings.serverUrl.value)
val serverUrlDraft: StateFlow<String> = _serverUrlDraft.asStateFlow()
@@ -161,6 +168,16 @@ class AppViewModel(
fun setRunSort(storageKey: String) = settings.setRunSort(storageKey)
fun setRunFilterStatuses(value: String) = settings.setRunFilterStatuses(value)
fun setRunFilterPipeline(value: String) = settings.setRunFilterPipeline(value)
fun setRunFilterTimeRange(value: String) = settings.setRunFilterTimeRange(value)
fun setPipelineFilterPresence(value: String) = settings.setPipelineFilterPresence(value)
fun setPipelineFilterRunStatuses(value: String) = settings.setPipelineFilterRunStatuses(value)
private fun awaitConnected() {
viewModelScope.launch {
val connected = withTimeoutOrNull(CONNECT_TIMEOUT_MILLIS) {
@@ -0,0 +1,178 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
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.platform.LocalConfiguration
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.toggleableState
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The tallest a list-filter menu may grow, as a fraction of the window height.
* Derived from the window rather than a fixed row count so the menu stays inside
* the window and clear of the navigation inset no matter how many distinct
* pipelines the runs list contributes (N made the old menu unbounded); beyond
* this the menu scrolls internally.
*/
internal fun filterMenuMaxHeight(screenHeightDp: Int): Dp = (screenHeightDp * 0.85f).dp
/**
* The filter icon's content description. With active filters the count is spoken
* ("Filter runs, 2 filters active") so the badge is not a purely visual signal;
* with none the plain [base] stands.
*/
internal fun filterMenuDescription(base: String, activeCount: Int): String = when {
activeCount <= 0 -> base
activeCount == 1 -> "$base, 1 filter active"
else -> "$base, $activeCount filters active"
}
/**
* The shared list-filter control: a top-bar icon carrying an active-filter count
* badge, opening the caller's [optionContent] plus one [resetLabel] action. It is
* its own action with a distinct glyph and content description, so it cannot
* collide with the adjacent sort or refresh actions, and the same control serves
* both list widths (a `DropdownMenu` is not width-dependent geometry).
*
* [activeCount] is drawn as a numeric badge (0 hides it) and folded into the
* icon's description, so "filters are active" is never colour alone and the
* count is announced. The menu is capped at a window-derived [filterMenuMaxHeight]
* and the reset action is the first item, so the reset is always in view on open
* and the last option is reachable by scrolling rather than clipped; a trailing
* navigation-bar spacer keeps the final option above the gesture inset.
* [optionContent] receives a `dismiss` callback: a single-select entry calls it to
* close the menu, while a multi-select toggle simply omits it to keep the menu
* open.
*/
@Composable
fun FilterMenu(
activeCount: Int,
contentDescription: String,
resetLabel: String,
onReset: () -> Unit,
modifier: Modifier = Modifier,
optionContent: @Composable (dismiss: () -> Unit) -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
val maxMenuHeight = filterMenuMaxHeight(LocalConfiguration.current.screenHeightDp)
val bottomInset = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
Box(modifier) {
BadgedBox(
badge = {
if (activeCount > 0) {
Badge { Text(activeCount.toString()) }
}
},
) {
IconButton(onClick = { expanded = true }) {
Icon(
Icons.Default.FilterList,
contentDescription = filterMenuDescription(contentDescription, activeCount),
)
}
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier.heightIn(max = maxMenuHeight),
) {
Row(
modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = "Filters",
style = pipelinesText().label,
color = MaterialTheme.colorScheme.primary,
)
TextButton(
onClick = {
onReset()
expanded = false
},
enabled = activeCount > 0,
) {
Text(resetLabel)
}
}
HorizontalDivider()
optionContent { expanded = false }
Spacer(Modifier.height(bottomInset))
}
}
}
/**
* One checkable filter entry, sharing the sort menu's leading-check idiom so the
* active value is conveyed by a glyph as well as by text, and exposing the
* checked state to accessibility ([toggleableState] plus [Role.Checkbox]) so
* TalkBack announces which facet is selected rather than only the label. The
* caller decides whether to dismiss: a single-select option closes the menu, a
* multi-select toggle leaves it open so several values can be gathered.
*/
@Composable
fun FilterCheckItem(
label: String,
checked: Boolean,
onClick: () -> Unit,
) {
DropdownMenuItem(
text = { Text(label) },
onClick = onClick,
modifier = Modifier.semantics {
role = Role.Checkbox
toggleableState = if (checked) ToggleableState.On else ToggleableState.Off
},
leadingIcon = {
if (checked) {
Icon(Icons.Default.Check, contentDescription = null)
}
},
)
}
/** A small section caption inside a filter menu (Status/Pipeline/Time range). */
@Composable
fun FilterSectionHeader(label: String) {
Text(
text = label,
style = pipelinesText().label,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
)
}
@@ -49,8 +49,18 @@ fun ErrorState(message: String, onRetry: (() -> Unit)? = null, modifier: Modifie
}
}
/**
* An empty-list message. [actionLabel]/[onAction] add one recovery action (the
* "nothing matches the current filters" case offers Clear filters); both are
* omitted for the "nothing exists" case, where there is nothing to clear.
*/
@Composable
fun EmptyState(message: String, modifier: Modifier = Modifier) {
fun EmptyState(
message: String,
modifier: Modifier = Modifier,
actionLabel: String? = null,
onAction: (() -> Unit)? = null,
) {
Column(
modifier = modifier.fillMaxSize().padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
@@ -62,6 +72,11 @@ fun EmptyState(message: String, modifier: Modifier = Modifier) {
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (actionLabel != null && onAction != null) {
Button(onClick = onAction, modifier = Modifier.padding(top = 16.dp)) {
Text(actionLabel)
}
}
}
}
@@ -0,0 +1,246 @@
package net.awan.pipelines.ui.screens
import java.time.LocalDate
import java.time.ZoneId
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.parseInstant
/**
* The run-list time windows offered by the filter control. [storageKey] is the
* stable value persisted in SharedPreferences; [fromStorage] tolerates a stale,
* unknown or blank stored value by returning [Default] ("any time").
*/
enum class RunTimeRange(val label: String, val storageKey: String) {
AnyTime("Any time", "any_time"),
Today("Today", "today"),
Last7Days("Last 7 days", "last_7_days"),
Last30Days("Last 30 days", "last_30_days");
companion object {
val Default = AnyTime
fun fromStorage(value: String?): RunTimeRange =
entries.firstOrNull { it.storageKey == value } ?: Default
}
}
/**
* Whether the pipeline list only shows pipelines that have (or have not)
* recorded a run, persisted like [RunTimeRange]. [Default] is no narrowing.
*/
enum class RunPresence(val label: String, val storageKey: String) {
Any("Any", "any"),
HasRuns("Has runs", "has_runs"),
NoRuns("No runs", "no_runs");
companion object {
val Default = Any
fun fromStorage(value: String?): RunPresence =
entries.firstOrNull { it.storageKey == value } ?: Default
}
}
/**
* The statuses a run filter can select. The server's own run vocabulary
* (internal/pipeline/runs.go: queued/running/succeeded/failed/canceled/
* interrupted); the app-only `active` usage bucket and the `unknown` fallback
* are deliberately not offered, so a status filter always names a real state.
*/
internal val RUN_STATUS_FILTERS: List<RunState> = listOf(
RunState.Queued,
RunState.Running,
RunState.Succeeded,
RunState.Failed,
RunState.Canceled,
RunState.Interrupted,
)
/** Adds [state] when absent, removes it when present — the multi-select toggle. */
internal fun Set<RunState>.toggle(state: RunState): Set<RunState> =
if (state in this) this - state else this + state
/**
* The stable stored form of a status set: the states' server status words in
* ordinal order, comma-joined. [RunState.label] is that word and is unique per
* state, so the encoding round-trips and stays meaningful in the prefs file.
*/
internal fun encodeRunStates(states: Set<RunState>): String =
states.sortedBy { it.ordinal }.joinToString(",") { it.label }
/** Decodes [encodeRunStates], dropping unknown or blank tokens rather than crashing. */
internal fun decodeRunStates(value: String?): Set<RunState> =
value.orEmpty().split(',').mapNotNull { token ->
val word = token.trim()
RunState.entries.firstOrNull { it.label == word }
}.toSet()
/**
* The runs-list filters, each defaulting to "no narrowing" so the default value
* filters nothing. [activeCount] is the number of active facets (one per
* status/pipeline/time choice), used for the control's badge.
*/
data class RunFilters(
val statuses: Set<RunState> = emptySet(),
val pipelineId: Long? = null,
val timeRange: RunTimeRange = RunTimeRange.Default,
) {
val activeCount: Int
get() = (if (statuses.isNotEmpty()) 1 else 0) +
(if (pipelineId != null) 1 else 0) +
(if (timeRange != RunTimeRange.Default) 1 else 0)
val isActive: Boolean get() = activeCount > 0
companion object {
val Default = RunFilters()
fun fromStorage(statuses: String?, pipelineId: String?, timeRange: String?): RunFilters =
RunFilters(
statuses = decodeRunStates(statuses),
pipelineId = pipelineId?.trim()?.takeIf { it.isNotEmpty() }?.toLongOrNull(),
timeRange = RunTimeRange.fromStorage(timeRange),
)
}
}
/**
* The pipelines-list run filters: whether a pipeline has any recorded run and
* the status of its most recent one. The name search stays a separate control
* (it narrows by text, not by run facts); these two are persisted per list.
*/
data class PipelineFilters(
val presence: RunPresence = RunPresence.Default,
val lastRunStatuses: Set<RunState> = emptySet(),
) {
val activeCount: Int
get() = (if (presence != RunPresence.Default) 1 else 0) +
(if (lastRunStatuses.isNotEmpty()) 1 else 0)
val isActive: Boolean get() = activeCount > 0
companion object {
val Default = PipelineFilters()
fun fromStorage(presence: String?, lastRunStatuses: String?): PipelineFilters =
PipelineFilters(
presence = RunPresence.fromStorage(presence),
lastRunStatuses = decodeRunStates(lastRunStatuses),
)
}
}
/** True when [run] is in [statuses]; an empty set means "any status". */
internal fun runMatchesStatuses(run: RunSummary, statuses: Set<RunState>): Boolean =
statuses.isEmpty() || runStateOf(run.status) in statuses
/** True when [run] belongs to [pipelineId]; null means "any pipeline". */
internal fun runMatchesPipeline(run: RunSummary, pipelineId: Long?): Boolean =
pipelineId == null || run.pipelineId == pipelineId
/** The run's start date in [zone], or null when blank/unparseable. */
internal fun runLocalDate(createdAt: String, zone: ZoneId): LocalDate? =
parseInstant(createdAt)?.atZoneSameInstant(zone)?.toLocalDate()
/**
* True when [run] falls inside [range] relative to [today]. A blank/unparseable
* timestamp and a future-dated run (clock skew) never match a finite window;
* [RunTimeRange.AnyTime] matches everything. The window is inclusive calendar
* days ending today: "last 7 days" covers today and the six days before it.
*/
internal fun runMatchesTimeRange(
run: RunSummary,
range: RunTimeRange,
today: LocalDate,
zone: ZoneId,
): Boolean {
if (range == RunTimeRange.AnyTime) return true
val date = runLocalDate(run.createdAt, zone) ?: return false
if (date.isAfter(today)) return false
return when (range) {
RunTimeRange.Today -> date == today
RunTimeRange.Last7Days -> !date.isBefore(today.minusDays(6))
RunTimeRange.Last30Days -> !date.isBefore(today.minusDays(29))
RunTimeRange.AnyTime -> true
}
}
/** Every run facet combined with AND. */
internal fun runMatchesFilters(
run: RunSummary,
filters: RunFilters,
today: LocalDate,
zone: ZoneId,
): Boolean =
runMatchesStatuses(run, filters.statuses) &&
runMatchesPipeline(run, filters.pipelineId) &&
runMatchesTimeRange(run, filters.timeRange, today, zone)
/** Narrows [runs] by [filters]; the default filters change nothing. */
internal fun filterRuns(
runs: List<RunSummary>,
filters: RunFilters,
today: LocalDate,
zone: ZoneId,
): List<RunSummary> =
if (!filters.isActive) runs else runs.filter { runMatchesFilters(it, filters, today, zone) }
/** True when [presence] is satisfied by whether the pipeline [hasRun]. */
internal fun pipelineMatchesPresence(presence: RunPresence, hasRun: Boolean): Boolean = when (presence) {
RunPresence.Any -> true
RunPresence.HasRuns -> hasRun
RunPresence.NoRuns -> !hasRun
}
/**
* True when [latestRun]'s status is in [statuses]; an empty set means "any
* status" and a pipeline with no run never matches a selected status (there is
* no last-run status to compare), so the filter genuinely narrows.
*/
internal fun pipelineMatchesLastRunStatus(latestRun: RunSummary?, statuses: Set<RunState>): Boolean =
statuses.isEmpty() || (latestRun != null && runStateOf(latestRun.status) in statuses)
/** Every pipeline run facet combined with AND. */
internal fun pipelineMatchesFilters(filters: PipelineFilters, latestRun: RunSummary?): Boolean =
pipelineMatchesPresence(filters.presence, latestRun != null) &&
pipelineMatchesLastRunStatus(latestRun, filters.lastRunStatuses)
/**
* Narrows [pipelines] by [filters]. Both facets depend on the run history, so
* while that history is still unknown (`runsKnown == false`) the list is left
* unfiltered rather than briefly hiding every pipeline.
*/
internal fun filterPipelines(
pipelines: List<PipelineSummary>,
filters: PipelineFilters,
latestRuns: Map<Long, RunSummary>,
runsKnown: Boolean = true,
): List<PipelineSummary> {
if (!filters.isActive || !runsKnown) return pipelines
return pipelines.filter { pipelineMatchesFilters(filters, latestRuns[it.id]) }
}
/** One selectable pipeline in the run filter, named from its runs. */
internal data class PipelineFilterOption(val id: Long, val name: String)
/**
* The distinct pipelines present in [runs], each named by its most recent
* non-blank run name and ordered case-insensitively by name then id, so the
* run-list pipeline filter needs no separate pipeline fetch. A blank name falls
* back to the id so the entry is never unlabelled.
*/
internal fun pipelineFilterOptions(runs: List<RunSummary>): List<PipelineFilterOption> {
val names = LinkedHashMap<Long, String>()
for (run in runs) {
val current = names[run.pipelineId]
if (current == null || current.isBlank()) names[run.pipelineId] = run.name
}
return names.map { (id, name) -> PipelineFilterOption(id, name.ifBlank { "Pipeline $id" }) }
.sortedWith(
compareBy<PipelineFilterOption, String>(String.CASE_INSENSITIVE_ORDER) { it.name }
.thenBy { it.id },
)
}
@@ -14,6 +14,7 @@ import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
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
@@ -37,9 +38,13 @@ import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.FilterCheckItem
import net.awan.pipelines.ui.components.FilterMenu
import net.awan.pipelines.ui.components.FilterSectionHeader
import net.awan.pipelines.ui.components.ListRow
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.PaneIdentity
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.RunStatusChip
import net.awan.pipelines.ui.components.SortMenu
import net.awan.pipelines.ui.theme.pipelinesText
@@ -57,6 +62,9 @@ fun PipelineListScreen(
val runsState by vm.runs.collectAsStateWithLifecycle()
val sortKey by vm.pipelineSort.collectAsStateWithLifecycle()
val sort = PipelineSort.fromStorage(sortKey)
val presenceKey by vm.pipelineFilterPresence.collectAsStateWithLifecycle()
val runStatusKey by vm.pipelineFilterRunStatuses.collectAsStateWithLifecycle()
val filters = PipelineFilters.fromStorage(presenceKey, runStatusKey)
var query by remember { mutableStateOf("") }
// The last-run line joins list_runs onto the pipelines client-side; runs are
@@ -80,6 +88,12 @@ fun PipelineListScreen(
// the explicit "no runs recorded" claim.
val runsKnown = runsState.data != null
val onClearFilters: () -> Unit = {
vm.setPipelineFilterPresence("")
vm.setPipelineFilterRunStatuses("")
query = ""
}
// A covered pane shows its compact identity only; the search field and list
// must never be drawn squeezed into the peek strip.
if (covered) {
@@ -98,6 +112,12 @@ fun PipelineListScreen(
TopAppBar(
title = { Text("Pipelines") },
actions = {
PipelineFilterControl(
filters = filters,
onPresence = { vm.setPipelineFilterPresence(it.storageKey) },
onRunStatuses = { vm.setPipelineFilterRunStatuses(encodeRunStates(it)) },
onClear = onClearFilters,
)
SortMenu(
options = PipelineSort.entries,
selected = sort,
@@ -131,15 +151,34 @@ fun PipelineListScreen(
state.loading && state.data == null -> LoadingState("Loading pipelines…")
state.error != null && state.data == null -> ErrorState(state.error!!, onRetry = vm::refreshPipelines)
else -> {
val items = remember(state.data, query, sort, latestRuns) {
sortPipelines(state.data ?: emptyList(), sort, latestRuns)
.filter { it.name.contains(query, ignoreCase = true) }
val all = state.data ?: emptyList()
val items = remember(all, query, sort, latestRuns, filters, runsKnown) {
filterPipelines(
sortPipelines(all, sort, latestRuns),
filters,
latestRuns,
runsKnown,
).filter { it.name.contains(query, ignoreCase = true) }
}
if (items.isEmpty()) {
EmptyState(
if (query.isBlank()) "No pipelines are defined on this server."
else "No pipelines match \"$query\".",
)
if (all.isEmpty()) {
// Nothing exists: neither the search nor the filters can
// reveal a pipeline, so there is no clear action.
EmptyState("No pipelines are defined on this server.")
} else {
val queryActive = query.isNotBlank()
val filtersActive = filters.isActive && runsKnown
EmptyState(
message = when {
queryActive && filtersActive ->
"No pipelines match the current search and filters."
queryActive -> "No pipelines match \"$query\"."
else -> "No pipelines match the current filters."
},
actionLabel = "Clear filters",
onAction = onClearFilters,
)
}
} else {
LazyColumn(
modifier = Modifier.fillMaxSize(),
@@ -169,6 +208,41 @@ fun PipelineListScreen(
}
}
/**
* The pipelines-list run filter control: presence (has/no runs) and the
* most-recent run's status (multi-select), with the shared active-count badge
* and one Clear filters action. The name search stays a separate field.
*/
@Composable
private fun PipelineFilterControl(
filters: PipelineFilters,
onPresence: (RunPresence) -> Unit,
onRunStatuses: (Set<RunState>) -> Unit,
onClear: () -> Unit,
) {
FilterMenu(
activeCount = filters.activeCount,
contentDescription = "Filter pipelines",
resetLabel = "Clear filters",
onReset = onClear,
) { dismiss ->
FilterSectionHeader("Runs")
RunPresence.entries.forEach { presence ->
FilterCheckItem(presence.label, filters.presence == presence) {
onPresence(presence)
dismiss()
}
}
HorizontalDivider()
FilterSectionHeader("Last run status")
RUN_STATUS_FILTERS.forEach { state ->
FilterCheckItem(state.label, state in filters.lastRunStatuses) {
onRunStatuses(filters.lastRunStatuses.toggle(state))
}
}
}
}
/**
* One pipeline as a row of the shared real list: a leading workflow glyph, the
* name as the title, the id/version/stage-count as the secondary line and the
@@ -20,6 +20,7 @@ import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@ -47,7 +48,11 @@ import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.RunStatusChip
import net.awan.pipelines.ui.components.RunStatusIcon
import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.FilterCheckItem
import net.awan.pipelines.ui.components.FilterMenu
import net.awan.pipelines.ui.components.FilterSectionHeader
import net.awan.pipelines.ui.components.ListRow
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.PaneIdentity
@@ -72,8 +77,23 @@ fun RunHistoryScreen(
val state by vm.runs.collectAsStateWithLifecycle()
val sortKey by vm.runSort.collectAsStateWithLifecycle()
val sort = RunSort.fromStorage(sortKey)
val statusFilterKey by vm.runFilterStatuses.collectAsStateWithLifecycle()
val pipelineFilterKey by vm.runFilterPipeline.collectAsStateWithLifecycle()
val timeRangeKey by vm.runFilterTimeRange.collectAsStateWithLifecycle()
val filters = RunFilters.fromStorage(statusFilterKey, pipelineFilterKey, timeRangeKey)
LaunchedEffect(Unit) { vm.refreshRuns() }
val onClearFilters: () -> Unit = {
vm.setRunFilterStatuses("")
vm.setRunFilterPipeline("")
vm.setRunFilterTimeRange("")
}
// The pipeline filter choices come from the runs already in hand, folded once
// per history load rather than rebuilt on every recomposition.
val pipelineOptions = remember(state.data) {
pipelineFilterOptions(state.data?.runs.orEmpty())
}
// A covered pane shows its compact identity only; the usage block, sticky day
// headers and run rows must never be drawn squeezed into the peek strip.
if (covered) {
@@ -92,6 +112,14 @@ fun RunHistoryScreen(
TopAppBar(
title = { Text(if (filterPipelineId == null) "Runs" else "Runs for this pipeline") },
actions = {
RunFilterControl(
filters = filters,
pipelines = pipelineOptions,
onStatuses = { vm.setRunFilterStatuses(encodeRunStates(it)) },
onPipeline = { vm.setRunFilterPipeline(it?.toString().orEmpty()) },
onTimeRange = { vm.setRunFilterTimeRange(it.storageKey) },
onClear = onClearFilters,
)
SortMenu(
options = RunSort.entries,
selected = sort,
@@ -120,14 +148,65 @@ fun RunHistoryScreen(
filterPipelineId = filterPipelineId,
selectedRunId = selectedRunId,
sort = sort,
filters = filters,
error = state.error,
onOpenRun = onOpenRun,
onClearFilters = onClearFilters,
modifier = Modifier.padding(padding),
)
}
}
}
/**
* The runs-list filter control: status (multi-select), pipeline (single-select)
* and time range, each section labelled inside one menu, with the shared
* active-count badge and one Clear filters action.
*/
@Composable
private fun RunFilterControl(
filters: RunFilters,
pipelines: List<PipelineFilterOption>,
onStatuses: (Set<RunState>) -> Unit,
onPipeline: (Long?) -> Unit,
onTimeRange: (RunTimeRange) -> Unit,
onClear: () -> Unit,
) {
FilterMenu(
activeCount = filters.activeCount,
contentDescription = "Filter runs",
resetLabel = "Clear filters",
onReset = onClear,
) { dismiss ->
FilterSectionHeader("Status")
RUN_STATUS_FILTERS.forEach { state ->
FilterCheckItem(state.label, state in filters.statuses) {
onStatuses(filters.statuses.toggle(state))
}
}
HorizontalDivider()
FilterSectionHeader("Pipeline")
FilterCheckItem("Any pipeline", filters.pipelineId == null) {
onPipeline(null)
dismiss()
}
pipelines.forEach { option ->
FilterCheckItem(option.name, filters.pipelineId == option.id) {
onPipeline(option.id)
dismiss()
}
}
HorizontalDivider()
FilterSectionHeader("Time range")
RunTimeRange.entries.forEach { range ->
FilterCheckItem(range.label, filters.timeRange == range) {
onTimeRange(range)
dismiss()
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun RunHistoryContent(
@@ -136,21 +215,26 @@ private fun RunHistoryContent(
filterPipelineId: Long?,
selectedRunId: Long?,
sort: RunSort,
filters: RunFilters,
error: String?,
onOpenRun: (Long) -> Unit,
onClearFilters: () -> Unit,
modifier: Modifier = Modifier,
) {
val zone = ZoneId.systemDefault()
val today = LocalDate.now(zone)
// The structural pipeline scope (a run list opened for one pipeline) and the
// user's filters both narrow, with AND semantics; the run history is folded
// once here, not per recomposition.
val scoped = remember(runs, filterPipelineId) {
if (filterPipelineId == null) runs else runs.filter { it.pipelineId == filterPipelineId }
}
val matched = remember(scoped, filters, today, zone) { filterRuns(scoped, filters, today, zone) }
// Day-grouping is derived once per data/order change (single pass, keyed on
// the stable source list), not per recomposition. The chosen comparator orders
// the runs first; the groups then follow the order their first run appears in.
val groups = remember(runs, filterPipelineId, sort) {
val filtered = if (filterPipelineId == null) {
runs
} else {
runs.filter { it.pipelineId == filterPipelineId }
}
val zone = ZoneId.systemDefault()
groupRunsByDay(filtered, LocalDate.now(zone), zone, runComparator(sort))
val groups = remember(matched, today, zone, sort) {
groupRunsByDay(matched, today, zone, runComparator(sort))
}
LazyColumn(
@@ -162,13 +246,20 @@ private fun RunHistoryContent(
UsageMetrics(usage, Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
}
}
if (groups.isEmpty()) {
if (scoped.isEmpty()) {
// Nothing exists at all: no filter could reveal a run, so there is no
// clear action.
item(key = "runs-empty") {
Text(
"No runs have been recorded yet.",
style = pipelinesText().body,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(24.dp),
EmptyState("No runs have been recorded yet.")
}
} else if (matched.isEmpty()) {
// Runs exist but every one is filtered out: distinguish this from the
// "nothing exists" case and offer the one clear action.
item(key = "runs-filtered-empty") {
EmptyState(
message = "No runs match the current filters.",
actionLabel = "Clear filters",
onAction = onClearFilters,
)
}
} else {
@@ -376,7 +467,7 @@ internal fun groupRunsByDay(
}
internal fun dayLabel(createdAt: String, today: LocalDate, zone: ZoneId): String {
val date = runDate(createdAt, zone) ?: return "Unknown date"
val date = runLocalDate(createdAt, zone) ?: return "Unknown date"
return when (date) {
today -> "Today"
today.minusDays(1) -> "Yesterday"
@@ -384,12 +475,5 @@ internal fun dayLabel(createdAt: String, today: LocalDate, zone: ZoneId): String
}
}
private fun runDate(createdAt: String, zone: ZoneId): LocalDate? {
if (createdAt.isBlank()) return null
return runCatching {
OffsetDateTime.parse(createdAt).atZoneSameInstant(zone).toLocalDate()
}.getOrNull()
}
private val DAY_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM yyyy")
private val START_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM HH:mm")
@@ -0,0 +1,29 @@
package net.awan.pipelines.ui.components
import androidx.compose.ui.unit.dp
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class FilterMenuTest {
// --- menu height ------------------------------------------------------------
@Test
fun menuHeightGrowsWithTheWindowAndStaysPositive() {
assertEquals(0.85f * 700f, filterMenuMaxHeight(700).value, 0.01f)
assertTrue(filterMenuMaxHeight(360) > 0.dp)
assertTrue(filterMenuMaxHeight(700) > filterMenuMaxHeight(360))
}
// --- accessibility description ---------------------------------------------
@Test
fun descriptionAnnouncesTheActiveCount() {
assertEquals("Filter runs", filterMenuDescription("Filter runs", 0))
assertEquals("Filter runs, 1 filter active", filterMenuDescription("Filter runs", 1))
assertEquals("Filter runs, 2 filters active", filterMenuDescription("Filter runs", 2))
// A negative count (defensive) is treated as no filters, never "-1 filters".
assertEquals("Filter pipelines", filterMenuDescription("Filter pipelines", -1))
}
}
@@ -0,0 +1,231 @@
package net.awan.pipelines.ui.screens
import java.time.LocalDate
import java.time.ZoneOffset
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.ui.components.RunState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ListFilterTest {
private val today = LocalDate.of(2026, 10, 16)
private val zone = ZoneOffset.UTC
private fun pipeline(id: Long, name: String = "p$id") =
PipelineSummary(id = id, name = name, version = 1, stages = 1)
private fun run(
id: Long,
pipelineId: Long = 1,
name: String = "p$pipelineId",
status: String = "succeeded",
createdAt: String = "2026-10-16T10:00:00Z",
finishedAt: String = "2026-10-16T10:00:10Z",
) = RunSummary(
id = id,
pipelineId = pipelineId,
name = name,
status = status,
createdAt = createdAt,
finishedAt = finishedAt,
)
// --- stored-value tolerance -------------------------------------------------
@Test
fun runFiltersFromStorageParsesEveryFacetAndFallsBackForStaleValues() {
assertEquals(
RunFilters(setOf(RunState.Succeeded, RunState.Failed), 7L, RunTimeRange.Last7Days),
RunFilters.fromStorage("succeeded,failed", "7", "last_7_days"),
)
// An unknown status token is dropped rather than crashing.
assertEquals(
setOf(RunState.Succeeded),
RunFilters.fromStorage("succeeded,bogus", null, null).statuses,
)
// Stale/blank/unknown values fall back to the defaults.
assertEquals(RunFilters.Default, RunFilters.fromStorage(null, null, null))
assertEquals(RunFilters.Default, RunFilters.fromStorage("", "", ""))
assertEquals(RunFilters.Default, RunFilters.fromStorage("nope", "not-a-number", "no_such_range"))
}
@Test
fun pipelineFiltersFromStorageParsesAndFallsBack() {
assertEquals(
PipelineFilters(RunPresence.NoRuns, setOf(RunState.Failed)),
PipelineFilters.fromStorage("no_runs", "failed"),
)
assertEquals(PipelineFilters.Default, PipelineFilters.fromStorage(null, null))
assertEquals(PipelineFilters.Default, PipelineFilters.fromStorage("garbage", "garbage"))
}
@Test
fun encodeDecodeRoundTripsAndToleratesGarbage() {
val states = setOf(RunState.Failed, RunState.Queued)
assertEquals(states, decodeRunStates(encodeRunStates(states)))
// Ordinal order, so the stored string is stable whatever the set order.
assertEquals("queued,failed", encodeRunStates(states))
assertEquals(emptySet<RunState>(), decodeRunStates(""))
assertEquals(emptySet<RunState>(), decodeRunStates(null))
assertEquals(setOf(RunState.Running), decodeRunStates("bogus,running,,"))
}
// --- run status -------------------------------------------------------------
@Test
fun anEmptyStatusSetMatchesAnyStatus() {
assertTrue(runMatchesStatuses(run(1, status = "running"), emptySet()))
assertTrue(runMatchesStatuses(run(1, status = ""), emptySet()))
}
@Test
fun statusFilterIsTheUnionOfTheSelectedStates() {
val statuses = setOf(RunState.Failed, RunState.Canceled)
assertTrue(runMatchesStatuses(run(1, status = "failed"), statuses))
assertTrue(runMatchesStatuses(run(2, status = "canceled"), statuses))
assertFalse(runMatchesStatuses(run(3, status = "succeeded"), statuses))
// The app-only buckets are not offered, so they never match a selection.
assertFalse(runMatchesStatuses(run(4, status = "active"), statuses))
assertFalse(runMatchesStatuses(run(5, status = "made-up"), statuses))
}
// --- run pipeline -----------------------------------------------------------
@Test
fun pipelineFilterMatchesOnlyThatPipelineAndNullMeansAny() {
assertTrue(runMatchesPipeline(run(1, pipelineId = 5), 5))
assertFalse(runMatchesPipeline(run(1, pipelineId = 5), 6))
assertTrue(runMatchesPipeline(run(1, pipelineId = 5), null))
}
// --- run time range ---------------------------------------------------------
@Test
fun timeRangeWindowsAreInclusiveCalendarDaysEndingToday() {
fun at(date: String) = run(1, createdAt = "${date}T09:00:00Z")
// Today.
assertTrue(runMatchesTimeRange(at("2026-10-16"), RunTimeRange.Today, today, zone))
assertFalse(runMatchesTimeRange(at("2026-10-15"), RunTimeRange.Today, today, zone))
// Last 7 days covers today and the six days before it.
assertTrue(runMatchesTimeRange(at("2026-10-16"), RunTimeRange.Last7Days, today, zone))
assertTrue(runMatchesTimeRange(at("2026-10-10"), RunTimeRange.Last7Days, today, zone))
assertFalse(runMatchesTimeRange(at("2026-10-09"), RunTimeRange.Last7Days, today, zone))
// Last 30 days covers today and the twenty-nine days before it.
assertTrue(runMatchesTimeRange(at("2026-09-17"), RunTimeRange.Last30Days, today, zone))
assertFalse(runMatchesTimeRange(at("2026-09-16"), RunTimeRange.Last30Days, today, zone))
// Any time matches an old run and a blank timestamp alike.
assertTrue(runMatchesTimeRange(at("2020-01-01"), RunTimeRange.AnyTime, today, zone))
assertTrue(runMatchesTimeRange(run(1, createdAt = ""), RunTimeRange.AnyTime, today, zone))
}
@Test
fun blankOrFutureTimestampsNeverMatchAFiniteRange() {
assertFalse(runMatchesTimeRange(run(1, createdAt = ""), RunTimeRange.Today, today, zone))
assertFalse(runMatchesTimeRange(run(1, createdAt = "not-a-date"), RunTimeRange.Last7Days, today, zone))
// A future-dated run (clock skew) is outside every past window.
assertFalse(runMatchesTimeRange(run(1, createdAt = "2026-10-17T09:00:00Z"), RunTimeRange.Today, today, zone))
assertFalse(runMatchesTimeRange(run(1, createdAt = "2026-10-17T09:00:00Z"), RunTimeRange.Last7Days, today, zone))
}
// --- run combination --------------------------------------------------------
@Test
fun defaultRunFiltersNarrowNothing() {
val runs = listOf(run(1, status = "running", createdAt = ""), run(2, status = "failed"))
assertEquals(runs, filterRuns(runs, RunFilters.Default, today, zone))
}
@Test
fun runFacetsCombineWithAnd() {
val filters = RunFilters(
statuses = setOf(RunState.Succeeded),
pipelineId = 2L,
timeRange = RunTimeRange.Today,
)
val runs = listOf(
// Right status but wrong pipeline.
run(1, pipelineId = 1, status = "succeeded", createdAt = "2026-10-16T08:00:00Z"),
// Right pipeline but wrong status.
run(2, pipelineId = 2, status = "failed", createdAt = "2026-10-16T08:00:00Z"),
// Right pipeline/status but outside today.
run(3, pipelineId = 2, status = "succeeded", createdAt = "2026-10-10T08:00:00Z"),
// The one match.
run(4, pipelineId = 2, status = "succeeded", createdAt = "2026-10-16T08:00:00Z"),
)
assertEquals(listOf(4L), filterRuns(runs, filters, today, zone).map { it.id })
}
// --- pipeline run facets ----------------------------------------------------
@Test
fun presenceSplitsPipelinesByWhetherTheyHaveARecordedRun() {
assertTrue(pipelineMatchesPresence(RunPresence.Any, hasRun = false))
assertTrue(pipelineMatchesPresence(RunPresence.HasRuns, hasRun = true))
assertFalse(pipelineMatchesPresence(RunPresence.HasRuns, hasRun = false))
assertTrue(pipelineMatchesPresence(RunPresence.NoRuns, hasRun = false))
assertFalse(pipelineMatchesPresence(RunPresence.NoRuns, hasRun = true))
}
@Test
fun lastRunStatusExcludesRunlessPipelinesAndEmptyMeansAny() {
val failed = setOf(RunState.Failed)
assertTrue(pipelineMatchesLastRunStatus(run(1, status = "failed"), failed))
assertFalse(pipelineMatchesLastRunStatus(run(1, status = "succeeded"), failed))
// No run at all: there is no last-run status, so a selection never matches.
assertFalse(pipelineMatchesLastRunStatus(null, failed))
// An empty selection matches a runless pipeline and any status.
assertTrue(pipelineMatchesLastRunStatus(null, emptySet()))
assertTrue(pipelineMatchesLastRunStatus(run(1, status = "running"), emptySet()))
}
@Test
fun defaultPipelineFiltersNarrowNothing() {
val pipelines = listOf(pipeline(1), pipeline(2))
assertEquals(pipelines, filterPipelines(pipelines, PipelineFilters.Default, emptyMap()))
}
@Test
fun pipelineFiltersCombineWithAnd() {
val filters = PipelineFilters(
presence = RunPresence.HasRuns,
lastRunStatuses = setOf(RunState.Failed),
)
val latest = mapOf(
1L to run(1, pipelineId = 1, status = "succeeded"),
2L to run(2, pipelineId = 2, status = "failed"),
)
val pipelines = listOf(pipeline(1), pipeline(2), pipeline(3))
// No runs (3) fails presence; succeeded last run (1) fails the status.
assertEquals(listOf(2L), filterPipelines(pipelines, filters, latest).map { it.id })
}
@Test
fun pipelineFiltersLeaveTheListUnfilteredUntilRunsAreKnown() {
val filters = PipelineFilters(presence = RunPresence.NoRuns)
val pipelines = listOf(pipeline(1))
// Runs not loaded yet: filtering by them would briefly hide everything.
assertEquals(pipelines, filterPipelines(pipelines, filters, emptyMap(), runsKnown = false))
// Once known, the filter applies (pipeline 1 has no run).
assertEquals(pipelines, filterPipelines(pipelines, filters, emptyMap(), runsKnown = true))
}
// --- pipeline options -------------------------------------------------------
@Test
fun pipelineFilterOptionsAreDistinctNamedFromRunsAndSorted() {
val runs = listOf(
run(1, pipelineId = 7, name = "Zeta"),
run(2, pipelineId = 3, name = "alpha"),
run(3, pipelineId = 7, name = "Zeta"),
run(4, pipelineId = 9, name = ""),
)
val options = pipelineFilterOptions(runs)
assertEquals(listOf(3L, 9L, 7L), options.map { it.id })
assertEquals(listOf("alpha", "Pipeline 9", "Zeta"), options.map { it.name })
assertEquals(3, options.size)
}
}