Show full audited run graphs and scope searchable run history

This commit is contained in:
2026-10-10 00:26:32 +01:00
parent a1c0eb4a72
commit e9a8eaf8ae
15 changed files with 438 additions and 66 deletions
+15 -5
View File
@@ -10,7 +10,13 @@ separately. Set `PIPELINES_URL` or pass `--url` to select another server.
## Dashboard and status ## 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. 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. 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: 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 active, even if a terminal status was already persisted. Run RPCs report
`executing` alongside status so clients can distinguish cleanup from completion. `executing` alongside status so clients can distinguish cleanup from completion.
The run inspector's upper half shows the actual execution path using the shared The run inspector's upper half shows the entire graph from the run's immutable
pipeline graph renderer and viewport. Visits are numbered, including repeated pinned version using the shared renderer and viewport. Executed stages and taken
visits in loops; only recorded routing decisions become edges. No unchosen stage routes retain their colors; unexecuted stages, unchosen routes and unreached
is added to the run path. On small terminals the details take precedence. Press 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` `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 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 or selected stage. Existing polling refreshes the graph once per second, and
+8 -1
View File
@@ -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) { 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 { if err != nil {
return nil, err return nil, err
} }
@@ -150,6 +150,13 @@ func (s *Store) GetRun(ctx context.Context, id int64) (*protocol.RunDetail, erro
return nil, err return nil, err
} }
var input, output, paths string 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 { 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 return nil, err
} }
+37
View File
@@ -2,10 +2,41 @@ package pipeline
import ( import (
"context" "context"
"fmt"
"path/filepath" "path/filepath"
"reflect"
"testing" "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) { func TestRunRecoveryAndVersionPinning(t *testing.T) {
ctx := context.Background() ctx := context.Background()
path := filepath.Join(t.TempDir(), "audit.db") path := filepath.Join(t.TempDir(), "audit.db")
@@ -44,6 +75,9 @@ func TestRunRecoveryAndVersionPinning(t *testing.T) {
if err := store.RecoverRuns(ctx); err != nil { if err := store.RecoverRuns(ctx); err != nil {
t.Fatal(err) 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) run, err := store.GetRun(ctx, id)
if err != nil { if err != nil {
t.Fatal(err) 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 { 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) 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) loaded, _ := store.Get(ctx, definition.ID, 1)
if loaded.Source != source { if loaded.Source != source {
t.Fatal("run modified immutable source") t.Fatal("run modified immutable source")
+3 -3
View File
@@ -80,8 +80,8 @@ func TestUsageStatsCountAllHistoryAndZeroFillDailyActivity(t *testing.T) {
if total != 60 { if total != 60 {
t.Fatal("daily totals", stats.Days) t.Fatal("daily totals", stats.Days)
} }
latest, err := store.ListRuns(ctx) runs, err := store.ListRuns(ctx)
if err != nil || len(latest) != 50 { if err != nil || len(runs) != stats.Total {
t.Fatal("fixture must exceed latest-runs cap", latest, err) t.Fatal("run list and all-history statistics disagree", len(runs), stats.Total, err)
} }
} }
+1
View File
@@ -65,6 +65,7 @@ type NotificationReceipt struct {
type RunDetail struct { type RunDetail struct {
RunSummary RunSummary
Graph Graph `json:"graph"`
RetryOf int64 `json:"retry_of,omitempty"` RetryOf int64 `json:"retry_of,omitempty"`
Workspace string `json:"workspace"` Workspace string `json:"workspace"`
AllowTools bool `json:"allow_tools"` AllowTools bool `json:"allow_tools"`
+6
View File
@@ -72,6 +72,9 @@ func TestRunWebSocketRemainsResponsiveAndAuditable(t *testing.T) {
if started.Type != protocol.RunStarted || started.RunDetail == nil { if started.Type != protocol.RunStarted || started.RunDetail == nil {
t.Fatal("run not started", started) t.Fatal("run not started", started)
} }
if len(started.RunDetail.Graph.Stages) == 0 {
t.Fatal("started run omitted pinned graph")
}
<-entered <-entered
if response := request(protocol.Message{Type: protocol.Ping, ID: "ping"}); response.Type != protocol.Pong { if response := request(protocol.Message{Type: protocol.Ping, ID: "ping"}); response.Type != protocol.Pong {
t.Fatal("active run blocked ping") 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" { 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) t.Fatal("missing canceled audit", result)
} }
if len(result.RunDetail.Graph.Stages) != len(started.RunDetail.Graph.Stages) {
t.Fatal("inspected run omitted pinned graph")
}
} }
+1 -10
View File
@@ -195,16 +195,7 @@ func (m Model) updatePalette(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
case ":run": case ":run":
return m.beginRun() return m.beginRun()
case ":runs": case ":runs":
m.runFailedOnly = false return m.openRuns()
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})
case ":logs": case ":logs":
m.logOpen = true m.logOpen = true
m.keys.logs = true m.keys.logs = true
+55 -15
View File
@@ -96,25 +96,65 @@ func graphStageRow(graph protocol.Graph, key string) int {
} }
func renderGraph(graph protocol.Graph, selection ...string) []string { func renderGraph(graph protocol.Graph, selection ...string) []string {
if len(graph.Stages) == 0 {
return []string{"(empty graph)"}
}
selected := "" selected := ""
if len(selection) > 0 { if len(selection) > 0 {
selected = 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) { if compactGraph(graph) {
var lines []string var lines []string
edges, index := graphEdges(graph), 0 edges, index := graphEdges(graph), 0
for _, stage := range graph.Stages { 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) { for range outcomes(stage) {
e := edges[index] e := edges[index]
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) layout := layoutGraph(graph)
type cell struct { type cell struct {
@@ -140,7 +180,7 @@ func renderGraph(graph protocol.Graph, selection ...string) []string {
for _, node := range layout.nodes { for _, node := range layout.nodes {
nodes[node.key] = node nodes[node.key] = node
x, w, y, h := node.x, node.width, node.y, node.height 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 active := node.key == selected
top, bottom, vertical := "╭"+strings.Repeat("─", w-2)+"╮", "╰"+strings.Repeat("─", w-2)+"╯", '│' top, bottom, vertical := "╭"+strings.Repeat("─", w-2)+"╮", "╰"+strings.Repeat("─", w-2)+"╯", '│'
if active { if active {
@@ -175,7 +215,7 @@ func renderGraph(graph protocol.Graph, selection ...string) []string {
} }
} }
for _, edge := range layout.edges { for _, edge := range layout.edges {
color := outcomeColor(edge.outcome) color, bold := appearance.edgeStyle(edge)
path := []graphPoint{} path := []graphPoint{}
for i := 1; i < len(edge.path); i++ { for i := 1; i < len(edge.path); i++ {
a, b := edge.path[i-1], 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] start, end := path[0], path[len(path)-1]
if edge.bottomExit { if edge.bottomExit {
put(start.x, start.y, '▼', color, true) put(start.x, start.y, '▼', color, bold)
} else { } else {
put(start.x, start.y, '├', color, false) put(start.x, start.y, '├', color, false)
put(start.x+1, start.y, '→', color, false) put(start.x+1, start.y, '→', color, false)
} }
if edge.topEntry { if edge.topEntry {
put(end.x, end.y, '▼', color, true) put(end.x, end.y, '▼', color, bold)
text(end.x-1, end.y-1, fmt.Sprintf("[%d]", edge.id), color, true) text(end.x-1, end.y-1, fmt.Sprintf("[%d]", edge.id), color, bold)
} else { } else {
put(end.x, end.y, '▶', color, true) put(end.x, end.y, '▶', color, bold)
target := nodes[edge.target] 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] 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) result := make([]string, layout.height)
for row, cells := range canvas { 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) left := ansi.Cut(result[row], 0, node.x+1)
title := " " + label + strings.Repeat(" ", node.width-3-ansi.StringWidth(label)) title := " " + label + strings.Repeat(" ", node.width-3-ansi.StringWidth(label))
right := ansi.Cut(result[row], node.x+node.width-1, layout.width) 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 return result
} }
+3 -1
View File
@@ -168,6 +168,8 @@ type Model struct {
runError string runError string
runPipelineID int64 runPipelineID int64
runFailedOnly bool runFailedOnly bool
runSearch textinput.Model
runSearchOpen bool
runGraphFocus bool runGraphFocus bool
runGraphTop int runGraphTop int
runGraphPan int runGraphPan int
@@ -537,7 +539,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.runForm != 0 { if m.runForm != 0 {
return m.updateRunForm(msg) return m.updateRunForm(msg)
} }
if m.runOpen && msg.String() != ":" { if m.runOpen && (msg.String() != ":" || m.runSearchOpen) {
return m.updateRuns(msg) return m.updateRuns(msg)
} }
if m.versionsOpen { if m.versionsOpen {
+1 -11
View File
@@ -204,17 +204,7 @@ func (m Model) updatePipeline(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
case "v": case "v":
return m.openVersions() return m.openVersions()
case "r": case "r":
m.runFailedOnly = false return m.openRuns()
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})
case "e": case "e":
return m.editPipeline() return m.editPipeline()
case "s": case "s":
+41 -5
View File
@@ -12,6 +12,7 @@ import (
tea "github.com/charmbracelet/bubbletea" tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss" "github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi" "github.com/charmbracelet/x/ansi"
"github.com/sahilm/fuzzy"
) )
func (m Model) selectedFailedRun() int64 { func (m Model) selectedFailedRun() int64 {
@@ -94,13 +95,16 @@ func (m *Model) closeRuns() {
m.runDetailFocus = false m.runDetailFocus = false
m.runPipelineID = 0 m.runPipelineID = 0
m.runFailedOnly = false m.runFailedOnly = false
m.runSearch = newInput()
m.runSearchOpen = false
m.runGraphFocus = false m.runGraphFocus = false
m.runGraphTop = 0 m.runGraphTop = 0
m.runGraphPan = 0 m.runGraphPan = 0
} }
func (m Model) visibleRuns() []protocol.RunSummary { 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 return m.runs
} }
var runs []protocol.RunSummary var runs []protocol.RunSummary
@@ -109,6 +113,26 @@ func (m Model) visibleRuns() []protocol.RunSummary {
runs = append(runs, run) 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 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) return fitBlock([]string{m.loading("Loading run…"), m.runError, "Esc returns to runs"}, m.width, height)
} }
rows := []string{} 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() 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++ { for i := start; i < end; i++ {
r := runs[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)) 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)) rows = append(rows, menuOption(text, i == m.runIndex))
} }
if len(rows) == 0 { if len(runs) == 0 {
rows = append(rows, "No runs yet.") rows = append(rows, "No runs yet.")
if m.runFailedOnly { 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 != "" { if m.runError != "" {
rows = append(rows, 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 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) 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)
+46 -14
View File
@@ -34,15 +34,51 @@ func (m Model) runVisitKey(index int) string {
} }
func (m Model) runGraphLines(_ int) []string { func (m Model) runGraphLines(_ int) []string {
graph := m.runPathGraph() graph, selected, appearance := m.runGraphState()
if len(graph.Stages) == 0 { if len(graph.Stages) == 0 {
return []string{"Waiting for the first stage…"} return []string{"Waiting for the first stage…"}
} }
selected := graph.Stages[len(graph.Stages)-1].Key return renderGraphAppearance(graph, selected, appearance)
if m.runStepIndex > 0 && m.runStepIndex <= len(graph.Stages) { }
selected = graph.Stages[m.runStepIndex-1].Key
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 { func (m Model) runsView(height int) string {
@@ -54,7 +90,7 @@ func (m Model) runsView(height int) string {
if !m.runGraphFocus { if !m.runGraphFocus {
top, pan = m.runGraphFollow() 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) details := m.runsDetailsView(height - graphHeight)
return fitBlock(strings.Split(graph+"\n"+details, "\n"), m.width, height) 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 { func (m Model) runGraphTitle() string {
r := m.runDetail r := m.runDetail
if r == nil { if r == nil {
return "Run path" return "Run graph"
} }
durationLabel := "elapsed" durationLabel := "elapsed"
if r.FinishedAt != "" { if r.FinishedAt != "" {
durationLabel = "duration" 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 != "" { if r.FinishedAt != "" {
title += " · finished " + dateLabel(r.FinishedAt) title += " · finished " + dateLabel(r.FinishedAt)
} }
@@ -76,17 +112,13 @@ func (m Model) runGraphTitle() string {
} }
func (m Model) runGraphFollow() (int, int) { func (m Model) runGraphFollow() (int, int) {
graph := m.runPathGraph() graph, selected, _ := m.runGraphState()
if len(graph.Stages) == 0 { if len(graph.Stages) == 0 {
return 0, 0 return 0, 0
} }
index := len(graph.Stages) - 1
if m.runStepIndex > 0 {
index = min(m.runStepIndex-1, index)
}
layout := layoutGraph(graph) layout := layoutGraph(graph)
for _, node := range layout.nodes { 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) return node.y, max(0, node.x-(m.width-4-node.width)/2)
} }
} }
+74 -1
View File
@@ -2,14 +2,87 @@ package tui
import ( import (
"context" "context"
"fmt"
"strings" "strings"
"testing" "testing"
"time" "time"
"git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi" "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) { func TestRunPathUsesSharedRendererAndRecordedRoutesWithRepeatedVisits(t *testing.T) {
m := New(context.Background(), "") m := New(context.Background(), "")
m.width = 120 m.width = 120
@@ -30,7 +103,7 @@ func TestRunPathUsesSharedRendererAndRecordedRoutesWithRepeatedVisits(t *testing
t.Fatal("run graph diverged from common renderer") t.Fatal("run graph diverged from common renderer")
} }
view := ansi.Strip(m.runsView(36)) 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) t.Fatal("run graph missing above details or current visit not visible", view)
} }
refreshed := *m.runDetail refreshed := *m.runDetail
+96
View File
@@ -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")
}
}
+51
View File
@@ -15,6 +15,22 @@ type runTick struct{}
func runPoll() tea.Cmd { return tea.Tick(time.Second, func(time.Time) tea.Msg { return runTick{} }) } 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) { func (m Model) runRequest(request protocol.Message) (tea.Model, tea.Cmd) {
return m.sendRunRequest(request) 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 { func (m *Model) startSelectedRun() tea.Cmd {
m.runForm = 0 m.runForm = 0
m.runPipelineID = m.detail.ID
m.runSearch = newInput()
m.runSearchOpen = false
m.runOpen = true m.runOpen = true
m.requestedRunID = 0 m.requestedRunID = 0
m.runStepIndex = 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) { 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() runs := m.visibleRuns()
if msg.String() == "g" && m.runDetail != nil { if msg.String() == "g" && m.runDetail != nil {
m.runGraphFocus = !m.runGraphFocus m.runGraphFocus = !m.runGraphFocus