fix: route graph exports through command writer (#5513)

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
This commit is contained in:
ecuthiell 2026-08-10 06:31:46 -06:00 • committed by GitHub
commit 10e23e0982
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 309 additions and 128 deletions

View file

@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
"io"
"sort"
"strings"
@ -101,11 +102,12 @@ in total before any individual status trips it.`,
return HandleErrorWithHintRespectJSON("issue ID required", "Use --all for all open issues")
}
out := cmd.OutOrStdout()
if usesProxiedServer() {
if err := rejectMaxRowsUnderProxiedServer(cmd); err != nil {
return err
}
return runGraphProxiedServer(rootCtx, args)
return runGraphProxiedServer(rootCtx, out, args)
}
ctx := rootCtx
@ -125,7 +127,7 @@ in total before any individual status trips it.`,
}
return HandleErrorRespectJSON("loading all issues: %v", err)
}
return renderGraphAllSubgraphs(subgraphs)
return renderGraphAllSubgraphs(out, subgraphs)
}
issueID, err := utils.ResolvePartialID(ctx, store, args[0])
@ -157,11 +159,11 @@ in total before any individual status trips it.`,
}
}
return renderGraphSingleSubgraph(subgraph)
return renderGraphSingleSubgraph(out, subgraph)
},
}
func renderGraphAllSubgraphs(subgraphs []*TemplateSubgraph) error {
func renderGraphAllSubgraphs(out io.Writer, subgraphs []*TemplateSubgraph) error {
if graphOpen {
var filtered []*TemplateSubgraph
for _, sg := range subgraphs {
@ -185,8 +187,7 @@ func renderGraphAllSubgraphs(subgraphs []*TemplateSubgraph) error {
if graphHTML && !graphOpen {
merged := mergeSubgraphsForHTML(subgraphs)
layout := computeLayout(merged)
renderGraphHTML(layout, merged)
return nil
return renderGraphHTML(out, layout, merged)
}
if graphOpen {
@ -203,7 +204,9 @@ func renderGraphAllSubgraphs(subgraphs []*TemplateSubgraph) error {
for i, subgraph := range subgraphs {
layout := computeLayout(subgraph)
if graphDOT {
renderGraphDOT(layout, subgraph)
if err := renderGraphDOT(out, layout, subgraph); err != nil {
return err
}
} else if graphCompact {
renderGraphCompact(layout, subgraph)
} else if graphBox {
@ -218,7 +221,7 @@ func renderGraphAllSubgraphs(subgraphs []*TemplateSubgraph) error {
return nil
}
func renderGraphSingleSubgraph(subgraph *TemplateSubgraph) error {
func renderGraphSingleSubgraph(out io.Writer, subgraph *TemplateSubgraph) error {
if graphOpen {
subgraph = filterSubgraphOpen(subgraph)
if subgraph == nil || len(subgraph.Issues) == 0 {
@ -243,9 +246,9 @@ func renderGraphSingleSubgraph(subgraph *TemplateSubgraph) error {
}
if graphDOT {
renderGraphDOT(layout, subgraph)
return renderGraphDOT(out, layout, subgraph)
} else if graphHTML {
renderGraphHTML(layout, subgraph)
return renderGraphHTML(out, layout, subgraph)
} else if graphCompact {
renderGraphCompact(layout, subgraph)
} else if graphBox {

View file

@ -3,9 +3,11 @@
package main
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
@ -25,6 +27,31 @@ func bdGraph(t *testing.T, bd, dir string, args ...string) string {
return stdout.String()
}
// runGraphWithReadOnlyStdout gives the child a real stdout handle that cannot
// be written. Unlike a closed pipe, this produces a normal write error on both
// Unix and Windows instead of depending on SIGPIPE behavior.
func runGraphWithReadOnlyStdout(t *testing.T, bd, dir string, env []string, args ...string) (string, error) {
t.Helper()
stdoutPath := filepath.Join(t.TempDir(), "stdout.txt")
if err := os.WriteFile(stdoutPath, nil, 0o600); err != nil {
t.Fatalf("create read-only stdout target: %v", err)
}
stdout, err := os.Open(stdoutPath)
if err != nil {
t.Fatalf("open read-only stdout target: %v", err)
}
defer func() { _ = stdout.Close() }()
cmd := exec.Command(bd, append([]string{"graph"}, args...)...)
cmd.Dir = dir
cmd.Env = env
cmd.Stdout = stdout
var stderr bytes.Buffer
cmd.Stderr = &stderr
err = cmd.Run()
return stderr.String(), err
}
func TestEmbeddedGraph(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
@ -99,6 +126,16 @@ func TestEmbeddedGraph(t *testing.T) {
}
})
t.Run("dot_output_error", func(t *testing.T) {
stderr, err := runGraphWithReadOnlyStdout(t, bd, dir, bdEnv(dir), "--dot", epic.ID)
if err == nil {
t.Fatalf("graph --dot succeeded with read-only stdout; stderr:\n%s", stderr)
}
if !strings.Contains(stderr, "writing DOT output") {
t.Fatalf("graph --dot stderr = %q, want writer diagnostic", stderr)
}
})
// ===== --json =====
t.Run("json_output", func(t *testing.T) {

View file

@ -4,7 +4,7 @@ import (
"encoding/json"
"fmt"
"html"
"os"
"io"
"strings"
"github.com/steveyegge/beads/internal/types"
@ -12,23 +12,24 @@ import (
// renderGraphDOT renders the graph in Graphviz DOT format.
// Output can be piped to graphviz: bd graph --dot <id> | dot -Tsvg > graph.svg
func renderGraphDOT(layout *GraphLayout, subgraph *TemplateSubgraph) {
func renderGraphDOT(out io.Writer, layout *GraphLayout, subgraph *TemplateSubgraph) error {
w := &graphExportWriter{out: out}
if len(layout.Nodes) == 0 {
fmt.Println("digraph beads { }")
return
w.println("digraph beads { }")
return w.wrapError("DOT")
}
fmt.Println("digraph beads {")
fmt.Println(" rankdir=LR;")
fmt.Println(" node [shape=box, style=\"rounded,filled\", fontname=\"Helvetica\", fontsize=11];")
fmt.Println(" edge [color=\"#666666\"];")
fmt.Println()
w.println("digraph beads {")
w.println(" rankdir=LR;")
w.println(" node [shape=box, style=\"rounded,filled\", fontname=\"Helvetica\", fontsize=11];")
w.println(" edge [color=\"#666666\"];")
w.println()
// Emit nodes grouped by layer using subgraph clusters for rank alignment
for layerIdx, layer := range layout.Layers {
fmt.Printf(" subgraph cluster_layer_%d {\n", layerIdx)
fmt.Println(" style=invis;")
fmt.Printf(" rank=same;\n")
w.printf(" subgraph cluster_layer_%d {\n", layerIdx)
w.println(" style=invis;")
w.printf(" rank=same;\n")
for _, id := range layer {
node := layout.Nodes[id]
if node == nil {
@ -37,12 +38,12 @@ func renderGraphDOT(layout *GraphLayout, subgraph *TemplateSubgraph) {
label, fillColor, fontColor := dotNodeAttrs(node)
// Escape quotes in label
label = strings.ReplaceAll(label, "\"", "\\\"")
fmt.Printf(" \"%s\" [label=\"%s\", fillcolor=\"%s\", fontcolor=\"%s\"];\n",
w.printf(" \"%s\" [label=\"%s\", fillcolor=\"%s\", fontcolor=\"%s\"];\n",
dotEscapeID(id), label, fillColor, fontColor)
}
fmt.Println(" }")
w.println(" }")
}
fmt.Println()
w.println()
// Emit edges
for _, dep := range subgraph.Dependencies {
@ -56,11 +57,41 @@ func renderGraphDOT(layout *GraphLayout, subgraph *TemplateSubgraph) {
}
edgeStyle := dotEdgeStyle(dep.Type)
// dep.DependsOnID -> dep.IssueID (blocker points to blocked)
fmt.Printf(" \"%s\" -> \"%s\"%s;\n",
w.printf(" \"%s\" -> \"%s\"%s;\n",
dotEscapeID(dep.DependsOnID), dotEscapeID(dep.IssueID), edgeStyle)
}
fmt.Println("}")
w.println("}")
return w.wrapError("DOT")
}
// graphExportWriter records the first output failure and suppresses later
// writes. Export commands can therefore return one stable root cause without
// buffering the whole graph or changing successful output bytes.
type graphExportWriter struct {
out io.Writer
err error
}
func (w *graphExportWriter) printf(format string, args ...interface{}) {
if w.err != nil {
return
}
_, w.err = fmt.Fprintf(w.out, format, args...)
}
func (w *graphExportWriter) println(args ...interface{}) {
if w.err != nil {
return
}
_, w.err = fmt.Fprintln(w.out, args...)
}
func (w *graphExportWriter) wrapError(kind string) error {
if w.err == nil {
return nil
}
return fmt.Errorf("writing %s output: %w", kind, w.err)
}
// dotNodeAttrs returns the DOT label, fill color, and font color for a node
@ -127,19 +158,17 @@ func statusPlainIcon(status types.Status) string {
// renderGraphHTML generates a self-contained HTML file with an interactive D3.js
// force-directed graph visualization. The output is a complete HTML document that
// can be opened in any browser.
func renderGraphHTML(layout *GraphLayout, subgraph *TemplateSubgraph) {
func renderGraphHTML(out io.Writer, layout *GraphLayout, subgraph *TemplateSubgraph) error {
nodes := buildHTMLGraphData(layout, subgraph)
edges := buildHTMLEdgeData(layout, subgraph)
nodesJSON, err := json.Marshal(nodes)
if err != nil {
fmt.Fprintf(os.Stderr, "Error marshaling nodes: %v\n", err)
return
return fmt.Errorf("marshaling HTML graph nodes: %w", err)
}
edgesJSON, err := json.Marshal(edges)
if err != nil {
fmt.Fprintf(os.Stderr, "Error marshaling edges: %v\n", err)
return
return fmt.Errorf("marshaling HTML graph edges: %w", err)
}
title := "Beads Dependency Graph"
@ -147,9 +176,10 @@ func renderGraphHTML(layout *GraphLayout, subgraph *TemplateSubgraph) {
title = fmt.Sprintf("Beads: %s (%s)", subgraph.Root.Title, subgraph.Root.ID)
}
if _, err := fmt.Fprintf(os.Stdout, htmlTemplate, html.EscapeString(title), string(nodesJSON), string(edgesJSON)); err != nil {
fmt.Fprintf(os.Stderr, "Error writing HTML output: %v\n", err)
if _, err := fmt.Fprintf(out, htmlTemplate, html.EscapeString(title), string(nodesJSON), string(edgesJSON)); err != nil {
return fmt.Errorf("writing HTML output: %w", err)
}
return nil
}
// HTMLNode is the JSON structure for a node in the HTML visualization

View file

@ -2,30 +2,15 @@ package main
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// captureGraphOutput captures stdout output during f() execution
func captureGraphOutput(f func()) string {
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
f()
w.Close()
os.Stdout = old
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}
func makeTestSubgraph() (*TemplateSubgraph, *GraphLayout) {
issueA := &types.Issue{
ID: "test-a", Title: "Root issue", Status: types.StatusOpen,
@ -63,44 +48,46 @@ func makeTestSubgraph() (*TemplateSubgraph, *GraphLayout) {
}
func TestRenderGraphDOT(t *testing.T) {
// Not parallel: captureGraphOutput redirects global os.Stdout
t.Parallel()
subgraph, layout := makeTestSubgraph()
output := captureGraphOutput(func() {
renderGraphDOT(layout, subgraph)
})
var output bytes.Buffer
if err := renderGraphDOT(&output, layout, subgraph); err != nil {
t.Fatalf("renderGraphDOT: %v", err)
}
got := output.String()
// Verify DOT structure
if !strings.HasPrefix(output, "digraph beads {") {
if !strings.HasPrefix(got, "digraph beads {") {
t.Error("DOT output should start with 'digraph beads {'")
}
if !strings.Contains(output, "rankdir=LR") {
if !strings.Contains(got, "rankdir=LR") {
t.Error("DOT output should specify left-to-right layout")
}
// Verify nodes are present
for _, id := range []string{"test-a", "test-b", "test-c", "test-d"} {
if !strings.Contains(output, fmt.Sprintf("\"%s\"", id)) {
if !strings.Contains(got, fmt.Sprintf("\"%s\"", id)) {
t.Errorf("DOT output should contain node %q", id)
}
}
// Verify edges exist
if !strings.Contains(output, "\"test-a\" -> \"test-b\"") {
if !strings.Contains(got, "\"test-a\" -> \"test-b\"") {
t.Error("DOT output should contain edge test-a -> test-b")
}
if !strings.Contains(output, "\"test-b\" -> \"test-c\"") {
if !strings.Contains(got, "\"test-b\" -> \"test-c\"") {
t.Error("DOT output should contain edge test-b -> test-c")
}
// Verify it ends with closing brace
if !strings.HasSuffix(strings.TrimSpace(output), "}") {
if !strings.HasSuffix(strings.TrimSpace(got), "}") {
t.Error("DOT output should end with '}'")
}
}
func TestRenderGraphDOT_Empty(t *testing.T) {
// Not parallel: captureGraphOutput redirects global os.Stdout
t.Parallel()
emptySubgraph := &TemplateSubgraph{
Root: &types.Issue{ID: "empty"},
Issues: []*types.Issue{},
@ -112,12 +99,13 @@ func TestRenderGraphDOT_Empty(t *testing.T) {
RootID: "empty",
}
output := captureGraphOutput(func() {
renderGraphDOT(layout, emptySubgraph)
})
var output bytes.Buffer
if err := renderGraphDOT(&output, layout, emptySubgraph); err != nil {
t.Fatalf("renderGraphDOT: %v", err)
}
if !strings.Contains(output, "digraph beads { }") {
t.Errorf("Empty DOT output should be 'digraph beads { }', got: %s", output)
if got, want := output.String(), "digraph beads { }\n"; got != want {
t.Errorf("Empty DOT output = %q, want %q", got, want)
}
}
@ -170,41 +158,43 @@ func TestStatusPlainIcon(t *testing.T) {
}
func TestRenderGraphHTML(t *testing.T) {
// Not parallel: captureGraphOutput redirects global os.Stdout
t.Parallel()
subgraph, layout := makeTestSubgraph()
output := captureGraphOutput(func() {
renderGraphHTML(layout, subgraph)
})
var output bytes.Buffer
if err := renderGraphHTML(&output, layout, subgraph); err != nil {
t.Fatalf("renderGraphHTML: %v", err)
}
got := output.String()
// Verify HTML structure
if !strings.Contains(output, "<!DOCTYPE html>") {
if !strings.Contains(got, "<!DOCTYPE html>") {
t.Error("HTML output should contain DOCTYPE")
}
if !strings.Contains(output, "d3.v7.min.js") {
if !strings.Contains(got, "d3.v7.min.js") {
t.Error("HTML output should reference D3.js")
}
// Verify node data is embedded
for _, id := range []string{"test-a", "test-b", "test-c", "test-d"} {
if !strings.Contains(output, id) {
if !strings.Contains(got, id) {
t.Errorf("HTML output should contain node %q", id)
}
}
// Verify it contains all statuses
if !strings.Contains(output, "open") {
if !strings.Contains(got, "open") {
t.Error("HTML should contain open status")
}
if !strings.Contains(output, "in_progress") {
if !strings.Contains(got, "in_progress") {
t.Error("HTML should contain in_progress status")
}
// Verify interactive elements
if !strings.Contains(output, "forceSimulation") {
if !strings.Contains(got, "forceSimulation") {
t.Error("HTML should contain D3 force simulation")
}
if !strings.Contains(output, "tooltip") {
if !strings.Contains(got, "tooltip") {
t.Error("HTML should contain tooltip")
}
}
@ -286,7 +276,7 @@ func TestDotEdgeStyle(t *testing.T) {
}
func TestMergeSubgraphsForHTML_SingleDOCTYPE(t *testing.T) {
// Not parallel: captureGraphOutput redirects global os.Stdout
t.Parallel()
// Create two disconnected subgraphs (separate components)
issueA := &types.Issue{
@ -312,34 +302,37 @@ func TestMergeSubgraphsForHTML_SingleDOCTYPE(t *testing.T) {
merged := mergeSubgraphsForHTML([]*TemplateSubgraph{sg1, sg2})
layout := computeLayout(merged)
output := captureGraphOutput(func() {
renderGraphHTML(layout, merged)
})
var output bytes.Buffer
if err := renderGraphHTML(&output, layout, merged); err != nil {
t.Fatalf("renderGraphHTML: %v", err)
}
got := output.String()
// Must contain exactly one DOCTYPE declaration
count := strings.Count(output, "<!DOCTYPE html>")
count := strings.Count(got, "<!DOCTYPE html>")
if count != 1 {
t.Errorf("expected exactly 1 <!DOCTYPE html>, got %d", count)
}
// Both issues must appear in the single document
if !strings.Contains(output, "comp-a") {
if !strings.Contains(got, "comp-a") {
t.Error("merged HTML should contain comp-a")
}
if !strings.Contains(output, "comp-b") {
if !strings.Contains(got, "comp-b") {
t.Error("merged HTML should contain comp-b")
}
// links must be [] not null — null breaks d3.forceLink (GH#3592)
if strings.Contains(output, "const links = null") {
if strings.Contains(got, "const links = null") {
t.Error("links must be [] not null for d3 compatibility")
}
if !strings.Contains(output, "const links = []") {
if !strings.Contains(got, "const links = []") {
t.Error("empty links should serialize as [] not null")
}
}
func TestRenderGraphHTML_EmptyEdgesNotNull(t *testing.T) {
t.Parallel()
// Verify that a single-node graph emits [] not null for links (GH#3592)
issue := &types.Issue{
ID: "solo-1", Title: "Solo node", Status: types.StatusOpen,
@ -353,17 +346,108 @@ func TestRenderGraphHTML_EmptyEdgesNotNull(t *testing.T) {
}
layout := computeLayout(subgraph)
output := captureGraphOutput(func() {
renderGraphHTML(layout, subgraph)
})
var output bytes.Buffer
if err := renderGraphHTML(&output, layout, subgraph); err != nil {
t.Fatalf("renderGraphHTML: %v", err)
}
got := output.String()
if strings.Contains(output, "const links = null") {
if strings.Contains(got, "const links = null") {
t.Error("single-node graph must emit const links = [] not null")
}
if !strings.Contains(output, "const links = []") {
if !strings.Contains(got, "const links = []") {
t.Error("single-node graph should have const links = []")
}
if strings.Contains(output, "const nodes = null") {
if strings.Contains(got, "const nodes = null") {
t.Error("nodes must never be null")
}
}
type graphFailWriter struct {
err error
failAt int
writes int
}
func (w *graphFailWriter) Write(p []byte) (int, error) {
w.writes++
if w.writes >= w.failAt {
return 0, w.err
}
return len(p), nil
}
func TestRenderGraphDOTWriterErrors(t *testing.T) {
t.Parallel()
t.Run("nonempty", func(t *testing.T) {
t.Parallel()
subgraph, layout := makeTestSubgraph()
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: 3}
err := renderGraphDOT(writer, layout, subgraph)
if !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("renderGraphDOT error = %v, want %v", err, io.ErrClosedPipe)
}
if writer.writes != writer.failAt {
t.Fatalf("renderGraphDOT made %d writes after failure at %d", writer.writes, writer.failAt)
}
})
t.Run("empty", func(t *testing.T) {
t.Parallel()
subgraph := &TemplateSubgraph{IssueMap: map[string]*types.Issue{}}
layout := &GraphLayout{Nodes: map[string]*GraphNode{}}
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: 1}
err := renderGraphDOT(writer, layout, subgraph)
if !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("renderGraphDOT error = %v, want %v", err, io.ErrClosedPipe)
}
})
}
func TestRenderGraphHTMLWriterError(t *testing.T) {
t.Parallel()
subgraph, layout := makeTestSubgraph()
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: 1}
err := renderGraphHTML(writer, layout, subgraph)
if !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("renderGraphHTML error = %v, want %v", err, io.ErrClosedPipe)
}
}
func TestGraphExportDispatchPropagatesWriterErrors(t *testing.T) {
oldDOT, oldHTML := graphDOT, graphHTML
oldOpen, oldCompact, oldBox := graphOpen, graphCompact, graphBox
oldJSON := jsonOutput
t.Cleanup(func() {
graphDOT, graphHTML = oldDOT, oldHTML
graphOpen, graphCompact, graphBox = oldOpen, oldCompact, oldBox
jsonOutput = oldJSON
})
graphOpen, graphCompact, graphBox, jsonOutput = false, false, false, false
t.Run("single DOT", func(t *testing.T) {
graphDOT, graphHTML = true, false
subgraph, _ := makeTestSubgraph()
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: 1}
err := renderGraphSingleSubgraph(writer, subgraph)
if !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("renderGraphSingleSubgraph error = %v, want %v", err, io.ErrClosedPipe)
}
})
t.Run("all HTML", func(t *testing.T) {
graphDOT, graphHTML = false, true
subgraph, _ := makeTestSubgraph()
writer := &graphFailWriter{err: io.ErrClosedPipe, failAt: 1}
err := renderGraphAllSubgraphs(writer, []*TemplateSubgraph{subgraph})
if !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("renderGraphAllSubgraphs error = %v, want %v", err, io.ErrClosedPipe)
}
})
}

View file

@ -120,6 +120,16 @@ func TestProxiedServerGraph(t *testing.T) {
}
})
t.Run("html_output_error", func(t *testing.T) {
stderr, err := runGraphWithReadOnlyStdout(t, bd, p.dir, bdProxiedEnv(p.dir), "--html", epic.ID)
if err == nil {
t.Fatalf("proxied graph --html succeeded with read-only stdout; stderr:\n%s", stderr)
}
if !strings.Contains(stderr, "writing HTML output") {
t.Fatalf("proxied graph --html stderr = %q, want writer diagnostic", stderr)
}
})
t.Run("json_output_contains_root", func(t *testing.T) {
out, err := bdProxiedRun(t, bd, p.dir, "graph", epic.ID, "--json")
if err != nil {

View file

@ -3,13 +3,14 @@ package main
import (
"context"
"fmt"
"io"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
)
func runGraphProxiedServer(ctx context.Context, args []string) error {
func runGraphProxiedServer(ctx context.Context, out io.Writer, args []string) error {
uw, err := openProxiedListUOW(ctx)
if err != nil {
return HandleError("%v", err)
@ -21,7 +22,7 @@ func runGraphProxiedServer(ctx context.Context, args []string) error {
if err != nil {
return HandleErrorRespectJSON("loading all issues: %v", err)
}
return renderGraphAllSubgraphs(subgraphs)
return renderGraphAllSubgraphs(out, subgraphs)
}
root, err := uw.IssueUseCase().GetIssue(ctx, args[0])
@ -32,7 +33,7 @@ func runGraphProxiedServer(ctx context.Context, args []string) error {
if err != nil {
return HandleErrorRespectJSON("loading graph: %v", err)
}
return renderGraphSingleSubgraph(subgraph)
return renderGraphSingleSubgraph(out, subgraph)
}
func runGraphCheckProxiedServer(ctx context.Context) error {

View file

@ -2,6 +2,8 @@ package main
import (
"fmt"
"io"
"os"
"strings"
"github.com/steveyegge/beads/internal/types"
@ -19,14 +21,28 @@ type dagEdgeInfo struct {
// Each layer is a vertical column of node boxes, with edges drawn in
// gutter areas between columns.
func renderGraphVisual(layout *GraphLayout, subgraph *TemplateSubgraph) {
renderGraphVisualTo(os.Stdout, layout, subgraph)
}
// renderGraphVisualTo is the writer-aware test seam for the terminal visual
// renderer. The production wrapper intentionally retains its existing stdout
// destination and ignored write-error behavior.
func renderGraphVisualTo(out io.Writer, layout *GraphLayout, subgraph *TemplateSubgraph) {
printf := func(format string, args ...interface{}) {
_, _ = fmt.Fprintf(out, format, args...)
}
println := func(args ...interface{}) {
_, _ = fmt.Fprintln(out, args...)
}
if len(layout.Nodes) == 0 {
fmt.Println("Empty graph")
println("Empty graph")
return
}
fmt.Printf("\n%s Dependency graph for %s:\n\n", ui.RenderAccent("📊"), layout.RootID)
fmt.Println(" Status: ○ open ◐ in_progress ● blocked ✓ closed ❄ deferred")
fmt.Println()
printf("\n%s Dependency graph for %s:\n\n", ui.RenderAccent("📊"), layout.RootID)
println(" Status: ○ open ◐ in_progress ● blocked ✓ closed ❄ deferred")
println()
numLayers := len(layout.Layers)
if numLayers == 0 {
@ -75,8 +91,8 @@ func renderGraphVisual(layout *GraphLayout, subgraph *TemplateSubgraph) {
headerLine.WriteString(strings.Repeat(" ", gutterW))
}
}
fmt.Println(headerLine.String())
fmt.Println()
println(headerLine.String())
println()
// Render each output line
for y := 0; y < totalLines; y++ {
@ -108,10 +124,10 @@ func renderGraphVisual(layout *GraphLayout, subgraph *TemplateSubgraph) {
}
}
fmt.Println(strings.TrimRight(line.String(), " "))
println(strings.TrimRight(line.String(), " "))
}
fmt.Println()
println()
// Summary
blocksDeps := 0
@ -121,9 +137,9 @@ func renderGraphVisual(layout *GraphLayout, subgraph *TemplateSubgraph) {
}
}
if blocksDeps > 0 {
fmt.Printf(" Dependencies: %d blocking relationships\n", blocksDeps)
printf(" Dependencies: %d blocking relationships\n", blocksDeps)
}
fmt.Printf(" Total: %d issues across %d layers\n\n", len(layout.Nodes), len(layout.Layers))
printf(" Total: %d issues across %d layers\n\n", len(layout.Nodes), len(layout.Layers))
}
// computeDAGNodeWidth calculates a consistent width for all DAG node boxes

View file

@ -1,6 +1,7 @@
package main
import (
"bytes"
"strings"
"testing"
@ -8,53 +9,53 @@ import (
)
func TestRenderGraphVisual(t *testing.T) {
// Not parallel: captureGraphOutput redirects global os.Stdout
t.Parallel()
subgraph, layout := makeTestSubgraph()
output := captureGraphOutput(func() {
renderGraphVisual(layout, subgraph)
})
var output bytes.Buffer
renderGraphVisualTo(&output, layout, subgraph)
got := output.String()
// Verify layer headers
if !strings.Contains(output, "LAYER 0") {
if !strings.Contains(got, "LAYER 0") {
t.Error("Visual output should contain LAYER 0 header")
}
if !strings.Contains(output, "ready") {
if !strings.Contains(got, "ready") {
t.Error("Visual output should mark layer 0 as ready")
}
// Verify all node IDs are present
for _, id := range []string{"test-a", "test-b", "test-c", "test-d"} {
if !strings.Contains(output, id) {
if !strings.Contains(got, id) {
t.Errorf("Visual output should contain node %q", id)
}
}
// Verify node titles are present
for _, title := range []string{"Root issue", "Child task", "Blocked task", "Done task"} {
if !strings.Contains(output, title) {
if !strings.Contains(got, title) {
t.Errorf("Visual output should contain title %q", title)
}
}
// Verify box-drawing characters are used
if !strings.Contains(output, "┌") || !strings.Contains(output, "┘") {
if !strings.Contains(got, "┌") || !strings.Contains(got, "┘") {
t.Error("Visual output should use box-drawing characters for node borders")
}
// Verify edge arrows exist (edges between layers)
if !strings.Contains(output, "▶") {
if !strings.Contains(got, "▶") {
t.Error("Visual output should contain arrow characters for edges")
}
// Verify summary
if !strings.Contains(output, "layers") {
if !strings.Contains(got, "layers") {
t.Error("Visual output should contain summary with layer count")
}
}
func TestRenderGraphVisual_Empty(t *testing.T) {
// Not parallel: captureGraphOutput redirects global os.Stdout
t.Parallel()
emptySubgraph := &TemplateSubgraph{
Root: &types.Issue{ID: "empty"},
Issues: []*types.Issue{},
@ -66,17 +67,16 @@ func TestRenderGraphVisual_Empty(t *testing.T) {
RootID: "empty",
}
output := captureGraphOutput(func() {
renderGraphVisual(layout, emptySubgraph)
})
var output bytes.Buffer
renderGraphVisualTo(&output, layout, emptySubgraph)
if !strings.Contains(output, "Empty graph") {
if !strings.Contains(output.String(), "Empty graph") {
t.Error("Empty visual output should say 'Empty graph'")
}
}
func TestRenderGraphVisual_SingleNode(t *testing.T) {
// Not parallel: captureGraphOutput redirects global os.Stdout
t.Parallel()
issue := &types.Issue{
ID: "solo-1", Title: "Solo issue", Status: types.StatusOpen,
Priority: 0, IssueType: types.TypeTask,
@ -88,18 +88,18 @@ func TestRenderGraphVisual_SingleNode(t *testing.T) {
}
layout := computeLayout(subgraph)
output := captureGraphOutput(func() {
renderGraphVisual(layout, subgraph)
})
var output bytes.Buffer
renderGraphVisualTo(&output, layout, subgraph)
got := output.String()
if !strings.Contains(output, "solo-1") {
if !strings.Contains(got, "solo-1") {
t.Error("Single-node visual should contain the issue ID")
}
if !strings.Contains(output, "Solo issue") {
if !strings.Contains(got, "Solo issue") {
t.Error("Single-node visual should contain the title")
}
// No edges for single node
if strings.Contains(output, "▶") {
if strings.Contains(got, "▶") {
t.Error("Single-node visual should not contain edge arrows")
}
}