feat: add interactive DAG selection and migrate progress display to Bubble Tea TUI (#1074)

This commit is contained in:
YotaHamada authored and GitHub committed 2025-06-29 18:18:32 +09:00
1 parent abe4b599ce
commit 9706bb7169
14 files changed
+2327 -1029

No files matched your search

+9 -1
View File
@@ -8,6 +8,8 @@ require (
dario.cat/mergo v1.0.1
github.com/Masterminds/sprig/v3 v3.2.3
github.com/adrg/xdg v0.5.0
github.com/charmbracelet/bubbles v0.21.0
github.com/charmbracelet/bubbletea v1.3.5
github.com/containerd/platforms v0.2.1
github.com/docker/docker v28.1.1+incompatible
github.com/fsnotify/fsnotify v1.8.0
@@ -48,9 +50,15 @@ require (
)
require (
github.com/atotto/clipboard v0.1.4 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cenkalti/backoff/v5 v5.0.2 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/sahilm/fuzzy v0.1.1 // indirect
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
@@ -99,7 +107,7 @@ require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charithe/durationcheck v0.0.10 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
github.com/charmbracelet/lipgloss v1.1.0 // indirect
github.com/charmbracelet/lipgloss v1.1.0
github.com/charmbracelet/x/ansi v0.8.0 // indirect
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
+21
View File
@@ -62,8 +62,12 @@ github.com/ashanbrown/forbidigo v1.6.0 h1:D3aewfM37Yb3pxHujIPSpTf6oQk9sc9WZi8ger
github.com/ashanbrown/forbidigo v1.6.0/go.mod h1:Y8j9jy9ZYAEHXdu723cUlraTqbzjKF1MUyfOKL+AjcU=
github.com/ashanbrown/makezero v1.2.0 h1:/2Lp1bypdmK9wDIq7uWBlDF1iMUpIIS4A+pF6C9IEUU=
github.com/ashanbrown/makezero v1.2.0/go.mod h1:dxlPhHbDMC6N6xICzFBSK+4njQDdK8euNO0qjQMtGY4=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=
github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
@@ -99,6 +103,10 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/charithe/durationcheck v0.0.10 h1:wgw73BiocdBDQPik+zcEoBG/ob8uyBHf2iyoHGPf5w4=
github.com/charithe/durationcheck v0.0.10/go.mod h1:bCWXb7gYRysD1CU3C+u4ceO49LoGOY1C1L6uouGNreQ=
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
github.com/charmbracelet/bubbletea v1.3.5 h1:JAMNLTbqMOhSwoELIr0qyP4VidFq72/6E9j7HHmRKQc=
github.com/charmbracelet/bubbletea v1.3.5/go.mod h1:TkCnmH+aBd4LrXhXcqrKiYwRs7qyQx5rBgH5fVY3v54=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
@@ -107,6 +115,8 @@ github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2ll
github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/chavacava/garif v0.1.0 h1:2JHa3hbYf5D9dsgseMKAmc/MZ109otzgNFk5s87H9Pc=
@@ -150,6 +160,8 @@ github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDD
github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58=
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 h1:PRxIJD8XjimM5aTknUK9w6DHLDox2r2M3DI4i2pnd3w=
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936/go.mod h1:ttYvX5qlB+mlV1okblJqcSMtR4c52UKxDiX9GRBS8+Q=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q=
github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
@@ -407,6 +419,8 @@ github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
@@ -437,6 +451,10 @@ github.com/moricho/tparallel v0.3.2 h1:odr8aZVFA3NZrNybggMkYO3rgPRcqjeQUlBBFVxKH
github.com/moricho/tparallel v0.3.2/go.mod h1:OQ+K3b4Ln3l2TZveGCywybl68glfLEwFGqvnjok8b+U=
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
@@ -541,6 +559,8 @@ github.com/ryanrolds/sqlclosecheck v0.5.1 h1:dibWW826u0P8jNLsLN+En7+RqWWTYrjCB9f
github.com/ryanrolds/sqlclosecheck v0.5.1/go.mod h1:2g3dUjoS6AL4huFdv6wn55WpLIDjY7ZgUR4J8HOO/XQ=
github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k=
github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=
github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM=
github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/samber/slog-multi v1.2.0 h1:JIebVdmeGkCMd5/ticlmU+aDYl4tdAZBmp5uLaSzr0k=
@@ -793,6 +813,7 @@ golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211105183446-c75c47738b0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+2 -4
View File
@@ -104,7 +104,7 @@ type Agent struct {
isChildDAGRun atomic.Bool
// progressDisplay is the progress display for showing real-time execution progress.
progressDisplay *ProgressDisplay
progressDisplay ProgressReporter
// stepRetry is the name of the step to retry, if specified.
stepRetry string
@@ -163,9 +163,7 @@ func New(
// Initialize progress display if enabled
if opts.ProgressDisplay {
a.progressDisplay = NewProgressDisplay(os.Stderr, dag)
// Set initial DAG run info
a.progressDisplay.SetDAGRunInfo(dagRunID, strings.Join(dag.Params, " "))
a.progressDisplay = createProgressReporter(dag, dagRunID, dag.Params)
}
return a
+14
View File
@@ -0,0 +1,14 @@
package agent
import (
"strings"
"github.com/dagu-org/dagu/internal/digraph"
)
// createProgressReporter creates the progress reporter
func createProgressReporter(dag *digraph.DAG, dagRunID string, params []string) ProgressReporter {
display := NewProgressTeaDisplay(dag)
display.SetDAGRunInfo(dagRunID, strings.Join(params, " "))
return display
}
-721
View File
@@ -1,721 +0,0 @@
package agent
import (
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/dagu-org/dagu/internal/digraph"
"github.com/dagu-org/dagu/internal/digraph/scheduler"
"github.com/dagu-org/dagu/internal/models"
"github.com/dagu-org/dagu/internal/stringutil"
"github.com/fatih/color"
"golang.org/x/term"
)
// ProgressDisplay manages the real-time progress display for DAG execution
type ProgressDisplay struct {
mu sync.Mutex
writer io.Writer
dag *digraph.DAG
status *models.DAGRunStatus
nodes map[string]*nodeProgress
startTime time.Time
ticker *time.Ticker
done chan bool
isEnabled bool
isTTY bool
// DAG run information
dagRunID string
params string
// Display options
showChildDetails bool
accentColor *color.Color
spinnerFrames []string
spinnerIndex int
// Terminal dimensions
termWidth int
termHeight int
}
type nodeProgress struct {
node *models.Node
startTime time.Time
endTime time.Time
status scheduler.NodeStatus
children []models.ChildDAGRun
}
// NewProgressDisplay creates a new progress display
func NewProgressDisplay(writer io.Writer, dag *digraph.DAG) *ProgressDisplay {
if writer == nil {
writer = os.Stderr // Use stderr by default for progress display
}
// Check if stderr is connected to a terminal
// We check stderr instead of the writer because progress should be
// shown when stderr is a TTY, regardless of where stdout is directed
isTTY := term.IsTerminal(int(os.Stderr.Fd()))
// Get terminal dimensions from stderr
termWidth, termHeight := 80, 24 // defaults
if isTTY {
if w, h, err := term.GetSize(int(os.Stderr.Fd())); err == nil {
termWidth, termHeight = w, h
}
}
pd := &ProgressDisplay{
writer: writer,
dag: dag,
nodes: make(map[string]*nodeProgress),
startTime: time.Now(),
isEnabled: isTTY, // Only enable for TTY
isTTY: isTTY,
showChildDetails: true,
accentColor: color.New(color.FgCyan),
spinnerFrames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
termWidth: termWidth,
termHeight: termHeight,
}
// Initialize all nodes from the DAG steps
if dag != nil {
for _, step := range dag.Steps {
pd.nodes[step.Name] = &nodeProgress{
node: &models.Node{
Step: step,
Status: scheduler.NodeStatusNone,
StartedAt: "-",
FinishedAt: "-",
},
status: scheduler.NodeStatusNone,
}
}
}
return pd
}
// Start begins the progress display
func (pd *ProgressDisplay) Start() {
if !pd.isEnabled {
return
}
pd.done = make(chan bool)
pd.ticker = time.NewTicker(100 * time.Millisecond)
// Clear screen and hide cursor
fmt.Fprint(pd.writer, "\033[?25l") // Hide cursor
fmt.Fprint(pd.writer, "\033[2J") // Clear screen
fmt.Fprint(pd.writer, "\033[H") // Move to top
go pd.runDisplayLoop()
}
// Stop stops the progress display
func (pd *ProgressDisplay) Stop() {
if !pd.isEnabled || pd.done == nil {
return
}
close(pd.done)
if pd.ticker != nil {
pd.ticker.Stop()
}
// Wait a bit to ensure the last render completes
time.Sleep(50 * time.Millisecond)
// Clear screen and render final state
fmt.Fprint(pd.writer, "\033[H\033[2J")
// Render the final state with all content
pd.mu.Lock()
pd.renderHeader()
pd.renderProgressBar()
pd.renderCurrentlyRunning()
pd.renderRecentlyCompleted()
pd.renderQueued()
pd.renderChildDAGs()
pd.renderFooter()
pd.mu.Unlock()
// Show cursor
fmt.Fprint(pd.writer, "\033[?25h")
// Add extra newlines at the bottom to ensure any following
// output (like "exit status 1") appears below the display
fmt.Fprint(pd.writer, "\n\n\n\n")
}
// UpdateNode updates the progress for a specific node
func (pd *ProgressDisplay) UpdateNode(node *models.Node) {
if !pd.isEnabled {
return
}
pd.mu.Lock()
defer pd.mu.Unlock()
// Get existing node progress or create new one if not found
np, exists := pd.nodes[node.Step.Name]
if !exists {
// This shouldn't happen if DAG was properly initialized, but handle it gracefully
np = &nodeProgress{}
pd.nodes[node.Step.Name] = np
}
// Update the node data
np.node = node
np.status = node.Status
if node.StartedAt != "" && node.StartedAt != "-" {
if t, err := stringutil.ParseTime(node.StartedAt); err == nil {
np.startTime = t
}
}
if node.FinishedAt != "" && node.FinishedAt != "-" {
if t, err := stringutil.ParseTime(node.FinishedAt); err == nil {
np.endTime = t
}
}
if node.Children != nil {
np.children = node.Children
}
}
// UpdateStatus updates the overall DAG status
func (pd *ProgressDisplay) UpdateStatus(status *models.DAGRunStatus) {
if !pd.isEnabled {
return
}
pd.mu.Lock()
defer pd.mu.Unlock()
pd.status = status
// Update DAG run info from status if available
if status != nil {
pd.dagRunID = status.DAGRunID
pd.params = status.Params
}
}
func (pd *ProgressDisplay) runDisplayLoop() {
for {
select {
case <-pd.done:
return
case <-pd.ticker.C:
pd.render()
}
}
}
func (pd *ProgressDisplay) render() {
pd.mu.Lock()
defer pd.mu.Unlock()
// Update terminal dimensions in case of resize
if pd.isTTY {
if w, h, err := term.GetSize(int(os.Stderr.Fd())); err == nil {
pd.termWidth, pd.termHeight = w, h
}
}
// Increment spinner
pd.spinnerIndex = (pd.spinnerIndex + 1) % len(pd.spinnerFrames)
// Clear screen and reset cursor
fmt.Fprint(pd.writer, "\033[H\033[2J")
// Render header
pd.renderHeader()
// Render progress bar
pd.renderProgressBar()
// Render sections
pd.renderCurrentlyRunning()
pd.renderRecentlyCompleted()
pd.renderQueued()
pd.renderChildDAGs()
// Render footer
pd.renderFooter()
}
func (pd *ProgressDisplay) renderHeader() {
elapsed := time.Since(pd.startTime)
// Build status indicator
statusStr := pd.formatStatus(pd.getOverallStatus())
// Calculate available width
boxWidth := pd.termWidth
if boxWidth > 100 {
boxWidth = 100 // Cap max width for readability
}
innerWidth := boxWidth - 2 // Account for box borders
// Build header
dagName := pd.dag.Name
if len(dagName) > 30 {
dagName = dagName[:27] + "..."
}
header := fmt.Sprintf(" DAG: %s ", dagName)
// Build the time part (no colors)
timePart := fmt.Sprintf("Started: %s | Elapsed: %s",
pd.startTime.Format("15:04:05"),
pd.formatDuration(elapsed))
// Calculate the plain text parts for spacing
statusPrefix := "Status: "
statusValuePlain := stripANSI(statusStr)
// Truncate time part if needed to fit within available width
maxTimePartLen := innerWidth - utf8.RuneCountInString(statusPrefix) -
utf8.RuneCountInString(statusValuePlain) - utf8.RuneCountInString(" | ") - 4
if maxTimePartLen < 20 && utf8.RuneCountInString(timePart) > maxTimePartLen {
// Just show elapsed time if space is tight
timePart = fmt.Sprintf("Elapsed: %s", pd.formatDuration(elapsed))
}
// Calculate available space for the middle padding
// Use rune count for visual width instead of byte length
usedSpace := utf8.RuneCountInString(statusPrefix) + utf8.RuneCountInString(statusValuePlain) +
utf8.RuneCountInString(" | ") + utf8.RuneCountInString(timePart) + 2 // 2 for space padding
middlePadding := innerWidth - usedSpace
if middlePadding < 1 {
middlePadding = 1
}
// Build the status line with calculated padding
// If the content is still too wide, truncate the time part
if usedSpace > innerWidth {
// Recalculate with truncated time
availableForTime := innerWidth - utf8.RuneCountInString(statusPrefix) -
utf8.RuneCountInString(statusValuePlain) - utf8.RuneCountInString(" | ") - 5
if availableForTime > 0 {
timeRunes := []rune(timePart)
if len(timeRunes) > availableForTime-3 && availableForTime > 3 && len(timeRunes) > 0 {
println(fmt.Sprintf("Truncating time part: %s availableForTime=%d", timePart, availableForTime))
timePart = string(timeRunes[:availableForTime-3]) + "..."
}
} else {
timePart = "..."
}
middlePadding = 1
}
statusLine := fmt.Sprintf(" %s%s%s | %s ",
statusPrefix,
statusStr, // This includes color codes
strings.Repeat(" ", middlePadding),
timePart)
// Apply color to header
coloredHeader := pd.accentColor.Sprint(header)
// Calculate header padding based on plain text length
// We need to account for the ─ after ┌ and before ┐
headerPadding := innerWidth - utf8.RuneCountInString(stripANSI(header)) - 2
if headerPadding < 0 {
headerPadding = 0
}
// Render the box
fmt.Fprintf(pd.writer, "┌─%s%s─┐\n",
coloredHeader,
strings.Repeat("─", headerPadding))
fmt.Fprintln(pd.writer, "│"+statusLine+"│")
// Add Run ID line
if pd.dagRunID != "" {
runIDStr := fmt.Sprintf("Run ID: %s", pd.truncateString(pd.dagRunID, innerWidth-12))
runIDLine := fmt.Sprintf(" %s%s ", runIDStr, strings.Repeat(" ", innerWidth-utf8.RuneCountInString(runIDStr)-2))
fmt.Fprintln(pd.writer, "│"+runIDLine+"│")
}
// Add Params line if present
if pd.params != "" {
paramsStr := fmt.Sprintf("Params: %s", pd.truncateString(pd.params, innerWidth-12))
paramsLine := fmt.Sprintf(" %s%s ", paramsStr, strings.Repeat(" ", innerWidth-utf8.RuneCountInString(paramsStr)-2))
fmt.Fprintln(pd.writer, "│"+paramsLine+"│")
}
fmt.Fprintf(pd.writer, "└%s┘\n\n", strings.Repeat("─", innerWidth))
}
func (pd *ProgressDisplay) renderProgressBar() {
completed := 0
total := len(pd.nodes)
for _, np := range pd.nodes {
if np.status == scheduler.NodeStatusSuccess ||
np.status == scheduler.NodeStatusError ||
np.status == scheduler.NodeStatusSkipped ||
np.status == scheduler.NodeStatusCancel {
completed++
}
}
if total == 0 {
return
}
percentage := (completed * 100) / total
barWidth := 40
filled := (percentage * barWidth) / 100
// Build progress bar
bar := strings.Repeat("█", filled) + strings.Repeat("░", barWidth-filled)
fmt.Fprintf(pd.writer, "Progress: %s %3d%% (%d/%d steps)\n\n",
pd.colorizeProgressBar(bar, percentage),
percentage, completed, total)
}
func (pd *ProgressDisplay) renderCurrentlyRunning() {
running := pd.getNodesByStatus(scheduler.NodeStatusRunning)
if len(running) == 0 {
return
}
fmt.Fprintln(pd.writer, color.New(color.Bold).Sprint("Currently Running:"))
for _, np := range running {
elapsed := time.Since(np.startTime)
spinner := pd.spinnerFrames[pd.spinnerIndex]
fmt.Fprintf(pd.writer, " %s %s %s\n",
color.New(color.FgHiGreen).Sprint(spinner),
pd.truncateString(np.node.Step.Name, 30),
color.New(color.Faint).Sprintf("[Running for %s]", pd.formatDuration(elapsed)))
}
fmt.Fprintln(pd.writer)
}
func (pd *ProgressDisplay) renderRecentlyCompleted() {
// Get completed nodes sorted by completion time
completed := pd.getCompletedNodes()
if len(completed) == 0 {
return
}
// Show only recent ones
maxShow := 5
if len(completed) > maxShow {
completed = completed[len(completed)-maxShow:]
}
fmt.Fprintln(pd.writer, color.New(color.Bold).Sprint("Recently Completed:"))
for _, np := range completed {
statusIcon := pd.getStatusIcon(np.status)
duration := ""
if !np.endTime.IsZero() && !np.startTime.IsZero() {
duration = fmt.Sprintf("[%s]", pd.formatDuration(np.endTime.Sub(np.startTime)))
}
line := fmt.Sprintf(" %s %s %s",
statusIcon,
pd.truncateString(np.node.Step.Name, 30),
color.New(color.Faint).Sprint(duration))
if np.status == scheduler.NodeStatusError && np.node.Error != "" {
// Calculate available space for error message
// Account for the line content already shown
lineLen := 2 + 1 + 1 + 30 + 1 + len(duration) + 8 // Approximate
availableSpace := pd.termWidth - lineLen - 10 // Leave some margin
if availableSpace < 20 {
availableSpace = 20
}
errorMsg := pd.truncateString(np.node.Error, availableSpace)
line += color.RedString(" Error: %s", errorMsg)
}
fmt.Fprintln(pd.writer, line)
}
fmt.Fprintln(pd.writer)
}
func (pd *ProgressDisplay) renderQueued() {
queued := pd.getNodesByStatus(scheduler.NodeStatusNone)
if len(queued) == 0 {
return
}
maxShow := 3
fmt.Fprintln(pd.writer, color.New(color.Bold).Sprint("Queued:"))
for i, np := range queued {
if i >= maxShow {
fmt.Fprintf(pd.writer, " %s ... and %d more\n",
color.New(color.Faint).Sprint("○"),
len(queued)-maxShow)
break
}
fmt.Fprintf(pd.writer, " %s %s\n",
color.New(color.Faint).Sprint("○"),
pd.truncateString(np.node.Step.Name, 30))
}
fmt.Fprintln(pd.writer)
}
func (pd *ProgressDisplay) renderChildDAGs() {
childNodes := pd.getNodesWithChildren()
if len(childNodes) == 0 {
return
}
fmt.Fprintln(pd.writer, color.New(color.Bold).Sprint("Child DAGs:"))
for _, np := range childNodes {
if len(np.children) == 1 {
// Single child DAG
child := np.children[0]
fmt.Fprintf(pd.writer, " ▸ %s → %s\n",
pd.truncateString(np.node.Step.Name, 20),
pd.formatChildStatus(child))
} else {
// Parallel execution
// For parallel execution, we'll show the count and basic info
// Actual status tracking would need to be implemented separately
total := len(np.children)
// Show a simplified view for now
statusInfo := fmt.Sprintf("(%d child DAGs)", total)
fmt.Fprintf(pd.writer, " ▸ %s %s %s\n",
pd.truncateString(np.node.Step.Name, 20),
statusInfo,
pd.getStatusIcon(np.status))
}
}
fmt.Fprintln(pd.writer)
}
func (pd *ProgressDisplay) renderFooter() {
hint := color.New(color.Faint).Sprint("Press Ctrl+C to stop")
fmt.Fprintln(pd.writer, hint)
}
// Helper functions
func (pd *ProgressDisplay) getOverallStatus() scheduler.Status {
if pd.status != nil {
return pd.status.Status
}
return scheduler.StatusRunning
}
func (pd *ProgressDisplay) formatStatus(status scheduler.Status) string {
switch status {
case scheduler.StatusSuccess:
return color.GreenString("Success ✓")
case scheduler.StatusError:
return color.RedString("Failed ✗")
case scheduler.StatusRunning:
return color.New(color.FgHiGreen).Sprint("Running ●")
case scheduler.StatusCancel:
return color.YellowString("Cancelled ⚠")
case scheduler.StatusQueued:
return color.BlueString("Queued ●")
default:
return color.New(color.Faint).Sprint("Not Started ○")
}
}
func (pd *ProgressDisplay) getStatusIcon(status scheduler.NodeStatus) string {
switch status {
case scheduler.NodeStatusSuccess:
return color.GreenString("✓")
case scheduler.NodeStatusError:
return color.RedString("✗")
case scheduler.NodeStatusRunning:
return color.New(color.FgHiGreen).Sprint("●")
case scheduler.NodeStatusCancel:
return color.YellowString("⚠")
case scheduler.NodeStatusSkipped:
return color.New(color.Faint).Sprint("⊘")
default:
return color.New(color.Faint).Sprint("○")
}
}
func (pd *ProgressDisplay) formatDuration(d time.Duration) string {
if d < time.Second {
return fmt.Sprintf("%dms", d.Milliseconds())
} else if d < time.Minute {
return fmt.Sprintf("%.1fs", d.Seconds())
} else if d < time.Hour {
mins := int(d.Minutes())
secs := int(d.Seconds()) % 60
return fmt.Sprintf("%dm %ds", mins, secs)
}
hours := int(d.Hours())
mins := int(d.Minutes()) % 60
return fmt.Sprintf("%dh %dm", hours, mins)
}
func (pd *ProgressDisplay) colorizeProgressBar(bar string, percentage int) string {
if percentage >= 80 {
return color.GreenString(bar)
} else if percentage >= 50 {
return pd.accentColor.Sprint(bar)
}
return bar
}
func (pd *ProgressDisplay) truncateString(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
return s[:maxLen-3] + "..."
}
func (pd *ProgressDisplay) formatChildStatus(child models.ChildDAGRun) string {
// For now, just show the child DAG run ID and params
// Status tracking for child DAGs would need to be retrieved separately
params := ""
if child.Params != "" {
params = color.New(color.Faint).Sprintf(" [%s]", pd.truncateString(child.Params, 20))
}
dagRunID := pd.truncateString(child.DAGRunID, 15)
return fmt.Sprintf("%s%s", dagRunID, params)
}
func (pd *ProgressDisplay) getNodesByStatus(status scheduler.NodeStatus) []*nodeProgress {
var nodes []*nodeProgress
for _, np := range pd.nodes {
if np.status == status {
nodes = append(nodes, np)
}
}
// Sort by start time (earliest first) for deterministic ordering
// If start times are equal, sort by step name
for i := 0; i < len(nodes)-1; i++ {
for j := i + 1; j < len(nodes); j++ {
if nodes[i].startTime.After(nodes[j].startTime) ||
(nodes[i].startTime.Equal(nodes[j].startTime) &&
nodes[i].node.Step.Name > nodes[j].node.Step.Name) {
nodes[i], nodes[j] = nodes[j], nodes[i]
}
}
}
return nodes
}
func (pd *ProgressDisplay) getCompletedNodes() []*nodeProgress {
var nodes []*nodeProgress
for _, np := range pd.nodes {
if np.status == scheduler.NodeStatusSuccess ||
np.status == scheduler.NodeStatusError ||
np.status == scheduler.NodeStatusSkipped ||
np.status == scheduler.NodeStatusCancel {
nodes = append(nodes, np)
}
}
// Sort by completion time
for i := 0; i < len(nodes)-1; i++ {
for j := i + 1; j < len(nodes); j++ {
switch {
case nodes[i].endTime.IsZero() && !nodes[j].endTime.IsZero():
// If i has no end time, it comes after j
nodes[i], nodes[j] = nodes[j], nodes[i]
case !nodes[i].endTime.IsZero() && nodes[j].endTime.IsZero():
// If j has no end time, it comes after i
// No swap needed
case nodes[i].endTime.Before(nodes[j].endTime):
// If i ends before j, i comes first
// No swap needed
case nodes[i].endTime.After(nodes[j].endTime):
// If i ends after j, swap them
nodes[i], nodes[j] = nodes[j], nodes[i]
default:
// If end times are equal, sort by step name
if nodes[i].node.Step.Name > nodes[j].node.Step.Name {
nodes[i], nodes[j] = nodes[j], nodes[i]
}
}
}
}
return nodes
}
func (pd *ProgressDisplay) getNodesWithChildren() []*nodeProgress {
var nodes []*nodeProgress
for _, np := range pd.nodes {
if len(np.children) > 0 {
nodes = append(nodes, np)
}
}
// Sort by step name for deterministic ordering
for i := 0; i < len(nodes)-1; i++ {
for j := i + 1; j < len(nodes); j++ {
if nodes[i].node.Step.Name > nodes[j].node.Step.Name {
nodes[i], nodes[j] = nodes[j], nodes[i]
}
}
}
return nodes
}
// stripANSI removes ANSI color codes from a string
func stripANSI(s string) string {
// Remove all ANSI escape sequences
var result strings.Builder
inEscape := false
for i := 0; i < len(s); i++ {
if s[i] == '\033' && i+1 < len(s) && s[i+1] == '[' {
inEscape = true
i++ // Skip the '['
continue
}
if inEscape {
// Skip until we find a letter that ends the escape sequence
if (s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z') {
inEscape = false
}
continue
}
result.WriteByte(s[i])
}
return result.String()
}
// SetAccentColor allows customizing the main accent color
func (pd *ProgressDisplay) SetAccentColor(c *color.Color) {
pd.mu.Lock()
defer pd.mu.Unlock()
if c != nil {
pd.accentColor = c
}
}
// SetDAGRunInfo sets the DAG run ID and parameters
func (pd *ProgressDisplay) SetDAGRunInfo(dagRunID, params string) {
pd.mu.Lock()
defer pd.mu.Unlock()
pd.dagRunID = dagRunID
pd.params = params
}
+26
View File
@@ -0,0 +1,26 @@
package agent
import (
"github.com/dagu-org/dagu/internal/models"
)
// ProgressReporter is the interface for progress display implementations
type ProgressReporter interface {
// Start begins the progress display
Start()
// Stop stops the progress display
Stop()
// UpdateNode updates the progress for a specific node
UpdateNode(node *models.Node)
// UpdateStatus updates the overall DAG status
UpdateStatus(status *models.DAGRunStatus)
// SetDAGRunInfo sets the DAG run ID and parameters
SetDAGRunInfo(dagRunID, params string)
}
// Ensure implementation satisfies the interface
var _ ProgressReporter = (*ProgressTeaDisplay)(nil)
+823
View File
@@ -0,0 +1,823 @@
package agent
import (
"fmt"
"strings"
"time"
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/dagu-org/dagu/internal/digraph"
"github.com/dagu-org/dagu/internal/digraph/scheduler"
"github.com/dagu-org/dagu/internal/models"
"github.com/dagu-org/dagu/internal/stringutil"
)
// nodeProgress represents the progress state of a single node
type nodeProgress struct {
node *models.Node
startTime time.Time
endTime time.Time
status scheduler.NodeStatus
children []models.ChildDAGRun
}
// Message types for Bubble Tea
type (
// TickMsg is sent periodically to update the display
TickMsg time.Time
// NodeUpdateMsg is sent when a node's status changes
NodeUpdateMsg struct {
Node *models.Node
}
// StatusUpdateMsg is sent when the overall DAG status changes
StatusUpdateMsg struct {
Status *models.DAGRunStatus
}
// FinalizeMsg is sent when the display should stop
FinalizeMsg struct{}
)
// ProgressModel represents the Bubble Tea model for progress display
type ProgressModel struct {
// DAG information
dag *digraph.DAG
status *models.DAGRunStatus
dagRunID string
params string
// Node tracking
nodes map[string]*nodeProgress
// Display state
startTime time.Time
finishTime time.Time
spinner spinner.Model
width int
height int
finalized bool
showChildDetails bool
// Styles
accentColor lipgloss.Color
headerStyle lipgloss.Style
progressBarStyle lipgloss.Style
sectionStyle lipgloss.Style
errorStyle lipgloss.Style
successStyle lipgloss.Style
runningStyle lipgloss.Style
faintStyle lipgloss.Style
boldStyle lipgloss.Style
}
// NewProgressModel creates a new progress model for Bubble Tea
func NewProgressModel(dag *digraph.DAG) ProgressModel {
s := spinner.New()
s.Spinner = spinner.Spinner{
Frames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
FPS: time.Second / 10,
}
// Initialize styles
accentColor := lipgloss.Color("6")
m := ProgressModel{
dag: dag,
nodes: make(map[string]*nodeProgress),
startTime: time.Now(),
spinner: s,
showChildDetails: true,
accentColor: accentColor,
headerStyle: lipgloss.NewStyle().Foreground(accentColor).Bold(true),
sectionStyle: lipgloss.NewStyle().Bold(true),
errorStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("1")),
successStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("2")),
runningStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("10")),
faintStyle: lipgloss.NewStyle().Faint(true),
boldStyle: lipgloss.NewStyle().Bold(true),
}
// Initialize all nodes from the DAG steps
if dag != nil {
for _, step := range dag.Steps {
m.nodes[step.Name] = &nodeProgress{
node: &models.Node{
Step: step,
Status: scheduler.NodeStatusNone,
StartedAt: "-",
FinishedAt: "-",
},
status: scheduler.NodeStatusNone,
}
}
}
return m
}
// Init initializes the model
func (m ProgressModel) Init() tea.Cmd {
return tea.Batch(
m.spinner.Tick,
tickCmd(),
)
}
// Update handles messages
func (m ProgressModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
return m, nil
case TickMsg:
if m.finalized {
return m, nil
}
return m, tickCmd()
case NodeUpdateMsg:
m.updateNode(msg.Node)
return m, nil
case StatusUpdateMsg:
m.status = msg.Status
if msg.Status != nil {
m.dagRunID = msg.Status.DAGRunID
m.params = msg.Status.Params
}
return m, nil
case FinalizeMsg:
m.finalized = true
m.finishTime = time.Now()
// Quit after a short delay to ensure final render
return m, tea.Tick(100*time.Millisecond, func(t time.Time) tea.Msg {
return tea.Quit()
})
case spinner.TickMsg:
var cmd tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c", "q":
m.finalized = true
return m, tea.Quit
}
}
return m, tea.Batch(cmds...)
}
// View renders the display
func (m ProgressModel) View() string {
// Always use the same rendering logic whether finalized or not
// This ensures the user sees the final state clearly
var sections []string
// Header
sections = append(sections, m.renderHeader())
// Progress bar
if bar := m.renderProgressBar(); bar != "" {
sections = append(sections, bar)
}
// Currently running
if running := m.renderCurrentlyRunning(); running != "" {
sections = append(sections, running)
}
// Show different sections based on finalized state
if m.finalized {
// Show all completed steps when finalized
if completed := m.renderAllCompleted(); completed != "" {
sections = append(sections, completed)
}
} else {
// Show recently completed and queued when running
if completed := m.renderRecentlyCompleted(); completed != "" {
sections = append(sections, completed)
}
if queued := m.renderQueued(); queued != "" {
sections = append(sections, queued)
}
}
// Child DAGs
if children := m.renderChildDAGs(); children != "" {
sections = append(sections, children)
}
// Footer
sections = append(sections, m.renderFooter())
return strings.Join(sections, "\n\n")
}
func (m *ProgressModel) updateNode(node *models.Node) {
np, exists := m.nodes[node.Step.Name]
if !exists {
np = &nodeProgress{}
m.nodes[node.Step.Name] = np
}
np.node = node
np.status = node.Status
if node.StartedAt != "" && node.StartedAt != "-" {
if t, err := stringutil.ParseTime(node.StartedAt); err == nil {
np.startTime = t
}
}
if node.FinishedAt != "" && node.FinishedAt != "-" {
if t, err := stringutil.ParseTime(node.FinishedAt); err == nil {
np.endTime = t
}
}
if node.Children != nil {
np.children = node.Children
}
}
func (m ProgressModel) renderHeader() string {
var elapsed time.Duration
if m.finalized && !m.finishTime.IsZero() {
elapsed = m.finishTime.Sub(m.startTime)
} else {
elapsed = time.Since(m.startTime)
}
// Build status indicator
statusStr := m.formatStatus(m.getOverallStatus())
// Box width calculation
boxWidth := m.width
if boxWidth == 0 {
boxWidth = 80 // Default width if not set yet
}
if boxWidth > 100 {
boxWidth = 100
}
if boxWidth < 40 {
boxWidth = 40
}
innerWidth := boxWidth - 2
// Build header
dagName := m.dag.Name
if len(dagName) > 30 {
dagName = dagName[:27] + "..."
}
header := fmt.Sprintf(" DAG: %s ", dagName)
// Build the time part
timePart := fmt.Sprintf("Started: %s | Elapsed: %s",
m.startTime.Format("15:04:05"),
formatDuration(elapsed))
// Build status line
statusPrefix := "Status: "
statusLine := fmt.Sprintf(" %s%s | %s ", statusPrefix, statusStr, timePart)
// Apply styles
headerStyled := m.headerStyle.Render(header)
// Create box
var box strings.Builder
box.WriteString("┌─")
box.WriteString(headerStyled)
// Calculate header padding, ensuring it's never negative
headerPadding := innerWidth - lipgloss.Width(header) - 2
if headerPadding < 0 {
headerPadding = 0
}
box.WriteString(strings.Repeat("─", headerPadding))
box.WriteString("─┐\n")
box.WriteString("│")
box.WriteString(statusLine)
// Calculate padding, ensuring it's never negative
padding := innerWidth - lipgloss.Width(statusLine) + 2
if padding < 0 {
padding = 0
}
box.WriteString(strings.Repeat(" ", padding))
box.WriteString("│\n")
// Add Run ID line
if m.dagRunID != "" {
runIDStr := fmt.Sprintf("Run ID: %s", truncateString(m.dagRunID, innerWidth-12))
// Calculate padding for run ID line
runIDPadding := innerWidth - len(runIDStr) - 2
if runIDPadding < 0 {
runIDPadding = 0
}
runIDLine := fmt.Sprintf(" %s%s ", runIDStr, strings.Repeat(" ", runIDPadding))
box.WriteString("│")
box.WriteString(runIDLine)
box.WriteString("│\n")
}
// Add Params line
if m.params != "" {
paramsStr := fmt.Sprintf("Params: %s", truncateString(m.params, innerWidth-12))
// Calculate padding for params line
paramsPadding := innerWidth - len(paramsStr) - 2
if paramsPadding < 0 {
paramsPadding = 0
}
paramsLine := fmt.Sprintf(" %s%s ", paramsStr, strings.Repeat(" ", paramsPadding))
box.WriteString("│")
box.WriteString(paramsLine)
box.WriteString("│\n")
}
box.WriteString("└")
// Ensure innerWidth is never negative
bottomPadding := innerWidth
if bottomPadding < 0 {
bottomPadding = 0
}
box.WriteString(strings.Repeat("─", bottomPadding))
box.WriteString("┘")
return box.String()
}
func (m ProgressModel) renderProgressBar() string {
completed := 0
total := len(m.nodes)
for _, np := range m.nodes {
if np.status == scheduler.NodeStatusSuccess ||
np.status == scheduler.NodeStatusError ||
np.status == scheduler.NodeStatusSkipped ||
np.status == scheduler.NodeStatusCancel {
completed++
}
}
if total == 0 {
return ""
}
percentage := (completed * 100) / total
barWidth := 40
if m.width < 60 {
barWidth = 20
}
filled := (percentage * barWidth) / 100
// Build progress bar
bar := strings.Repeat("█", filled) + strings.Repeat("░", barWidth-filled)
// Colorize based on percentage
var barStyled string
if percentage >= 80 {
barStyled = m.successStyle.Render(bar)
} else if percentage >= 50 {
barStyled = lipgloss.NewStyle().Foreground(m.accentColor).Render(bar)
} else {
barStyled = bar
}
return fmt.Sprintf("Progress: %s %3d%% (%d/%d steps)",
barStyled, percentage, completed, total)
}
func (m ProgressModel) renderCurrentlyRunning() string {
running := m.getNodesByStatus(scheduler.NodeStatusRunning)
if len(running) == 0 {
return ""
}
var lines []string
lines = append(lines, m.sectionStyle.Render("Currently Running:"))
for _, np := range running {
elapsed := time.Since(np.startTime)
spinner := m.spinner.View()
line := fmt.Sprintf(" %s %s %s",
m.runningStyle.Render(spinner),
truncateString(np.node.Step.Name, 30),
m.faintStyle.Render(fmt.Sprintf("[Running for %s]", formatDuration(elapsed))))
lines = append(lines, line)
}
return strings.Join(lines, "\n")
}
func (m ProgressModel) renderRecentlyCompleted() string {
completed := m.getCompletedNodes()
if len(completed) == 0 {
return ""
}
// Show only recent ones
maxShow := 5
if len(completed) > maxShow {
completed = completed[len(completed)-maxShow:]
}
var lines []string
lines = append(lines, m.sectionStyle.Render("Recently Completed:"))
for _, np := range completed {
statusIcon := m.getStatusIcon(np.status)
duration := ""
if !np.endTime.IsZero() && !np.startTime.IsZero() {
duration = fmt.Sprintf("[%s]", formatDuration(np.endTime.Sub(np.startTime)))
}
line := fmt.Sprintf(" %s %s %s",
statusIcon,
truncateString(np.node.Step.Name, 30),
m.faintStyle.Render(duration))
if np.status == scheduler.NodeStatusError && np.node.Error != "" {
availableSpace := m.width - 50
if availableSpace < 20 {
availableSpace = 20
}
errorMsg := truncateString(np.node.Error, availableSpace)
line += m.errorStyle.Render(fmt.Sprintf(" Error: %s", errorMsg))
}
lines = append(lines, line)
}
return strings.Join(lines, "\n")
}
func (m ProgressModel) renderAllCompleted() string {
completed := m.getCompletedNodes()
if len(completed) == 0 {
return ""
}
var lines []string
lines = append(lines, m.sectionStyle.Render("Completed Steps:"))
for _, np := range completed {
statusIcon := m.getStatusIcon(np.status)
duration := ""
if !np.endTime.IsZero() && !np.startTime.IsZero() {
duration = fmt.Sprintf("[%s]", formatDuration(np.endTime.Sub(np.startTime)))
}
line := fmt.Sprintf(" %s %s %s",
statusIcon,
truncateString(np.node.Step.Name, 30),
m.faintStyle.Render(duration))
if np.status == scheduler.NodeStatusError && np.node.Error != "" {
availableSpace := m.width - 50
if availableSpace < 20 {
availableSpace = 20
}
errorMsg := truncateString(np.node.Error, availableSpace)
line += m.errorStyle.Render(fmt.Sprintf(" Error: %s", errorMsg))
}
lines = append(lines, line)
}
return strings.Join(lines, "\n")
}
func (m ProgressModel) renderQueued() string {
queued := m.getNodesByStatus(scheduler.NodeStatusNone)
if len(queued) == 0 {
return ""
}
maxShow := 3
var lines []string
lines = append(lines, m.sectionStyle.Render("Queued:"))
for i, np := range queued {
if i >= maxShow {
lines = append(lines, fmt.Sprintf(" %s ... and %d more",
m.faintStyle.Render("○"),
len(queued)-maxShow))
break
}
lines = append(lines, fmt.Sprintf(" %s %s",
m.faintStyle.Render("○"),
truncateString(np.node.Step.Name, 30)))
}
return strings.Join(lines, "\n")
}
func (m ProgressModel) renderChildDAGs() string {
childNodes := m.getNodesWithChildren()
if len(childNodes) == 0 {
return ""
}
var lines []string
lines = append(lines, m.sectionStyle.Render("Child DAGs:"))
for _, np := range childNodes {
if len(np.children) == 1 {
// Single child DAG
child := np.children[0]
lines = append(lines, fmt.Sprintf(" ▸ %s → %s",
truncateString(np.node.Step.Name, 20),
m.formatChildStatus(child)))
} else {
// Parallel execution
total := len(np.children)
statusInfo := fmt.Sprintf("(%d child DAGs)", total)
lines = append(lines, fmt.Sprintf(" ▸ %s %s %s",
truncateString(np.node.Step.Name, 20),
statusInfo,
m.getStatusIcon(np.status)))
}
}
return strings.Join(lines, "\n")
}
func (m ProgressModel) renderFooter() string {
if m.finalized {
status := m.getOverallStatus()
switch status {
case scheduler.StatusSuccess:
return m.successStyle.Render("✓ Execution completed successfully")
case scheduler.StatusError:
return m.errorStyle.Render("✗ Execution failed")
case scheduler.StatusCancel:
return lipgloss.NewStyle().Foreground(lipgloss.Color("3")).Render("⚠ Execution cancelled")
default:
return m.boldStyle.Render("Execution finished")
}
}
return m.faintStyle.Render("Press Ctrl+C to stop")
}
func (m ProgressModel) getOverallStatus() scheduler.Status {
if m.status != nil {
return m.status.Status
}
return scheduler.StatusRunning
}
func (m ProgressModel) formatStatus(status scheduler.Status) string {
switch status {
case scheduler.StatusSuccess:
return m.successStyle.Render("Success ✓")
case scheduler.StatusError:
return m.errorStyle.Render("Failed ✗")
case scheduler.StatusRunning:
return m.runningStyle.Render("Running ●")
case scheduler.StatusCancel:
return lipgloss.NewStyle().Foreground(lipgloss.Color("3")).Render("Cancelled ⚠")
case scheduler.StatusQueued:
return lipgloss.NewStyle().Foreground(lipgloss.Color("4")).Render("Queued ●")
default:
return m.faintStyle.Render("Not Started ○")
}
}
func (m ProgressModel) getStatusIcon(status scheduler.NodeStatus) string {
switch status {
case scheduler.NodeStatusSuccess:
return m.successStyle.Render("✓")
case scheduler.NodeStatusError:
return m.errorStyle.Render("✗")
case scheduler.NodeStatusRunning:
return m.runningStyle.Render("●")
case scheduler.NodeStatusCancel:
return lipgloss.NewStyle().Foreground(lipgloss.Color("3")).Render("⚠")
case scheduler.NodeStatusSkipped:
return m.faintStyle.Render("⊘")
default:
return m.faintStyle.Render("○")
}
}
func (m ProgressModel) formatChildStatus(child models.ChildDAGRun) string {
params := ""
if child.Params != "" {
params = m.faintStyle.Render(fmt.Sprintf(" [%s]", truncateString(child.Params, 20)))
}
dagRunID := truncateString(child.DAGRunID, 15)
return fmt.Sprintf("%s%s", dagRunID, params)
}
func (m ProgressModel) getNodesByStatus(status scheduler.NodeStatus) []*nodeProgress {
var nodes []*nodeProgress
for _, np := range m.nodes {
if np.status == status {
nodes = append(nodes, np)
}
}
// Sort by start time (earliest first) for deterministic ordering
sortNodesByStartTime(nodes)
return nodes
}
func (m ProgressModel) getCompletedNodes() []*nodeProgress {
var nodes []*nodeProgress
for _, np := range m.nodes {
if np.status == scheduler.NodeStatusSuccess ||
np.status == scheduler.NodeStatusError ||
np.status == scheduler.NodeStatusSkipped ||
np.status == scheduler.NodeStatusCancel {
nodes = append(nodes, np)
}
}
// Sort by completion time
sortNodesByEndTime(nodes)
return nodes
}
func (m ProgressModel) getNodesWithChildren() []*nodeProgress {
var nodes []*nodeProgress
for _, np := range m.nodes {
if len(np.children) > 0 {
nodes = append(nodes, np)
}
}
// Sort by step name for deterministic ordering
sortNodesByName(nodes)
return nodes
}
// Helper functions
func tickCmd() tea.Cmd {
return tea.Tick(100*time.Millisecond, func(t time.Time) tea.Msg {
return TickMsg(t)
})
}
func formatDuration(d time.Duration) string {
if d < time.Second {
return fmt.Sprintf("%dms", d.Milliseconds())
} else if d < time.Minute {
return fmt.Sprintf("%.1fs", d.Seconds())
} else if d < time.Hour {
mins := int(d.Minutes())
secs := int(d.Seconds()) % 60
return fmt.Sprintf("%dm %ds", mins, secs)
}
hours := int(d.Hours())
mins := int(d.Minutes()) % 60
return fmt.Sprintf("%dh %dm", hours, mins)
}
func truncateString(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
return s[:maxLen-3] + "..."
}
func sortNodesByStartTime(nodes []*nodeProgress) {
for i := 0; i < len(nodes)-1; i++ {
for j := i + 1; j < len(nodes); j++ {
if nodes[i].startTime.After(nodes[j].startTime) ||
(nodes[i].startTime.Equal(nodes[j].startTime) &&
nodes[i].node.Step.Name > nodes[j].node.Step.Name) {
nodes[i], nodes[j] = nodes[j], nodes[i]
}
}
}
}
func sortNodesByEndTime(nodes []*nodeProgress) {
for i := 0; i < len(nodes)-1; i++ {
for j := i + 1; j < len(nodes); j++ {
switch {
case nodes[i].endTime.IsZero() && !nodes[j].endTime.IsZero():
nodes[i], nodes[j] = nodes[j], nodes[i]
case !nodes[i].endTime.IsZero() && nodes[j].endTime.IsZero():
// No swap needed
case nodes[i].endTime.After(nodes[j].endTime):
nodes[i], nodes[j] = nodes[j], nodes[i]
case nodes[i].endTime.Equal(nodes[j].endTime):
if nodes[i].node.Step.Name > nodes[j].node.Step.Name {
nodes[i], nodes[j] = nodes[j], nodes[i]
}
}
}
}
}
func sortNodesByName(nodes []*nodeProgress) {
for i := 0; i < len(nodes)-1; i++ {
for j := i + 1; j < len(nodes); j++ {
if nodes[i].node.Step.Name > nodes[j].node.Step.Name {
nodes[i], nodes[j] = nodes[j], nodes[i]
}
}
}
}
// ProgressTeaDisplay wraps the Bubble Tea program for the progress display
type ProgressTeaDisplay struct {
program *tea.Program
model ProgressModel
useAltScreen bool
done chan struct{}
finalOutput string
}
// NewProgressTeaDisplay creates a new Bubble Tea-based progress display
func NewProgressTeaDisplay(dag *digraph.DAG) *ProgressTeaDisplay {
model := NewProgressModel(dag)
return &ProgressTeaDisplay{
model: model,
useAltScreen: true,
done: make(chan struct{}),
}
}
// Start initializes and runs the Bubble Tea program
func (p *ProgressTeaDisplay) Start() {
// Manually manage alternate screen to keep it after exit
p.program = tea.NewProgram(p.model)
go func() {
defer func() {
// Ensure cursor is visible and mouse tracking is disabled if program crashes
fmt.Print("\033[?25h") // Show cursor
fmt.Print("\033[?1000l") // Disable mouse tracking
fmt.Print("\033[?1002l") // Disable mouse cell motion tracking
fmt.Print("\033[?1003l") // Disable all mouse tracking
fmt.Print("\033[?1006l") // Disable SGR mouse mode
// DON'T exit alternate screen - keep the UI visible
// Signal that the program has exited
close(p.done)
}()
// Enter alternate screen manually
fmt.Print("\033[?1049h") // Enter alternate screen
fmt.Print("\033[2J") // Clear screen
fmt.Print("\033[H") // Move cursor to home
_, _ = p.program.Run()
// Don't exit alternate screen - stay in it!
}()
}
// Stop gracefully stops the display
func (p *ProgressTeaDisplay) Stop() {
if p.program != nil {
p.program.Send(FinalizeMsg{})
// Wait for the program to exit
<-p.done
// UI stays visible in alternate screen buffer
}
}
// UpdateNode sends a node update to the display
func (p *ProgressTeaDisplay) UpdateNode(node *models.Node) {
if p.program != nil {
p.model.updateNode(node)
p.program.Send(NodeUpdateMsg{Node: node})
}
}
// UpdateStatus sends a status update to the display
func (p *ProgressTeaDisplay) UpdateStatus(status *models.DAGRunStatus) {
if p.program != nil {
p.model.status = status
p.program.Send(StatusUpdateMsg{Status: status})
}
}
// SetDAGRunInfo sets the DAG run ID and parameters
func (p *ProgressTeaDisplay) SetDAGRunInfo(dagRunID, params string) {
if p.program != nil {
status := &models.DAGRunStatus{
DAGRunID: dagRunID,
Params: params,
}
p.program.Send(StatusUpdateMsg{Status: status})
}
}
+316
View File
@@ -0,0 +1,316 @@
package agent
import (
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/dagu-org/dagu/internal/digraph"
"github.com/dagu-org/dagu/internal/digraph/scheduler"
"github.com/dagu-org/dagu/internal/models"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestProgressModel_Init(t *testing.T) {
dag := &digraph.DAG{
Name: "test-dag",
Steps: []digraph.Step{
{Name: "step1"},
{Name: "step2"},
},
}
model := NewProgressModel(dag)
// Test initialization
assert.Equal(t, "test-dag", model.dag.Name)
assert.Len(t, model.nodes, 2)
assert.NotNil(t, model.nodes["step1"])
assert.NotNil(t, model.nodes["step2"])
assert.Equal(t, scheduler.NodeStatusNone, model.nodes["step1"].status)
assert.Equal(t, scheduler.NodeStatusNone, model.nodes["step2"].status)
// Test Init command
cmd := model.Init()
assert.NotNil(t, cmd)
}
func TestProgressModel_UpdateNode(t *testing.T) {
dag := &digraph.DAG{
Name: "test-dag",
Steps: []digraph.Step{
{Name: "step1"},
},
}
model := NewProgressModel(dag)
// Update node status
node := &models.Node{
Step: digraph.Step{Name: "step1"},
Status: scheduler.NodeStatusRunning,
StartedAt: time.Now().Format(time.RFC3339),
}
updatedModel, _ := model.Update(NodeUpdateMsg{Node: node})
m := updatedModel.(ProgressModel)
assert.Equal(t, scheduler.NodeStatusRunning, m.nodes["step1"].status)
assert.False(t, m.nodes["step1"].startTime.IsZero())
}
func TestProgressModel_UpdateStatus(t *testing.T) {
dag := &digraph.DAG{Name: "test-dag"}
model := NewProgressModel(dag)
status := &models.DAGRunStatus{
DAGRunID: "run-123",
Params: "KEY=value",
Status: scheduler.StatusRunning,
}
updatedModel, _ := model.Update(StatusUpdateMsg{Status: status})
m := updatedModel.(ProgressModel)
assert.Equal(t, "run-123", m.dagRunID)
assert.Equal(t, "KEY=value", m.params)
assert.Equal(t, scheduler.StatusRunning, m.status.Status)
}
func TestProgressModel_WindowResize(t *testing.T) {
dag := &digraph.DAG{Name: "test-dag"}
model := NewProgressModel(dag)
// Test window resize
updatedModel, _ := model.Update(tea.WindowSizeMsg{Width: 120, Height: 40})
m := updatedModel.(ProgressModel)
assert.Equal(t, 120, m.width)
assert.Equal(t, 40, m.height)
}
func TestProgressModel_View(t *testing.T) {
dag := &digraph.DAG{
Name: "test-dag",
Steps: []digraph.Step{
{Name: "step1"},
{Name: "step2"},
},
}
model := NewProgressModel(dag)
model.width = 80
model.height = 24
// Test initial view
view := model.View()
assert.Contains(t, view, "DAG: test-dag")
assert.Contains(t, view, "Status:")
assert.Contains(t, view, "Progress:")
assert.Contains(t, view, "0% (0/2 steps)")
assert.Contains(t, view, "Press Ctrl+C to stop")
}
func TestProgressModel_Finalize(t *testing.T) {
dag := &digraph.DAG{Name: "test-dag"}
model := NewProgressModel(dag)
// Test finalize
updatedModel, cmd := model.Update(FinalizeMsg{})
m := updatedModel.(ProgressModel)
assert.True(t, m.finalized)
assert.NotNil(t, cmd) // Should return tea.Quit
}
func TestProgressModel_ProgressCalculation(t *testing.T) {
dag := &digraph.DAG{
Name: "test-dag",
Steps: []digraph.Step{
{Name: "step1"},
{Name: "step2"},
{Name: "step3"},
{Name: "step4"},
},
}
model := NewProgressModel(dag)
model.width = 80
// Mark some steps as completed
model.nodes["step1"].status = scheduler.NodeStatusSuccess
model.nodes["step2"].status = scheduler.NodeStatusError
model.nodes["step3"].status = scheduler.NodeStatusRunning
model.nodes["step4"].status = scheduler.NodeStatusNone
view := model.View()
// 2 out of 4 steps completed (50%)
assert.Contains(t, view, "50% (2/4 steps)")
assert.Contains(t, view, "Currently Running:")
assert.Contains(t, view, "step3")
}
func TestProgressModel_StatusFormatting(t *testing.T) {
dag := &digraph.DAG{Name: "test-dag"}
model := NewProgressModel(dag)
tests := []struct {
status scheduler.Status
expected string
}{
{scheduler.StatusSuccess, "Success ✓"},
{scheduler.StatusError, "Failed ✗"},
{scheduler.StatusRunning, "Running ●"},
{scheduler.StatusCancel, "Cancelled ⚠"},
{scheduler.StatusQueued, "Queued ●"},
{scheduler.StatusNone, "Not Started ○"},
}
for _, tt := range tests {
result := model.formatStatus(tt.status)
// Strip ANSI codes for comparison
assert.Contains(t, result, tt.expected)
}
}
func TestProgressModel_NodeSorting(t *testing.T) {
// Test sorting by start time
now := time.Now()
nodes := []*nodeProgress{
{
node: &models.Node{Step: digraph.Step{Name: "b"}},
startTime: now.Add(2 * time.Second),
},
{
node: &models.Node{Step: digraph.Step{Name: "a"}},
startTime: now.Add(1 * time.Second),
},
{
node: &models.Node{Step: digraph.Step{Name: "c"}},
startTime: now,
},
}
sortNodesByStartTime(nodes)
assert.Equal(t, "c", nodes[0].node.Step.Name)
assert.Equal(t, "a", nodes[1].node.Step.Name)
assert.Equal(t, "b", nodes[2].node.Step.Name)
}
func TestProgressModel_DurationFormatting(t *testing.T) {
tests := []struct {
duration time.Duration
expected string
}{
{500 * time.Millisecond, "500ms"},
{5 * time.Second, "5.0s"},
{2*time.Minute + 30*time.Second, "2m 30s"},
{3*time.Hour + 15*time.Minute, "3h 15m"},
}
for _, tt := range tests {
result := formatDuration(tt.duration)
assert.Equal(t, tt.expected, result)
}
}
func TestProgressModel_TruncateString(t *testing.T) {
tests := []struct {
input string
maxLen int
expected string
}{
{"hello", 10, "hello"},
{"hello world", 8, "hello..."},
{"test", 4, "test"}, // String equal to maxLen should not be truncated
{"testing", 4, "t..."}, // String longer than maxLen should be truncated
{"", 5, ""},
}
for _, tt := range tests {
result := truncateString(tt.input, tt.maxLen)
assert.Equal(t, tt.expected, result)
}
}
func TestProgressTeaDisplay_Integration(t *testing.T) {
dag := &digraph.DAG{
Name: "test-dag",
Steps: []digraph.Step{
{Name: "step1"},
{Name: "step2"},
},
}
display := NewProgressTeaDisplay(dag)
require.NotNil(t, display)
// Set DAG run info
display.SetDAGRunInfo("run-123", "KEY=value")
// Update a node
node := &models.Node{
Step: digraph.Step{Name: "step1"},
Status: scheduler.NodeStatusRunning,
StartedAt: time.Now().Format(time.RFC3339),
}
display.UpdateNode(node)
// Update status
status := &models.DAGRunStatus{
DAGRunID: "run-123",
Status: scheduler.StatusRunning,
}
display.UpdateStatus(status)
}
func TestProgressModel_ChildDAGsRendering(t *testing.T) {
dag := &digraph.DAG{
Name: "test-dag",
Steps: []digraph.Step{
{Name: "parent-step"},
},
}
model := NewProgressModel(dag)
model.width = 80
// Add child DAG info
model.nodes["parent-step"].children = []models.ChildDAGRun{
{
DAGRunID: "child-run-1",
Params: "CHILD_KEY=value",
},
}
view := model.View()
assert.Contains(t, view, "Child DAGs:")
assert.Contains(t, view, "parent-step")
assert.Contains(t, view, "child-run-1")
}
func TestProgressModel_ErrorDisplay(t *testing.T) {
dag := &digraph.DAG{
Name: "test-dag",
Steps: []digraph.Step{
{Name: "failing-step"},
},
}
model := NewProgressModel(dag)
model.width = 100
// Mark step as failed with error
model.nodes["failing-step"].status = scheduler.NodeStatusError
model.nodes["failing-step"].node.Error = "Connection timeout"
model.nodes["failing-step"].endTime = time.Now()
model.nodes["failing-step"].startTime = time.Now().Add(-5 * time.Second)
view := model.View()
assert.Contains(t, view, "Recently Completed:")
assert.Contains(t, view, "failing-step")
assert.Contains(t, view, "Error: Connection timeout")
}
-297
View File
@@ -1,297 +0,0 @@
package agent
import (
"bytes"
"strings"
"testing"
"time"
"github.com/dagu-org/dagu/internal/digraph"
"github.com/dagu-org/dagu/internal/digraph/scheduler"
"github.com/dagu-org/dagu/internal/models"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestProgressDisplay_SetDAGRunInfo(t *testing.T) {
var buf bytes.Buffer
dag := &digraph.DAG{Name: "test-dag"}
pd := NewProgressDisplay(&buf, dag)
dagRunID := "test-run-123"
params := "ENV=production DEBUG=true"
pd.SetDAGRunInfo(dagRunID, params)
// Verify the values were set
pd.mu.Lock()
assert.Equal(t, dagRunID, pd.dagRunID)
assert.Equal(t, params, pd.params)
pd.mu.Unlock()
}
func TestProgressDisplay_UpdateStatus_WithDAGRunInfo(t *testing.T) {
var buf bytes.Buffer
dag := &digraph.DAG{Name: "test-dag"}
pd := NewProgressDisplay(&buf, dag)
pd.isEnabled = true // Enable the progress display for testing
status := &models.DAGRunStatus{
DAGRunID: "status-run-456",
Params: "BATCH_SIZE=100 MODE=async",
Status: scheduler.StatusRunning,
}
pd.UpdateStatus(status)
// Verify the DAG run info was updated from status
pd.mu.Lock()
assert.Equal(t, "status-run-456", pd.dagRunID)
assert.Equal(t, "BATCH_SIZE=100 MODE=async", pd.params)
pd.mu.Unlock()
}
func TestProgressDisplay_RenderHeader_WithDAGRunInfo(t *testing.T) {
tests := []struct {
name string
dagName string
dagRunID string
params string
termWidth int
wantRunID bool
wantParams bool
}{
{
name: "Display both run ID and params",
dagName: "test-dag",
dagRunID: "abc123-def456",
params: "ENV=prod DEBUG=false",
termWidth: 80,
wantRunID: true,
wantParams: true,
},
{
name: "Display only run ID when no params",
dagName: "test-dag",
dagRunID: "xyz789",
params: "",
termWidth: 80,
wantRunID: true,
wantParams: false,
},
{
name: "No run ID or params",
dagName: "test-dag",
dagRunID: "",
params: "",
termWidth: 80,
wantRunID: false,
wantParams: false,
},
{
name: "Long params are truncated",
dagName: "test-dag",
dagRunID: "run-123",
params: "VERY_LONG_PARAMETER_NAME=value1 ANOTHER_LONG_PARAMETER=value2 YET_ANOTHER_PARAM=value3",
termWidth: 60,
wantRunID: true,
wantParams: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
dag := &digraph.DAG{Name: tt.dagName}
pd := NewProgressDisplay(&buf, dag)
pd.termWidth = tt.termWidth
pd.termHeight = 24
pd.startTime = time.Now()
pd.dagRunID = tt.dagRunID
pd.params = tt.params
// Set a default status
pd.status = &models.DAGRunStatus{
Status: scheduler.StatusRunning,
}
// Render the header
pd.renderHeader()
output := buf.String()
lines := strings.Split(strings.TrimSpace(output), "\n")
// Check for Run ID line
hasRunID := false
hasParams := false
for _, line := range lines {
if strings.Contains(line, "Run ID:") {
hasRunID = true
if tt.wantRunID {
assert.Contains(t, line, tt.dagRunID)
}
}
if strings.Contains(line, "Params:") {
hasParams = true
if tt.wantParams && len(tt.params) < tt.termWidth-12 {
// If params fit, they should be shown in full
assert.Contains(t, line, tt.params)
} else if tt.wantParams {
// If params are long, they should be truncated
assert.Contains(t, line, "...")
}
}
}
assert.Equal(t, tt.wantRunID, hasRunID, "Run ID presence mismatch")
assert.Equal(t, tt.wantParams, hasParams, "Params presence mismatch")
// Verify box structure is maintained
assert.True(t, strings.HasPrefix(lines[0], "┌"), "First line should start with top-left corner")
assert.True(t, strings.HasSuffix(lines[0], "┐"), "First line should end with top-right corner")
assert.True(t, strings.HasPrefix(lines[len(lines)-1], "└"), "Last line should start with bottom-left corner")
assert.True(t, strings.HasSuffix(lines[len(lines)-1], "┘"), "Last line should end with bottom-right corner")
// Check all middle lines have proper borders
for i := 1; i < len(lines)-1; i++ {
assert.True(t, strings.HasPrefix(lines[i], "│"), "Line %d should start with vertical bar", i+1)
assert.True(t, strings.HasSuffix(lines[i], "│"), "Line %d should end with vertical bar", i+1)
}
})
}
}
func TestProgressDisplay_HeaderFormatting(t *testing.T) {
var buf bytes.Buffer
dag := &digraph.DAG{
Name: "data-pipeline",
Params: []string{"ENV=staging", "VERSION=2.0"},
}
pd := NewProgressDisplay(&buf, dag)
pd.termWidth = 100
pd.termHeight = 30
pd.startTime = time.Now()
pd.SetDAGRunInfo("pipeline-run-12345", "ENV=staging VERSION=2.0")
// Set status
pd.status = &models.DAGRunStatus{
Status: scheduler.StatusSuccess,
DAGRunID: "pipeline-run-12345",
Params: "ENV=staging VERSION=2.0",
}
// Render header
pd.renderHeader()
output := buf.String()
// Verify the output contains expected information
assert.Contains(t, output, "DAG: data-pipeline")
assert.Contains(t, output, "Status:")
assert.Contains(t, output, "Success ✓")
assert.Contains(t, output, "Run ID: pipeline-run-12345")
assert.Contains(t, output, "Params: ENV=staging VERSION=2.0")
assert.Contains(t, output, "Started:")
assert.Contains(t, output, "Elapsed:")
}
func TestProgressDisplay_Integration(t *testing.T) {
var buf bytes.Buffer
dag := &digraph.DAG{
Name: "integration-test",
Steps: []digraph.Step{
{Name: "setup"},
{Name: "process"},
{Name: "cleanup"},
},
Params: []string{"MODE=test"},
}
pd := NewProgressDisplay(&buf, dag)
pd.termWidth = 80
pd.termHeight = 24
// Simulate agent setting DAG run info
pd.SetDAGRunInfo("test-run-789", "MODE=test")
// Simulate status update
status := &models.DAGRunStatus{
Name: "integration-test",
DAGRunID: "test-run-789",
Params: "MODE=test",
Status: scheduler.StatusRunning,
Nodes: []*models.Node{
{
Step: digraph.Step{Name: "setup"},
Status: scheduler.NodeStatusSuccess,
},
{
Step: digraph.Step{Name: "process"},
Status: scheduler.NodeStatusRunning,
},
{
Step: digraph.Step{Name: "cleanup"},
Status: scheduler.NodeStatusNone,
},
},
}
pd.UpdateStatus(status)
// Update nodes - make sure to update the internal node status
pd.mu.Lock()
for _, node := range status.Nodes {
if np, exists := pd.nodes[node.Step.Name]; exists {
np.status = node.Status
np.node = node
}
}
pd.mu.Unlock()
// Render the display
pd.mu.Lock()
pd.renderHeader()
pd.renderProgressBar()
pd.mu.Unlock()
output := buf.String()
// Verify output contains all expected elements
require.Contains(t, output, "integration-test")
require.Contains(t, output, "test-run-789")
require.Contains(t, output, "MODE=test")
require.Contains(t, output, "Progress:")
require.Contains(t, output, "(1/3 steps)") // Shows completed count
}
// Test helper function
func TestStripANSI(t *testing.T) {
tests := []struct {
input string
expected string
}{
{
input: "plain text",
expected: "plain text",
},
{
input: "\033[31mred text\033[0m",
expected: "red text",
},
{
input: "\033[1;32mgreen bold\033[0m and \033[33myellow\033[0m",
expected: "green bold and yellow",
},
{
input: "Status: \033[32mSuccess ✓\033[0m",
expected: "Status: Success ✓",
},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
result := stripANSI(tt.input)
assert.Equal(t, tt.expected, result)
})
}
}
+488
View File
@@ -0,0 +1,488 @@
package dagpicker
import (
"bufio"
"context"
"fmt"
"os"
"strings"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/dagu-org/dagu/internal/digraph"
"github.com/dagu-org/dagu/internal/models"
)
var docStyle = lipgloss.NewStyle().Margin(1, 2)
// State represents the current state of the picker
type State int
const (
StateSelectingDAG State = iota
StateEnteringParams
StateConfirming
StateDone
)
// DAGItem represents a DAG in the list
type DAGItem struct {
Name string
Path string // Path is stored but not displayed
Desc string
Tags []string
Params string // Parameters that the DAG accepts
}
func (i DAGItem) Title() string {
title := i.Name
if len(i.Tags) > 0 {
title += " [" + strings.Join(i.Tags, ", ") + "]"
}
return title
}
func (i DAGItem) Description() string {
desc := i.Desc
if i.Params != "" {
if desc != "" {
desc += " | params: " + i.Params
} else {
desc = "params: " + i.Params
}
}
return desc
}
func (i DAGItem) FilterValue() string { return i.Name }
// Model represents the state of the DAG picker
type Model struct {
// State management
state State
// DAG selection
list list.Model
choice *DAGItem
// Parameter input
paramInput textinput.Model
dag *digraph.DAG
params string
// Confirmation
confirmed bool
// General
quitting bool
width int
height int
}
// Result contains the final selections
type Result struct {
DAGName string
DAGPath string
Params string
Cancelled bool
}
// Init initializes the model
func (m Model) Init() tea.Cmd {
return textinput.Blink
}
// Update handles messages
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Handle global keys first
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
h, v := docStyle.GetFrameSize()
m.list.SetSize(msg.Width-h, msg.Height-v)
return m, nil
case tea.KeyMsg:
// Ctrl+C quits from any state
if key.Matches(msg, key.NewBinding(key.WithKeys("ctrl+c"))) {
m.quitting = true
m.state = StateDone
return m, tea.Quit
}
}
// Handle state-specific updates
switch m.state {
case StateSelectingDAG:
return m.updateDAGSelection(msg)
case StateEnteringParams:
return m.updateParamInput(msg)
case StateConfirming:
return m.updateConfirmation(msg)
case StateDone:
return m, tea.Quit
default:
return m, nil
}
}
func (m Model) updateDAGSelection(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "esc":
m.quitting = true
m.state = StateDone
return m, tea.Quit
case "enter":
if item, ok := m.list.SelectedItem().(DAGItem); ok {
m.choice = &item
// Check if the selected DAG has parameters
hasParams := item.Params != ""
if hasParams {
m.state = StateEnteringParams
// Initialize parameter input with the display params
m.paramInput.SetValue(item.Params)
return m, textinput.Blink
} else {
// Skip to confirmation if no params needed
m.state = StateConfirming
return m, nil
}
}
}
}
var cmd tea.Cmd
m.list, cmd = m.list.Update(msg)
return m, cmd
}
func (m Model) updateParamInput(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "esc":
// Go back to DAG selection
m.state = StateSelectingDAG
return m, nil
case "enter":
m.params = m.paramInput.Value()
m.state = StateConfirming
return m, nil
}
}
var cmd tea.Cmd
m.paramInput, cmd = m.paramInput.Update(msg)
return m, cmd
}
func (m Model) updateConfirmation(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch strings.ToLower(msg.String()) {
case "esc":
// Go back to parameter input or DAG selection
hasParams := m.choice != nil && m.choice.Params != ""
if hasParams {
m.state = StateEnteringParams
} else {
m.state = StateSelectingDAG
}
return m, nil
case "y", "enter":
m.confirmed = true
m.state = StateDone
return m, tea.Quit
case "n":
// Cancel and exit
m.quitting = true
m.state = StateDone
return m, tea.Quit
}
}
return m, nil
}
// View renders the UI
func (m Model) View() string {
if m.state == StateDone {
return ""
}
switch m.state {
case StateSelectingDAG:
return m.viewDAGSelection()
case StateEnteringParams:
return m.viewParamInput()
case StateConfirming:
return m.viewConfirmation()
case StateDone:
return ""
default:
return ""
}
}
func (m Model) viewDAGSelection() string {
return docStyle.Render(m.list.View())
}
func (m Model) viewParamInput() string {
// Define styles
titleStyle := lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("170")).
MarginBottom(1)
selectedDAGStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("214")).
MarginBottom(2)
helpStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("241")).
MarginTop(2)
content := lipgloss.JoinVertical(lipgloss.Left,
titleStyle.Render("Enter Parameters"),
selectedDAGStyle.Render(fmt.Sprintf("DAG: %s", m.choice.Name)),
"",
m.paramInput.View(),
"",
helpStyle.Render("Enter: Confirm • ESC: Back • Ctrl+C: Cancel"),
)
return docStyle.Render(content)
}
func (m Model) viewConfirmation() string {
// Define styles
titleStyle := lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("170")).
MarginBottom(2)
dagNameStyle := lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("214"))
paramStyle := lipgloss.NewStyle().
Italic(true).
Foreground(lipgloss.Color("243"))
promptStyle := lipgloss.NewStyle().
Bold(true).
MarginTop(2)
helpStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("241")).
MarginTop(1)
var content []string
content = append(content, titleStyle.Render("Confirm Execution"))
content = append(content, fmt.Sprintf("Ready to run DAG: %s", dagNameStyle.Render(m.choice.Name)))
if m.params != "" {
content = append(content, fmt.Sprintf("With parameters: %s", paramStyle.Render(m.params)))
}
content = append(content, "")
content = append(content, promptStyle.Render("Run this DAG? [Y/n]"))
content = append(content, helpStyle.Render("Y/Enter: Run • N: Cancel • ESC: Back"))
return docStyle.Render(lipgloss.JoinVertical(lipgloss.Left, content...))
}
// pickerModel holds context data for the picker
type pickerModel struct {
ctx context.Context
dagStore models.DAGStore
dagMap map[string]*digraph.DAG
}
// PickDAGInteractive shows a unified fullscreen UI for DAG selection, parameter input, and confirmation
func PickDAGInteractive(ctx context.Context, dagStore models.DAGStore, dag *digraph.DAG) (Result, error) {
// Create an internal picker model
pickerModel := &pickerModel{
ctx: ctx,
dagStore: dagStore,
dagMap: make(map[string]*digraph.DAG),
}
// Get list of DAGs
result, errs, err := dagStore.List(ctx, models.ListDAGsOptions{})
if err != nil {
return Result{}, fmt.Errorf("failed to list DAGs: %w", err)
}
if len(errs) > 0 {
// Log errors but continue
for _, e := range errs {
fmt.Printf("Warning: %s\n", e)
}
}
if len(result.Items) == 0 {
return Result{}, fmt.Errorf("no DAGs found in the configured directory")
}
// Convert DAGs to list items
items := make([]list.Item, 0, len(result.Items))
for _, d := range result.Items {
// Format parameters for display
var params string
if d.DefaultParams != "" {
params = d.DefaultParams
} else if len(d.Params) > 0 {
params = strings.Join(d.Params, " ")
}
item := DAGItem{
Name: d.Name,
Path: d.Location,
Desc: d.Description,
Tags: d.Tags,
Params: params,
}
items = append(items, item)
pickerModel.dagMap[d.Name] = d
}
// Create list with custom delegate for better rendering
l := list.New(items, list.NewDefaultDelegate(), 80, 20)
l.Title = "Select a DAG to run"
l.SetShowStatusBar(true)
l.SetStatusBarItemName("DAG", "DAGs")
l.SetFilteringEnabled(true)
l.SetShowHelp(true)
l.SetShowTitle(true)
l.DisableQuitKeybindings()
// Style the title
l.Styles.Title = lipgloss.NewStyle().
Background(lipgloss.Color("#6B46C1")).
Foreground(lipgloss.Color("#FFFDF5")).
Padding(0, 1)
// Initialize parameter input
ti := textinput.New()
ti.Placeholder = "Enter parameters..."
ti.Focus()
ti.CharLimit = 1024
ti.Width = 60
m := Model{
state: StateSelectingDAG,
list: l,
paramInput: ti,
dag: dag,
}
// Use the default delegate since we'll handle DAG updates differently
m.list.SetDelegate(list.NewDefaultDelegate())
// Run the picker
p := tea.NewProgram(m, tea.WithAltScreen())
finalModel, err := p.Run()
if err != nil {
return Result{}, fmt.Errorf("failed to run DAG picker: %w", err)
}
// Get the selection
finalM, ok := finalModel.(Model)
if !ok {
return Result{}, fmt.Errorf("unexpected model type")
}
// Build result
if finalM.quitting || finalM.choice == nil {
return Result{Cancelled: true}, nil
}
return Result{
DAGName: finalM.choice.Name,
DAGPath: finalM.choice.Path,
Params: finalM.params,
Cancelled: false,
}, nil
}
// PickDAG shows an interactive DAG picker and returns the selected DAG path
// Deprecated: Use PickDAGInteractive instead for a better user experience
func PickDAG(ctx context.Context, dagStore models.DAGStore) (string, error) {
result, err := PickDAGInteractive(ctx, dagStore, nil)
if err != nil {
return "", err
}
if result.Cancelled {
fmt.Println("No DAG selected.")
os.Exit(0)
}
return result.DAGPath, nil
}
// PromptForParams prompts the user to enter parameters for a DAG
func PromptForParams(dag *digraph.DAG) (string, error) {
if dag.DefaultParams == "" && len(dag.Params) == 0 {
return "", nil
}
fmt.Println("\nThis DAG accepts the following parameters:")
// Display default parameters if available
if dag.DefaultParams != "" {
fmt.Printf(" Default: %s\n", dag.DefaultParams)
}
// Display current parameters if available
if len(dag.Params) > 0 {
fmt.Printf(" Current: %s\n", strings.Join(dag.Params, " "))
}
fmt.Print("\nEnter parameters (press Enter to use defaults): ")
// Read full line of input
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
return "", fmt.Errorf("failed to read input: %w", err)
}
// Trim whitespace and return
return strings.TrimSpace(input), nil
}
// ConfirmRunDAG prompts the user for Y/n confirmation before running a DAG
func ConfirmRunDAG(dagName string, params string) (bool, error) {
// Build confirmation message
fmt.Println()
fmt.Printf("Ready to run DAG: %s\n", lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("170")).Render(dagName))
if params != "" {
fmt.Printf("With parameters: %s\n", lipgloss.NewStyle().Italic(true).Foreground(lipgloss.Color("214")).Render(params))
}
fmt.Print("\nRun this DAG? [Y/n]: ")
// Read user input
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
return false, fmt.Errorf("failed to read input: %w", err)
}
// Trim and convert to lowercase
response := strings.ToLower(strings.TrimSpace(input))
// Accept 'y', 'yes', or empty (default to yes)
return response == "" || response == "y" || response == "yes", nil
}
+486
View File
@@ -0,0 +1,486 @@
package dagpicker
import (
"context"
"errors"
"os"
"strings"
"testing"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/dagu-org/dagu/internal/digraph"
"github.com/dagu-org/dagu/internal/models"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestDAGItem(t *testing.T) {
t.Run("DAGItem implements list.Item interface", func(t *testing.T) {
item := DAGItem{
Name: "test-dag",
Path: "/path/to/test.yaml",
Desc: "Test DAG description",
Tags: []string{"test", "example"},
Params: "KEY1=value1 KEY2=value2",
}
assert.Equal(t, "test-dag [test, example]", item.Title())
assert.Equal(t, "Test DAG description | params: KEY1=value1 KEY2=value2", item.Description())
assert.Equal(t, "test-dag", item.FilterValue())
})
t.Run("DAGItem with empty description but params", func(t *testing.T) {
item := DAGItem{
Name: "test-dag",
Path: "/path/to/test.yaml",
Desc: "",
Tags: []string{"test"},
Params: "KEY=value",
}
assert.Equal(t, "params: KEY=value", item.Description())
})
t.Run("DAGItem with description but no params", func(t *testing.T) {
item := DAGItem{
Name: "test-dag",
Path: "/path/to/test.yaml",
Desc: "Just a description",
Tags: []string{"test"},
Params: "",
}
assert.Equal(t, "Just a description", item.Description())
})
}
func TestPromptForParams(t *testing.T) {
t.Run("Returns empty string when DAG has no parameters", func(t *testing.T) {
dag := &digraph.DAG{
DefaultParams: "",
Params: []string{},
}
params, err := PromptForParams(dag)
assert.NoError(t, err)
assert.Empty(t, params)
})
t.Run("DAG with default parameters", func(_ *testing.T) {
dag := &digraph.DAG{
DefaultParams: "KEY1=value1 KEY2=value2",
Params: []string{},
}
// Note: This test won't actually prompt for input in a test environment
// It's mainly to ensure the function doesn't panic with valid input
_ = dag
})
}
func TestModel(t *testing.T) {
t.Run("Model initialization", func(t *testing.T) {
ti := textinput.New()
m := Model{
paramInput: ti,
}
cmd := m.Init()
assert.NotNil(t, cmd) // Now returns textinput.Blink
})
t.Run("Model view when done", func(t *testing.T) {
m := Model{
state: StateDone,
}
view := m.View()
assert.Equal(t, "", view)
})
t.Run("Model view in selecting state", func(t *testing.T) {
items := []list.Item{
DAGItem{Name: "test", Desc: "Test DAG"},
}
l := list.New(items, list.NewDefaultDelegate(), 80, 20)
m := Model{
state: StateSelectingDAG,
list: l,
}
view := m.View()
assert.Contains(t, view, "test") // Should show the DAG name
assert.Contains(t, view, "Test DAG") // Should show the description
})
t.Run("Model handles escape key in DAG selection", func(t *testing.T) {
items := []list.Item{
DAGItem{Name: "test", Desc: "Test DAG"},
}
l := list.New(items, list.NewDefaultDelegate(), 80, 20)
m := Model{
state: StateSelectingDAG,
list: l,
}
escMsg := tea.KeyMsg{Type: tea.KeyEsc}
updatedModel, cmd := m.Update(escMsg)
updatedM := updatedModel.(Model)
assert.True(t, updatedM.quitting)
assert.Equal(t, StateDone, updatedM.state)
assert.NotNil(t, cmd)
})
t.Run("Model handles ctrl+c", func(t *testing.T) {
m := Model{
state: StateSelectingDAG,
}
ctrlCMsg := tea.KeyMsg{Type: tea.KeyCtrlC}
updatedModel, cmd := m.Update(ctrlCMsg)
updatedM := updatedModel.(Model)
assert.True(t, updatedM.quitting)
assert.Equal(t, StateDone, updatedM.state)
assert.NotNil(t, cmd)
})
t.Run("Model handles window size", func(t *testing.T) {
// Create a model with an initialized list
items := []list.Item{
DAGItem{Name: "test", Desc: "Test DAG"},
}
l := list.New(items, list.NewDefaultDelegate(), 80, 20)
m := Model{
list: l,
}
sizeMsg := tea.WindowSizeMsg{Width: 100, Height: 50}
_, cmd := m.Update(sizeMsg)
assert.Nil(t, cmd)
})
}
// mockDAGStore is a mock implementation of models.DAGStore
type mockDAGStore struct {
mock.Mock
}
func (m *mockDAGStore) Create(ctx context.Context, fileName string, spec []byte) error {
args := m.Called(ctx, fileName, spec)
return args.Error(0)
}
func (m *mockDAGStore) Delete(ctx context.Context, fileName string) error {
args := m.Called(ctx, fileName)
return args.Error(0)
}
func (m *mockDAGStore) List(ctx context.Context, params models.ListDAGsOptions) (models.PaginatedResult[*digraph.DAG], []string, error) {
args := m.Called(ctx, params)
return args.Get(0).(models.PaginatedResult[*digraph.DAG]), args.Get(1).([]string), args.Error(2)
}
func (m *mockDAGStore) GetMetadata(ctx context.Context, fileName string) (*digraph.DAG, error) {
args := m.Called(ctx, fileName)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*digraph.DAG), args.Error(1)
}
func (m *mockDAGStore) GetDetails(ctx context.Context, fileName string, opts ...digraph.LoadOption) (*digraph.DAG, error) {
args := m.Called(ctx, fileName, opts)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*digraph.DAG), args.Error(1)
}
func (m *mockDAGStore) Grep(ctx context.Context, pattern string) ([]*models.GrepDAGsResult, []string, error) {
args := m.Called(ctx, pattern)
return args.Get(0).([]*models.GrepDAGsResult), args.Get(1).([]string), args.Error(2)
}
func (m *mockDAGStore) Rename(ctx context.Context, oldID, newID string) error {
args := m.Called(ctx, oldID, newID)
return args.Error(0)
}
func (m *mockDAGStore) GetSpec(ctx context.Context, fileName string) (string, error) {
args := m.Called(ctx, fileName)
return args.String(0), args.Error(1)
}
func (m *mockDAGStore) UpdateSpec(ctx context.Context, fileName string, spec []byte) error {
args := m.Called(ctx, fileName, spec)
return args.Error(0)
}
func (m *mockDAGStore) LoadSpec(ctx context.Context, spec []byte, opts ...digraph.LoadOption) (*digraph.DAG, error) {
args := m.Called(ctx, spec, opts)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*digraph.DAG), args.Error(1)
}
func (m *mockDAGStore) TagList(ctx context.Context) ([]string, []string, error) {
args := m.Called(ctx)
return args.Get(0).([]string), args.Get(1).([]string), args.Error(2)
}
func (m *mockDAGStore) ToggleSuspend(ctx context.Context, fileName string, suspend bool) error {
args := m.Called(ctx, fileName, suspend)
return args.Error(0)
}
func (m *mockDAGStore) IsSuspended(ctx context.Context, fileName string) bool {
args := m.Called(ctx, fileName)
return args.Bool(0)
}
func TestPickDAG(t *testing.T) {
t.Run("Returns error when DAG store fails", func(t *testing.T) {
mockStore := new(mockDAGStore)
ctx := context.Background()
mockStore.On("List", ctx, models.ListDAGsOptions{}).Return(
models.PaginatedResult[*digraph.DAG]{},
[]string{},
errors.New("database error"),
)
_, err := PickDAG(ctx, mockStore)
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to list DAGs")
mockStore.AssertExpectations(t)
})
t.Run("Returns error when no DAGs found", func(t *testing.T) {
mockStore := new(mockDAGStore)
ctx := context.Background()
mockStore.On("List", ctx, models.ListDAGsOptions{}).Return(
models.PaginatedResult[*digraph.DAG]{
Items: []*digraph.DAG{},
},
[]string{},
nil,
)
_, err := PickDAG(ctx, mockStore)
assert.Error(t, err)
assert.Contains(t, err.Error(), "no DAGs found")
mockStore.AssertExpectations(t)
})
t.Run("Handles DAGs with warnings", func(t *testing.T) {
// This test would require mocking the entire terminal UI interaction
// which is complex and not practical for unit tests
t.Skip("Interactive UI testing requires terminal mocking")
})
t.Run("Creates proper DAGItems from DAGs", func(t *testing.T) {
// This tests the internal logic of converting DAGs to list items
dags := []*digraph.DAG{
{
Name: "dag1",
Location: "/path/to/dag1.yaml",
Description: "First DAG",
Tags: []string{"production", "critical"},
},
{
Name: "dag2",
Location: "/path/to/dag2.yaml",
Description: "Second DAG",
Tags: []string{"test"},
},
}
// Convert to DAGItems
items := make([]DAGItem, 0, len(dags))
for _, dag := range dags {
// Format parameters for display
var params string
if dag.DefaultParams != "" {
params = dag.DefaultParams
} else if len(dag.Params) > 0 {
params = strings.Join(dag.Params, " ")
}
items = append(items, DAGItem{
Name: dag.Name,
Path: dag.Location,
Desc: dag.Description,
Tags: dag.Tags,
Params: params,
})
}
assert.Len(t, items, 2)
assert.Equal(t, "dag1", items[0].Name)
assert.Equal(t, "/path/to/dag1.yaml", items[0].Path)
assert.Equal(t, "First DAG", items[0].Desc)
assert.Equal(t, []string{"production", "critical"}, items[0].Tags)
})
}
func TestPromptForParamsReturnsInput(t *testing.T) {
t.Run("Returns user input as-is", func(t *testing.T) {
// This test verifies that PromptForParams returns the input without modification
// In a real test, we would mock stdin, but for now we just verify the concept
// Test cases showing what kind of input would be returned
testInputs := []string{
"KEY1=value1 KEY2=value2",
`{"key": "value", "nested": {"item": 123}}`,
"some free text parameter",
"KEY=value with spaces",
"",
}
for _, input := range testInputs {
// In the actual function, strings.TrimSpace(input) would be returned
expected := strings.TrimSpace(input)
assert.Equal(t, expected, strings.TrimSpace(input))
}
})
}
func TestConfirmRunDAG(t *testing.T) {
t.Run("AcceptWithY", func(t *testing.T) {
// Mock stdin and stdout
oldStdin := os.Stdin
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdin = r
// Redirect stdout to prevent interference with test output
_, stdoutW, _ := os.Pipe()
os.Stdout = stdoutW
defer func() {
os.Stdin = oldStdin
os.Stdout = oldStdout
_ = r.Close()
_ = stdoutW.Close()
}()
go func() {
_, _ = w.WriteString("y\n")
_ = w.Close()
}()
confirmed, err := ConfirmRunDAG("test-dag", "param1=value1")
assert.NoError(t, err)
assert.True(t, confirmed)
})
t.Run("AcceptWithYes", func(t *testing.T) {
// Mock stdin and stdout
oldStdin := os.Stdin
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdin = r
// Redirect stdout to prevent interference with test output
_, stdoutW, _ := os.Pipe()
os.Stdout = stdoutW
defer func() {
os.Stdin = oldStdin
os.Stdout = oldStdout
_ = r.Close()
_ = stdoutW.Close()
}()
go func() {
_, _ = w.WriteString("yes\n")
_ = w.Close()
}()
confirmed, err := ConfirmRunDAG("test-dag", "")
assert.NoError(t, err)
assert.True(t, confirmed)
})
t.Run("AcceptWithEmpty", func(t *testing.T) {
// Mock stdin and stdout
oldStdin := os.Stdin
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdin = r
// Redirect stdout to prevent interference with test output
_, stdoutW, _ := os.Pipe()
os.Stdout = stdoutW
defer func() {
os.Stdin = oldStdin
os.Stdout = oldStdout
_ = r.Close()
_ = stdoutW.Close()
}()
go func() {
_, _ = w.WriteString("\n")
_ = w.Close()
}()
confirmed, err := ConfirmRunDAG("test-dag", "param1=value1")
assert.NoError(t, err)
assert.True(t, confirmed)
})
t.Run("RejectWithN", func(t *testing.T) {
// Mock stdin and stdout
oldStdin := os.Stdin
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdin = r
// Redirect stdout to prevent interference with test output
_, stdoutW, _ := os.Pipe()
os.Stdout = stdoutW
defer func() {
os.Stdin = oldStdin
os.Stdout = oldStdout
_ = r.Close()
_ = stdoutW.Close()
}()
go func() {
_, _ = w.WriteString("n\n")
_ = w.Close()
}()
confirmed, err := ConfirmRunDAG("test-dag", "")
assert.NoError(t, err)
assert.False(t, confirmed)
})
t.Run("RejectWithNo", func(t *testing.T) {
// Mock stdin and stdout
oldStdin := os.Stdin
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdin = r
// Redirect stdout to prevent interference with test output
_, stdoutW, _ := os.Pipe()
os.Stdout = stdoutW
defer func() {
os.Stdin = oldStdin
os.Stdout = oldStdout
_ = r.Close()
_ = stdoutW.Close()
}()
go func() {
_, _ = w.WriteString("no\n")
_ = w.Close()
}()
confirmed, err := ConfirmRunDAG("test-dag", "params here")
assert.NoError(t, err)
assert.False(t, confirmed)
})
}
+47 -5
View File
@@ -7,10 +7,12 @@ import (
"path/filepath"
"github.com/dagu-org/dagu/internal/agent"
"github.com/dagu-org/dagu/internal/cmd/dagpicker"
"github.com/dagu-org/dagu/internal/digraph"
"github.com/dagu-org/dagu/internal/logger"
"github.com/dagu-org/dagu/internal/models"
"github.com/spf13/cobra"
"golang.org/x/term"
"github.com/dagu-org/dagu/internal/stringutil"
)
@@ -46,7 +48,7 @@ Example:
This command parses the DAG definition, resolves parameters, and initiates the DAG-run execution.
`,
Args: cobra.MinimumNArgs(1),
Args: cobra.ArbitraryArgs,
}, startFlags, runStart,
)
}
@@ -163,8 +165,44 @@ func getDAGRunInfo(ctx *Context) (dagRunID, rootDAGRun, parentDAGRun string, isC
// loadDAGWithParams loads the DAG and its parameters from command arguments
func loadDAGWithParams(ctx *Context, args []string) (*digraph.DAG, string, error) {
var dagPath string
var interactiveParams string
// Check if DAG path is provided
if len(args) == 0 {
return nil, "", fmt.Errorf("DAG file path is required")
// Check if we're in an interactive terminal
if !term.IsTerminal(int(os.Stdin.Fd())) {
return nil, "", fmt.Errorf("DAG file path is required")
}
// Use interactive picker
logger.Info(ctx, "No DAG specified, opening interactive selector...")
// Get DAG store
dagStore, err := ctx.dagStore(nil, nil)
if err != nil {
return nil, "", fmt.Errorf("failed to initialize DAG store: %w", err)
}
// Load DAG metadata first to pass to the picker
// This will be updated when user selects a DAG
var tempDAG *digraph.DAG
// Show unified interactive UI
result, err := dagpicker.PickDAGInteractive(ctx, dagStore, tempDAG)
if err != nil {
return nil, "", err
}
if result.Cancelled {
fmt.Println("DAG execution cancelled.")
os.Exit(0)
}
dagPath = result.DAGPath
interactiveParams = result.Params
} else {
dagPath = args[0]
}
// Prepare load options with base configuration
@@ -178,9 +216,13 @@ func loadDAGWithParams(ctx *Context, args []string) (*digraph.DAG, string, error
var err error
// Check if parameters are provided after "--"
if argsLenAtDash := ctx.Command.ArgsLenAtDash(); argsLenAtDash != -1 {
if argsLenAtDash := ctx.Command.ArgsLenAtDash(); argsLenAtDash != -1 && len(args) > 0 {
// Get parameters from command line arguments after "--"
loadOpts = append(loadOpts, digraph.WithParams(args[argsLenAtDash:]))
} else if interactiveParams != "" {
// Use interactive parameters
loadOpts = append(loadOpts, digraph.WithParams(stringutil.RemoveQuotes(interactiveParams)))
params = interactiveParams
} else {
// Get parameters from flags
params, err = ctx.Command.Flags().GetString("params")
@@ -191,9 +233,9 @@ func loadDAGWithParams(ctx *Context, args []string) (*digraph.DAG, string, error
}
// Load the DAG from the specified file
dag, err := digraph.Load(ctx, args[0], loadOpts...)
dag, err := digraph.Load(ctx, dagPath, loadOpts...)
if err != nil {
return nil, "", fmt.Errorf("failed to load DAG from %s: %w", args[0], err)
return nil, "", fmt.Errorf("failed to load DAG from %s: %w", dagPath, err)
}
return dag, params, nil
+89
View File
@@ -1,10 +1,13 @@
package cmd_test
import (
"os"
"testing"
"github.com/dagu-org/dagu/internal/cmd"
"github.com/dagu-org/dagu/internal/test"
"github.com/stretchr/testify/require"
"golang.org/x/term"
)
func TestStartCommand(t *testing.T) {
@@ -44,3 +47,89 @@ func TestStartCommand(t *testing.T) {
})
}
}
func TestCmdStart_InteractiveMode(t *testing.T) {
t.Run("Non-TTY behavior", func(t *testing.T) {
// The command behavior depends on whether we're in a TTY
// In test environment (non-TTY), it should require a DAG path
// We can't fully test this without proper context setup
t.Skip("Requires context setup to test interactive mode behavior")
})
t.Run("Works with explicit DAG path", func(t *testing.T) {
// Create a test DAG
tmpDir := t.TempDir()
dagFile := tmpDir + "/test.yaml"
dagContent := `
name: test-dag
steps:
- name: step1
command: echo test
`
err := os.WriteFile(dagFile, []byte(dagContent), 0644)
require.NoError(t, err)
// Providing a DAG path should work
cmd := cmd.CmdStart()
cmd.SetArgs([]string{dagFile})
// The actual execution might fail for other reasons in test environment,
// but it should accept the DAG file argument
_ = cmd.Execute()
})
t.Run("Terminal detection function available", func(t *testing.T) {
// Verify that term.IsTerminal is available and doesn't panic
isTTY := term.IsTerminal(int(os.Stdin.Fd()))
require.False(t, isTTY, "Tests should not run in a TTY")
})
t.Run("Interactive mode info message", func(t *testing.T) {
// Verify the info message is appropriate
expectedMsg := "No DAG specified, opening interactive selector..."
require.Contains(t, expectedMsg, "interactive selector")
})
}
func TestCmdStart_BackwardCompatibility(t *testing.T) {
t.Run("Should accept parameters after --", func(t *testing.T) {
tmpDir := t.TempDir()
dagFile := tmpDir + "/test-params.yaml"
dagContent := `
name: test-params
params: KEY1=default1 KEY2=default2
steps:
- name: step1
command: echo $KEY1 $KEY2
`
err := os.WriteFile(dagFile, []byte(dagContent), 0644)
require.NoError(t, err)
cmd := cmd.CmdStart()
cmd.SetArgs([]string{dagFile, "--", "KEY1=value1", "KEY2=value2"})
// Execute will fail due to missing context setup, but we're testing
// that the command accepts the arguments
_ = cmd.Execute()
})
t.Run("Should accept --params flag", func(t *testing.T) {
tmpDir := t.TempDir()
dagFile := tmpDir + "/test-params-flag.yaml"
dagContent := `
name: test-params-flag
params: KEY=default
steps:
- name: step1
command: echo $KEY
`
err := os.WriteFile(dagFile, []byte(dagContent), 0644)
require.NoError(t, err)
cmd := cmd.CmdStart()
cmd.SetArgs([]string{dagFile, "--params", "KEY=value"})
// Execute will fail due to missing context setup, but we're testing
// that the command accepts the arguments
_ = cmd.Execute()
})
}
+6 -1
View File
@@ -301,7 +301,12 @@ func loadDAGsFromFile(ctx BuildContext, filePath string, baseDef *definition) ([
var dest *DAG
if baseDef != nil {
// Build a new base DAG for this document
baseDAG, err := build(ctx, baseDef)
buildCtx := ctx
// Don't parse parameters for the base DAG
buildCtx.opts.Parameters = ""
buildCtx.opts.ParametersList = nil
// Build the base DAG
baseDAG, err := build(buildCtx, baseDef)
if err != nil {
return nil, fmt.Errorf("failed to build base DAG for document %d: %w", docIndex, err)
}