Merge lane-go: keep the lane's reviewed work

Combines lane-go's typed omni search, launch-time model overrides, TUI
artifacts view, run-state websocket push, and the "reflect the change where
it belongs" committer rule with the Templates gallery, chat/omni-search and
other reviewed work already on main. The 12 files both sides touched keep
both intents composed rather than dropping either side: the omni search keeps
the typed search contract (CLI `pipelines search` and the TUI popup with type
badges and marked snippets) alongside the run-list quick filter; cli.md and
ui-ux-review.md document both the search rework and the artifacts view;
orchestration.md, harnesses.md and operations.md keep the model-override and
reflect-where-it-belongs guidance; and the protocol/CLI/server/TUI code keeps
the new search, run-event, override and artifacts paths alongside the existing
run, title and help surfaces.

Checks before committing:
- go build ./...  -- pass
- go vet ./...  -- pass
- go test -count=1 ./internal/... ./cmd/...  -- all pass

Doc check before committing: nothing needs updating. The lane's own docs and
references (docs/cli.md, docs/ui-ux-review.md, and the orchestration,
harnesses and operations skill references) already carry the new features.
format.md and the packaged templates already describe the line-oriented result
format and the human decision stage from the earlier lane-go merge. The root
README already describes the omni search popup. Model overrides, the search
command, run events and the artifacts view are runtime/CLI/TUI surfaces that
cli.md documents; no template, README or topic-doc edit is required by this
merge.
This commit is contained in:
2026-10-17 02:04:58 +01:00
41 changed files with 3772 additions and 170 deletions
+469
View File
@@ -0,0 +1,469 @@
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 = "› "
}
// Keep the image marker only while it still leaves room for a usable name:
// at very narrow widths the name is more useful than the marker, and the
// decision depends only on width, so every row's columns stay aligned
// whether or not the marker is shown.
if width >= artifactCursorWidth+artifactMarkerWidth+1+artifactMinName {
if isImageContentType(artifact.ContentType) {
prefix += "[img] "
} else {
prefix += strings.Repeat(" ", artifactMarkerWidth) + " "
}
}
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()
}
// artifactContent renders the grouped artifact lines and the line index of each
// flat artifact ref for the model's current width and selection, so selection
// and the scroll offset always agree on the same content.
func (m Model) artifactContent() ([]string, []int) {
visits, _ := m.artifactViewVisits()
widths := artifactWidthsFor(visits)
return artifactViewContent(visits, widths, max(1, m.width-4), m.artifactIndex)
}
// clampArtifactTop bounds the scroll offset to the range the current page can
// actually show.
func (m *Model) clampArtifactTop() {
lines, _ := m.artifactContent()
m.artifactTop = max(0, min(m.artifactTop, max(0, len(lines)-m.artifactsPageSize())))
}
// scrollArtifactBy moves the scroll offset by delta and clamps it, independent
// of the selection, so the offset can reach lines past the last artifact (a
// trailing visit's header and capture summary).
func (m *Model) scrollArtifactBy(delta int) {
m.artifactTop += delta
m.clampArtifactTop()
}
// scrollArtifactToEnd puts the window's last line on screen, exposing any
// trailing visits that recorded no artifacts.
func (m *Model) scrollArtifactToEnd() {
lines, _ := m.artifactContent()
m.artifactTop = max(0, len(lines)-m.artifactsPageSize())
}
// revealArtifactSelection nudges the scroll offset by the minimum needed to put
// the selected artifact row on screen; it never scrolls past the end.
func (m *Model) revealArtifactSelection() {
lines, refLines := m.artifactContent()
if m.artifactIndex < len(refLines) {
m.artifactTop = artifactScrollTop(m.artifactTop, refLines[m.artifactIndex], m.artifactsPageSize(), len(lines))
}
}
// clampArtifactScroll keeps the selection valid and its row on screen after a
// selection move.
func (m *Model) clampArtifactScroll() {
if m.runDetail == nil {
m.artifactIndex, m.artifactTop = 0, 0
return
}
_, refs := m.artifactViewVisits()
m.artifactIndex = max(0, min(m.artifactIndex, max(0, len(refs)-1)))
m.revealArtifactSelection()
}
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":
// Select the last artifact and show the tail of the list, so a trailing
// visit that recorded none (running or finished) is on screen.
m.artifactIndex = max(0, count-1)
m.clampArtifactScroll()
m.scrollArtifactToEnd()
return m, nil
case "pgdown", "ctrl+d":
m.scrollArtifactBy(max(1, m.artifactsPageSize()))
return m, nil
case "pgup", "ctrl+u":
m.scrollArtifactBy(-max(1, m.artifactsPageSize()))
return m, nil
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, _ := artifactViewContent(visits, widths, inner, selected)
page := max(0, height-4)
// The offset is authoritative and free: selection moves keep the selected
// row on screen, while page scroll and end can move past the last artifact
// to a trailing visit's header and capture summary.
top := max(0, min(m.artifactTop, max(0, len(lines)-page)))
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)
}
+63
View File
@@ -0,0 +1,63 @@
package tui
import (
"context"
"encoding/json"
"os"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/charmbracelet/x/ansi"
)
// TestLiveArtifactsFromCapture renders the artifacts view from real
// `pipelines inspect RUN_ID --json` captures. It is env-gated and skips unless
// PIPELINES_ARTIFACT_CAPTURES names one or more capture files, so it never
// depends on a running server in CI; the operator points it at real captures to
// re-confirm that mixed artifact types, a partial capture, a running visit and
// a finished visit with none all render.
func TestLiveArtifactsFromCapture(t *testing.T) {
list := os.Getenv("PIPELINES_ARTIFACT_CAPTURES")
if strings.TrimSpace(list) == "" {
t.Skip("set PIPELINES_ARTIFACT_CAPTURES to comma-separated `pipelines inspect RUN_ID --json` files")
}
m := New(context.Background(), "ws://127.0.0.1:8080/connect")
// Height chosen so artifactsViewHeight() is 50, keeping the view's page size
// and the model's scroll page size identical (as they are in the app).
m.width, m.height = 120, 54
var rendered strings.Builder
for _, path := range strings.Split(list, ",") {
path = strings.TrimSpace(path)
if path == "" {
continue
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var detail protocol.RunDetail
if err := json.Unmarshal(data, &detail); err != nil {
t.Fatal(err)
}
m.runDetail = &detail
m.artifactsOpen = true
m.artifactIndex, m.artifactTop = 0, 0
top := ansi.Strip(m.artifactsView(m.artifactsViewHeight()))
t.Logf("capture %s (run #%d executing=%t) top:\n%s", path, detail.ID, detail.Executing, top)
rendered.WriteString(top)
// Scroll to the tail so a trailing running visit's capture summary is
// rendered regardless of how many artifacts precede it; a fixed top
// page used to clip it once a run accumulated enough artifacts.
m = artifactKey(m, 'G')
tail := ansi.Strip(m.artifactsView(m.artifactsViewHeight()))
t.Logf("capture %s (run #%d executing=%t) tail:\n%s", path, detail.ID, detail.Executing, tail)
rendered.WriteString(tail)
}
text := rendered.String()
for _, want := range []string{"[img]", "partial capture", "capture pending", "not recorded for this visit", "image/png", "KiB"} {
if !strings.Contains(text, want) {
t.Errorf("live captures did not render %q", want)
}
}
}
+345
View File
@@ -0,0 +1,345 @@
package tui
import (
"context"
"fmt"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
)
func artifactsFixtureModel() Model {
m := New(context.Background(), "ws://127.0.0.1:8080/connect")
m.width, m.height = 100, 30
m.runOpen = true
m.keys.runs = true
m.runDetailFocus = true
m.requestedRunID = 169
m.runDetail = &protocol.RunDetail{
RunSummary: protocol.RunSummary{ID: 169, Name: "demo", Version: 3, Status: "succeeded"},
Steps: []protocol.RunStep{
{Sequence: 1, Stage: "implementer", Status: "completed", Artifacts: []protocol.StageArtifact{
{Name: "build.log", SizeBytes: 2337, ContentType: "text/plain; charset=utf-8", URL: "/artifacts/169/1/build.log"},
}, ArtifactsSkipped: 1, ArtifactsTruncated: 2},
{Sequence: 2, Stage: "ui_reviewer", Status: "completed", Artifacts: []protocol.StageArtifact{
{Name: "01-pill.png", SizeBytes: 80544, ContentType: "image/png", URL: "/artifacts/169/2/01-pill.png"},
{Name: "morph.mp4", SizeBytes: 645782, ContentType: "video/mp4", URL: "/artifacts/169/2/morph.mp4"},
}},
{Sequence: 3, Stage: "committer", Status: "completed"},
{Sequence: 4, Stage: "reviewer", Status: "running"},
},
}
return m
}
func artifactKey(m Model, key rune) Model {
updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{key}})
return updated.(Model)
}
func TestRunArtifactVisitsGroupAndOrder(t *testing.T) {
steps := []protocol.RunStep{
{Sequence: 3, Stage: "build"},
{Sequence: 2, Stage: "plan"},
{Sequence: 1, Stage: "plan", Control: &protocol.ControlEvidence{Visit: 1}, Artifacts: []protocol.StageArtifact{{Name: "plan.md"}}},
}
visits := runArtifactVisits(steps)
want := []struct {
stage string
visit int
}{{"build", 1}, {"plan", 1}, {"plan", 2}}
if len(visits) != len(want) {
t.Fatalf("visits = %d, want %d", len(visits), len(want))
}
for i, w := range want {
if visits[i].stage != w.stage || visits[i].visit != w.visit {
t.Fatalf("visit %d = %s/%d, want %s/%d", i, visits[i].stage, visits[i].visit, w.stage, w.visit)
}
}
}
func TestArtifactsViewGroupsMarkersAndWording(t *testing.T) {
m := artifactsFixtureModel()
m.width = 120
view := ansi.Strip(m.artifactsView(24))
for _, want := range []string{
"implementer · visit 1",
"ui_reviewer · visit 1",
"committer · visit 1",
"reviewer · visit 1",
"Artifacts · 1 recorded · partial capture",
"1 files excluded from artifact capture.",
"2 files omitted by artifact capture limits.",
"Artifacts · 2 recorded",
"Artifacts · not recorded for this visit",
"Artifacts · capture pending",
"[img]",
"01-pill.png",
"morph.mp4",
"video/mp4",
"78.7 KiB",
"630.6 KiB",
"/artifacts/169/2/01-pill.png",
} {
if !strings.Contains(view, want) {
t.Fatalf("artifacts view missing %q:\n%s", want, view)
}
}
for _, line := range strings.Split(view, "\n") {
if strings.Contains(line, "morph.mp4") && strings.Contains(line, "[img]") {
t.Fatalf("non-image artifact marked as an image: %q", line)
}
}
}
func TestArtifactsViewColumnsAlign(t *testing.T) {
m := artifactsFixtureModel()
m.width = 120
lines := strings.Split(ansi.Strip(m.artifactsView(24)), "\n")
var image, video string
for _, line := range lines {
if strings.Contains(line, "01-pill.png") {
image = line
}
if strings.Contains(line, "morph.mp4") {
video = line
}
}
if image == "" || video == "" {
t.Fatalf("artifact rows not both rendered:\n%s", strings.Join(lines, "\n"))
}
name := strings.Index(image, "01-pill.png")
typeStart := strings.Index(image, "image/png")
sizeStart := strings.Index(image, "78.7 KiB")
if name != strings.Index(video, "morph.mp4") || name < 0 {
t.Fatalf("name column misaligned:\n%q\n%q", image, video)
}
if typeStart != strings.Index(video, "video/mp4") || typeStart < 0 {
t.Fatalf("type column misaligned:\n%q\n%q", image, video)
}
if sizeStart+len("78.7 KiB") != strings.Index(video, "630.6 KiB")+len("630.6 KiB") || sizeStart < 0 {
t.Fatalf("size column misaligned:\n%q\n%q", image, video)
}
}
func TestArtifactsViewNeverOverflows(t *testing.T) {
for _, width := range []int{160, 120, 80, 63, 40, 24, 12} {
m := artifactsFixtureModel()
m.width = width
for _, line := range strings.Split(m.artifactsView(24), "\n") {
if got := ansi.StringWidth(line); got > width {
t.Fatalf("width %d: line width %d: %q", width, got, line)
}
}
}
m := artifactsFixtureModel()
m.width = 40
view := ansi.Strip(m.artifactsView(24))
if !strings.Contains(view, "/artifacts/169/1/build.log") {
t.Fatalf("narrow view must keep the selected URL available:\n%s", view)
}
}
func TestArtifactsViewEmptyRun(t *testing.T) {
m := New(context.Background(), "ws://127.0.0.1:8080/connect")
m.width, m.height = 100, 24
m.runDetail = &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 5}}
view := ansi.Strip(m.artifactsView(20))
for _, want := range []string{"Artifacts · run #5", "No recorded visits yet.", "No artifacts recorded"} {
if !strings.Contains(view, want) {
t.Fatalf("empty artifacts view missing %q:\n%s", want, view)
}
}
}
func artifactsScrollFixture() (Model, []string) {
m := New(context.Background(), "ws://127.0.0.1:8080/connect")
m.width, m.height = 80, 14
m.runOpen = true
m.keys.runs = true
m.runDetailFocus = true
m.requestedRunID = 7
var steps []protocol.RunStep
names := make([]string, 0, 12)
for i := 0; i < 12; i++ {
name := fmt.Sprintf("shot-%02d.png", i)
names = append(names, name)
steps = append(steps, protocol.RunStep{Sequence: i + 1, Stage: "ui_reviewer", Status: "completed",
Artifacts: []protocol.StageArtifact{{Name: name, SizeBytes: 1024, ContentType: "image/png", URL: "/artifacts/7/" + name}}})
}
m.runDetail = &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 7}, Steps: steps}
m.artifactsOpen = true
return m, names
}
func TestArtifactsViewKeepsSelectionVisible(t *testing.T) {
m, names := artifactsScrollFixture()
for i := 0; i < len(names)-1; i++ {
m = artifactKey(m, 'j')
}
if view := ansi.Strip(m.View()); !strings.Contains(view, names[len(names)-1]) {
t.Fatalf("last artifact scrolled out of view:\n%s", view)
}
for i := 0; i < len(names)-1; i++ {
m = artifactKey(m, 'k')
}
if view := ansi.Strip(m.View()); !strings.Contains(view, names[0]) {
t.Fatalf("first artifact not visible after scrolling back:\n%s", view)
}
}
func TestArtifactsSelectByNameScrollsIntoView(t *testing.T) {
m, names := artifactsScrollFixture()
m.selectArtifactByName(names[len(names)-1])
if view := ansi.Strip(m.View()); !strings.Contains(view, names[len(names)-1]) {
t.Fatalf("selectArtifactByName did not scroll the match into view:\n%s", view)
}
}
func TestResolveArtifactURL(t *testing.T) {
cases := []struct {
server, artifact, want string
ok bool
}{
{"ws://127.0.0.1:8080/connect", "/artifacts/1/2/a.png", "http://127.0.0.1:8080/artifacts/1/2/a.png", true},
{"wss://host/connect", "/artifacts/1/2/a.png", "https://host/artifacts/1/2/a.png", true},
{"ws://host/connect", "artifacts/1/2/a.png", "http://host/artifacts/1/2/a.png", true},
{"ws://host/connect", "https://cdn.example/a.png", "https://cdn.example/a.png", true},
{"", "/artifacts/1/2/a.png", "", false},
{"http://host/connect", "/artifacts/1/2/a.png", "", false},
}
for _, tc := range cases {
got, ok := resolveArtifactURL(tc.server, tc.artifact)
if ok != tc.ok || got != tc.want {
t.Fatalf("resolveArtifactURL(%q, %q) = %q,%t want %q,%t", tc.server, tc.artifact, got, ok, tc.want, tc.ok)
}
}
}
func TestArtifactsViewOpenAndCopyKeys(t *testing.T) {
previousOpen, previousCopy := openExternal, copyText
defer func() { openExternal, copyText = previousOpen, previousCopy }()
var opened, copied string
openExternal = func(target string) error { opened = target; return nil }
copyText = func(text string) error { copied = text; return nil }
m := artifactsFixtureModel()
m = artifactKey(m, 'A')
if !m.artifactsOpen {
t.Fatal("A did not open the artifacts view")
}
if m.artifactIndex != 0 {
t.Fatalf("selection = %d, want the first artifact", m.artifactIndex)
}
updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
if cmd == nil {
t.Fatal("Enter did not produce an open command")
}
updated, _ = m.Update(cmd())
m = updated.(Model)
if opened != "http://127.0.0.1:8080/artifacts/169/1/build.log" {
t.Fatalf("opened %q", opened)
}
m = artifactKey(m, 'j')
updated, cmd = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'y'}})
m = updated.(Model)
if cmd == nil {
t.Fatal("y did not produce a copy command")
}
updated, _ = m.Update(cmd())
m = updated.(Model)
if copied != "http://127.0.0.1:8080/artifacts/169/2/01-pill.png" {
t.Fatalf("copied %q", copied)
}
if !strings.Contains(strings.Join(m.lines, "\n"), "Copied artifact URL") {
t.Fatalf("copy outcome not surfaced: %v", m.lines)
}
}
func TestArtifactsViewRenderedInRunDetail(t *testing.T) {
m := artifactsFixtureModel()
m.artifactsOpen = true
view := ansi.Strip(m.View())
if !strings.Contains(view, "Artifacts · run #169") {
t.Fatalf("run view did not render the artifacts view:\n%s", view)
}
if !strings.Contains(m.activeFooter(), "y copy URL") {
t.Fatalf("footer does not advertise the artifact controls: %q", m.activeFooter())
}
if !strings.Contains(m.activeFooter(), "PgUp/PgDn scroll") {
t.Fatalf("footer does not advertise the scroll keys: %q", m.activeFooter())
}
}
// artifactsTrailingFixture is a run whose last visit is still running and
// recorded no artifacts, so its summary sits after every artifact row.
func artifactsTrailingFixture() Model {
m := New(context.Background(), "ws://127.0.0.1:8080/connect")
m.width, m.height = 80, 14
m.runOpen = true
m.keys.runs = true
m.runDetailFocus = true
m.requestedRunID = 7
var steps []protocol.RunStep
for i := 0; i < 12; i++ {
name := fmt.Sprintf("shot-%02d.png", i)
steps = append(steps, protocol.RunStep{Sequence: i + 1, Stage: "ui_reviewer", Status: "completed",
Artifacts: []protocol.StageArtifact{{Name: name, SizeBytes: 1024, ContentType: "image/png", URL: "/artifacts/7/" + name}}})
}
steps = append(steps, protocol.RunStep{Sequence: 13, Stage: "reviewer", Status: "running"})
m.runDetail = &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 7}, Steps: steps}
m.artifactsOpen = true
return m
}
func TestArtifactsViewEndRevealsTrailingVisit(t *testing.T) {
m := artifactsTrailingFixture()
if top := ansi.Strip(m.artifactsView(m.artifactsViewHeight())); strings.Contains(top, "capture pending") {
t.Fatalf("trailing running visit visible before scrolling:\n%s", top)
}
m = artifactKey(m, 'G')
view := ansi.Strip(m.View())
for _, want := range []string{"reviewer · visit 1", "Artifacts · capture pending"} {
if !strings.Contains(view, want) {
t.Fatalf("end did not reveal the trailing running visit (%q missing):\n%s", want, view)
}
}
if m.artifactIndex != 11 {
t.Fatalf("end did not keep the last artifact selected: %d", m.artifactIndex)
}
}
func TestArtifactsViewPageScrollRevealsTrailingVisit(t *testing.T) {
m := artifactsTrailingFixture()
for i := 0; i < 100; i++ {
before := m.artifactTop
updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
m = updated.(Model)
if m.artifactTop == before {
break
}
}
if view := ansi.Strip(m.View()); !strings.Contains(view, "capture pending") {
t.Fatalf("page scroll did not reveal the trailing running visit:\n%s", view)
}
}
func TestArtifactsViewNarrowKeepsNames(t *testing.T) {
m := artifactsFixtureModel()
m.width = 12
view := ansi.Strip(m.artifactsView(24))
if !strings.Contains(view, "build") {
t.Fatalf("narrow view dropped the artifact name:\n%s", view)
}
for _, line := range strings.Split(view, "\n") {
if got := ansi.StringWidth(line); got > m.width {
t.Fatalf("narrow view overflowed: line width %d: %q", got, line)
}
}
}
+4
View File
@@ -13,6 +13,10 @@ type RunOptions struct {
Pipeline, Prompt, Title, Workspace string
Yes, AllowTools bool
WritePaths []string
// Model and StageModels are the CLI's launch-time model overrides, passed
// through to the run request without adding a TUI picker (that is a follow-up).
Model string
StageModels map[string]string
}
func NewRun(ctx context.Context, url string, options RunOptions) Model {
+6 -2
View File
@@ -15,6 +15,8 @@ func (m Model) activeFooter() string {
text = "Refreshing published state · draft retained"
case m.decisionOpen:
text = "↑/↓ choose · Tab feedback · Enter decide · Esc cancel"
case m.artifactsOpen:
text = "j/k select · PgUp/PgDn scroll · Enter open · y copy URL · Esc back"
case m.actionConfirm != nil || m.mutationCommand != nil:
text = "y confirm · n/Esc cancel · j/k read"
case m.draftDeletingPath != "":
@@ -35,7 +37,7 @@ func (m Model) activeFooter() string {
case m.versionsOpen:
text = "↑/↓ choose · Enter view version · Esc back"
case m.paletteOpen && m.searchOpen:
text = "Type to search · ↑/↓ choose · Enter open · Esc cancel"
text = "Search pipelines, runs, steps, artifacts and text · ↑/↓ choose · Enter open · Esc cancel"
case m.paletteOpen:
text = "Type a command · ↑/↓ choose · Enter execute · Esc cancel"
case m.logOpen:
@@ -63,6 +65,8 @@ func (m Model) activeFooter() string {
text = "Refreshing · draft retained"
case m.decisionOpen:
text = "Esc cancel · Enter decide · ↑↓ select"
case m.artifactsOpen:
text = "Esc back · Enter open · y copy · PgUp/PgDn"
case m.actionConfirm != nil || m.mutationCommand != nil:
text = "Esc cancel · y confirm · j/k read"
case m.draftDeletingPath != "":
@@ -83,7 +87,7 @@ func (m Model) activeFooter() string {
case m.versionsOpen:
text = "Esc back · Enter view · ↑↓ select"
case m.paletteOpen && m.searchOpen:
text = "Esc back · Enter open · ↑↓ select"
text = "Esc cancel · Enter open · ↑↓ select"
case m.paletteOpen:
text = "Esc back · Enter run · ↑↓ select"
case m.logOpen:
+5
View File
@@ -374,6 +374,11 @@ func (m Model) updateLogs(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m, nil
}
// popup centres a dialog of at most preferredWidth (clamped to width-6) and
// truncates every line to that width so a modal cannot break the layout. Below
// roughly 20 columns the boxed dialog no longer fits, so popup falls back to the
// bare truncated lines without chrome; the TUI is designed for terminals at
// least 20 columns wide.
func popup(width, height, preferredWidth int, lines []string) string {
inner := min(preferredWidth, max(1, width-6))
for i := range lines {
+9 -10
View File
@@ -57,23 +57,22 @@ func humanBytes(size int64) string {
return fmt.Sprintf("%.1f %ciB", float64(size)/float64(div), "KMGTPE"[exp])
}
// artifactLines lists one step's recorded artifacts (name and size) for the
// retained-evidence view, matching the file-changes style.
func artifactLines(step protocol.RunStep) []string {
// artifactCaptureNotes lists the partial-capture notes for one visit: one line
// per non-zero excluded/omitted count, and nothing when the capture was
// complete. A visit with no recorded artifacts yields no notes, mirroring the
// app's artifactCaptureNotes, so notes never accompany an empty-state summary.
func artifactCaptureNotes(step protocol.RunStep) []string {
if len(step.Artifacts) == 0 {
return nil
}
lines := []string{artifactsSummary(step)}
for _, artifact := range step.Artifacts {
lines = append(lines, fmt.Sprintf("%s · %s · %s", ansi.Strip(artifact.Name), humanBytes(artifact.SizeBytes), ansi.Strip(artifact.ContentType)))
}
var notes []string
if step.ArtifactsSkipped > 0 {
lines = append(lines, fmt.Sprintf("%d files excluded from artifact capture.", step.ArtifactsSkipped))
notes = append(notes, fmt.Sprintf("%d files excluded from artifact capture.", step.ArtifactsSkipped))
}
if step.ArtifactsTruncated > 0 {
lines = append(lines, fmt.Sprintf("%d files omitted by artifact capture limits.", step.ArtifactsTruncated))
notes = append(notes, fmt.Sprintf("%d files omitted by artifact capture limits.", step.ArtifactsTruncated))
}
return lines
return notes
}
func diffHighlight(line string) string {
+58
View File
@@ -134,6 +134,13 @@ type Model struct {
commandIndex int
homeTop int
searchOpen bool
searchResults []protocol.SearchResult
searchText string
searchRequest string
searchInFlight bool
searchQueued bool
searchError string
pendingRunNav *searchNav
detail *protocol.PipelineDetail
detailRequest string
detailLoading bool
@@ -197,6 +204,9 @@ type Model struct {
decisionIndex int
decisionFeedback textinput.Model
decisionFeedbackFocus bool
artifactsOpen bool
artifactIndex int
artifactTop int
editorOpen bool
editorInput textinput.Model
editorIndex int
@@ -269,6 +279,17 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.appendLine("Harness debug: " + msg.err.Error())
}
return m, nil
case artifactActionMsg:
if msg.err != nil {
m.appendLine("Artifact " + msg.verb + ": " + msg.err.Error())
return m, nil
}
if msg.verb == "copy" {
m.appendLine("Copied artifact URL: " + msg.url)
} else {
m.appendLine("Opened artifact URL: " + msg.url)
}
return m, nil
case spinner.TickMsg:
var cmd tea.Cmd
m.runSpinner, cmd = m.runSpinner.Update(msg)
@@ -353,6 +374,22 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.statusError = msg.Error
m.statusRequest = ""
}
if msg.Type == protocol.SearchResults {
if msg.ID == m.searchRequest && msg.SearchResults != nil {
m.searchInFlight = false
m.searchResults = msg.SearchResults.Results
m.searchText = msg.SearchResults.Query
m.searchError = ""
m.commandIndex = min(m.commandIndex, max(0, len(msg.SearchResults.Results)-1))
if m.searchQueued {
m.searchQueued = false
updated, cmd := m.requestSearch()
m = updated.(Model)
return m, tea.Batch(m.read(), cmd)
}
}
return m, m.read()
}
if msg.Type == protocol.PipelineList || msg.Type == protocol.Submitted {
m.notificationEndpoints = msg.NotificationEndpoints
if msg.DefaultModel != "" {
@@ -386,6 +423,11 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.requestedRunID = msg.RunDetail.ID
m.runError = ""
m.runStepIndex = min(m.runStepIndex, len(msg.RunDetail.Steps))
if m.pendingRunNav != nil && m.pendingRunNav.runID == msg.RunDetail.ID {
nav := *m.pendingRunNav
m.pendingRunNav = nil
m.applyRunNav(nav)
}
}
} else if msg.Type == protocol.Pong {
m.appendLine(fmt.Sprintf("pong #%s: %s", msg.ID, msg.Time))
@@ -412,6 +454,13 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.keys.confirm = true
}
}
if msg.ID != "" && msg.ID == m.searchRequest {
m.searchInFlight = false
m.searchQueued = false
m.searchResults = nil
m.searchText = ""
m.searchError = msg.Error
}
} else if msg.Type == protocol.Submitted {
m.templateConfirm = false
m.draftOpen = false
@@ -602,6 +651,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.decisionOpen {
return m.updateDecision(msg)
}
if m.artifactsOpen {
return m.updateArtifacts(msg)
}
if m.runOpen && (msg.String() != ":" || m.runSearchOpen) {
return m.updateRuns(msg)
}
@@ -630,6 +682,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.commandIndex = 0
m.commandInput = newInput()
if m.searchOpen {
m.searchResults = nil
m.searchText = ""
m.searchError = ""
m.commandInput.Placeholder = "Type to search…"
return m, m.commandInput.Focus()
}
@@ -807,6 +862,9 @@ func (m Model) View() string {
if m.decisionOpen {
content = m.decisionView(bodyHeight)
}
if m.artifactsOpen {
content = m.artifactsView(bodyHeight)
}
if m.mutationCommand != nil {
paragraphs := []string{"This opens a new session/editor and may modify a retained draft.", "Published definitions and previous run history are unchanged."}
if strings.Contains(m.mutationTitle, "debugging") {
+259 -31
View File
@@ -7,7 +7,7 @@ import (
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/sahilm/fuzzy"
"github.com/charmbracelet/x/ansi"
"git.a-wan.net/alan/pipelines/internal/draft"
"git.a-wan.net/alan/pipelines/internal/pipeline"
@@ -19,29 +19,57 @@ func selectionWindow(count, index, capacity int) (int, int) {
return start, min(count, start+capacity)
}
func (m Model) searchMatches() []protocol.PipelineSummary {
query := strings.TrimPrefix(strings.TrimSpace(m.commandInput.Value()), "/")
if query == "" {
return m.pipelines
// searchNav remembers the step and section to focus once an asynchronously
// requested run arrives, so Enter on a step/artifact/field match lands exactly
// where it matched.
type searchNav struct {
runID int64
sequence int
section int
artifact string
}
// requestSearch asks the server for the current query. At most one request is in
// flight: a keystroke while a request is outstanding is coalesced and the latest
// text is sent when the response arrives. Stale responses are dropped by ID, so
// no keystroke triggers overlapping or unbounded scans. The server owns parsing
// (status words, dates and the optional kind filter), so the client sends the
// raw text and needs no second matcher.
func (m Model) requestSearch() (tea.Model, tea.Cmd) {
query := strings.TrimSpace(m.commandInput.Value())
if m.conn == nil {
m.searchResults = nil
m.searchText = ""
return m, nil
}
names := make([]string, len(m.pipelines))
for i, p := range m.pipelines {
names[i] = p.Name
if m.searchInFlight {
m.searchQueued = true
return m, nil
}
result := []protocol.PipelineSummary{}
for _, match := range fuzzy.Find(query, names) {
result = append(result, m.pipelines[match.Index])
}
return result
m.nextID++
m.searchRequest = strconv.FormatUint(m.nextID, 10)
m.searchInFlight = true
m.searchError = ""
return m, m.send(protocol.Message{Type: protocol.Search, ID: m.searchRequest, Search: &protocol.SearchRequest{Query: query}})
}
func (m *Model) closeSearch() {
m.paletteOpen = false
m.searchOpen = false
m.keys.palette = false
m.searchResults = nil
m.searchText = ""
m.searchRequest = ""
m.searchInFlight = false
m.searchQueued = false
m.searchError = ""
}
func (m Model) updateSearch(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
items := m.searchMatches()
items := m.searchResults
switch msg.String() {
case "esc":
m.paletteOpen = false
m.searchOpen = false
m.keys.palette = false
m.closeSearch()
return m, nil
case "down", "ctrl+n":
m.commandIndex = min(m.commandIndex+1, max(0, len(items)-1))
@@ -53,35 +81,235 @@ func (m Model) updateSearch(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
if len(items) == 0 {
return m, nil
}
selected := items[min(m.commandIndex, len(items)-1)]
m.paletteOpen = false
m.searchOpen = false
m.keys.palette = false
return m.requestPipeline(selected.ID, 0)
return m.openSearchResult(items[min(m.commandIndex, len(items)-1)])
}
var cmd tea.Cmd
m.commandInput, cmd = m.commandInput.Update(msg)
m.commandIndex = 0
return m, cmd
updated, send := m.requestSearch()
return updated, tea.Batch(cmd, send)
}
// openSearchResult navigates straight to a result: a pipeline/version opens its
// detail, and a run/step/artifact/field match opens the run with that step and
// section selected once the run arrives.
func (m Model) openSearchResult(result protocol.SearchResult) (tea.Model, tea.Cmd) {
m.closeSearch()
switch result.Kind {
case protocol.SearchKindPipeline:
if result.Pipeline != nil {
return m.requestPipeline(result.Pipeline.ID, result.Pipeline.Version)
}
case protocol.SearchKindVersion:
if result.Version != nil {
return m.requestPipeline(result.Version.PipelineID, result.Version.Version)
}
}
runID, sequence, field, artifact := searchResultTarget(result)
if runID <= 0 {
return m, nil
}
m.closeRuns()
m.runOpen = true
m.keys.runs = true
m.runIndex = 0
nav := &searchNav{runID: runID, sequence: sequence, section: runSectionNone}
switch result.Kind {
case protocol.SearchKindStep:
nav.section = runSectionProgress
case protocol.SearchKindField:
nav.section = sectionForField(field)
case protocol.SearchKindArtifact:
// Artifacts have their own grouped view; open it with the matched entry
// selected so the operator can open or copy its URL.
nav.section = runSectionNone
nav.artifact = artifact
}
m.pendingRunNav = nav
return m.runRequest(protocol.Message{Type: protocol.GetRun, RunID: runID})
}
// searchResultTarget returns the run, step, field and artifact a result points
// at, read from its typed payload rather than re-parsing the target token.
func searchResultTarget(result protocol.SearchResult) (runID int64, sequence int, field, artifact string) {
switch result.Kind {
case protocol.SearchKindRun:
if result.Run != nil {
runID = result.Run.ID
}
case protocol.SearchKindStep:
if result.Step != nil {
runID, sequence = result.Step.RunID, result.Step.Sequence
}
case protocol.SearchKindField:
if result.Field != nil {
runID, sequence, field = result.Field.RunID, result.Field.Sequence, result.Field.Field
}
case protocol.SearchKindArtifact:
if result.Artifact != nil {
runID, sequence, artifact = result.Artifact.RunID, result.Artifact.Sequence, result.Artifact.Name
}
}
return runID, sequence, field, artifact
}
func sectionForField(field string) int {
switch field {
case "input":
return runSectionInput
case "output":
return runSectionResult
case "evidence", "transcript":
return runSectionEvidence
default:
return runSectionDetails
}
}
// applyRunNav selects the matched step and scrolls to the matched section.
func (m *Model) applyRunNav(nav searchNav) {
if m.runDetail == nil {
return
}
if nav.sequence > 0 {
for i, step := range m.runDetail.Steps {
if step.Sequence == nav.sequence {
m.selectRunStep(i + 1)
break
}
}
}
if nav.section != runSectionNone {
m.runGraphFocus = false
m.runDetailFocus = true
m.focusRunSection(nav.section)
}
if nav.section == runSectionNone && nav.artifact != "" {
m.openArtifacts()
m.selectArtifactByName(nav.artifact)
}
}
// focusRunSection opens the section and scrolls the run detail to its header,
// reusing the same shortcut markers runSectionLines renders.
func (m *Model) focusRunSection(section int) {
if m.runDetail == nil || section < 0 || section >= runSectionCount {
return
}
if m.runCollapsed == nil {
m.runCollapsed = map[string]bool{}
}
m.runCollapsed[m.runSectionKey(section)] = false
marker := "[" + runSections[section].Shortcut + "]"
for i, line := range m.runSectionLines(m.runDetailWidth()) {
if strings.HasPrefix(ansi.Strip(line), marker) {
m.runTop = i
return
}
}
}
// searchBadge is the short type label a result shows. A pipeline version folds
// into the pipeline badge and a body-text field into the match badge, so the
// row reads the way the operator thinks about it rather than the wire kind.
func searchBadge(kind string) string {
switch kind {
case protocol.SearchKindVersion:
return "pipeline"
case protocol.SearchKindField:
return "match"
default:
return kind
}
}
// markedSnippet brackets the first case-insensitive occurrence of query in a
// field snippet so the matched part is distinguishable without relying on
// colour, then clips the result to budget runes with the bracketed match kept
// inside the window. It tracks the exact marker span it inserts, so a snippet
// that itself contains '[' cannot make the window centre on the wrong bracket.
// The server centres the snippet on the match, so the text is present
// case-insensitively; the snippet is shown unchanged when it is not. The budget
// excludes the row's two-rune indent, since the result is clipped before the
// row is styled.
func markedSnippet(snippet, query string, budget int) string {
runes := []rune(snippet)
needle := []rune(strings.TrimSpace(query))
if len(needle) == 0 || len(runes) == 0 {
return snippet
}
at := protocol.RuneIndexFold(runes, needle)
if at < 0 {
return snippet
}
marked := string(runes[:at]) + "[" + string(runes[at:at+len(needle)]) + "]" + string(runes[at+len(needle):])
markedRunes := []rune(marked)
if budget <= 0 || len(markedRunes) <= budget {
return marked
}
// The inserted '[' sits at rune `at` and the ']' at at+len(needle)+1, so the
// span to keep in view is [at, at+len(needle)+2).
spanStart, spanEnd := at, at+len(needle)+2
if spanEnd-spanStart >= budget {
return string(markedRunes[:budget])
}
lo := max(0, spanStart-(budget-(spanEnd-spanStart))/2)
hi := min(len(markedRunes), lo+budget)
lo = max(0, hi-budget)
out := string(markedRunes[lo:hi])
if lo > 0 {
out = "…" + out
}
if hi < len(markedRunes) {
out += "…"
}
return out
}
// searchRowLines renders one result. A body-text match keeps its (windowed)
// snippet on its own indented line so the marker is visible at the popup width
// instead of being clipped after a long badge and label.
func searchRowLines(result protocol.SearchResult, query string, snippetBudget int) []string {
head := "[" + searchBadge(result.Kind) + "] " + result.Label()
if result.Kind == protocol.SearchKindField && result.Field != nil && result.Field.Snippet != "" {
return []string{head, " " + markedSnippet(result.Field.Snippet, query, snippetBudget)}
}
return []string{head}
}
func (m Model) searchView(height int) string {
field := m.commandInput
field.Width = max(1, min(54, m.width-10))
lines := []string{"Search pipelines", field.View(), ""}
items := m.searchMatches()
if len(items) == 0 {
lines = append(lines, "No matching pipelines")
field.Width = max(1, min(64, m.width-10))
inner := min(72, max(1, m.width-6))
snippetBudget := max(8, inner-4)
lines := []string{"Search", field.View(), ""}
items := m.searchResults
query := strings.TrimSpace(m.commandInput.Value())
switch {
case m.searchError != "":
lines = append(lines, "Search failed: "+m.searchError)
case len(items) == 0 && m.searchInFlight:
lines = append(lines, "Searching…")
case len(items) == 0 && query != "":
lines = append(lines, "No matches for "+query)
case len(items) == 0:
lines = append(lines, "Type to search pipelines, runs, steps, text and artifacts.")
}
start, end := selectionWindow(len(items), m.commandIndex, max(1, height-5))
// A field match renders two lines, so budget the window by rendered lines.
start, end := selectionWindow(len(items), m.commandIndex, max(1, (height-4)/2))
for i := start; i < end; i++ {
prefix := " "
if i == m.commandIndex {
prefix = "› "
}
lines = append(lines, menuOption(fmt.Sprintf("%s%s · v%d · %d stages", prefix, items[i].Name, items[i].Version, items[i].Stages), i == m.commandIndex))
for j, row := range searchRowLines(items[i], m.searchText, snippetBudget) {
if j == 0 {
row = prefix + row
}
lines = append(lines, menuOption(row, i == m.commandIndex))
}
}
return popup(m.width, height, 64, lines)
return popup(m.width, height, 72, lines)
}
func (m Model) requestPipeline(id int64, version int) (tea.Model, tea.Cmd) {
+25 -3
View File
@@ -17,6 +17,28 @@ import (
"git.a-wan.net/alan/pipelines/internal/server"
)
// typeSearch types into the omni popup, flushes the outgoing search request and
// reads the server response, so a test observes real server-side matches.
func typeSearch(t *testing.T, m Model, text string) Model {
t.Helper()
for _, r := range text {
updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
m = updated.(Model)
if cmd != nil {
if batch, ok := cmd().(tea.BatchMsg); ok {
for _, c := range batch {
if c != nil {
c()
}
}
}
}
updated, _ = m.Update(m.read()())
m = updated.(Model)
}
return m
}
func TestSearchVersionsAndEditSubmission(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -44,9 +66,9 @@ func TestSearchVersionsAndEditSubmission(t *testing.T) {
updated, read = m.Update(read())
m = updated.(Model)
m = press(m, "/")
m = press(m, "dmo")
if !m.searchOpen || !m.paletteOpen || len(m.searchMatches()) != 1 {
t.Fatal("omnisearch failed")
m = typeSearch(t, m, "demo")
if !m.searchOpen || !m.paletteOpen || len(m.searchResults) != 1 || m.searchResults[0].Kind != protocol.SearchKindPipeline {
t.Fatalf("omnisearch failed: %+v", m.searchResults)
}
updated, send := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
+13 -3
View File
@@ -101,6 +101,9 @@ func (m *Model) closeRuns() {
m.runGraphFocus = false
m.runGraphTop = 0
m.runGraphPan = 0
m.artifactsOpen = false
m.artifactIndex = 0
m.artifactTop = 0
m.closeDecision()
}
@@ -359,6 +362,11 @@ func evidenceLines(step protocol.RunStep) []string {
if step.SessionID == "" {
lines = []string{"Recorded result evidence"}
}
// The effective provider/model this visit ran with, for a model stage; it
// reflects any launch-time override rather than the pinned model.
if step.Provider != "" || step.Model != "" {
lines = append(lines, "Ran with model: "+step.Provider+"/"+step.Model)
}
if step.Transcript == "" {
return append(lines, "No captured tool evidence yet.")
}
@@ -547,7 +555,9 @@ func (m Model) runSectionLines(width int) []string {
}
var diff []string
if !m.runSectionClosed(runSectionFiles) {
diff = append(stageDiffLines(step), artifactLines(step)...)
// Artifacts have their own grouped view (A); this section is the
// observed workspace diff only.
diff = stageDiffLines(step)
}
content = append(content, diff)
for _, receipt := range step.Notifications {
@@ -641,7 +651,7 @@ func (m Model) runActions() string {
text += " · D debug"
}
if m.runDetail != nil {
text += " · a evidence"
text += " · a evidence · A artifacts"
}
if m.runDetail != nil && m.runDetail.Status == protocol.RunStatusWaiting {
text += " · c decide"
@@ -724,7 +734,7 @@ func (m Model) runsDetailsView(height int) string {
lines := m.runSectionLines(m.runDetailWidth())
page := max(0, innerHeight-5)
top := max(0, min(m.runTop, max(0, len(lines)-page)))
footerHint := "o result · d diff · s progress · i input · t evidence · m details"
footerHint := "o result · d diff · s progress · i input · t evidence · m details · A artifacts"
if r.Status == protocol.RunStatusWaiting {
footerHint += " · c decide"
}
+1 -1
View File
@@ -193,7 +193,7 @@ func TestRunningDurationAndOpenCodeEvidenceShortcut(t *testing.T) {
m := runInspectionModel()
m.runDetail.Steps[1].AgentActive = true
m = runKey(m, "a")
if m.runStepIndex != 2 || !m.runDetailFocus || m.runSectionClosed(3) || !m.runSectionClosed(0) {
if m.runStepIndex != 2 || !m.runDetailFocus || m.runSectionClosed(runSectionEvidence) || !m.runSectionClosed(runSectionProgress) {
t.Fatal("OpenCode evidence shortcut did not select active session")
}
view := ansi.Strip(strings.Join(m.runSectionLines(90), "\n"))
+24
View File
@@ -0,0 +1,24 @@
package tui
import (
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// TestEvidenceLinesShowEffectiveModel proves the Evidence pane renders the
// provider/model a step actually ran with, so a launch-time override is visible
// rather than the pinned model.
func TestEvidenceLinesShowEffectiveModel(t *testing.T) {
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Provider: "acme", Model: "strong"}
text := strings.Join(evidenceLines(step), "\n")
if !strings.Contains(text, "acme/strong") {
t.Fatalf("evidence pane omitted the effective model:\n%s", text)
}
// A non-model step records no provider/model and shows no model line.
plain := strings.Join(evidenceLines(protocol.RunStep{Sequence: 2, Stage: "note", Status: "completed", Outcome: "success"}), "\n")
if strings.Contains(plain, "Ran with model:") {
t.Fatalf("non-model step claimed a model:\n%s", plain)
}
}
+14 -5
View File
@@ -147,7 +147,7 @@ func (m *Model) startSelectedRun() tea.Cmd {
m.runCollapsed = nil
m.runDetail = nil
m.runTop = 0
request := protocol.Message{Type: protocol.RunPipeline, PipelineID: m.detail.ID, Version: m.detail.Version, RequestKey: fmt.Sprintf("tui-%d", time.Now().UnixNano()), Title: m.cliOptions.Title, Input: initialRunInput(m.runTask), AllowTools: m.runHasMutationTools(), WritePaths: m.runPaths, Workspace: m.runWorkspace}
request := protocol.Message{Type: protocol.RunPipeline, PipelineID: m.detail.ID, Version: m.detail.Version, RequestKey: fmt.Sprintf("tui-%d", time.Now().UnixNano()), Title: m.cliOptions.Title, Input: initialRunInput(m.runTask), AllowTools: m.runHasMutationTools(), WritePaths: m.runPaths, Workspace: m.runWorkspace, Model: m.cliOptions.Model, StageModels: m.cliOptions.StageModels}
updated, cmd := m.runRequest(request)
*m = updated.(Model)
return cmd
@@ -322,10 +322,16 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m.debugRun()
case "a":
return m.openOpenCodeEvidence()
case "A":
if m.runDetail != nil {
m.openArtifacts()
}
return m, nil
case "r":
return m.retrySelectedRun()
case "esc":
m.runGraphFocus = false
m.artifactsOpen = false
if m.runDetail != nil || m.requestedRunID > 0 || m.runStartRequest != "" {
m.runDetail = nil
m.requestedRunID = 0
@@ -400,18 +406,21 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
}
case "s", "i", "o", "t", "m":
if m.runDetail != nil {
m.toggleRunSection(strings.Index("siotm", msg.String()))
if index, ok := runSectionForShortcut(msg.String()); ok {
m.toggleRunSection(index)
}
}
case "d":
if m.runDetail != nil {
m.runGraphFocus = false
m.runDetailFocus = true
_, focused := runFocusedSection(m.runSectionLines(m.runDetailWidth()), m.runTop)
if m.runSectionClosed(5) || focused == "File changes" {
m.toggleRunSection(5)
if m.runSectionClosed(runSectionFiles) || focused == runSections[runSectionFiles].Title {
m.toggleRunSection(runSectionFiles)
}
marker := "[" + runSections[runSectionFiles].Shortcut + "]"
for i, line := range m.runSectionLines(m.runDetailWidth()) {
if strings.HasPrefix(ansi.Strip(line), "[d]") {
if strings.HasPrefix(ansi.Strip(line), marker) {
m.runTop = i
break
}
+149
View File
@@ -0,0 +1,149 @@
package tui
import (
"context"
"os"
"strconv"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// TestLiveOmniSearchAgainstServer is an env-gated check against a running
// server: it drives the TUI's own '/' search, renders the popup, and presses
// Enter on a live result of each kind, reporting where navigation lands. It
// skips unless PIPELINES_LIVE_SEARCH is set so CI never needs a server.
func TestLiveOmniSearchAgainstServer(t *testing.T) {
if os.Getenv("PIPELINES_LIVE_SEARCH") == "" {
t.Skip("set PIPELINES_LIVE_SEARCH=1 to query the running server")
}
url := os.Getenv("PIPELINES_URL")
if url == "" {
url = "ws://127.0.0.1:8080/connect"
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
m := New(ctx, url)
m.width, m.height = 120, 40
connected := m.connect()().(connectedMsg)
defer connected.conn.CloseNow()
updated, _ := m.Update(connected)
m = updated.(Model)
// Plain-text (never a type prefix) candidates per kind. The live store keeps
// changing as runs land, so a fixed query can stop matching a kind; the test
// uses the first candidate that still returns the kind it is checking.
candidates := map[string][]string{
protocol.SearchKindPipeline: {"demo", "pipeline", "test", "a"},
protocol.SearchKindVersion: {"1", "demo", "review", "test"},
protocol.SearchKindRun: {"succeeded", "failed", "running", "1"},
protocol.SearchKindStep: {"implementer", "reviewer", "planner", "success"},
protocol.SearchKindField: {"identity", "search", "error", "the"},
protocol.SearchKindArtifact: {"identity", "png", "log", "txt"},
}
for _, kind := range protocol.SearchKinds {
picked, query := -1, ""
for _, candidate := range candidates[kind] {
m = resetLiveSearch(m)
m = liveType(m, tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'/'}})
m = liveType(m, tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(candidate)})
m = drainLiveSearch(t, m)
query = candidate
picked = -1
for i, result := range m.searchResults {
if result.Kind == kind {
picked = i
break
}
}
if picked >= 0 {
break
}
}
if picked < 0 {
t.Errorf("%s: no candidate query returned a %s result", kind, kind)
continue
}
m.commandIndex = picked
view := ansi.Strip(m.searchView(20))
t.Logf("%s: query %q rendered\n%s", kind, query, view)
updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
if where := liveNavigation(m); where == "" {
t.Errorf("%s: Enter did not navigate (result %+v)", kind, m.searchResults[picked])
} else {
t.Logf("%s: Enter navigates to %s", kind, where)
}
}
}
// liveType delivers one key and runs any command it produced (a text-input
// update or a search request written to the socket), mirroring the real
// bubbletea loop.
func liveType(m Model, msg tea.Msg) Model {
updated, cmd := m.Update(msg)
m = updated.(Model)
if cmd == nil {
return m
}
if batch, ok := cmd().(tea.BatchMsg); ok {
for _, c := range batch {
if c != nil {
c()
}
}
}
return m
}
// drainLiveSearch reads server frames until the outstanding search request is
// answered, so a slow or interleaved reply is still observed.
func drainLiveSearch(t *testing.T, m Model) Model {
t.Helper()
for i := 0; i < 100; i++ {
if !m.searchInFlight {
return m
}
updated, _ := m.Update(m.read()())
m = updated.(Model)
}
t.Fatalf("timed out waiting for the search reply")
return m
}
// resetLiveSearch returns the model to the home screen with no overlay, ready
// for the next '/' query.
func resetLiveSearch(m Model) Model {
m.closeSearch()
m.closeRuns()
m.keys.detail = false
m.detail = nil
m.detailLoading = false
m.requestedPipelineID = 0
m.requestedVersion = 0
m.artifactsOpen = false
return m
}
// liveNavigation describes where the last Enter landed, read from the same
// state the views use.
func liveNavigation(m Model) string {
switch {
case m.detailLoading:
return "pipeline detail #" + strconv.FormatInt(m.requestedPipelineID, 10)
case m.runOpen && m.pendingRunNav != nil && m.pendingRunNav.artifact != "":
return "run #" + strconv.FormatInt(m.pendingRunNav.runID, 10) + " artifacts (" + m.pendingRunNav.artifact + ")"
case m.runOpen && m.pendingRunNav != nil && m.pendingRunNav.section >= 0:
return "run #" + strconv.FormatInt(m.pendingRunNav.runID, 10) + " section " + runSections[m.pendingRunNav.section].Title
case m.runOpen && m.pendingRunNav != nil:
return "run #" + strconv.FormatInt(m.pendingRunNav.runID, 10) + " detail"
case m.artifactsOpen:
return "artifacts view"
}
return ""
}
+236
View File
@@ -0,0 +1,236 @@
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)
}
}
}
}