Rework omni search onto a typed search contract and add a TUI artifacts view

Protocol: replace the loose Query/Kind/Matches/Limit search fields with a Search request object and a SearchResults response, and have the server answer search from Store.Search over the shared run projections (runFrom/runStamps).

CLI: add the read-only 'pipelines search QUERY [--type KIND] [--limit N] [--json]' command with usage/help, and document the typed targets, ranking and bounds in docs/cli.md.

TUI: the '/' popup keeps type-to-search, up/down, Enter and Esc, renders one ranked list with kind badges and a bracketed (non-colour) match snippet, and Enter opens the matched pipeline, run, step, artifact or field; footer text updated to match.

TUI: add a dedicated run artifacts view ('A') with open/copy of recorded files, and move artifacts out of the run-detail File changes section (artifactCaptureNotes).

Tests: add Store.OpenReadOnly for read-only inspection of a live database plus pipeline/server/TUI search tests and artifacts tests, including env-gated live checks.
This commit is contained in:
2026-10-16 23:48:38 +01:00
parent fae1005962
commit 865993b200
24 changed files with 1761 additions and 68 deletions
+424
View File
@@ -0,0 +1,424 @@
package tui
import (
"fmt"
"net/url"
"os/exec"
"runtime"
"sort"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/atotto/clipboard"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
)
// artifactVisit is one recorded stage visit and the artifacts the server
// observed for it. A visit is kept even when it recorded none, so the view can
// say plainly that nothing was captured rather than omitting it.
type artifactVisit struct {
stage string
visit int
step protocol.RunStep
artifacts []protocol.StageArtifact
}
// runArtifactVisits groups a run's recorded steps by stage and visit in the
// order the run produced them: stages in first-appearance order and each
// stage's visits by sequence. The display visit number is the recorded control
// visit when present, else the position within the stage (mirroring the app's
// runTimeline/runArtifactGroups). Pure, O(n), and it never dedupes steps, so a
// repeated stage's visits stay distinct.
func runArtifactVisits(steps []protocol.RunStep) []artifactVisit {
order := make([]string, 0)
index := map[string]int{}
byStage := make([][]protocol.RunStep, 0)
for _, step := range steps {
at, ok := index[step.Stage]
if !ok {
at = len(order)
index[step.Stage] = at
order = append(order, step.Stage)
byStage = append(byStage, nil)
}
byStage[at] = append(byStage[at], step)
}
visits := make([]artifactVisit, 0, len(steps))
for i, stage := range order {
stageSteps := byStage[i]
sort.SliceStable(stageSteps, func(a, b int) bool { return stageSteps[a].Sequence < stageSteps[b].Sequence })
for j, step := range stageSteps {
visit := j + 1
if step.Control != nil && step.Control.Visit > 0 {
visit = step.Control.Visit
}
visits = append(visits, artifactVisit{stage: stage, visit: visit, step: step, artifacts: step.Artifacts})
}
}
return visits
}
// artifactRef addresses one artifact row in the flat selection order the view
// uses (group order, then recorded order within the group).
type artifactRef struct {
visit int
artifact protocol.StageArtifact
}
func artifactRefs(visits []artifactVisit) []artifactRef {
var refs []artifactRef
for i, visit := range visits {
for _, artifact := range visit.artifacts {
refs = append(refs, artifactRef{visit: i, artifact: artifact})
}
}
return refs
}
// isImageContentType mirrors the app's isImageContentType: an image the
// terminal cannot render and therefore marks distinctly.
func isImageContentType(contentType string) bool {
return strings.HasPrefix(contentType, "image/")
}
// Column geometry for one aligned artifact row. The name and type widths are
// clamped so one very long value cannot widen every other row; the size column
// is right-aligned.
const (
artifactCursorWidth = 2
artifactMarkerWidth = 5 // "[img]" or five spaces
artifactColumnGap = 2
artifactMinName = 8
artifactMinURLWidth = 12
artifactMaxName = 40
artifactMaxType = 28
)
type artifactWidths struct{ name, typ, size int }
func artifactWidthsFor(visits []artifactVisit) artifactWidths {
widths := artifactWidths{}
for _, visit := range visits {
for _, artifact := range visit.artifacts {
widths.name = min(artifactMaxName, max(widths.name, lipgloss.Width(ansi.Strip(artifact.Name))))
widths.typ = min(artifactMaxType, max(widths.typ, lipgloss.Width(ansi.Strip(artifact.ContentType))))
widths.size = max(widths.size, lipgloss.Width(humanBytes(artifact.SizeBytes)))
}
}
return widths
}
func padRight(text string, width int) string {
if deficit := width - lipgloss.Width(text); deficit > 0 {
return text + strings.Repeat(" ", deficit)
}
return text
}
func padLeft(text string, width int) string {
if deficit := width - lipgloss.Width(text); deficit > 0 {
return strings.Repeat(" ", deficit) + text
}
return text
}
// artifactScrollTop returns the offset that keeps the selected row visible in a
// window of page rows, given the current offset and the total line count. It
// scrolls by the minimum needed, so a one-row move shifts the window by one
// rather than recentring it, and it never leaves the viewport past the end.
// Both the selection clamp and the renderer use it, so they can never disagree
// about which row is on screen.
func artifactScrollTop(from, row, page, total int) int {
if page <= 0 {
return 0
}
maxTop := max(0, total-page)
from = max(0, min(from, maxTop))
if row < from {
from = row
} else if row >= from+page {
from = row - page + 1
}
return max(0, min(from, maxTop))
}
// artifactsViewHeight is the frame body height the artifacts panel is rendered
// at, matching View: a one-line header and a one-line footer, each followed by
// a separating row.
func (m Model) artifactsViewHeight() int { return max(0, m.height-4) }
// artifactsPageSize is the number of artifact body rows the panel shows: the
// frame body less the panel's own bar and border, matching artifactsView.
func (m Model) artifactsPageSize() int { return max(0, m.artifactsViewHeight()-4) }
// artifactRowText renders one artifact as an aligned row: the image marker, the
// name, the content type and the human-readable size, with the URL appended
// when the terminal is wide enough. Optional columns drop as width shrinks and
// every cell is truncated, so the row never exceeds width.
func artifactRowText(artifact protocol.StageArtifact, widths artifactWidths, width int, selected bool) string {
prefix := strings.Repeat(" ", artifactCursorWidth)
if selected {
prefix = "› "
}
marker := strings.Repeat(" ", artifactMarkerWidth)
if isImageContentType(artifact.ContentType) {
marker = "[img]"
}
prefix += marker + " "
available := width - lipgloss.Width(prefix)
if available <= 0 {
return ansi.Truncate(prefix, max(1, width), "")
}
name := ansi.Strip(artifact.Name)
contentType := ansi.Strip(artifact.ContentType)
if strings.TrimSpace(contentType) == "" {
contentType = "unknown type"
}
size := humanBytes(artifact.SizeBytes)
gap := strings.Repeat(" ", artifactColumnGap)
nameCell := func(w int) string { return padRight(ansi.Truncate(name, max(1, w), "…"), w) }
typeCell := padRight(ansi.Truncate(contentType, max(1, widths.typ), "…"), widths.typ)
sizeCell := padLeft(size, widths.size)
switch {
case available >= widths.name+artifactColumnGap+widths.typ+artifactColumnGap+widths.size+artifactColumnGap+artifactMinURLWidth:
urlWidth := available - (widths.name + artifactColumnGap + widths.typ + artifactColumnGap + widths.size + artifactColumnGap)
return prefix + nameCell(widths.name) + gap + typeCell + gap + sizeCell + gap + ansi.Truncate(artifact.URL, max(1, urlWidth), "…")
case available >= widths.name+artifactColumnGap+widths.typ+artifactColumnGap+widths.size:
return prefix + nameCell(widths.name) + gap + typeCell + gap + sizeCell
case available >= artifactMinName+artifactColumnGap+widths.size:
nameWidth := min(widths.name, available-artifactColumnGap-widths.size)
return prefix + nameCell(nameWidth) + gap + sizeCell
default:
return prefix + ansi.Truncate(name, max(1, available), "…")
}
}
// artifactViewContent renders the grouped artifact lines for one content width
// and returns the line index of each flat artifact ref, so selection can scroll
// it into view. Group headers, the shared capture summary and the partial
// capture notes precede each visit's aligned rows.
func artifactViewContent(visits []artifactVisit, widths artifactWidths, width, selected int) ([]string, []int) {
if len(visits) == 0 {
return []string{"No recorded visits yet."}, nil
}
var lines []string
var refLines []int
ref := 0
for i, visit := range visits {
if i > 0 {
lines = append(lines, "")
}
lines = append(lines, lipgloss.NewStyle().Bold(true).Foreground(themeAccent).Render(fmt.Sprintf("%s · visit %d", ansi.Strip(visit.stage), visit.visit)))
lines = append(lines, lipgloss.NewStyle().Foreground(themePrimary).Render(artifactsSummary(visit.step)))
for _, note := range artifactCaptureNotes(visit.step) {
lines = append(lines, lipgloss.NewStyle().Foreground(themeMuted).Render(note))
}
for _, artifact := range visit.artifacts {
lines = append(lines, artifactRowText(artifact, widths, width, ref == selected))
refLines = append(refLines, len(lines)-1)
ref++
}
}
return lines, refLines
}
func (m Model) artifactViewVisits() ([]artifactVisit, []artifactRef) {
if m.runDetail == nil {
return nil, nil
}
visits := runArtifactVisits(m.runDetail.Steps)
return visits, artifactRefs(visits)
}
func (m *Model) openArtifacts() {
if m.runDetail == nil {
m.runError = "Open a run to inspect its artifacts."
return
}
m.artifactsOpen = true
m.artifactIndex = 0
m.artifactTop = 0
}
func (m *Model) selectArtifactByName(name string) {
_, refs := m.artifactViewVisits()
for i, ref := range refs {
if ref.artifact.Name == name {
m.artifactIndex = i
break
}
}
m.clampArtifactScroll()
}
// clampArtifactScroll keeps the selected artifact row inside the visible page
// after a selection move, using the same page size as the renderer.
func (m *Model) clampArtifactScroll() {
if m.runDetail == nil {
m.artifactIndex, m.artifactTop = 0, 0
return
}
visits, refs := m.artifactViewVisits()
m.artifactIndex = max(0, min(m.artifactIndex, max(0, len(refs)-1)))
if len(refs) == 0 {
m.artifactTop = 0
return
}
widths := artifactWidthsFor(visits)
inner := max(1, m.width-4)
lines, refLines := artifactViewContent(visits, widths, inner, m.artifactIndex)
if m.artifactIndex >= len(refLines) {
return
}
m.artifactTop = artifactScrollTop(m.artifactTop, refLines[m.artifactIndex], m.artifactsPageSize(), len(lines))
}
func (m Model) updateArtifacts(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
_, refs := m.artifactViewVisits()
count := len(refs)
switch msg.String() {
case "esc":
m.artifactsOpen = false
return m, nil
case "j", "down":
m.artifactIndex = min(m.artifactIndex+1, max(0, count-1))
case "k", "up":
m.artifactIndex = max(0, m.artifactIndex-1)
case "g", "home":
m.artifactIndex = 0
case "G", "end":
m.artifactIndex = max(0, count-1)
case "enter", "o":
if count == 0 {
return m, nil
}
return m, openArtifactCmd(m.url, refs[m.artifactIndex].artifact)
case "y":
if count == 0 {
return m, nil
}
return m, copyArtifactCmd(m.url, refs[m.artifactIndex].artifact)
}
m.clampArtifactScroll()
return m, nil
}
func (m Model) artifactsView(height int) string {
if m.runDetail == nil {
return fitBlock([]string{"Open a run to inspect its artifacts."}, m.width, height)
}
if height <= 0 || m.width <= 0 {
return ""
}
visits, refs := m.artifactViewVisits()
widths := artifactWidthsFor(visits)
selected := max(0, min(m.artifactIndex, max(0, len(refs)-1)))
inner := max(1, m.width-4)
lines, refLines := artifactViewContent(visits, widths, inner, selected)
page := max(0, height-4)
top := max(0, min(m.artifactTop, max(0, len(lines)-page)))
if selected < len(refLines) {
// Keep the selected row on screen even if a slightly different page
// size left the stored offset behind.
top = artifactScrollTop(top, refLines[selected], page, len(lines))
}
body := lines[top:min(len(lines), top+page)]
title := fmt.Sprintf("Artifacts · run #%d", m.runDetail.ID)
if len(visits) > 0 {
title = fmt.Sprintf("Artifacts · run #%d · %d recorded · %d visits", m.runDetail.ID, len(refs), len(visits))
}
right := ""
if len(refs) > 0 {
right = fmt.Sprintf("%d/%d", selected+1, len(refs))
}
footer := "No artifacts recorded"
if len(refs) > 0 {
// Keep the selected entry's URL available even when the row is too
// narrow to carry its own URL column.
footer = refs[selected].artifact.URL
}
return panel(m.width, height, []string{bar(title, right, inner, true)}, body, footer, true)
}
// artifactActionMsg reports the outcome of handing a URL to the opener or the
// clipboard, so a failure is surfaced instead of silently dropped.
type artifactActionMsg struct {
verb string
url string
err error
}
// openExternal and copyText are seams so tests can observe the resolved URL
// without launching a process or touching the system clipboard.
var (
openExternal = func(target string) error { return openerCommand(target).Run() }
copyText = clipboard.WriteAll
)
// openerCommand is the platform command that hands target to the system opener.
func openerCommand(target string) *exec.Cmd {
switch runtime.GOOS {
case "darwin":
return exec.Command("open", target)
case "windows":
return exec.Command("rundll32", "url.dll,FileProtocolHandler", target)
default:
return exec.Command("xdg-open", target)
}
}
// resolveArtifactURL resolves a server-relative artifact URL against the
// configured websocket server URL by mapping ws/wss to http/https and keeping
// host:port, mirroring the app's ServerUrl.resolveArtifactUrl; it never
// hardcodes a host. An already-absolute http(s) URL is returned unchanged, and
// a blank or invalid configuration fails.
func resolveArtifactURL(serverURL, artifactURL string) (string, bool) {
target := strings.TrimSpace(artifactURL)
if target == "" {
return "", false
}
if strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://") {
return target, true
}
parsed, err := url.Parse(strings.TrimSpace(serverURL))
if err != nil || (parsed.Scheme != "ws" && parsed.Scheme != "wss") || parsed.Hostname() == "" {
return "", false
}
scheme := "http"
if parsed.Scheme == "wss" {
scheme = "https"
}
if !strings.HasPrefix(target, "/") {
target = "/" + target
}
return scheme + "://" + parsed.Host + target, true
}
func artifactURLAction(verb, serverURL string, artifact protocol.StageArtifact) tea.Cmd {
resolved, ok := resolveArtifactURL(serverURL, artifact.URL)
if !ok {
return func() tea.Msg {
return artifactActionMsg{verb: verb, err: fmt.Errorf("no server URL to resolve %q", artifact.Name)}
}
}
action := openExternal
if verb == "copy" {
action = copyText
}
return func() tea.Msg {
if err := action(resolved); err != nil {
return artifactActionMsg{verb: verb, url: resolved, err: err}
}
return artifactActionMsg{verb: verb, url: resolved}
}
}
func openArtifactCmd(serverURL string, artifact protocol.StageArtifact) tea.Cmd {
return artifactURLAction("open", serverURL, artifact)
}
func copyArtifactCmd(serverURL string, artifact protocol.StageArtifact) tea.Cmd {
return artifactURLAction("copy", serverURL, artifact)
}