Files
alan 80232a4ffe Add omni search: ranked mixed results in the TUI and CLI
Back the TUI "/" popup with the server's search command and add a matching
pipelines search CLI command.

- protocol: SearchRequest/SearchResponse and per-kind SearchResult payloads,
  one shared Label for the six-kind badge dispatch and RuneIndexFold for
  case-insensitive matching.
- pipeline: the read-only, ranked, bounded Store.Search implementation.
- cli: search QUERY [--type KIND] [--limit N] [--json], printing the shared
  label plus a text-field snippet when present.
- tui: type to search, up/down to choose, Enter to open and Esc to cancel over
  one mixed ranked list, with short type badges and a bracketed non-colour
  match marker; Enter navigates to the matched pipeline, run, step, field
  section or artifact entry.
- tests: protocol and TUI coverage, including an env-gated live test against
  the running server.
2026-10-16 23:03:17 +01:00

237 lines
9.0 KiB
Go

package tui
import (
"context"
"strings"
"testing"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"github.com/coder/websocket"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// searchFixtureModel renders the omni popup over a fixed, mixed result set so
// the badges, labels and marked snippet are asserted without a server.
func searchFixtureModel() Model {
m := New(context.Background(), "ws://localhost/connect")
m.width, m.height = 100, 30
m.conn = &websocket.Conn{}
m.paletteOpen = true
m.searchOpen = true
m.keys.palette = true
m.searchText = "needle"
m.searchResults = []protocol.SearchResult{
{Kind: protocol.SearchKindPipeline, Target: "pipeline:1", Pipeline: &protocol.SearchPipeline{ID: 1, Name: "demo", Version: 2, Stages: 3}},
{Kind: protocol.SearchKindRun, Target: "run:7", Run: &protocol.SearchRun{ID: 7, PipelineName: "demo", Status: "succeeded"}},
{Kind: protocol.SearchKindStep, Target: "run:7:1", Step: &protocol.SearchStep{RunID: 7, Sequence: 1, Stage: "reviewer"}},
{Kind: protocol.SearchKindArtifact, Target: "/artifacts/7/1/shot.png", Artifact: &protocol.SearchArtifact{RunID: 7, Sequence: 1, Name: "shot.png", URL: "/artifacts/7/1/shot.png"}},
{Kind: protocol.SearchKindField, Target: "run:7:1:output", Field: &protocol.SearchField{RunID: 7, Sequence: 1, Field: "output", Snippet: "…needle output…"}},
}
return m
}
func TestOmniSearchShowsBadgesAndMarkedSnippet(t *testing.T) {
m := searchFixtureModel()
view := ansi.Strip(m.searchView(20))
for _, badge := range []string{"[pipeline]", "[run]", "[step]", "[artifact]", "[match]"} {
if !strings.Contains(view, badge) {
t.Fatalf("missing badge %q in %q", badge, view)
}
}
if !strings.Contains(view, "[needle]") {
t.Fatalf("field snippet match must be marked without colour: %q", view)
}
}
// TestOmniSearchRealSnippetMarkerVisible guards the regression where a body
// match's snippet centres the token ~60 runes in, so a single-line
// "[match] label · snippet" row was clipped and the marker was invisible at
// every realistic width. The snippet is rendered on its own windowed line.
func TestOmniSearchRealSnippetMarkerVisible(t *testing.T) {
body := strings.Repeat("backgroundcontext ", 6) + "needle output"
for _, width := range []int{80, 100} {
m := searchFixtureModel()
m.width = width
m.searchResults[4].Field.Snippet = body
view := ansi.Strip(m.View())
if !strings.Contains(view, "[needle]") {
t.Fatalf("width %d: matched span not visible after ansi.Strip: %q", width, view)
}
}
}
// TestOmniSearchSnippetWithOwnBracket guards the regression where the window
// located the marker by the first '[' in the marked snippet. A snippet that
// itself contains a '[' before the match (common in code/log evidence) centred
// the window on the wrong bracket and clipped the real "[match]" span, so the
// match became indistinguishable without colour.
func TestOmniSearchSnippetWithOwnBracket(t *testing.T) {
m := searchFixtureModel()
m.width = 100
m.searchResults[4].Field.Snippet = "[x] " + strings.Repeat("word ", 30) + "needle"
view := ansi.Strip(m.View())
if !strings.Contains(view, "[needle]") {
t.Fatalf("real bracket pair must survive a snippet that contains '[': %q", view)
}
}
func TestOmniSearchEmptyStates(t *testing.T) {
t.Run("empty query", func(t *testing.T) {
m := searchFixtureModel()
m.searchResults = nil
if view := ansi.Strip(m.searchView(20)); !strings.Contains(view, "Type to search") {
t.Fatalf("empty query must prompt: %q", view)
}
})
t.Run("no matches", func(t *testing.T) {
m := searchFixtureModel()
m.searchResults = nil
m.commandInput.SetValue("zzz")
view := ansi.Strip(m.searchView(20))
if !strings.Contains(view, "No matches for zzz") || strings.Contains(view, "Type to search") {
t.Fatalf("non-empty query with no results must say so: %q", view)
}
})
t.Run("error", func(t *testing.T) {
m := searchFixtureModel()
m.searchResults = nil
m.commandInput.SetValue("zzz")
m.searchError = "boom"
view := ansi.Strip(m.searchView(20))
if !strings.Contains(view, "Search failed: boom") {
t.Fatalf("failed search must be distinct from no matches: %q", view)
}
})
t.Run("in flight", func(t *testing.T) {
m := searchFixtureModel()
m.searchResults = nil
m.commandInput.SetValue("zz")
m.searchInFlight = true
if view := ansi.Strip(m.searchView(20)); !strings.Contains(view, "Searching…") {
t.Fatalf("outstanding request must show progress: %q", view)
}
})
}
func TestOmniSearchEscCancels(t *testing.T) {
m := searchFixtureModel()
updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyEsc})
m = updated.(Model)
if m.searchOpen || m.paletteOpen || m.searchResults != nil {
t.Fatal("Esc must cancel and clear the omni popup")
}
}
func TestOmniSearchDropsStaleResponses(t *testing.T) {
m := searchFixtureModel()
m.searchResults = nil
m.searchRequest = "2"
updated, _ := m.Update(receivedMsg{Type: protocol.SearchResults, ID: "1", SearchResults: &protocol.SearchResponse{Results: []protocol.SearchResult{{Kind: protocol.SearchKindRun}}}})
m = updated.(Model)
if len(m.searchResults) != 0 {
t.Fatal("stale search response replaced current results")
}
updated, _ = m.Update(receivedMsg{Type: protocol.SearchResults, ID: "2", SearchResults: &protocol.SearchResponse{Query: "demo", Results: []protocol.SearchResult{{Kind: protocol.SearchKindRun}}}})
m = updated.(Model)
if len(m.searchResults) != 1 || m.searchText != "demo" {
t.Fatal("matching search response was dropped or its query not retained")
}
}
func TestOmniSearchEnterNavigatesByKind(t *testing.T) {
detail := &protocol.RunDetail{
RunSummary: protocol.RunSummary{ID: 7, Name: "demo", Status: "succeeded"},
Steps: []protocol.RunStep{{Sequence: 1, Stage: "one"}, {Sequence: 2, Stage: "two"}},
}
cases := []struct {
result protocol.SearchResult
section int
}{
{protocol.SearchResult{Kind: protocol.SearchKindRun, Run: &protocol.SearchRun{ID: 7}}, -1},
{protocol.SearchResult{Kind: protocol.SearchKindStep, Step: &protocol.SearchStep{RunID: 7, Sequence: 2}}, 0},
{protocol.SearchResult{Kind: protocol.SearchKindField, Field: &protocol.SearchField{RunID: 7, Sequence: 2, Field: "input"}}, 1},
{protocol.SearchResult{Kind: protocol.SearchKindArtifact, Artifact: &protocol.SearchArtifact{RunID: 7, Sequence: 2, Name: "shot.png"}}, -2},
}
for _, tc := range cases {
m := searchFixtureModel()
m.searchResults = []protocol.SearchResult{tc.result}
updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
if !m.runOpen || m.searchOpen || m.pendingRunNav == nil {
t.Fatalf("%s: Enter did not open the run: %+v", tc.result.Kind, m)
}
updated, _ = m.Update(receivedMsg{Type: protocol.Run, ID: "run", RunDetail: detail})
m = updated.(Model)
if sequence := searchResultSequence(tc.result); sequence > 0 && m.runStepIndex != 2 {
t.Fatalf("%s: matched step not selected: %d", tc.result.Kind, m.runStepIndex)
}
if tc.result.Kind == protocol.SearchKindArtifact {
if !m.artifactsOpen {
t.Fatalf("artifact match must open the artifacts view: %+v", m)
}
continue
}
if tc.section >= 0 {
marker := "[" + runSections[tc.section].Shortcut + "]"
lines := m.runSectionLines(m.runDetailWidth())
if m.runTop >= len(lines) || !strings.HasPrefix(ansi.Strip(lines[m.runTop]), marker) {
t.Fatalf("%s: section %d not focused: top=%d", tc.result.Kind, tc.section, m.runTop)
}
}
}
}
func searchResultSequence(result protocol.SearchResult) int {
if result.Step != nil {
return result.Step.Sequence
}
if result.Field != nil {
return result.Field.Sequence
}
if result.Artifact != nil {
return result.Artifact.Sequence
}
return 0
}
func TestOmniSearchPipelineEnterOpensDetail(t *testing.T) {
m := searchFixtureModel()
m.searchResults = []protocol.SearchResult{{Kind: protocol.SearchKindPipeline, Pipeline: &protocol.SearchPipeline{ID: 3, Version: 4}}}
updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
if m.searchOpen || !m.detailLoading || m.requestedPipelineID != 3 || m.requestedVersion != 4 {
t.Fatalf("pipeline Enter did not request the detail: %+v", m)
}
}
func TestOmniSearchCoalescesInFlightRequests(t *testing.T) {
m := searchFixtureModel()
updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'d'}})
m = updated.(Model)
if !m.searchInFlight {
t.Fatal("first keystroke must start a search")
}
before := m.nextID
updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'e'}})
m = updated.(Model)
if m.searchInFlight == false || !m.searchQueued || m.nextID != before {
t.Fatalf("second keystroke must coalesce instead of overlapping: inFlight=%t queued=%t", m.searchInFlight, m.searchQueued)
}
}
func TestOmniSearchLayoutStaysWithinWidth(t *testing.T) {
for _, width := range []int{100, 40, 12} {
m := searchFixtureModel()
m.width = width
m.searchResults[4].Field.Snippet = strings.Repeat("wide ", 40) + "needle"
lines := strings.Split(ansi.Strip(m.View()), "\n")
for _, line := range lines {
if len([]rune(line)) > width {
t.Fatalf("width %d: line too wide: %q", width, line)
}
}
}
}