From 80f7b0adbc6554b656fed9fe7dd6b67c28e12771 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 19:29:40 +0100 Subject: [PATCH] android: add omni-search entry point and pill morph Add the fourth Search destination to the floating bottom container and morph that container into the omni-search field. - PipelinesApp: the destination pill gains a Search icon; tapping it animates the icons out and turns the same Surface into a focused text field whose size and position derive from the pill's own layout and the window insets rather than fixed pill sizes. Back, the back gesture and a scrim tap play the reverse and restore the pill with its previous destination still selected. The open field covers the content behind a scrim and shows a results panel above it. - OmniSearch: pure state model (open/focused/query) with the open, dismiss, focus and query transitions and a Bundle-able Saver, so an open field survives a saved-state round trip. - OmniSearchResults / SearchResultsPanel: map the typed search reply to rows and render the ranked results, keeping the last accepted results while a newer query loads and reporting a failure without blanking. - AppViewModel / PipelinesRepository: drive queries over the existing transport with debounce and reply ordering; the server search command arrives in a later item, so a reply is classified by envelope type and a non-search_results reply is reported with a clear message instead of being mis-parsed, never a crash. - Message: SEARCH / SEARCH_RESULTS constants and the SearchRequest, SearchResponse and per-kind result payloads. - AndroidManifest: adjustNothing so the app reads the IME from Compose window insets and the field is not cleared twice by a window resize. - Dimens: spacing for the search surface. - Unit tests for the state model (pill, opening, focused, dismissed and restored after the Saver round trip) and for the result-row mapping. --- android/app/src/main/AndroidManifest.xml | 12 +- .../pipelines/data/PipelinesRepository.kt | 11 + .../awan/pipelines/data/protocol/Message.kt | 126 +++++ .../net/awan/pipelines/ui/AppViewModel.kt | 73 +++ .../java/net/awan/pipelines/ui/OmniSearch.kt | 67 +++ .../awan/pipelines/ui/OmniSearchResults.kt | 288 ++++++++++++ .../net/awan/pipelines/ui/PipelinesApp.kt | 437 +++++++++++++++--- .../awan/pipelines/ui/SearchResultsPanel.kt | 213 +++++++++ .../net/awan/pipelines/ui/theme/Dimens.kt | 5 + .../data/protocol/ProtocolModelTest.kt | 73 +++ .../pipelines/ui/OmniSearchResultsTest.kt | 277 +++++++++++ .../net/awan/pipelines/ui/OmniSearchTest.kt | 77 +++ 12 files changed, 1583 insertions(+), 76 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/OmniSearch.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/OmniSearchResults.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/SearchResultsPanel.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/OmniSearchResultsTest.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/OmniSearchTest.kt diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 39130db7..6fbfba89 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -18,11 +18,21 @@ unencrypted ws:// on a trusted LAN/VPN. It is deliberately broad because the user types an arbitrary host. Do not expose the server to the internet. --> + + android:theme="@style/Theme.Pipelines" + android:windowSoftInputMode="adjustNothing"> diff --git a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt index 7ddf2975..ddf88040 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt @@ -10,6 +10,7 @@ import net.awan.pipelines.data.protocol.PipelineSummary import net.awan.pipelines.data.protocol.Protocol import net.awan.pipelines.data.protocol.RunDetail import net.awan.pipelines.data.protocol.RunSummary +import net.awan.pipelines.data.protocol.SearchRequest import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.data.protocol.UsageStats import net.awan.pipelines.data.transport.NotConnectedException @@ -72,6 +73,16 @@ class PipelinesRepository( suspend fun getRunEvidence(id: Long): List = client.call(Message(type = Protocol.GET_RUN_EVIDENCE, runId = id)).evidence ?: emptyList() + /** + * Sends one omni-search query over the shared transport and returns the raw + * reply envelope. The server command is still landing, so the reply is + * classified by its envelope type: [Protocol.SEARCH_RESULTS] is the accepted + * search, and any other type is an unexpected reply the caller reports rather + * than parsing. The typed result payload is added with the results item. + */ + suspend fun search(query: String): Message = + client.call(Message(type = Protocol.SEARCH, search = SearchRequest(query = query.trim()))) + /** Fetches an artifact's bytes (image preview) over the shared HTTP client. */ suspend fun fetchArtifactBytes(url: String): ByteArray = client.fetchBytes(url) diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt index 6f07efc3..a5c608f0 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt @@ -41,6 +41,19 @@ object Protocol { const val GET_STATUS = "get_status" const val STATUS = "status" + // search.go + const val SEARCH = "search" + const val SEARCH_RESULTS = "search_results" + + // search.go result kinds (mirrors protocol.SearchKind*); an empty kind + // searches every kind and an unknown kind is shown read-only. + const val SEARCH_KIND_PIPELINE = "pipeline" + const val SEARCH_KIND_VERSION = "version" + const val SEARCH_KIND_RUN = "run" + const val SEARCH_KIND_STEP = "step" + const val SEARCH_KIND_FIELD = "field" + const val SEARCH_KIND_ARTIFACT = "artifact" + // terminals.go const val SUCCESS_END = "#success" const val FAILURE_END = "#failure" @@ -376,6 +389,117 @@ data class SystemStatus( val note: String = "", ) +/** + * The omni-search request body (internal/protocol/search.go SearchRequest): the + * free text query, an optional single-kind narrowing, and an optional result + * cap (0 = server default). The typed, ranked result payload is added with the + * search-results item; for now the reply is classified by its envelope type so a + * server that cannot answer is reported, never mis-parsed. + */ +@Serializable +data class SearchRequest( + val query: String = "", + val kind: String = "", + val limit: Int = 0, +) + +/** + * The typed, ranked omni-search reply body (internal/protocol/search.go + * SearchResponse). [results] are ordered by score, then recency, then a stable + * kind/target tie-break; [truncated] reports that the result cap or the + * field-scan budget dropped matches and the scan counters make that bound + * observable. An empty [results] list is a real, empty result, not a failure. + */ +@Serializable +data class SearchResponse( + val query: String = "", + val kind: String = "", + val results: List = emptyList(), + val truncated: Boolean = false, + @SerialName("scanned_steps") val scannedSteps: Int = 0, + @SerialName("scanned_bytes") val scannedBytes: Int = 0, + val cap: Int = 0, + @SerialName("scan_bound_bytes") val scanBoundBytes: Int = 0, +) + +/** + * One typed search match (internal/protocol/search.go SearchResult). [kind] + * selects which payload is set; [target] is a stable token an existing command + * resolves and [matchedField] records why it matched. Every payload is + * nullable, so an unknown kind decodes without crashing and is shown read-only + * rather than dropped. + */ +@Serializable +data class SearchResult( + val kind: String = "", + val target: String = "", + val score: Int = 0, + @SerialName("matched_field") val matchedField: String = "", + val recency: String? = null, + val pipeline: SearchPipeline? = null, + val version: SearchVersion? = null, + val run: SearchRun? = null, + val step: SearchStep? = null, + val field: SearchField? = null, + val artifact: SearchArtifact? = null, +) + +@Serializable +data class SearchPipeline( + val id: Long = 0, + val name: String = "", + val version: Int = 0, + val stages: Int = 0, +) + +@Serializable +data class SearchVersion( + @SerialName("pipeline_id") val pipelineId: Long = 0, + val version: Int = 0, + @SerialName("content_hash") val contentHash: String = "", + @SerialName("created_at") val createdAt: String = "", +) + +@Serializable +data class SearchRun( + val id: Long = 0, + @SerialName("pipeline_name") val pipelineName: String = "", + val status: String = "", + val workspace: String? = null, + @SerialName("created_at") val createdAt: String = "", + @SerialName("finished_at") val finishedAt: String? = null, + @SerialName("duration_seconds") val durationSeconds: Double = 0.0, +) + +@Serializable +data class SearchStep( + @SerialName("run_id") val runId: Long = 0, + val sequence: Int = 0, + val stage: String = "", + val visit: Int = 0, + val outcome: String? = null, + val target: String? = null, + val diagnostic: String? = null, +) + +@Serializable +data class SearchField( + @SerialName("run_id") val runId: Long = 0, + val sequence: Int = 0, + val field: String = "", + val snippet: String = "", +) + +@Serializable +data class SearchArtifact( + @SerialName("run_id") val runId: Long = 0, + val sequence: Int = 0, + val name: String = "", + @SerialName("content_type") val contentType: String = "", + @SerialName("size_bytes") val sizeBytes: Long = 0, + val url: String = "", +) + /** * The shared JSON envelope. Every field is optional/nullable with defaults so * unknown or missing server fields never crash the client. @@ -406,6 +530,8 @@ data class Message( @SerialName("run_id") val runId: Long = 0, @SerialName("run_detail") val runDetail: RunDetail? = null, val runs: List? = null, + val search: SearchRequest? = null, + @SerialName("search_results") val searchResults: SearchResponse? = null, val input: Map? = null, @SerialName("allow_tools") val allowTools: Boolean = false, @SerialName("write_paths") val writePaths: List? = null, diff --git a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt index d29e9ea8..0bd11535 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt @@ -6,6 +6,8 @@ import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -21,7 +23,9 @@ import net.awan.pipelines.data.SettingsRepository import net.awan.pipelines.data.protocol.BuildInfo import net.awan.pipelines.data.protocol.PipelineDetail import net.awan.pipelines.data.protocol.PipelineSummary +import net.awan.pipelines.data.protocol.Protocol import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.data.protocol.SearchResponse import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.data.transport.ConnectionState import net.awan.pipelines.data.transport.ServerUrl @@ -92,6 +96,16 @@ class AppViewModel( private val _evidence = MutableStateFlow(LoadState>()) val evidence: StateFlow>> = _evidence.asStateFlow() + private val _search = MutableStateFlow(SearchUiState()) + + /** The omni-search panel state: query, last results, loading and any error. */ + val search: StateFlow = _search.asStateFlow() + + // Debounces keystrokes and gates replies so an older query can never land on + // top of a newer one; the pure ordering lives in SearchSequencer. + private val searchSequencer = SearchSequencer() + private var searchJob: Job? = null + private val startKeys = ConcurrentHashMap() private val retryKeys = ConcurrentHashMap() @@ -217,6 +231,62 @@ class AppViewModel( suspend fun fetchArtifactBytes(url: String): ByteArray? = runCatching { repository.fetchArtifactBytes(url) }.getOrNull() + /** + * Records a keystroke and, after a short quiet period, issues one request for + * the latest query. A burst of keystrokes cancels the pending request and + * collapses to the last one; the previous results stay visible throughout, so + * the panel never flickers to empty. A blank query clears the panel locally + * (no server scan). + */ + fun onSearchQueryChanged(query: String) { + val edit = searchSequencer.edit(query) + searchJob?.cancel() + _search.value = _search.value.editing(query) + if (query.isBlank()) { + _search.value = SearchUiState() + return + } + searchJob = viewModelScope.launch { + delay(SEARCH_DEBOUNCE_MILLIS) + searchSequencer.begin(edit)?.let { runSearch(it) } + } + } + + /** Runs the current query immediately (the IME's search action), skipping the debounce. */ + fun searchNow() { + val query = _search.value.query + if (query.isBlank()) return + val edit = searchSequencer.edit(query) + searchJob?.cancel() + searchJob = viewModelScope.launch { searchSequencer.begin(edit)?.let { runSearch(it) } } + } + + /** Dismissing the field clears the panel and forgets the pending query. */ + fun clearSearch() { + searchJob?.cancel() + searchSequencer.edit("") + _search.value = SearchUiState() + } + + private suspend fun runSearch(request: SentSearch) { + _search.value = _search.value.copy(loading = true, error = null) + try { + val reply = repository.search(request.query) + // A reply for a superseded query must never land: the sequencer only + // accepts the newest sent token. + if (!searchSequencer.accepts(request.token)) return + _search.value = if (reply.type == Protocol.SEARCH_RESULTS) { + _search.value.loaded(reply.searchResults ?: SearchResponse()) + } else { + _search.value.failed("This server does not support search. Update the Pipelines server, then try again.") + } + } catch (t: Throwable) { + if (t is CancellationException) throw t + if (!searchSequencer.accepts(request.token)) return + _search.value = _search.value.failed(ErrorMessages.describe(t)) + } + } + /** * Drops any previously loaded evidence so a different run never shows the * previous run's records. Evidence is then fetched on demand, never polled. @@ -299,6 +369,9 @@ class AppViewModel( companion object { private const val CONNECT_TIMEOUT_MILLIS = 20_000L + /** How long the field waits after the last keystroke before issuing one request. */ + const val SEARCH_DEBOUNCE_MILLIS = 250L + fun factory(app: PipelinesApplication) = viewModelFactory { initializer { AppViewModel(app.repository, app.settings) } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/OmniSearch.kt b/android/app/src/main/java/net/awan/pipelines/ui/OmniSearch.kt new file mode 100644 index 00000000..3ef760b6 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/OmniSearch.kt @@ -0,0 +1,67 @@ +package net.awan.pipelines.ui + +import androidx.compose.runtime.saveable.Saver + +/** + * The floating bottom container's two surfaces: the destination icons (the + * pill) and the omni-search field it morphs into. [open] is that morph; + * [focused] records whether the field owns the keyboard's focus; [query] is the + * typed text. + * + * Opening and dismissing deliberately change nothing else, so the destination + * the pill had selected is untouched by a search: the nav route is owned + * elsewhere and never navigated away from here, so the reverse morph restores + * exactly the pill that was on screen. + */ +data class OmniSearchState( + val open: Boolean = false, + val focused: Boolean = false, + val query: String = "", +) { + companion object { + /** The resting pill: no field, no text. */ + val Closed = OmniSearchState() + } +} + +/** Tapping the Search icon opens the field and asks for focus (keyboard up). */ +fun openOmniSearch(state: OmniSearchState): OmniSearchState = + state.copy(open = true, focused = true) + +/** + * Dismissing (Back, the back gesture or a scrim tap) plays the reverse and + * returns to the resting pill, clearing the text so the next open starts fresh. + */ +fun dismissOmniSearch(state: OmniSearchState): OmniSearchState = OmniSearchState.Closed + +/** The field gained ([focused] true) or lost the focus; [open] is unchanged. */ +fun setOmniSearchFocus(state: OmniSearchState, focused: Boolean): OmniSearchState = + state.copy(focused = focused) + +/** Records the typed query; [open] and [focused] are unchanged. */ +fun setOmniSearchQuery(state: OmniSearchState, query: String): OmniSearchState = + state.copy(query = query) + +/** + * Encodes an [OmniSearchState] as Bundle-able primitives (a small `List`), + * so a still-open field survives rotation, configuration change and process + * death. Paired with [decodeOmniSearch]. + */ +internal fun encodeOmniSearch(state: OmniSearchState): List = + listOf(state.open, state.focused, state.query) + +/** Restores an [OmniSearchState] encoded by [encodeOmniSearch]. */ +internal fun decodeOmniSearch(encoded: List): OmniSearchState = OmniSearchState( + open = encoded[0] as Boolean, + focused = encoded[1] as Boolean, + query = encoded[2] as String, +) + +/** + * Saves/restores an [OmniSearchState] across configuration change and process + * death. The payload is primitives only (see [encodeOmniSearch]). + */ +val OmniSearchStateSaver: Saver> = Saver( + save = { encodeOmniSearch(it) }, + restore = { decodeOmniSearch(it) }, +) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/OmniSearchResults.kt b/android/app/src/main/java/net/awan/pipelines/ui/OmniSearchResults.kt new file mode 100644 index 00000000..67c6d21e --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/OmniSearchResults.kt @@ -0,0 +1,288 @@ +package net.awan.pipelines.ui + +import androidx.compose.runtime.Immutable +import net.awan.pipelines.data.protocol.Protocol +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.SearchArtifact +import net.awan.pipelines.data.protocol.SearchField +import net.awan.pipelines.data.protocol.SearchPipeline +import net.awan.pipelines.data.protocol.SearchResponse +import net.awan.pipelines.data.protocol.SearchResult +import net.awan.pipelines.data.protocol.SearchRun +import net.awan.pipelines.data.protocol.SearchStep +import net.awan.pipelines.data.protocol.SearchVersion +import net.awan.pipelines.ui.screens.runTimeline + +// --------------------------------------------------------------------------- +// Row model: the badge, title and secondary line of one result. Pure (no +// Compose, no coroutines), so the mapping for every kind is unit-testable. +// --------------------------------------------------------------------------- + +/** The short mixed-list type badge for a result kind. */ +fun searchBadge(kind: String): String = when (kind) { + Protocol.SEARCH_KIND_PIPELINE, Protocol.SEARCH_KIND_VERSION -> "pipeline" + Protocol.SEARCH_KIND_RUN -> "run" + Protocol.SEARCH_KIND_STEP -> "step" + Protocol.SEARCH_KIND_ARTIFACT -> "artifact" + // A text ("field") match and an unknown kind both read as a generic match; + // the unknown one is additionally labelled read-only by [searchRow]. + else -> "match" +} + +/** + * One run of snippet text with [matched] true for the span the query hit. The row + * renders a matched span with a weight/underline difference, so the match stays + * legible without relying on colour. + */ +@Immutable +data class SnippetSpan(val text: String, val matched: Boolean) + +/** + * One rendered search row: its type badge, a title and a secondary line. [snippet] + * is non-null only for a text ("field") match and carries the snippet split so the + * matched span is distinguishable without colour. + */ +@Immutable +data class SearchRow( + val badge: String, + val title: String, + val secondary: String, + val snippet: List? = null, +) + +/** + * The row for one [hit]. [query] is the typed text, used only to locate the + * matched span in a text snippet. An unknown/absent payload is never dropped: it + * renders its stable target (or a placeholder) and a `read-only` note. + */ +fun searchRow(hit: SearchResult, query: String): SearchRow { + val badge = searchBadge(hit.kind) + val pipeline: SearchPipeline? = hit.pipeline + val version: SearchVersion? = hit.version + val run: SearchRun? = hit.run + val step: SearchStep? = hit.step + val field: SearchField? = hit.field + val artifact: SearchArtifact? = hit.artifact + return when { + pipeline != null -> SearchRow( + badge, + pipeline.name.ifBlank { "pipeline ${pipeline.id}" }, + "pipeline ${pipeline.id} · v${pipeline.version} · ${pipeline.stages} stages", + ) + version != null -> SearchRow( + badge, + "pipeline ${version.pipelineId} · v${version.version}", + listOfNotNull( + version.contentHash.takeIf { it.isNotBlank() }?.let { "content $it" }, + version.createdAt.takeIf { it.isNotBlank() }, + ).joinToString(" · "), + ) + run != null -> SearchRow( + badge, + "run #${run.id}" + run.pipelineName.takeIf { it.isNotBlank() }?.let { " · $it" }.orEmpty(), + listOfNotNull( + run.status.takeIf { it.isNotBlank() }, + run.workspace?.takeIf { it.isNotBlank() }, + run.createdAt.takeIf { it.isNotBlank() }, + ).joinToString(" · "), + ) + step != null -> SearchRow( + badge, + "run #${step.runId} · ${step.stage.ifBlank { "step" }} visit ${step.visit}", + stepSecondary(step), + ) + field != null -> SearchRow( + badge, + "run #${field.runId} · step ${field.sequence} · ${field.field.ifBlank { "field" }}", + field.snippet, + snippetSpans(field.snippet, query), + ) + artifact != null -> SearchRow( + badge, + artifact.name.ifBlank { "artifact" }, + listOfNotNull( + "run #${artifact.runId}", + "step ${artifact.sequence}", + artifact.contentType.takeIf { it.isNotBlank() }, + humanBytes(artifact.sizeBytes), + ).joinToString(" · "), + ) + else -> SearchRow( + badge, + hit.target.ifBlank { "Unrecognised result" }, + if (hit.kind.isBlank()) "read-only" else "kind \"${hit.kind}\" · read-only", + ) + } +} + +/** The one-line non-snippet summary of a step hit: its outcome, route and first diagnostic line. */ +private fun stepSecondary(step: SearchStep): String { + val parts = listOfNotNull( + step.outcome?.takeIf { it.isNotBlank() }, + step.target?.takeIf { it.isNotBlank() }?.let { "→ $it" }, + step.diagnostic?.lineSequence()?.firstOrNull { it.isNotBlank() }?.trim()?.takeIf { it.isNotBlank() }, + ) + return parts.joinToString(" · ").ifBlank { "step ${step.sequence}" } +} + +/** + * Splits [snippet] into runs so the first case-insensitive occurrence of [query] + * is a distinct, [SnippetSpan.matched] span. When the query is blank or does not + * appear (a bare status/date query, or a server-trimmed snippet), the whole + * snippet is returned unmatched, so the caller never drops text. + */ +fun snippetSpans(snippet: String, query: String): List { + if (snippet.isEmpty()) return emptyList() + val trimmed = query.trim() + if (trimmed.isEmpty()) return listOf(SnippetSpan(snippet, false)) + val index = snippet.indexOf(trimmed, ignoreCase = true) + if (index < 0) return listOf(SnippetSpan(snippet, false)) + val end = index + trimmed.length + return buildList { + if (index > 0) add(SnippetSpan(snippet.substring(0, index), false)) + add(SnippetSpan(snippet.substring(index, end), true)) + if (end < snippet.length) add(SnippetSpan(snippet.substring(end), false)) + } +} + +// --------------------------------------------------------------------------- +// Navigation: the destination a result resolves to. Pure, so the mapping for +// every kind is unit-testable. +// --------------------------------------------------------------------------- + +/** + * The navigation a selected search result asks for. A null target (see + * [searchTarget]) means the result is shown read-only and selecting it does + * nothing. + */ +sealed interface SearchTarget { + /** Open the Pipelines destination at this pipeline's detail (version 0 = latest). */ + data class Pipeline(val pipelineId: Long, val version: Int) : SearchTarget + + /** + * Open the Runs destination at this run. [sequence] > 0 opens the recorded + * visit, and [field]/[artifacts] name the section to reveal: a text match + * opens the run-detail section holding the matched field, an artifact hit the + * visit's stage pane (whose gallery leads), and a step hit the visit's pane. + */ + data class Run( + val runId: Long, + val sequence: Int = 0, + val field: String = "", + val artifacts: Boolean = false, + ) : SearchTarget +} + +/** + * The navigation target for [hit], or null for a kind with no known payload (an + * unknown match), which is shown read-only rather than dropped. + */ +fun searchTarget(hit: SearchResult): SearchTarget? = when { + hit.pipeline != null -> SearchTarget.Pipeline(hit.pipeline.id, hit.pipeline.version) + hit.version != null -> SearchTarget.Pipeline(hit.version.pipelineId, hit.version.version) + hit.run != null -> SearchTarget.Run(hit.run.id) + hit.step != null -> SearchTarget.Run(hit.step.runId, hit.step.sequence) + hit.field != null -> SearchTarget.Run(hit.field.runId, hit.field.sequence, field = hit.field.field) + hit.artifact != null -> SearchTarget.Run(hit.artifact.runId, hit.artifact.sequence, artifacts = true) + else -> null +} + +/** The run-detail tab holding a matched step field's text (see `runDetailTabs`). */ +fun searchFieldSection(field: String): Int = when (field) { + "input" -> 2 + "output" -> 3 + "evidence", "transcript" -> 4 + else -> 0 +} + +/** + * Resolves a [SearchTarget.Run] against the loaded run's [steps] into the pane + * selection showing the requested visit/section. A visit that cannot be located + * (or a bare run target) falls back to the run detail itself, so a hit is never + * dropped. [runId] is the run the target named. + */ +fun resolveRunTarget(target: SearchTarget.Run, runId: Long, steps: List): PaneSelection { + // A text match names a section (tab) directly; the matched field's own text + // lives in the run-detail section with that name. + if (target.field.isNotBlank()) { + return PaneSelection(MasterPane.Detail, runId, sectionIndex = searchFieldSection(target.field)) + } + if (target.sequence <= 0) return PaneSelection(MasterPane.Detail, runId) + val step = steps.firstOrNull { it.sequence == target.sequence } + ?: return PaneSelection(MasterPane.Detail, runId) + // The visit's stage pane, with the correct zero-based visit index for that + // stage (the server's visit number need not equal the index). + val visits = runTimeline(steps).visitsByStage[step.stage].orEmpty() + val visitIndex = visits.indexOfFirst { it.sequence == target.sequence }.coerceAtLeast(0) + return PaneSelection( + pane = MasterPane.Stage, + itemId = runId, + stageKey = step.stage, + stageVisit = visitIndex, + ) +} + +// --------------------------------------------------------------------------- +// Query sequencing: debounce + stale-response gating. Pure (no coroutines and +// no clock) so a keystroke burst and an out-of-order reply are unit-testable. +// --------------------------------------------------------------------------- + +/** One typed query awaiting its debounce window. */ +data class SearchEdit(val token: Long, val query: String) + +/** A query whose debounce elapsed and which is still the newest edit. */ +data class SentSearch(val token: Long, val query: String) + +/** + * The pure ordering behind omni-search. + * + * [edit] records a keystroke and returns the pending edit to debounce; when the + * quiet period elapses the caller passes it to [begin], which returns the query + * to send only if no newer keystroke arrived — so a burst of keystrokes collapses + * into one request for the last one. Every sent request carries a monotonically + * increasing token and [accepts] is true only for the newest sent token, so a + * slower older reply can never overwrite a newer one. + */ +class SearchSequencer { + private var edits = 0L + private var newestSent = 0L + + fun edit(query: String): SearchEdit = SearchEdit(++edits, query) + + fun begin(edit: SearchEdit): SentSearch? { + if (edit.token != edits) return null + newestSent = edit.token + return SentSearch(edit.token, edit.query) + } + + fun accepts(token: Long): Boolean = token == newestSent +} + +/** The omni-search panel state; the previous results stay put while a new query loads. */ +@Immutable +data class SearchUiState( + val query: String = "", + val results: List = emptyList(), + val loading: Boolean = false, + val error: String? = null, + val loaded: Boolean = false, +) + +/** A keystroke: keep the previous results (no flicker to empty) and mark a request in flight. */ +fun SearchUiState.editing(query: String): SearchUiState = + copy(query = query, loading = query.isNotBlank(), error = null, loaded = false) + +/** A reply landed: replace the results and stop loading. */ +fun SearchUiState.loaded(response: SearchResponse): SearchUiState = + copy(results = response.results, loading = false, error = null, loaded = true) + +/** + * A load failed: stop loading and record the reason, keeping any previous results + * visible rather than blanking the panel. + */ +fun SearchUiState.failed(message: String?): SearchUiState = + copy(loading = false, error = message, loaded = true) + +/** Whether the panel shows the explicit, query-naming empty state. */ +fun SearchUiState.isEmptyResult(): Boolean = + error == null && !loading && loaded && results.isEmpty() && query.isNotBlank() 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 79b92778..6b24fb90 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,9 +1,20 @@ 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 @@ -12,6 +23,7 @@ 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 @@ -20,25 +32,39 @@ import androidx.compose.foundation.layout.windowInsetsPadding 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.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 import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.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 @@ -47,6 +73,7 @@ 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.components.ConnectionBanner import net.awan.pipelines.ui.components.MotionStandard @@ -65,6 +92,9 @@ 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.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 private data class TopDestination(val route: String, val label: String, val icon: ImageVector) @@ -104,11 +134,54 @@ fun PipelinesApp(vm: AppViewModel) { // every width; only the section index presentation (tab row vs rail) changes. val wide = isWideLayout(LocalConfiguration.current.screenWidthDp) - // The Runs destination's selection is hoisted here so the Pipelines detail can - // jump to a freshly started run (there is no longer a run route to navigate to). + // The Pipelines and Runs destinations' selections are hoisted here so a search + // result can open either one (and the Pipelines detail can jump to a freshly + // started run). There is no longer a run/route to navigate to. + var pipelineSelection by rememberSaveable(stateSaver = PaneSelectionSaver) { + mutableStateOf(PaneSelection()) + } var runSelection by rememberSaveable(stateSaver = PaneSelectionSaver) { mutableStateOf(PaneSelection()) } + // A run search hit that names a recorded visit cannot be resolved until the + // run's steps are loaded; the Runs destination applies it then (see below). + var runSearchNav by remember { mutableStateOf(null) } + + // The bottom container's morph (destination pill <-> omni-search field) is + // saved state, so a still-open field survives rotation, configuration change + // and process death. Opening never navigates, so the destination the pill had + // selected is untouched and dismissing restores exactly that pill. + var searchState by rememberSaveable(stateSaver = OmniSearchStateSaver) { + mutableStateOf(OmniSearchState()) + } + val search by vm.search.collectAsStateWithLifecycle() + + /** Back/scrim/close and a selection all dismiss the morph and clear the panel. */ + val dismissSearch: () -> Unit = { + vm.clearSearch() + searchState = dismissOmniSearch(searchState) + } + + // Selecting a result navigates and closes the search. A read-only (unknown + // kind) result has a null target and only closes. + val onSelectResult: (SearchResult) -> Unit = { hit -> + when (val target = searchTarget(hit)) { + is SearchTarget.Pipeline -> { + pipelineSelection = PaneSelection(MasterPane.Detail, target.pipelineId, target.version) + navController.navigate("pipelines") { + popUpTo("pipelines") { inclusive = false } + launchSingleTop = true + } + } + is SearchTarget.Run -> { + runSelection = PaneSelection(MasterPane.Detail, target.runId) + runSearchNav = target.takeIf { it.sequence > 0 } + navController.navigate("runs") { launchSingleTop = true } + } + null -> Unit + } + dismissSearch() + } val onNavigate: (TopDestination) -> Unit = { destination -> if (currentRoute != destination.route) { @@ -159,6 +232,8 @@ fun PipelinesApp(vm: AppViewModel) { PipelineDestination( vm = vm, wide = wide, + selection = pipelineSelection, + onSelectionChange = { pipelineSelection = it }, onOpenRun = { runId -> runSelection = PaneSelection( pane = MasterPane.Detail, @@ -174,6 +249,8 @@ fun PipelinesApp(vm: AppViewModel) { wide = wide, selection = runSelection, onSelectionChange = { runSelection = it }, + pendingNav = runSearchNav, + onPendingNavResolved = { runSearchNav = null }, ) } composable("settings") { @@ -181,19 +258,73 @@ fun PipelinesApp(vm: AppViewModel) { } } } - DestinationPill( - destinations = destinations, - currentRoute = currentRoute, - onSelect = onNavigate, + // The open search covers the content behind a scrim; tapping it plays + // the reverse morph, the same dismissal as Back. + AnimatedVisibility( + visible = searchState.open, + enter = fadeIn(animationSpec = MotionStandard.spec()), + exit = fadeOut(animationSpec = MotionStandard.spec()), + ) { + Box( + Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.scrim.copy(alpha = SEARCH_SCRIM_ALPHA)) + .pointerInput(Unit) { + detectTapGestures { dismissSearch() } + }, + ) + } + // Composed after the NavHost, so while the field is open Back (button + // or gesture) dismisses the morph before any pane's own Back handler. + BackHandler(enabled = searchState.open) { dismissSearch() } + // The results panel and the destination bar share one bottom-anchored, + // inset-clearing column. `paneSafeArea` (WindowInsets.safeDrawing) is + // applied once here: the panel then takes exactly the height the IME and + // navigation bar leave (weight, `fill = false` so a short panel wraps) + // and scrolls inside it, and the input always sits directly below the + // panel and above the keyboard. This is the only place the IME is + // cleared because the activity declares `adjustNothing`: the window is + // never resized for the IME, so the inset below is not counted twice. + Column( modifier = Modifier - .align(Alignment.BottomEnd) + .fillMaxSize() .windowInsetsPadding(paneSafeArea()) .padding(end = 16.dp, bottom = 16.dp), - ) + verticalArrangement = Arrangement.Bottom, + horizontalAlignment = Alignment.End, + ) { + if (searchState.open && searchState.query.isNotBlank()) { + SearchResultsPanel( + state = search, + onSelect = onSelectResult, + modifier = Modifier + .fillMaxWidth() + .weight(1f, fill = false) + .padding(bottom = 16.dp), + ) + } + DestinationBar( + destinations = destinations, + currentRoute = currentRoute, + state = searchState, + onSelect = onNavigate, + onOpenSearch = { searchState = openOmniSearch(searchState) }, + onDismissSearch = dismissSearch, + onQueryChange = { + searchState = setOmniSearchQuery(searchState, it) + vm.onSearchQueryChanged(it) + }, + onFocusChange = { searchState = setOmniSearchFocus(searchState, it) }, + onSubmitSearch = { vm.searchNow() }, + ) + } } } } +/** 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 @@ -203,12 +334,15 @@ fun PipelinesApp(vm: AppViewModel) { * closes every pane to its right via [popTo]. */ @Composable -private fun PipelineDestination(vm: AppViewModel, wide: Boolean, onOpenRun: (Long) -> Unit) { - var selection by rememberSaveable(stateSaver = PaneSelectionSaver) { - mutableStateOf(PaneSelection()) - } +private fun PipelineDestination( + vm: AppViewModel, + wide: Boolean, + selection: PaneSelection, + onSelectionChange: (PaneSelection) -> Unit, + onOpenRun: (Long) -> Unit, +) { val depth = selection.depth - val onBack: () -> Unit = { selection = backFrom(selection) } + val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) } PredictiveBackHandler(enabled = depth >= 1) { progress -> // Consume the gesture; on completion perform exactly one Back step. @@ -219,14 +353,14 @@ private fun PipelineDestination(vm: AppViewModel, wide: Boolean, onOpenRun: (Lon SlidingPaneStack( depth = depth, wide = wide, - onPopTo = { level -> selection = popTo(selection, level) }, + onPopTo = { level -> onSelectionChange(popTo(selection, level)) }, backContentDescription = { level -> if (level == 0) "Back to pipelines" else "Back to pipeline" }, pane = { level, covered, paneModifier -> when (level) { 0 -> PipelineListScreen( vm = vm, onOpen = { id, version -> - selection = PaneSelection(MasterPane.Detail, id, version) + onSelectionChange(PaneSelection(MasterPane.Detail, id, version)) }, modifier = paneModifier, selectedId = selection.itemId.takeIf { depth >= 1 }, @@ -244,11 +378,13 @@ private fun PipelineDestination(vm: AppViewModel, wide: Boolean, onOpenRun: (Lon onBack = onBack, onOpenRun = onOpenRun, selectedSection = clampTabIndex(sectionIndex, pipelineDetailTabs.size), - onSelectSection = { selection = selection.copy(sectionIndex = it) }, + onSelectSection = { onSelectionChange(selection.copy(sectionIndex = it)) }, modifier = paneModifier, wide = wide, onOpenStage = { key -> - selection = selection.copy(pane = MasterPane.Stage, stageKey = key, stageVisit = 0) + onSelectionChange( + selection.copy(pane = MasterPane.Stage, stageKey = key, stageVisit = 0), + ) }, covered = covered, ) @@ -285,10 +421,24 @@ private fun RunsDestination( wide: Boolean, selection: PaneSelection, onSelectionChange: (PaneSelection) -> Unit, + pendingNav: SearchTarget.Run?, + onPendingNavResolved: () -> Unit, ) { 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() @@ -359,23 +509,87 @@ internal fun destinationIndicatorOffsetDp(index: Int, itemSize: Dp, gap: Dp): Dp gap + (itemSize + gap) * index.coerceAtLeast(0) /** - * The Pipelines/Runs/Settings destinations as a floating rounded pill at the - * bottom right: the three destinations as icons, inset from the bottom/right - * edges (it clears the safe area — system bars, cutout, gesture area and IME — - * via windowInsetsPadding), 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 switches destination 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 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 DestinationPill( +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, - modifier: Modifier = Modifier, + onOpenSearch: () -> Unit, ) { val scheme = MaterialTheme.colorScheme val selectedIndex = destinations.indexOfFirst { destinationSelected(currentRoute, it.route) } @@ -390,58 +604,131 @@ private fun DestinationPill( animationSpec = MotionStandard.spec(), label = "destination-indicator", ) - Surface( - modifier = modifier, - shape = RoundedCornerShape(50), - color = scheme.surfaceContainerHigh, - tonalElevation = 3.dp, - shadowElevation = 6.dp, - ) { - 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 { + // 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 - .offset(x = indicatorOffset, y = DESTINATION_ITEM_GAP) + modifier = Modifier .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", + .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) - .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") } } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/SearchResultsPanel.kt b/android/app/src/main/java/net/awan/pipelines/ui/SearchResultsPanel.kt new file mode 100644 index 00000000..838339b6 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/SearchResultsPanel.kt @@ -0,0 +1,213 @@ +package net.awan.pipelines.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +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.semantics.Role +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import net.awan.pipelines.data.protocol.SearchResult +import net.awan.pipelines.ui.theme.SEARCH_PROGRESS_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.SPACING_XL +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * The omni-search results panel: one scrolling surface that sits above the search + * field. It renders the last accepted results, and while a newer query loads it + * keeps those results and adds a thin progress bar rather than blanking; a + * failure is reported without discarding what is already shown. Its height is + * bounded by the caller (the window's IME/navigation-bar insets), so it scrolls + * inside the remainder instead of running under the keyboard. + */ +@Composable +internal fun SearchResultsPanel( + state: SearchUiState, + onSelect: (SearchResult) -> Unit, + modifier: Modifier = Modifier, +) { + val scheme = MaterialTheme.colorScheme + val error = state.error + Surface( + modifier = modifier, + shape = RoundedCornerShape(SPACING_XL), + color = scheme.surfaceContainerHigh, + tonalElevation = 3.dp, + shadowElevation = 6.dp, + ) { + Column(Modifier.fillMaxWidth()) { + // A refresh of an already-populated panel shows progress without + // replacing the results; the first load shows the searching row below. + if (state.loading && state.results.isNotEmpty()) { + LinearProgressIndicator(Modifier.fillMaxWidth()) + } + when { + error != null -> PanelMessage(error, isError = true) + state.isEmptyResult() -> PanelMessage("No matches for \"${state.query}\".", isError = false) + state.loading && state.results.isEmpty() -> SearchingRow() + state.results.isNotEmpty() -> SearchResultList(state.results, state.query, onSelect) + } + } + } +} + +@Composable +private fun PanelMessage(message: String, isError: Boolean) { + Text( + text = message, + style = MaterialTheme.typography.bodyMedium, + color = if (isError) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_M), + ) +} + +@Composable +private fun SearchingRow() { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_M), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_M), + ) { + CircularProgressIndicator(Modifier.size(SEARCH_PROGRESS_DP)) + Text( + text = "Searching…", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +@Composable +private fun SearchResultList( + results: List, + query: String, + onSelect: (SearchResult) -> Unit, +) { + LazyColumn(Modifier.fillMaxWidth()) { + items(results) { hit -> + SearchResultRow( + hit = hit, + query = query, + onClick = searchTarget(hit)?.let { { onSelect(hit) } }, + ) + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + } + } +} + +/** + * One result row: its type badge, a title and a secondary line. A text match's + * secondary line is its snippet with the matched span rendered bold+underlined, + * so the match is distinguishable without relying on colour. A result with no + * navigation target (an unknown kind) is shown read-only and is not clickable. + */ +@Composable +private fun SearchResultRow( + hit: SearchResult, + query: String, + onClick: (() -> Unit)?, +) { + val text = pipelinesText() + val row = remember(hit, query) { searchRow(hit, query) } + Row( + modifier = Modifier + .fillMaxWidth() + .then( + if (onClick != null) { + Modifier.clickable(role = Role.Button, onClick = onClick) + } else { + Modifier + }, + ) + .padding(horizontal = SPACING_L, vertical = SPACING_M), + horizontalArrangement = Arrangement.spacedBy(SPACING_M), + ) { + TypeBadge(row.badge) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(SPACING_XXS), + ) { + Text( + text = row.title, + style = text.cardTitle, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + val snippet = row.snippet + if (snippet != null) { + Text( + text = annotatedSnippet(snippet), + style = text.meta, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } else { + Text( + text = row.secondary, + style = text.meta, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + } +} + +/** The row's type badge; its label carries the type, so it never relies on colour. */ +@Composable +private fun TypeBadge(label: String) { + Surface( + shape = RoundedCornerShape(50), + color = MaterialTheme.colorScheme.secondaryContainer, + ) { + Text( + text = label, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.padding(horizontal = SPACING_S, vertical = SPACING_XXS), + ) + } +} + +/** Renders a snippet, emphasising the matched span with weight+underline (not colour). */ +private fun annotatedSnippet(spans: List): AnnotatedString = buildAnnotatedString { + spans.forEach { span -> + if (span.matched) { + withStyle(SpanStyle(fontWeight = FontWeight.Bold, textDecoration = TextDecoration.Underline)) { + append(span.text) + } + } else { + append(span.text) + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt index 80f9712f..f592ca24 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt @@ -204,3 +204,8 @@ internal val ARTIFACT_PROGRESS_STROKE_DP = 2.dp /** Horizontal padding inside the stage-type chip (wider than the shared chip). */ internal val STAGE_CHIP_PAD_H = 10.dp + +// ---- Omni-search results panel (ui/SearchResultsPanel.kt) ------------------ + +/** The omni-search panel's inline progress spinner. */ +internal val SEARCH_PROGRESS_DP = 18.dp diff --git a/android/app/src/test/java/net/awan/pipelines/data/protocol/ProtocolModelTest.kt b/android/app/src/test/java/net/awan/pipelines/data/protocol/ProtocolModelTest.kt index eff871cc..69e95ba9 100644 --- a/android/app/src/test/java/net/awan/pipelines/data/protocol/ProtocolModelTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/data/protocol/ProtocolModelTest.kt @@ -2,6 +2,7 @@ package net.awan.pipelines.data.protocol import kotlinx.serialization.json.JsonPrimitive import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -96,6 +97,78 @@ class ProtocolModelTest { assertEquals(11L, decoded.runId) } + @Test + fun searchRequestRoundTripsTheQueryAndOmitsEmptyNarrowing() { + val request = Message( + type = Protocol.SEARCH, + id = "android-3", + search = SearchRequest(query = "release"), + ) + val encoded = PipelinesJson.encodeToString(Message.serializer(), request) + // The query nests under the server's `search` field; the empty kind/limit + // narrowing is omitted so it matches internal/protocol/search.go. + assertTrue(encoded.contains("\"search\"")) + assertTrue(encoded.contains("\"query\":\"release\"")) + assertFalse(encoded.contains("\"kind\"")) + val decoded = PipelinesJson.decodeFromString(Message.serializer(), encoded) + assertEquals(Protocol.SEARCH, decoded.type) + assertEquals("release", decoded.search?.query) + } + + @Test + fun searchResultsDecodeEveryKindAndAnUnknownPayload() { + val json = """ + { + "type": "search_results", + "id": "android-4", + "search_results": { + "query": "release", + "truncated": true, + "scanned_steps": 12, + "scanned_bytes": 4096, + "cap": 50, + "scan_bound_bytes": 1048576, + "results": [ + {"kind": "pipeline", "target": "pipeline:1", "score": 3, "matched_field": "name", + "pipeline": {"id": 1, "name": "release", "version": 2, "stages": 3}}, + {"kind": "version", "target": "pipeline:1:v2", "score": 2, "matched_field": "source", + "version": {"pipeline_id": 1, "version": 2, "content_hash": "abc", "created_at": "2026-01-01T00:00:00Z"}}, + {"kind": "run", "target": "run:11", "score": 2, "matched_field": "status", + "run": {"id": 11, "pipeline_name": "release", "status": "failed", "workspace": "/work", "created_at": "2026-01-01T00:00:00Z"}}, + {"kind": "step", "target": "run:11:4", "score": 1, "matched_field": "diagnostic", + "step": {"run_id": 11, "sequence": 4, "stage": "builder", "visit": 2, "outcome": "error"}}, + {"kind": "field", "target": "run:11:4:output", "score": 1, "matched_field": "output", + "field": {"run_id": 11, "sequence": 4, "field": "output", "snippet": "release ready"}}, + {"kind": "artifact", "target": "/artifacts/11/4/notes.md", "score": 1, "matched_field": "artifact", + "artifact": {"run_id": 11, "sequence": 4, "name": "notes.md", "content_type": "text/markdown", "size_bytes": 2048, "url": "/artifacts/11/4/notes.md"}}, + {"kind": "future_kind", "target": "widget:7", "score": 0, "matched_field": "?"} + ] + } + } + """.trimIndent() + val message = PipelinesJson.decodeFromString(Message.serializer(), json) + assertEquals(Protocol.SEARCH_RESULTS, message.type) + val response = message.searchResults!! + assertEquals("release", response.query) + assertTrue(response.truncated) + assertEquals(12, response.scannedSteps) + assertEquals(50, response.cap) + assertEquals(1048576, response.scanBoundBytes) + assertEquals(7, response.results.size) + assertEquals("release", response.results[0].pipeline?.name) + assertEquals(2, response.results[1].version?.version) + assertEquals("/work", response.results[2].run?.workspace) + assertEquals(4, response.results[3].step?.sequence) + assertEquals("release ready", response.results[4].field?.snippet) + assertEquals("/artifacts/11/4/notes.md", response.results[5].artifact?.url) + // An unknown kind decodes with no known payload and is not dropped. + val unknown = response.results[6] + assertEquals("future_kind", unknown.kind) + assertEquals("widget:7", unknown.target) + assertNull(unknown.pipeline) + assertNull(unknown.run) + } + @Test fun runStepArtifactsParseWithExactWireNamesOrAbsent() { val json = """ diff --git a/android/app/src/test/java/net/awan/pipelines/ui/OmniSearchResultsTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/OmniSearchResultsTest.kt new file mode 100644 index 00000000..3a026675 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/OmniSearchResultsTest.kt @@ -0,0 +1,277 @@ +package net.awan.pipelines.ui + +import net.awan.pipelines.data.protocol.Protocol +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.SearchArtifact +import net.awan.pipelines.data.protocol.SearchField +import net.awan.pipelines.data.protocol.SearchPipeline +import net.awan.pipelines.data.protocol.SearchResponse +import net.awan.pipelines.data.protocol.SearchResult +import net.awan.pipelines.data.protocol.SearchRun +import net.awan.pipelines.data.protocol.SearchStep +import net.awan.pipelines.data.protocol.SearchVersion +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class OmniSearchResultsTest { + + // ---- Badges and rows --------------------------------------------------- + + @Test + fun everyKindMapsToItsBadge() { + assertEquals("pipeline", searchBadge(Protocol.SEARCH_KIND_PIPELINE)) + assertEquals("pipeline", searchBadge(Protocol.SEARCH_KIND_VERSION)) + assertEquals("run", searchBadge(Protocol.SEARCH_KIND_RUN)) + assertEquals("step", searchBadge(Protocol.SEARCH_KIND_STEP)) + assertEquals("artifact", searchBadge(Protocol.SEARCH_KIND_ARTIFACT)) + assertEquals("match", searchBadge(Protocol.SEARCH_KIND_FIELD)) + // A kind the client does not know still gets a badge and is shown. + assertEquals("match", searchBadge("future_kind")) + assertEquals("match", searchBadge("")) + } + + @Test + fun eachRowCarriesABadgeTitleAndSecondaryLine() { + results().forEach { hit -> + val row = searchRow(hit, "release") + assertTrue("badge for ${hit.kind}", row.badge.isNotBlank()) + assertTrue("title for ${hit.kind}", row.title.isNotBlank()) + assertTrue("secondary for ${hit.kind}", row.secondary.isNotBlank()) + } + } + + @Test + fun onlyATextMatchCarriesASnippet() { + val field = searchRow(hit(Protocol.SEARCH_KIND_FIELD), "release") + assertNotNull(field.snippet) + // A non-text result has no snippet and keeps its plain secondary line. + val run = searchRow(hit(Protocol.SEARCH_KIND_RUN), "release") + assertNull(run.snippet) + } + + @Test + fun anUnknownKindIsShownReadOnlyAndNotDropped() { + val unknown = SearchResult(kind = "future_kind", target = "widget:7") + val row = searchRow(unknown, "x") + assertEquals("widget:7", row.title) + assertTrue(row.secondary.contains("read-only")) + assertNull("an unknown kind is not navigable", searchTarget(unknown)) + } + + // ---- Snippet highlighting --------------------------------------------- + + @Test + fun theMatchedSpanIsSplitOutCaseInsensitively() { + val spans = snippetSpans("the Release notes mention it", "release") + assertEquals(3, spans.size) + assertEquals("the ", spans[0].text) + assertEquals("Release", spans[1].text) + assertTrue(spans[1].matched) + assertEquals(" notes mention it", spans[2].text) + assertFalse(spans[2].matched) + } + + @Test + fun aSnippetWithoutTheQueryIsKeptWholeAndUnmatched() { + assertEquals(listOf(SnippetSpan("nothing here", false)), snippetSpans("nothing here", "release")) + assertEquals(listOf(SnippetSpan("nothing here", false)), snippetSpans("nothing here", " ")) + assertTrue(snippetSpans("", "release").isEmpty()) + } + + // ---- Result-to-target mapping for every kind --------------------------- + + @Test + fun pipelineAndVersionHitsOpenThePipelineDetail() { + assertEquals( + SearchTarget.Pipeline(7L, 3), + searchTarget(hit(Protocol.SEARCH_KIND_PIPELINE)), + ) + assertEquals( + SearchTarget.Pipeline(9L, 2), + searchTarget(hit(Protocol.SEARCH_KIND_VERSION)), + ) + } + + @Test + fun runStepFieldAndArtifactHitsOpenRuns() { + assertEquals(SearchTarget.Run(11L), searchTarget(hit(Protocol.SEARCH_KIND_RUN))) + assertEquals( + SearchTarget.Run(11L, sequence = 4), + searchTarget(hit(Protocol.SEARCH_KIND_STEP)), + ) + assertEquals( + SearchTarget.Run(11L, sequence = 4, field = "output"), + searchTarget(hit(Protocol.SEARCH_KIND_FIELD)), + ) + assertEquals( + SearchTarget.Run(11L, sequence = 4, artifacts = true), + searchTarget(hit(Protocol.SEARCH_KIND_ARTIFACT)), + ) + } + + // ---- Resolving a run target against the loaded run --------------------- + + private val steps = listOf( + RunStep(sequence = 1, stage = "planner"), + RunStep(sequence = 2, stage = "builder"), + RunStep(sequence = 3, stage = "builder"), + ) + + @Test + fun aBareRunTargetOpensTheRunDetail() { + assertEquals( + PaneSelection(MasterPane.Detail, 11L), + resolveRunTarget(SearchTarget.Run(11L), 11L, emptyList()), + ) + } + + @Test + fun aTextFieldTargetOpensTheRunDetailSectionHoldingIt() { + assertEquals(2, searchFieldSection("input")) + assertEquals(3, searchFieldSection("output")) + assertEquals(4, searchFieldSection("evidence")) + assertEquals(4, searchFieldSection("transcript")) + assertEquals(0, searchFieldSection("other")) + + assertEquals( + PaneSelection(MasterPane.Detail, 11L, sectionIndex = 3), + resolveRunTarget(SearchTarget.Run(11L, 4, field = "output"), 11L, steps), + ) + } + + @Test + fun aStepTargetOpensTheVisitsStagePaneAtTheRightVisitIndex() { + // "builder" has two visits; sequence 3 is its second (index 1). + val resolved = resolveRunTarget(SearchTarget.Run(11L, sequence = 3), 11L, steps) + assertEquals(MasterPane.Stage, resolved.pane) + assertEquals(11L, resolved.itemId) + assertEquals("builder", resolved.stageKey) + assertEquals(1, resolved.stageVisit) + } + + @Test + fun anArtifactTargetOpensTheVisitsStagePane() { + val resolved = resolveRunTarget(SearchTarget.Run(11L, sequence = 2, artifacts = true), 11L, steps) + assertEquals(MasterPane.Stage, resolved.pane) + assertEquals("builder", resolved.stageKey) + assertEquals(0, resolved.stageVisit) + } + + @Test + fun aVisitThatCannotBeLocatedFallsBackToTheRunDetail() { + assertEquals( + PaneSelection(MasterPane.Detail, 11L), + resolveRunTarget(SearchTarget.Run(11L, sequence = 99), 11L, steps), + ) + } + + // ---- Debounce + stale-response sequencing ------------------------------ + + @Test + fun aBurstOfKeystrokesCollapsesToTheLastQuery() { + val sequencer = SearchSequencer() + val first = sequencer.edit("r") + val second = sequencer.edit("re") + val third = sequencer.edit("rel") + assertNull("a superseded edit is never sent", sequencer.begin(first)) + assertNull(sequencer.begin(second)) + assertEquals(SentSearch(third.token, "rel"), sequencer.begin(third)) + } + + @Test + fun anOlderReplyCanNeverOverwriteANewerOne() { + val sequencer = SearchSequencer() + val sentOld = sequencer.begin(sequencer.edit("old"))!! + val sentNew = sequencer.begin(sequencer.edit("new"))!! + assertFalse(sequencer.accepts(sentOld.token)) + assertTrue(sequencer.accepts(sentNew.token)) + // A token never sent is not accepted either. + assertFalse(sequencer.accepts(sentOld.token + 100)) + } + + // ---- Panel state transitions ------------------------------------------- + + @Test + fun loadingANewQueryKeepsThePreviousResults() { + val previous = listOf(hit(Protocol.SEARCH_KIND_RUN)) + val state = SearchUiState(query = "old", results = previous, loaded = true) + val edited = state.editing("new") + assertEquals("new", edited.query) + assertEquals(previous, edited.results) + assertTrue(edited.loading) + } + + @Test + fun aReplyReplacesTheResultsAndAFailureKeepsThem() { + val previous = listOf(hit(Protocol.SEARCH_KIND_RUN)) + val loaded = SearchUiState(query = "q").loaded(SearchResponse(results = previous)) + assertEquals(previous, loaded.results) + assertTrue(loaded.loaded) + assertFalse(loaded.loading) + + val failed = loaded.editing("q2").failed("boom") + assertEquals(previous, failed.results) + assertEquals("boom", failed.error) + assertFalse(failed.loading) + } + + @Test + fun theEmptyStateNamesTheQueryAndOnlyAppearsWhenLoaded() { + val empty = SearchUiState(query = "release").loaded(SearchResponse(results = emptyList())) + assertTrue(empty.isEmptyResult()) + // Still loading: not the empty state. + assertFalse(empty.editing("release2").isEmptyResult()) + // A failure is an error, not an empty result. + assertFalse(SearchUiState(query = "release").failed("boom").isEmptyResult()) + } + + // ---- Fixtures ---------------------------------------------------------- + + private fun hit(kind: String): SearchResult = when (kind) { + Protocol.SEARCH_KIND_PIPELINE -> SearchResult( + kind = kind, + target = "pipeline:7", + pipeline = SearchPipeline(id = 7, name = "release", version = 3, stages = 4), + ) + Protocol.SEARCH_KIND_VERSION -> SearchResult( + kind = kind, + target = "pipeline:9:v2", + version = SearchVersion(pipelineId = 9, version = 2, contentHash = "abc", createdAt = "2026-01-01T00:00:00Z"), + ) + Protocol.SEARCH_KIND_RUN -> SearchResult( + kind = kind, + target = "run:11", + run = SearchRun(id = 11, pipelineName = "release", status = "succeeded", createdAt = "2026-01-01T00:00:00Z"), + ) + Protocol.SEARCH_KIND_STEP -> SearchResult( + kind = kind, + target = "run:11:4", + step = SearchStep(runId = 11, sequence = 4, stage = "builder", visit = 2, outcome = "success"), + ) + Protocol.SEARCH_KIND_FIELD -> SearchResult( + kind = kind, + target = "run:11:4:output", + field = SearchField(runId = 11, sequence = 4, field = "output", snippet = "the release is ready"), + ) + Protocol.SEARCH_KIND_ARTIFACT -> SearchResult( + kind = kind, + target = "/artifacts/11/4/notes.md", + artifact = SearchArtifact(runId = 11, sequence = 4, name = "notes.md", contentType = "text/markdown", sizeBytes = 2048, url = "/artifacts/11/4/notes.md"), + ) + else -> SearchResult(kind = kind, target = "") + } + + private fun results(): List = listOf( + Protocol.SEARCH_KIND_PIPELINE, + Protocol.SEARCH_KIND_VERSION, + Protocol.SEARCH_KIND_RUN, + Protocol.SEARCH_KIND_STEP, + Protocol.SEARCH_KIND_FIELD, + Protocol.SEARCH_KIND_ARTIFACT, + "future_kind", + ).map(::hit) +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/OmniSearchTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/OmniSearchTest.kt new file mode 100644 index 00000000..e7a550a8 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/OmniSearchTest.kt @@ -0,0 +1,77 @@ +package net.awan.pipelines.ui + +import androidx.compose.runtime.saveable.SaverScope +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class OmniSearchTest { + + @Test + fun restingPillIsClosedUnfocusedAndEmpty() { + val state = OmniSearchState() + assertFalse(state.open) + assertFalse(state.focused) + assertEquals("", state.query) + // The named closed value is the same resting pill. + assertEquals(OmniSearchState.Closed, state) + } + + @Test + fun openingRequestsTheFieldAndItsFocus() { + val opened = openOmniSearch(OmniSearchState()) + assertTrue(opened.open) + assertTrue("opening asks for focus so the keyboard is up", opened.focused) + assertEquals("", opened.query) + } + + @Test + fun focusAndQueryUpdateWithoutClosing() { + val typed = setOmniSearchQuery(openOmniSearch(OmniSearchState()), "release") + assertEquals("release", typed.query) + assertTrue(typed.open) + + // Losing focus (for example the keyboard being dismissed) does not close + // the field; it only records the focus change. + val blurred = setOmniSearchFocus(typed, false) + assertTrue(blurred.open) + assertFalse(blurred.focused) + assertEquals("release", blurred.query) + } + + @Test + fun dismissingRestoresTheRestingPillAndClearsTheText() { + val open = setOmniSearchQuery(openOmniSearch(OmniSearchState()), "release") + val dismissed = dismissOmniSearch(open) + assertEquals(OmniSearchState.Closed, dismissed) + assertFalse(dismissed.open) + assertFalse(dismissed.focused) + assertEquals("", dismissed.query) + } + + @Test + fun savedStateRoundTripsThroughTheSaver() { + val scope = SaverScope { true } + val cases = listOf( + OmniSearchState(), + OmniSearchState(open = true, focused = true, query = ""), + OmniSearchState(open = true, focused = false, query = "acceptance check"), + OmniSearchState(open = true, focused = true, query = "failed"), + ) + cases.forEach { state -> + val saved = with(OmniSearchStateSaver) { scope.save(state) } + assertEquals(state, OmniSearchStateSaver.restore(saved!!)) + } + } + + @Test + fun encodedPayloadIsPrimitivesOnly() { + val encoded = encodeOmniSearch(OmniSearchState(open = true, focused = true, query = "release")) + assertEquals(listOf(true, true, "release"), encoded) + assertEquals( + OmniSearchState(open = true, focused = false, query = "release"), + decodeOmniSearch(listOf(true, false, "release")), + ) + } +}