diff --git a/docs/cli.md b/docs/cli.md index 6d91c3ce..5d69e5d6 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -10,7 +10,13 @@ separately. Set `PIPELINES_URL` or pass `--url` to select another server. ## Dashboard and status -Home's `r` opens **all** recent runs (latest 50), not only failures. Wide terminals +Home's `r` opens **all** runs, not only failures or the newest 50. Inside a pipeline, +`r` and `:runs` show only that pipeline's runs across its versions. In any run list, +press `/` for fuzzy search, type to filter, and Enter to return to the results. +Search includes pipeline name, version, status, outcome, stage and diagnostic; +`#123` searches run-ID prefixes. Esc while searching clears the filter without +closing the list. The filter survives inspection/back and live list refreshes. +Wide terminals show runs and pipelines side by side, with stacked panels on narrow terminals. Run cards show status, duration, start time and the current stage when active. The usage summary is aggregated over all stored history, including retry attempts: @@ -169,10 +175,14 @@ Retry is hidden and rejected while a run is executing or agent cleanup remains active, even if a terminal status was already persisted. Run RPCs report `executing` alongside status so clients can distinguish cleanup from completion. -The run inspector's upper half shows the actual execution path using the shared -pipeline graph renderer and viewport. Visits are numbered, including repeated -visits in loops; only recorded routing decisions become edges. No unchosen stage -is added to the run path. On small terminals the details take precedence. Press +The run inspector's upper half shows the entire graph from the run's immutable +pinned version using the shared renderer and viewport. Executed stages and taken +routes retain their colors; unexecuted stages, unchosen routes and unreached +terminals are dimmed. Queued runs show the full graph before the first visit. +Repeated visits remain individually inspectable in the stage sidebar, while the +graph highlights every audited route through a loop. On small terminals details +take precedence. Older servers without a graph fall back to a matching loaded +definition or the recorded execution path, never a different pipeline/version. Press `g` to focus the graph, arrows to pan, and `j/k` or PgUp/PgDn to scroll. Press `g` or Tab to return to details. When not focused, the graph follows the latest visit or selected stage. Existing polling refreshes the graph once per second, and diff --git a/internal/pipeline/runs.go b/internal/pipeline/runs.go index b734a462..792e1d9f 100644 --- a/internal/pipeline/runs.go +++ b/internal/pipeline/runs.go @@ -105,7 +105,7 @@ func scanRun(row interface{ Scan(...any) error }, r *protocol.RunSummary) error } func (s *Store) ListRuns(ctx context.Context) ([]protocol.RunSummary, error) { - rows, err := s.db.QueryContext(ctx, runSelect+" ORDER BY r.id DESC LIMIT 50") + rows, err := s.db.QueryContext(ctx, runSelect+" ORDER BY r.id DESC") if err != nil { return nil, err } @@ -150,6 +150,13 @@ func (s *Store) GetRun(ctx context.Context, id int64) (*protocol.RunDetail, erro return nil, err } var input, output, paths string + var graphJSON string + if err := tx.QueryRowContext(ctx, "SELECT graph_json FROM pipeline_versions WHERE pipeline_id=? AND version=?", r.PipelineID, r.Version).Scan(&graphJSON); err != nil { + return nil, err + } + if err := json.Unmarshal([]byte(graphJSON), &r.Graph); err != nil { + return nil, err + } if err := tx.QueryRowContext(ctx, "SELECT workspace,allow_tools,write_paths,input_json,output_json,COALESCE((SELECT original_run_id FROM run_retries WHERE run_id=pipeline_runs.id),0) FROM pipeline_runs WHERE id=?", id).Scan(&r.Workspace, &r.AllowTools, &paths, &input, &output, &r.RetryOf); err != nil { return nil, err } diff --git a/internal/pipeline/runs_test.go b/internal/pipeline/runs_test.go index e87971d0..c281c479 100644 --- a/internal/pipeline/runs_test.go +++ b/internal/pipeline/runs_test.go @@ -2,10 +2,41 @@ package pipeline import ( "context" + "fmt" "path/filepath" + "reflect" "testing" ) +func TestRunListIncludesHistoryBeyondFiftyForSearchAndPipelineScope(t *testing.T) { + ctx := context.Background() + store, err := Open(filepath.Join(t.TempDir(), "runs.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if _, err := store.Submit(ctx, "history", Template([]string{"one"}, true)); err != nil { + t.Fatal(err) + } + items, err := store.List(ctx) + if err != nil { + t.Fatal(err) + } + definition, err := store.Get(ctx, items[0].ID, 1) + if err != nil { + t.Fatal(err) + } + for i := 0; i < 55; i++ { + if _, _, err := store.CreateRun(ctx, definition, fmt.Sprintf("history-%d", i), "workspace", false, nil, nil); err != nil { + t.Fatal(err) + } + } + runs, err := store.ListRuns(ctx) + if err != nil || len(runs) != 55 || runs[len(runs)-1].ID != 1 { + t.Fatal("older searchable runs missing", len(runs), err) + } +} + func TestRunRecoveryAndVersionPinning(t *testing.T) { ctx := context.Background() path := filepath.Join(t.TempDir(), "audit.db") @@ -44,6 +75,9 @@ func TestRunRecoveryAndVersionPinning(t *testing.T) { if err := store.RecoverRuns(ctx); err != nil { t.Fatal(err) } + if _, err := store.Submit(ctx, "audit", Template([]string{"replacement", "another"}, true)); err != nil { + t.Fatal(err) + } run, err := store.GetRun(ctx, id) if err != nil { t.Fatal(err) @@ -51,6 +85,9 @@ func TestRunRecoveryAndVersionPinning(t *testing.T) { if run.Status != "interrupted" || run.Steps[0].Status != "interrupted" || run.Steps[0].AgentActive || run.ContentHash != definition.ContentHash || run.Version != 1 { t.Fatal("recovery silently resumed or changed version", run) } + if !reflect.DeepEqual(run.Graph, definition.Graph) { + t.Fatal("run graph did not retain its pinned definition", run.Graph) + } loaded, _ := store.Get(ctx, definition.ID, 1) if loaded.Source != source { t.Fatal("run modified immutable source") diff --git a/internal/pipeline/stats_test.go b/internal/pipeline/stats_test.go index 341062b0..4b9567b5 100644 --- a/internal/pipeline/stats_test.go +++ b/internal/pipeline/stats_test.go @@ -80,8 +80,8 @@ func TestUsageStatsCountAllHistoryAndZeroFillDailyActivity(t *testing.T) { if total != 60 { t.Fatal("daily totals", stats.Days) } - latest, err := store.ListRuns(ctx) - if err != nil || len(latest) != 50 { - t.Fatal("fixture must exceed latest-runs cap", latest, err) + runs, err := store.ListRuns(ctx) + if err != nil || len(runs) != stats.Total { + t.Fatal("run list and all-history statistics disagree", len(runs), stats.Total, err) } } diff --git a/internal/protocol/runs.go b/internal/protocol/runs.go index 152485f2..cbe0c0a9 100644 --- a/internal/protocol/runs.go +++ b/internal/protocol/runs.go @@ -65,6 +65,7 @@ type NotificationReceipt struct { type RunDetail struct { RunSummary + Graph Graph `json:"graph"` RetryOf int64 `json:"retry_of,omitempty"` Workspace string `json:"workspace"` AllowTools bool `json:"allow_tools"` diff --git a/internal/server/run_websocket_test.go b/internal/server/run_websocket_test.go index 73ab0880..eaffbddc 100644 --- a/internal/server/run_websocket_test.go +++ b/internal/server/run_websocket_test.go @@ -72,6 +72,9 @@ func TestRunWebSocketRemainsResponsiveAndAuditable(t *testing.T) { if started.Type != protocol.RunStarted || started.RunDetail == nil { t.Fatal("run not started", started) } + if len(started.RunDetail.Graph.Stages) == 0 { + t.Fatal("started run omitted pinned graph") + } <-entered if response := request(protocol.Message{Type: protocol.Ping, ID: "ping"}); response.Type != protocol.Pong { t.Fatal("active run blocked ping") @@ -87,4 +90,7 @@ func TestRunWebSocketRemainsResponsiveAndAuditable(t *testing.T) { if result.RunDetail == nil || result.RunDetail.Status != "canceled" || len(result.RunDetail.Steps) != 1 || result.RunDetail.Steps[0].Input["prompt"] != "test" { t.Fatal("missing canceled audit", result) } + if len(result.RunDetail.Graph.Stages) != len(started.RunDetail.Graph.Stages) { + t.Fatal("inspected run omitted pinned graph") + } } diff --git a/internal/tui/dashboard.go b/internal/tui/dashboard.go index bb014147..a355b28b 100644 --- a/internal/tui/dashboard.go +++ b/internal/tui/dashboard.go @@ -195,16 +195,7 @@ func (m Model) updatePalette(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case ":run": return m.beginRun() case ":runs": - m.runFailedOnly = false - m.runPipelineID = 0 - m.runOpen = true - m.keys.runs = true - m.runDetail = nil - m.requestedRunID = 0 - m.runStartRequest = "" - m.runError = "" - m.runTop = 0 - return m.runRequest(protocol.Message{Type: protocol.ListRuns}) + return m.openRuns() case ":logs": m.logOpen = true m.keys.logs = true diff --git a/internal/tui/graph.go b/internal/tui/graph.go index 6553da2b..3de141bd 100644 --- a/internal/tui/graph.go +++ b/internal/tui/graph.go @@ -96,25 +96,65 @@ func graphStageRow(graph protocol.Graph, key string) int { } func renderGraph(graph protocol.Graph, selection ...string) []string { - if len(graph.Stages) == 0 { - return []string{"(empty graph)"} - } selected := "" if len(selection) > 0 { selected = selection[0] } + return renderGraphAppearance(graph, selected, nil) +} + +// A nil appearance is the normal definition view. Run views dim all nodes and +// routes not present in the audit, without removing any definition branches. +type graphAppearance struct { + nodes map[string]bool + routes map[graphRoute]bool +} + +type graphRoute struct{ source, outcome, target string } + +func (a *graphAppearance) nodeColor(key string, graph protocol.Graph) lipgloss.Color { + if a != nil && !a.nodes[key] { + return themeMuted + } + return stageColor(key, graph) +} + +func (a *graphAppearance) title(key, label string, selected bool, graph protocol.Graph) string { + if a == nil { + return stageTitle(key, label, selected, graph) + } + s := lipgloss.NewStyle().Foreground(a.nodeColor(key, graph)).Bold(a.nodes[key]) + if selected { + s = s.Background(themeSelection) + } + return s.Render(label) +} + +func (a *graphAppearance) edgeStyle(edge graphEdge) (lipgloss.Color, bool) { + if a != nil && !a.routes[graphRoute{edge.source, edge.outcome, edge.target}] { + return themeMuted, false + } + return outcomeColor(edge.outcome), true +} + +func renderGraphAppearance(graph protocol.Graph, selected string, appearance *graphAppearance) []string { + if len(graph.Stages) == 0 { + return []string{"(empty graph)"} + } if compactGraph(graph) { var lines []string edges, index := graphEdges(graph), 0 for _, stage := range graph.Stages { - lines = append(lines, stageTitle(stage.Key, "["+stage.Key+"]", stage.Key == selected, graph)) + lines = append(lines, appearance.title(stage.Key, "["+stage.Key+"]", stage.Key == selected, graph)) for range outcomes(stage) { e := edges[index] index++ - lines = append(lines, " "+outcomeLabel(e.outcome, fmt.Sprintf("└─ %s [%d] → ", e.label, e.id))+stageTitle(e.target, "["+nodeLabel(e.target)+"]", false, graph)) + color, bold := appearance.edgeStyle(e) + label := lipgloss.NewStyle().Foreground(color).Bold(bold).Render(fmt.Sprintf("└─ %s [%d] → ", e.label, e.id)) + lines = append(lines, " "+label+appearance.title(e.target, "["+nodeLabel(e.target)+"]", false, graph)) } } - return append(lines, stageTitle(protocol.FailureEnd, "[FAILURE]", false)+" "+stageTitle(protocol.SuccessEnd, "[SUCCESS]", false)) + return append(lines, appearance.title(protocol.FailureEnd, "[FAILURE]", false, graph)+" "+appearance.title(protocol.SuccessEnd, "[SUCCESS]", false, graph)) } layout := layoutGraph(graph) type cell struct { @@ -140,7 +180,7 @@ func renderGraph(graph protocol.Graph, selection ...string) []string { for _, node := range layout.nodes { nodes[node.key] = node x, w, y, h := node.x, node.width, node.y, node.height - color := stageColor(node.key, graph) + color := appearance.nodeColor(node.key, graph) active := node.key == selected top, bottom, vertical := "╭"+strings.Repeat("─", w-2)+"╮", "╰"+strings.Repeat("─", w-2)+"╯", '│' if active { @@ -175,7 +215,7 @@ func renderGraph(graph protocol.Graph, selection ...string) []string { } } for _, edge := range layout.edges { - color := outcomeColor(edge.outcome) + color, bold := appearance.edgeStyle(edge) path := []graphPoint{} for i := 1; i < len(edge.path); i++ { a, b := edge.path[i-1], edge.path[i] @@ -221,21 +261,21 @@ func renderGraph(graph protocol.Graph, selection ...string) []string { } start, end := path[0], path[len(path)-1] if edge.bottomExit { - put(start.x, start.y, '▼', color, true) + put(start.x, start.y, '▼', color, bold) } else { put(start.x, start.y, '├', color, false) put(start.x+1, start.y, '→', color, false) } if edge.topEntry { - put(end.x, end.y, '▼', color, true) - text(end.x-1, end.y-1, fmt.Sprintf("[%d]", edge.id), color, true) + put(end.x, end.y, '▼', color, bold) + text(end.x-1, end.y-1, fmt.Sprintf("[%d]", edge.id), color, bold) } else { - put(end.x, end.y, '▶', color, true) + put(end.x, end.y, '▶', color, bold) target := nodes[edge.target] - text(target.x+2, edge.to, fmt.Sprintf("in [%d]", edge.id), color, true) + text(target.x+2, edge.to, fmt.Sprintf("in [%d]", edge.id), color, bold) } source := nodes[edge.source] - text(source.x+2, edge.from, fmt.Sprintf("%s [%d]", edge.label, edge.id), color, true) + text(source.x+2, edge.from, fmt.Sprintf("%s [%d]", edge.label, edge.id), color, bold) } result := make([]string, layout.height) for row, cells := range canvas { @@ -267,7 +307,7 @@ func renderGraph(graph protocol.Graph, selection ...string) []string { left := ansi.Cut(result[row], 0, node.x+1) title := " " + label + strings.Repeat(" ", node.width-3-ansi.StringWidth(label)) right := ansi.Cut(result[row], node.x+node.width-1, layout.width) - result[row] = left + stageTitle(node.key, title, node.key == selected, graph) + right + result[row] = left + appearance.title(node.key, title, node.key == selected, graph) + right } return result } diff --git a/internal/tui/model.go b/internal/tui/model.go index 93890905..b311c639 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -168,6 +168,8 @@ type Model struct { runError string runPipelineID int64 runFailedOnly bool + runSearch textinput.Model + runSearchOpen bool runGraphFocus bool runGraphTop int runGraphPan int @@ -537,7 +539,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.runForm != 0 { return m.updateRunForm(msg) } - if m.runOpen && msg.String() != ":" { + if m.runOpen && (msg.String() != ":" || m.runSearchOpen) { return m.updateRuns(msg) } if m.versionsOpen { diff --git a/internal/tui/pipeline.go b/internal/tui/pipeline.go index e0a2353e..a1571c27 100644 --- a/internal/tui/pipeline.go +++ b/internal/tui/pipeline.go @@ -204,17 +204,7 @@ func (m Model) updatePipeline(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case "v": return m.openVersions() case "r": - m.runFailedOnly = false - m.runOpen = true - m.keys.runs = true - m.runPipelineID = m.requestedPipelineID - m.runDetail = nil - m.requestedRunID = 0 - m.runStartRequest = "" - m.runIndex = 0 - m.runTop = 0 - m.runError = "" - return m.runRequest(protocol.Message{Type: protocol.ListRuns}) + return m.openRuns() case "e": return m.editPipeline() case "s": diff --git a/internal/tui/run_detail.go b/internal/tui/run_detail.go index 5f291966..b8a3a4f7 100644 --- a/internal/tui/run_detail.go +++ b/internal/tui/run_detail.go @@ -12,6 +12,7 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" + "github.com/sahilm/fuzzy" ) func (m Model) selectedFailedRun() int64 { @@ -94,13 +95,16 @@ func (m *Model) closeRuns() { m.runDetailFocus = false m.runPipelineID = 0 m.runFailedOnly = false + m.runSearch = newInput() + m.runSearchOpen = false m.runGraphFocus = false m.runGraphTop = 0 m.runGraphPan = 0 } func (m Model) visibleRuns() []protocol.RunSummary { - if m.runPipelineID == 0 && !m.runFailedOnly { + query := strings.TrimSpace(m.runSearch.Value()) + if m.runPipelineID == 0 && !m.runFailedOnly && query == "" { return m.runs } var runs []protocol.RunSummary @@ -109,6 +113,26 @@ func (m Model) visibleRuns() []protocol.RunSummary { runs = append(runs, run) } } + if query != "" { + if strings.HasPrefix(query, "#") { + matched := make([]protocol.RunSummary, 0) + for _, run := range runs { + if strings.HasPrefix(fmt.Sprintf("#%d", run.ID), query) { + matched = append(matched, run) + } + } + return matched + } + labels := make([]string, len(runs)) + for i, run := range runs { + labels[i] = fmt.Sprintf("#%d %s v%d %s %s %s %s", run.ID, run.Name, run.Version, run.Status, run.Outcome, run.CurrentStage, run.Diagnostic) + } + matched := make([]protocol.RunSummary, 0) + for _, match := range fuzzy.Find(query, labels) { + matched = append(matched, runs[match.Index]) + } + return matched + } return runs } @@ -455,23 +479,35 @@ func (m Model) runsDetailsView(height int) string { return fitBlock([]string{m.loading("Loading run…"), m.runError, "Esc returns to runs"}, m.width, height) } rows := []string{} + searching := m.runSearchOpen || strings.TrimSpace(m.runSearch.Value()) != "" + if searching { + m.runSearch.Width = max(1, m.width-12) + rows = append(rows, "Search: "+m.runSearch.View()) + } runs := m.visibleRuns() - start, end := selectionWindow(len(runs), m.runIndex, max(1, height-4)) + start, end := selectionWindow(len(runs), m.runIndex, max(1, height-4-len(rows))) for i := start; i < end; i++ { r := runs[i] text := fmt.Sprintf("#%d %s · v%d · %s · %s", r.ID, r.Name, r.Version, m.progress(r.Status), dateLabel(r.FinishedAt)) rows = append(rows, menuOption(text, i == m.runIndex)) } - if len(rows) == 0 { + if len(runs) == 0 { rows = append(rows, "No runs yet.") if m.runFailedOnly { - rows[0] = "No failed runs." + rows[len(rows)-1] = "No failed runs." + } + if strings.TrimSpace(m.runSearch.Value()) != "" { + rows[len(rows)-1] = "No matching runs." } } if m.runError != "" { rows = append(rows, m.runError) } - return panel(m.width, height, []string{bar(title, fmt.Sprint(len(runs)), max(1, m.width-4), true)}, rows, "j/k select · Enter inspect · "+m.runActions(), true) + footer := "/ fuzzy search · j/k select · Enter inspect · " + m.runActions() + if m.runSearchOpen { + footer = "Type to filter · Enter results · Esc clear" + } + return panel(m.width, height, []string{bar(title, fmt.Sprint(len(runs)), max(1, m.width-4), true)}, rows, footer, true) } r := m.runDetail header := bar(fmt.Sprintf("#%d %s · v%d", r.ID, r.Name, r.Version), m.progress(r.Status)+" · "+runDuration(r.CreatedAt, r.FinishedAt), m.width, false) diff --git a/internal/tui/run_graph.go b/internal/tui/run_graph.go index d761c99f..5a0d9ae9 100644 --- a/internal/tui/run_graph.go +++ b/internal/tui/run_graph.go @@ -34,15 +34,51 @@ func (m Model) runVisitKey(index int) string { } func (m Model) runGraphLines(_ int) []string { - graph := m.runPathGraph() + graph, selected, appearance := m.runGraphState() if len(graph.Stages) == 0 { return []string{"Waiting for the first stage…"} } - selected := graph.Stages[len(graph.Stages)-1].Key - if m.runStepIndex > 0 && m.runStepIndex <= len(graph.Stages) { - selected = graph.Stages[m.runStepIndex-1].Key + return renderGraphAppearance(graph, selected, appearance) +} + +func (m Model) runGraphState() (protocol.Graph, string, *graphAppearance) { + if m.runDetail == nil { + return protocol.Graph{}, "", nil } - return renderGraph(graph, selected) + r := m.runDetail + graph := r.Graph + // Older servers may omit the graph. Never substitute a different version. + if len(graph.Stages) == 0 && m.detail != nil && m.detail.ID == r.PipelineID && m.detail.Version == r.Version { + graph = m.detail.Graph + } + index := len(r.Steps) - 1 + if m.runStepIndex > 0 && m.runStepIndex <= len(r.Steps) { + index = m.runStepIndex - 1 + } + if len(graph.Stages) == 0 { + graph = m.runPathGraph() + selected := "" + if index >= 0 { + selected = graph.Stages[index].Key + } + return graph, selected, nil + } + appearance := &graphAppearance{nodes: map[string]bool{}, routes: map[graphRoute]bool{}} + for _, step := range r.Steps { + appearance.nodes[step.Stage] = true + if step.Target != "" && step.Outcome != "" { + target := protocol.ResolveTarget(step.Outcome, step.Target) + appearance.routes[graphRoute{step.Stage, step.Outcome, target}] = true + if protocol.IsTerminal(target) { + appearance.nodes[target] = true + } + } + } + selected := r.CurrentStage + if index >= 0 { + selected = r.Steps[index].Stage + } + return graph, selected, appearance } func (m Model) runsView(height int) string { @@ -54,7 +90,7 @@ func (m Model) runsView(height int) string { if !m.runGraphFocus { top, pan = m.runGraphFollow() } - graph := graphViewport(m.runGraphTitle(), m.runGraphLines(max(3, m.width-4)), m.width, graphHeight, top, pan, m.runGraphFocus, "g graph/details · arrows pan · j/k scroll · live") + graph := graphViewport(m.runGraphTitle(), m.runGraphLines(max(3, m.width-4)), m.width, graphHeight, top, pan, m.runGraphFocus, "g graph/details · arrows pan · j/k scroll · dim = not executed") details := m.runsDetailsView(height - graphHeight) return fitBlock(strings.Split(graph+"\n"+details, "\n"), m.width, height) } @@ -62,13 +98,13 @@ func (m Model) runsView(height int) string { func (m Model) runGraphTitle() string { r := m.runDetail if r == nil { - return "Run path" + return "Run graph" } durationLabel := "elapsed" if r.FinishedAt != "" { durationLabel = "duration" } - title := "Run path · " + durationLabel + " " + runDuration(r.CreatedAt, r.FinishedAt) + " · started " + dateLabel(r.CreatedAt) + title := "Run graph · " + durationLabel + " " + runDuration(r.CreatedAt, r.FinishedAt) + " · started " + dateLabel(r.CreatedAt) if r.FinishedAt != "" { title += " · finished " + dateLabel(r.FinishedAt) } @@ -76,17 +112,13 @@ func (m Model) runGraphTitle() string { } func (m Model) runGraphFollow() (int, int) { - graph := m.runPathGraph() + graph, selected, _ := m.runGraphState() if len(graph.Stages) == 0 { return 0, 0 } - index := len(graph.Stages) - 1 - if m.runStepIndex > 0 { - index = min(m.runStepIndex-1, index) - } layout := layoutGraph(graph) for _, node := range layout.nodes { - if node.key == graph.Stages[index].Key { + if node.key == selected { return node.y, max(0, node.x-(m.width-4-node.width)/2) } } diff --git a/internal/tui/run_graph_test.go b/internal/tui/run_graph_test.go index b3f2d917..3c36c3ef 100644 --- a/internal/tui/run_graph_test.go +++ b/internal/tui/run_graph_test.go @@ -2,14 +2,87 @@ package tui import ( "context" + "fmt" "strings" "testing" "time" "git.a-wan.net/alan/pipelines/internal/protocol" + "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" ) +func TestRunFullGraphDimsUnexecutedBranchesAndRoutes(t *testing.T) { + previous := lipgloss.ColorProfile() + lipgloss.SetColorProfile(termenv.ANSI) + defer lipgloss.SetColorProfile(previous) + m := New(context.Background(), "") + m.width = 120 + graph := protocol.Graph{Stages: []protocol.Stage{ + {Key: "parity", Edges: map[string]string{"odd": "add_one", "even": "halve", "error": protocol.FailureEnd}}, + {Key: "add_one", Edges: map[string]string{"success": "report", "revise": "parity"}}, + {Key: "halve", Edges: map[string]string{"success": "report"}}, + {Key: "report", Edges: map[string]string{"success": protocol.SuccessEnd}}, + }} + m.runDetail = &protocol.RunDetail{Graph: graph, Steps: []protocol.RunStep{ + {Sequence: 1, Stage: "parity", Outcome: "odd", Target: "add_one"}, + {Sequence: 2, Stage: "add_one", Outcome: "revise", Target: "parity"}, + {Sequence: 3, Stage: "parity", Outcome: "odd", Target: "add_one"}, + {Sequence: 4, Stage: "add_one", Outcome: "success", Target: "report"}, + {Sequence: 5, Stage: "report", Outcome: "success", Target: protocol.SuccessEnd}, + }} + // An unrelated/open latest definition must not replace this run's graph. + m.detail = &protocol.PipelineDetail{Graph: protocol.Graph{Stages: []protocol.Stage{{Key: "latest"}}}} + full, selected, appearance := m.runGraphState() + if len(full.Stages) != 4 || selected != "report" || appearance.nodes["halve"] || !appearance.nodes["parity"] { + t.Fatal("full graph or visitation state lost", full, selected, appearance) + } + rows := m.runGraphLines(116) + view := strings.Join(rows, "\n") + for _, key := range []string{"parity", "add_one", "halve", "report", "SUCCESS", "FAILURE"} { + if !strings.Contains(ansi.Strip(view), key) { + t.Fatal("missing graph node", key) + } + } + if foregroundAt(t, view, "halve") != 8 || foregroundAt(t, view, "FAILURE") != 8 || foregroundAt(t, view, "SUCCESS") != 2 { + t.Fatal("unexecuted nodes/terminals not dimmed", view) + } + for _, edge := range layoutGraph(full).edges { + color := foregroundAt(t, rows[edge.from], fmt.Sprintf("%s [%d]", edge.label, edge.id)) + taken := appearance.routes[graphRoute{edge.source, edge.outcome, edge.target}] + if (color == 8) == taken { + t.Fatal("route dimming does not match audited traversal", edge, color, taken) + } + } + m.runStepIndex = 3 + _, selected, _ = m.runGraphState() + if selected != "parity" { + t.Fatal("repeated visit selection lost", selected) + } + // Queued runs still display every node, all dimmed, before the first visit. + m.runDetail.Steps = nil + _, _, appearance = m.runGraphState() + if len(appearance.nodes) != 0 || !strings.Contains(ansi.Strip(strings.Join(m.runGraphLines(116), "\n")), "halve") { + t.Fatal("queued graph hidden or marked executed") + } +} + +func TestCompactRunGraphRetainsDimmedNodes(t *testing.T) { + previous := lipgloss.ColorProfile() + lipgloss.SetColorProfile(termenv.ANSI) + defer lipgloss.SetColorProfile(previous) + m := New(context.Background(), "") + m.runDetail = &protocol.RunDetail{Steps: []protocol.RunStep{{Stage: "stage_000"}}} + for i := 0; i < 201; i++ { + m.runDetail.Graph.Stages = append(m.runDetail.Graph.Stages, protocol.Stage{Key: fmt.Sprintf("stage_%03d", i), Edges: map[string]string{"success": protocol.SuccessEnd}}) + } + view := strings.Join(m.runGraphLines(80), "\n") + if foregroundAt(t, view, "stage_200") != 8 || foregroundAt(t, view, "stage_000") == 8 { + t.Fatal("compact run graph lost dimming") + } +} + func TestRunPathUsesSharedRendererAndRecordedRoutesWithRepeatedVisits(t *testing.T) { m := New(context.Background(), "") m.width = 120 @@ -30,7 +103,7 @@ func TestRunPathUsesSharedRendererAndRecordedRoutesWithRepeatedVisits(t *testing t.Fatal("run graph diverged from common renderer") } view := ansi.Strip(m.runsView(36)) - if strings.Index(view, "Run path") < 0 || strings.Index(view, "Run path") > strings.Index(view, "Run overview") || !strings.Contains(view, "3. plan (running)") { + if strings.Index(view, "Run graph") < 0 || strings.Index(view, "Run graph") > strings.Index(view, "Run overview") || !strings.Contains(view, "3. plan (running)") { t.Fatal("run graph missing above details or current visit not visible", view) } refreshed := *m.runDetail diff --git a/internal/tui/run_search_test.go b/internal/tui/run_search_test.go new file mode 100644 index 00000000..7656aa47 --- /dev/null +++ b/internal/tui/run_search_test.go @@ -0,0 +1,96 @@ +package tui + +import ( + "context" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" +) + +func TestRunsPaletteRespectsPipelineContext(t *testing.T) { + m := panelModel(t) + m.requestedPipelineID = 42 + m.runs = []protocol.RunSummary{{ID: 1, PipelineID: 9}, {ID: 2, PipelineID: 42, Version: 1}, {ID: 3, PipelineID: 42, Version: 2}} + m = press(m, ":") + m = press(m, "runs") + m = press(m, "enter") + if !m.runOpen || m.runPipelineID != 42 || len(m.visibleRuns()) != 2 { + t.Fatal("palette runs escaped pipeline scope", m.runPipelineID, m.visibleRuns()) + } + m.closeRuns() + m.keys.detail = false + m = press(m, ":") + m = press(m, "runs") + m = press(m, "enter") + if m.runPipelineID != 0 || len(m.visibleRuns()) != 3 { + t.Fatal("home runs retained pipeline scope") + } +} + +func TestRunsFuzzySearchInputRefreshAndScope(t *testing.T) { + m := New(context.Background(), "") + m.width, m.height = 100, 30 + m.runOpen, m.keys.runs = true, true + m.runs = []protocol.RunSummary{ + {ID: 12, PipelineID: 2, Name: "Math Demo", Version: 1, Status: "failed", CurrentStage: "sum", Diagnostic: "StructuredOutputError"}, + {ID: 13, PipelineID: 3, Name: "Release Builder", Version: 2, Status: "succeeded"}, + {ID: 14, PipelineID: 2, Name: "Math Demo", Version: 2, Status: "running"}, + } + m = press(m, "/") + m = press(m, "mtdm") + if !m.runSearchOpen || len(m.visibleRuns()) != 2 || m.paletteOpen { + t.Fatal("run fuzzy search not applied", m.visibleRuns()) + } + m = press(m, "enter") + if m.runSearchOpen || m.runSearch.Value() != "mtdm" { + t.Fatal("Enter lost filter") + } + view := ansi.Strip(m.runsView(25)) + if !strings.Contains(view, "Search:") || strings.Contains(view, "Release Builder") { + t.Fatal("run filter not rendered", view) + } + for _, query := range []string{"#12", "v1", "fld", "sm", "StrctrdOtptErrr"} { + m.runSearch.SetValue(query) + if runs := m.visibleRuns(); len(runs) != 1 || runs[0].ID != 12 { + t.Fatal("search field not fuzzy searchable", query, runs) + } + } + m.runPipelineID = 3 + m.runSearch.SetValue("mtdm") + if len(m.visibleRuns()) != 0 || !strings.Contains(ansi.Strip(m.runsView(25)), "No matching runs.") { + t.Fatal("search bypassed scope or no-match feedback") + } + m.runPipelineID = 0 + m = press(m, "/") + m = press(m, "esc") + if m.runSearchOpen || m.runSearch.Value() != "" || !m.runOpen { + t.Fatal("Esc did not clear search without closing runs") + } + m = press(m, "/") + m = press(m, "q:") + if m.runSearch.Value() != "q:" || m.paletteOpen { + t.Fatal("search text invoked shortcut", m.runSearch.Value()) + } + m = press(m, "esc") + m.runSearch.SetValue("mtdm") + m.runIndex = 99 + updated, _ := m.Update(receivedMsg(protocol.Message{Type: protocol.Runs, Runs: m.runs[:2]})) + m = updated.(Model) + if len(m.visibleRuns()) != 1 || m.runIndex != 0 { + t.Fatal("refresh discarded filter or failed to clamp selection") + } + // Navigating back from an inspected run retains the list's query. + m.runDetail = &protocol.RunDetail{RunSummary: m.runs[0]} + updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyEsc}) + m = updated.(Model) + if m.runDetail != nil || m.runSearch.Value() != "mtdm" { + t.Fatal("inspect/back discarded query") + } + m.closeRuns() + if m.runSearch.Value() != "" || m.runSearchOpen { + t.Fatal("search leaked into next list") + } +} diff --git a/internal/tui/runs.go b/internal/tui/runs.go index 119ae0fc..ef888f99 100644 --- a/internal/tui/runs.go +++ b/internal/tui/runs.go @@ -15,6 +15,22 @@ type runTick struct{} func runPoll() tea.Cmd { return tea.Tick(time.Second, func(time.Time) tea.Msg { return runTick{} }) } +func (m Model) openRuns() (tea.Model, tea.Cmd) { + scope := int64(0) + if m.keys.detail { + scope = m.requestedPipelineID + if scope == 0 && m.detail != nil { + scope = m.detail.ID + } + } + m.closeRuns() + m.runPipelineID = scope + m.runOpen = true + m.keys.runs = true + m.runIndex = 0 + return m.runRequest(protocol.Message{Type: protocol.ListRuns}) +} + func (m Model) runRequest(request protocol.Message) (tea.Model, tea.Cmd) { return m.sendRunRequest(request) } @@ -116,6 +132,9 @@ func (m Model) updateRunForm(msg tea.KeyMsg) (tea.Model, tea.Cmd) { func (m *Model) startSelectedRun() tea.Cmd { m.runForm = 0 + m.runPipelineID = m.detail.ID + m.runSearch = newInput() + m.runSearchOpen = false m.runOpen = true m.requestedRunID = 0 m.runStepIndex = 0 @@ -174,6 +193,38 @@ func (m Model) runFormView(height int) string { } func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + if m.runSearchOpen && m.runDetail == nil { + switch msg.String() { + case "enter": + m.runSearchOpen = false + m.runSearch.Blur() + return m, nil + case "esc": + m.runSearchOpen = false + m.runSearch.SetValue("") + m.runSearch.Blur() + m.runIndex = 0 + return m, nil + case "down", "ctrl+n": + m.runIndex = min(m.runIndex+1, max(0, len(m.visibleRuns())-1)) + return m, nil + case "up", "ctrl+p": + m.runIndex = max(0, m.runIndex-1) + return m, nil + } + var cmd tea.Cmd + m.runSearch, cmd = m.runSearch.Update(msg) + m.runIndex = 0 + return m, cmd + } + if msg.String() == "/" && m.runDetail == nil && m.requestedRunID == 0 && m.runStartRequest == "" { + if m.runSearch.Placeholder == "" { + m.runSearch = newInput() + } + m.runSearch.Placeholder = "Search runs…" + m.runSearchOpen = true + return m, m.runSearch.Focus() + } runs := m.visibleRuns() if msg.String() == "g" && m.runDetail != nil { m.runGraphFocus = !m.runGraphFocus