package tui import ( "fmt" "regexp" "strconv" "strings" "testing" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" "github.com/muesli/termenv" ) var sgr = regexp.MustCompile(`\x1b\[([0-9;]*)m`) func TestPipelineStageColorsResolveCollisions(t *testing.T) { keys := []string{"planner", "implementer", "verifier", "reviewer", "report"} old := []lipgloss.Color{"4", "6", "3", "5", "12", "14", "11", "13"} if nameColor(keys[0], old) != nameColor(keys[2], old) || nameColor(keys[0], old) != nameColor(keys[4], old) { t.Fatal("expected original bug-fix color collision") } graph := protocol.Graph{} for _, key := range keys { graph.Stages = append(graph.Stages, protocol.Stage{Key: key}) } reversed := protocol.Graph{} for i := len(keys) - 1; i >= 0; i-- { reversed.Stages = append(reversed.Stages, protocol.Stage{Key: keys[i]}) } used := map[lipgloss.Color]bool{} for _, key := range keys { color := stageColor(key, graph) if used[color] { t.Fatal("stage color collision", key, color) } used[color] = true if color == "1" || color == "2" || color == "9" || color == "10" { t.Fatal("stage consumed reserved color") } if stageColor(key, reversed) != color { t.Fatal("reordering changed stage identity") } t.Log(key, color) } } func TestStageColorsExcludeOutcomeColors(t *testing.T) { for i := 0; i < 256; i++ { for _, key := range []string{fmt.Sprintf("stage_%d", i), "#"} { color := stageColor(key) if color == "1" || color == "2" || color == "9" || color == "10" { t.Fatalf("stage %s uses reserved outcome color %s", key, color) } } } if outcomeColor("error") != themeError || outcomeColor("success") != themeSuccess { t.Fatal("reserved outcome colors changed") } } // Read the actual emitted ANSI foreground, independent of the style helpers. func foregroundAt(t *testing.T, text, needle string) int { return paletteAt(t, text, needle, false) } func backgroundAt(t *testing.T, text, needle string) int { return paletteAt(t, text, needle, true) } func paletteAt(t *testing.T, text, needle string, background bool) int { t.Helper() color := -1 start := 0 var plain strings.Builder var colors []int appendRun := func(run string) { plain.WriteString(run) for range []byte(run) { colors = append(colors, color) } } for _, match := range sgr.FindAllStringSubmatchIndex(text, -1) { appendRun(text[start:match[0]]) for _, code := range strings.Split(text[match[2]:match[3]], ";") { value, _ := strconv.Atoi(code) reset, base, bright := 39, 30, 90 if background { reset, base, bright = 49, 40, 100 } switch { case value == 0 || value == reset: color = -1 case value >= base && value <= base+7: color = value - base case value >= bright && value <= bright+7: color = value - bright + 8 } } start = match[1] } appendRun(text[start:]) if index := strings.Index(plain.String(), needle); index >= 0 { return colors[index] } t.Fatalf("could not find %q in %q", needle, text) return -1 } func TestStageAndDestinationHighlightsMatch(t *testing.T) { previous := lipgloss.ColorProfile() lipgloss.SetColorProfile(termenv.ANSI) defer lipgloss.SetColorProfile(previous) m := panelModel(t) graph := strings.Join(m.graphLines(), "\n") lines := strings.Join(m.stageLines(60), "\n") destinationColor := foregroundAt(t, lines, "reviewer") if destinationColor < 0 || foregroundAt(t, graph, "reviewer") != destinationColor { t.Fatal("outcome destination must match its rendered stage title") } m.stageIndex = 1 selectionColor := backgroundAt(t, stageTitle("reviewer", "reviewer", true, m.detail.Graph), "reviewer") if selectionColor < 0 || backgroundAt(t, strings.Join(m.graphLines(), "\n"), "reviewer") != selectionColor || foregroundAt(t, strings.Join(m.graphLines(), "\n"), "reviewer") != destinationColor || foregroundAt(t, m.stageTabs(80), "reviewer") != destinationColor { t.Fatal("selection must preserve stage identity color") } for _, stage := range m.detail.Graph.Stages { if foregroundAt(t, graph, stage.Key) < 0 { t.Fatalf("stage %s is not highlighted", stage.Key) } } if !strings.Contains(graph, "\x1b[") || foregroundAt(t, stageTitle("reviewer", "reviewer", true, m.detail.Graph), "reviewer") != destinationColor { t.Fatal("selected stage should retain its identity on a soft highlight") } layout := layoutGraph(m.detail.Graph) rows := m.graphLines() for _, node := range layout.nodes { if node.key != "reviewer" { continue } for x := node.x + 1; x < node.x+node.width-1; x++ { cell := ansi.Cut(rows[node.y+1], x, x+1) if backgroundAt(t, cell, ansi.Strip(cell)) != selectionColor { t.Fatalf("selected title padding at column %d is not filled", x) } } } for _, match := range sgr.FindAllStringSubmatch(stageTitle("reviewer", "reviewer", false), -1) { for _, code := range strings.Split(match[1], ";") { if code == "7" { t.Fatal("unselected titles must not have a filled highlight") } } } } func TestEdgesAreColoredIncludingInjectedErrors(t *testing.T) { previous := lipgloss.ColorProfile() lipgloss.SetColorProfile(termenv.ANSI) defer lipgloss.SetColorProfile(previous) graph, err := pipeline.Parse(strings.ReplaceAll(pipeline.Template([]string{"implementer", "reviewer"}, true), "error -> #failure\n", "")) if err != nil { t.Fatal(err) } layout := layoutGraph(graph) rows := renderGraph(graph, "implementer") view := strings.Join(rows, "\n") if foregroundAt(t, view, "SUCCESS") != 2 || foregroundAt(t, view, "FAILURE") != 1 { t.Fatal("system terminals must use success/error theme colors") } for _, edge := range layout.edges { label := fmt.Sprintf("%s [%d]", edge.label, edge.id) color := foregroundAt(t, rows[edge.from], label) if color < 0 { t.Fatalf("edge %d has no highlight", edge.id) } if edge.outcome == "error" && color != 1 { t.Fatal("error outcomes must use terminal red") } if edge.outcome == "success" && color != 2 { t.Fatal("success outcomes must use terminal green") } port, row := fmt.Sprintf("[%d]", edge.id), edge.to if edge.topEntry { port = fmt.Sprintf("[%d]", edge.id) row-- } if foregroundAt(t, rows[row], port) != color { t.Fatal("source and destination ports must share edge color") } start := edge.path[0] arrow := "→" if edge.bottomExit { arrow = "▼" } if foregroundAt(t, ansi.Cut(rows[start.y], start.x, start.x+2), arrow) != color { t.Fatal("route arrow must match outcome color") } } for _, row := range rows { if lipgloss.Width(row) > layout.width { t.Fatal("colors changed graph dimensions") } } plain := ansi.Strip(strings.Join(rows, "\n")) if strings.Count(plain, "error* [") != 2 { t.Fatal("injected error labels are missing") } } func TestCrossingsKeepEarlierRouteShapeAndColor(t *testing.T) { previous := lipgloss.ColorProfile() lipgloss.SetColorProfile(termenv.ANSI) defer lipgloss.SetColorProfile(previous) graph := protocol.Graph{Stages: []protocol.Stage{ {Key: "a", Edges: map[string]string{"success": "b", "jump": "d", "error": protocol.FailureEnd}}, {Key: "b", Edges: map[string]string{"success": "c", "retry": "a", "error": protocol.FailureEnd}}, {Key: "c", Edges: map[string]string{"success": "d", "retry": "b", "error": protocol.FailureEnd}}, {Key: "d", Edges: map[string]string{"success": protocol.SuccessEnd, "retry": "a", "error": protocol.FailureEnd}}, }} layout := layoutGraph(graph) rows := renderGraph(graph) blocked := map[graphPoint]bool{} for _, node := range layout.nodes { for y := node.y; y < node.y+node.height; y++ { for x := node.x; x < node.x+node.width; x++ { blocked[graphPoint{x, y}] = true } } } for _, edge := range layout.edges { start, end := edge.path[0], edge.path[len(edge.path)-1] blocked[start] = true blocked[end] = true if !edge.bottomExit { blocked[graphPoint{start.x + 1, start.y}] = true } if edge.topEntry { for x := end.x - 1; x < end.x-1+len(fmt.Sprintf("[%d]", edge.id)); x++ { blocked[graphPoint{x, end.y - 1}] = true } } } type owner struct { glyph rune color int } owners := map[graphPoint]owner{} crossings := map[graphPoint]bool{} for _, edge := range layout.edges { path := []graphPoint{edge.path[0]} for i := 1; i < len(edge.path); i++ { a, b := edge.path[i-1], edge.path[i] dx, dy := 0, 0 if b.x > a.x { dx = 1 } else if b.x < a.x { dx = -1 } if b.y > a.y { dy = 1 } else if b.y < a.y { dy = -1 } for a != b { a.x += dx a.y += dy path = append(path, a) } } for i := 1; i < len(path)-1; i++ { p, a, b := path[i], path[i-1], path[i+1] if blocked[p] { continue } glyph := rune(0) if a.x == b.x { glyph = '│' } else if a.y == b.y { glyph = '─' } color, err := strconv.Atoi(string(outcomeColor(edge.outcome))) if err != nil { t.Fatal(err) } if prior, ok := owners[p]; ok { if glyph != 0 && prior.glyph != 0 && glyph != prior.glyph { crossings[p] = true } } else { owners[p] = owner{glyph, color} } } } if len(crossings) == 0 { t.Fatal("fixture must exercise actual route intersections") } for point := range crossings { cell := ansi.Cut(rows[point.y], point.x, point.x+1) expected := owners[point] if ansi.Strip(cell) != string(expected.glyph) || foregroundAt(t, cell, string(expected.glyph)) != expected.color { t.Fatalf("crossing %+v did not preserve the earlier route: %q", point, cell) } } }