feat: add generic approval field for human-in-the-loop on any step type (#1743)

This commit is contained in:
Yota Hamada authored and GitHub committed 2026-03-08 20:38:20 +09:00
1 parent 95b8bfb07e
commit f1b080319a
49 files changed
+3054 -1632

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ Dagu is a self-contained, single-binary workflow orchestration engine. Workflows
- **`core/`** — DAG and step definitions, validation, status types. The DAG spec is rich (~100 fields) supporting schedules, lifecycle hooks, container specs, parameters, and three execution types: `graph`, `chain`, `agent`.
- **`core/exec/`** — Interfaces for DAG run tracking, queue, and process stores (`DAGRunStore`, `QueueStore`, `ProcStore`, `Dispatcher`).
- **`runtime/`** — Execution engine. `runner.go` orchestrates parallel execution with dependency resolution. `node.go` manages individual step execution with retry logic. `manager.go` coordinates the overall lifecycle.
- **`runtime/builtin/`** — 19+ built-in executor implementations: `command`, `docker`, `http`, `ssh`, `jq`, `mail`, `sql`, `redis`, `s3`, `dag` (sub-DAG), `chat` (LLM), `router`, `hitl` (human-in-the-loop), `agentstep`, etc.
- **`runtime/builtin/`** — 18+ built-in executor implementations: `command`, `docker`, `http`, `ssh`, `jq`, `mail`, `sql`, `redis`, `s3`, `dag` (sub-DAG), `chat` (LLM), `router`, `agentstep`, etc.
- **`runtime/executor/`** — Executor factory pattern with global registry. Executors implement `Run(ctx) error` with stdout/stderr/kill support.
- **`persis/`** — File-based persistence layer. Each store type (`filedag`, `filedagrun`, `filequeue`, `fileproc`, `fileuser`, `filesession`, `fileaudit`, etc.) follows the same pattern: file I/O with structured data marshaling.
- **`service/frontend/`** — HTTP server using Chi router. REST API v1 with 43+ endpoint handlers, SSE for real-time updates, static asset serving. API handlers are in `api/v1/`.
+1 -1
View File
@@ -233,7 +233,7 @@ For more examples, see the [Examples](https://docs.dagu.sh/writing-workflows/exa
- [Distributed execution](https://docs.dagu.sh/features/distributed-execution) — coordinator/worker mode across machines
- [19+ built-in executors](https://docs.dagu.sh/reference/executors) — HTTP, SQL, Redis, S3, jq, mail, archive, and more
- [RBAC](https://docs.dagu.sh/configurations/authentication) with 5 roles, OIDC, API keys, and audit logging
- [Human-in-the-loop](https://docs.dagu.sh/writing-workflows/examples) approval gates
- [Approval gates](https://docs.dagu.sh/features/approval) on any step type
### AI-Native
+896 -485
View File
File diff suppressed because it is too large. Load diff
+166 -9
View File
@@ -2287,7 +2287,7 @@ paths:
/dag-runs/{name}/{dagRunId}/steps/{stepName}/approve:
post:
summary: "Approve a waiting step for HITL"
summary: "Approve a waiting step"
description: "Approves a step that is in Waiting status, optionally providing input parameters that will be available as environment variables in subsequent steps"
operationId: "approveDAGRunStep"
tags:
@@ -2331,7 +2331,7 @@ paths:
/dag-runs/{name}/{dagRunId}/steps/{stepName}/reject:
post:
summary: "Reject a waiting step for HITL"
summary: "Reject a waiting step"
description: "Rejects a step that is in Waiting status, optionally providing a reason for rejection"
operationId: "rejectDAGRunStep"
tags:
@@ -2373,6 +2373,50 @@ paths:
schema:
$ref: "#/components/schemas/Error"
/dag-runs/{name}/{dagRunId}/steps/{stepName}/push-back:
post:
summary: "Push back a waiting step for re-execution with feedback"
description: "Pushes back a step that is in Waiting status, providing input parameters that will be injected as environment variables when the step re-executes. The step must have an approval configuration."
operationId: "pushBackDAGRunStep"
tags:
- "dag-runs"
parameters:
- $ref: "#/components/parameters/RemoteNode"
- $ref: "#/components/parameters/DAGName"
- $ref: "#/components/parameters/DAGRunId"
- $ref: "#/components/parameters/StepName"
requestBody:
required: false
content:
application/json:
schema:
$ref: "#/components/schemas/PushBackStepRequest"
responses:
"200":
description: "Step pushed back successfully"
content:
application/json:
schema:
$ref: "#/components/schemas/PushBackStepResponse"
"400":
description: "Step is not in Waiting status, missing required inputs, or step does not have approval config"
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
"404":
description: "DAG-run or step not found"
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
default:
description: "Generic error response"
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}:
get:
summary: "Retrieve detailed status of a sub DAG-run"
@@ -2719,7 +2763,7 @@ paths:
/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/approve:
post:
summary: "Approve a waiting step in a sub DAG-run for HITL"
summary: "Approve a waiting step in a sub DAG-run"
description: "Approves a step that is in Waiting status within a sub DAG-run, optionally providing input parameters that will be available as environment variables in subsequent steps"
operationId: "approveSubDAGRunStep"
tags:
@@ -2769,7 +2813,7 @@ paths:
/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/reject:
post:
summary: "Reject a waiting step in a sub DAG-run for HITL"
summary: "Reject a waiting step in a sub DAG-run"
description: "Rejects a step that is in Waiting status within a sub DAG-run, optionally providing a reason for rejection"
operationId: "rejectSubDAGRunStep"
tags:
@@ -2817,6 +2861,56 @@ paths:
schema:
$ref: "#/components/schemas/Error"
/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/push-back:
post:
summary: "Push back a waiting step in a sub DAG-run for re-execution with feedback"
description: "Pushes back a step that is in Waiting status within a sub DAG-run, providing input parameters that will be injected as environment variables when the step re-executes. The step must have an approval configuration."
operationId: "pushBackSubDAGRunStep"
tags:
- "dag-runs"
parameters:
- $ref: "#/components/parameters/RemoteNode"
- $ref: "#/components/parameters/DAGName"
- $ref: "#/components/parameters/DAGRunId"
- name: "subDAGRunId"
in: "path"
required: true
schema:
type: "string"
description: "ID of the sub DAG-run containing the step to push back"
- $ref: "#/components/parameters/StepName"
requestBody:
required: false
content:
application/json:
schema:
$ref: "#/components/schemas/PushBackStepRequest"
responses:
"200":
description: "Step pushed back successfully"
content:
application/json:
schema:
$ref: "#/components/schemas/PushBackStepResponse"
"400":
description: "Step is not in Waiting status, missing required inputs, or step does not have approval config"
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
"404":
description: "Sub DAG-run or step not found"
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
default:
description: "Generic error response"
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/queues:
get:
summary: "List all execution queues with summary statistics"
@@ -6540,6 +6634,59 @@ components:
- dagRunId
- stepName
PushBackStepRequest:
type: object
description: "Request body for pushing back a waiting step for re-execution with feedback"
properties:
inputs:
type: object
additionalProperties:
type: string
description: "Key-value parameters to provide as feedback. These will be injected as environment variables when the step re-executes."
PushBackStepResponse:
type: object
description: "Response after pushing back a waiting step"
properties:
dagRunId:
type: string
description: "The DAG run ID"
stepName:
type: string
description: "The pushed-back step name"
approvalIteration:
type: integer
description: "The current approval iteration count after push-back"
resumed:
type: boolean
description: "Whether the DAG run was re-enqueued for execution"
subDAGRunId:
type: string
description: "The sub-DAG run ID, present only for sub-DAG push-back operations"
required:
- dagRunId
- stepName
- approvalIteration
- resumed
ApprovalConfig:
type: object
description: "Configuration for a human approval gate on a step"
properties:
prompt:
type: string
description: "Message displayed to the approver"
input:
type: array
items:
type: string
description: "List of expected input field names from the approver"
required:
type: array
items:
type: string
description: "Subset of input fields that must be provided"
Error:
type: object
description: "Generic error response object"
@@ -7362,24 +7509,32 @@ components:
description: "Error message if the step failed"
approvedAt:
type: string
description: "RFC3339 timestamp when the HITL step was approved"
description: "RFC3339 timestamp when the step was approved"
approvedBy:
type: string
description: "Username of who approved the HITL step"
description: "Username of who approved the step"
approvalInputs:
type: object
additionalProperties:
type: string
description: "Key-value inputs provided during HITL approval"
description: "Key-value inputs provided during approval"
rejectedAt:
type: string
description: "RFC3339 timestamp when the HITL step was rejected"
description: "RFC3339 timestamp when the step was rejected"
rejectedBy:
type: string
description: "Username of who rejected the HITL step"
description: "Username of who rejected the step"
rejectionReason:
type: string
description: "Optional reason for rejection"
approvalIteration:
type: integer
description: "Number of times this step has been pushed back for re-execution"
pushBackInputs:
type: object
additionalProperties:
type: string
description: "Key-value inputs from the last push-back, injected as environment variables during re-execution"
required:
- step
- stdout
@@ -7549,6 +7704,8 @@ components:
type: string
minLength: 1
description: "Step names to route to"
approval:
$ref: "#/components/schemas/ApprovalConfig"
required:
- name
+21
View File
@@ -274,6 +274,27 @@ steps:
},
{
ID: 11,
Name: "approval-gate",
Description: "Add human approval gates to a workflow",
Content: `type: graph
steps:
- name: build
command: echo "build artifact v1.2.3"
output: VERSION
- name: review
command: echo "ready to deploy v${VERSION}"
approval:
prompt: "Approve deployment to production?"
input: [APPROVER, NOTES]
required: [APPROVER]
depends: [build]
- name: deploy
command: echo "deploying v${VERSION} approved by ${APPROVER}"
depends: [review]
`,
},
{
ID: 12,
Name: "agent-step",
Description: "Run an AI agent as a workflow step",
Content: `type: graph
+2 -34
View File
@@ -29,27 +29,12 @@ func TestExampleCommand(t *testing.T) {
require.NoError(t, err)
assert.Contains(t, out, "parallel-steps")
assert.Contains(t, out, "agent-step")
assert.Contains(t, out, "dagu schema dag")
})
t.Run("ShowExample1", func(t *testing.T) {
t.Run("ShowByID", func(t *testing.T) {
out, err := runExampleCmd("example", "1")
require.NoError(t, err)
assert.Contains(t, out, "type: graph")
assert.Contains(t, out, "Parallel Steps")
assert.NotContains(t, out, "dagu schema dag")
})
t.Run("ShowExample10", func(t *testing.T) {
out, err := runExampleCmd("example", "10")
require.NoError(t, err)
assert.Contains(t, out, "router")
})
t.Run("ShowExample11", func(t *testing.T) {
out, err := runExampleCmd("example", "11")
require.NoError(t, err)
assert.Contains(t, out, "agent")
})
t.Run("InvalidID", func(t *testing.T) {
@@ -58,24 +43,7 @@ func TestExampleCommand(t *testing.T) {
assert.Contains(t, err.Error(), fmt.Sprintf("between 1 and %d", cmd.ExampleCount()))
})
t.Run("NonNumericID", func(t *testing.T) {
_, err := runExampleCmd("example", "abc")
require.Error(t, err)
assert.Contains(t, err.Error(), "must be a number")
})
t.Run("ZeroID", func(t *testing.T) {
_, err := runExampleCmd("example", "0")
require.Error(t, err)
assert.Contains(t, err.Error(), fmt.Sprintf("between 1 and %d", cmd.ExampleCount()))
})
t.Run("Help", func(t *testing.T) {
_, err := runExampleCmd("example", "help")
require.NoError(t, err)
})
t.Run("AllExamplesUseGraph", func(t *testing.T) {
t.Run("AllExamplesValid", func(t *testing.T) {
for i := 1; i <= cmd.ExampleCount(); i++ {
out, err := runExampleCmd("example", fmt.Sprintf("%d", i))
require.NoError(t, err, "example %d failed", i)
+3 -41
View File
@@ -1334,14 +1334,6 @@
}
}
},
{
"if": { "properties": { "type": { "const": "hitl" } } },
"then": {
"properties": {
"config": { "$ref": "#/definitions/hitlExecutorConfig" }
}
}
},
{
"if": { "properties": { "type": { "const": "redis" } } },
"then": {
@@ -2882,27 +2874,6 @@
],
"description": "Redis executor configuration for executing Redis commands, managing cache, pub/sub, streams, and distributed locks."
},
"hitlExecutorConfig": {
"type": "object",
"additionalProperties": false,
"properties": {
"prompt": {
"type": "string",
"description": "Message displayed to the approver explaining what approval is needed."
},
"input": {
"type": "array",
"items": { "type": "string" },
"description": "List of input field names expected from the approver."
},
"required": {
"type": "array",
"items": { "type": "string" },
"description": "Subset of input fields that must be provided. All values must exist in 'input' array."
}
},
"description": "Human-in-the-loop executor configuration. Pauses workflow execution until human approval is received."
},
"llmProvider": {
"type": "string",
"enum": [
@@ -3109,7 +3080,7 @@
"safe_mode": {
"type": "boolean",
"default": true,
"description": "Enable command approval via HITL for bash commands. Default: true."
"description": "Enable command approval via human review for bash commands. Default: true."
},
"skills": {
"type": "array",
@@ -3158,8 +3129,8 @@
},
"deny_behavior": {
"type": "string",
"enum": ["block", "hitl"],
"description": "What happens when a command is denied: 'block' rejects it, 'hitl' asks for approval."
"enum": ["block", "ask_user"],
"description": "What happens when a command is denied: 'block' rejects it, 'ask_user' asks for approval."
},
"rules": {
"type": "array",
@@ -3212,7 +3183,6 @@
"parallel",
"archive",
"chat",
"hitl",
"postgres",
"sqlite",
"redis",
@@ -3316,14 +3286,6 @@
}
}
},
{
"if": { "properties": { "type": { "const": "hitl" } } },
"then": {
"properties": {
"config": { "$ref": "#/definitions/hitlExecutorConfig" }
}
}
},
{
"if": { "properties": { "type": { "const": "redis" } } },
"then": {
+5 -5
View File
@@ -249,12 +249,12 @@ func (d *DAG) Clone() *DAG {
return &clone
}
// HasHITLSteps returns true if the DAG contains any HITL executor steps.
// DAGs with HITL steps cannot be dispatched to workers because
// HITL steps require local storage access for approval.
func (d *DAG) HasHITLSteps() bool {
// HasApprovalSteps returns true if the DAG contains any steps that require
// human approval. DAGs with approval steps cannot be dispatched to workers
// because approval steps require local storage access.
func (d *DAG) HasApprovalSteps() bool {
for _, step := range d.Steps {
if step.ExecutorConfig.Type == ExecutorTypeHITL {
if step.Approval != nil {
return true
}
}
+7 -7
View File
@@ -834,7 +834,7 @@ func TestDAG_GetName(t *testing.T) {
}
}
func TestDAGHasHITLSteps(t *testing.T) {
func TestDAGHasApprovalSteps(t *testing.T) {
t.Parallel()
tests := []struct {
@@ -848,7 +848,7 @@ func TestDAGHasHITLSteps(t *testing.T) {
expected: false,
},
{
name: "NoHITL",
name: "NoApproval",
steps: []core.Step{
{Name: "step1", ExecutorConfig: core.ExecutorConfig{Type: "command"}},
{Name: "step2", ExecutorConfig: core.ExecutorConfig{Type: "dag"}},
@@ -856,17 +856,17 @@ func TestDAGHasHITLSteps(t *testing.T) {
expected: false,
},
{
name: "HasHITL",
name: "ApprovalField",
steps: []core.Step{
{Name: "step1", ExecutorConfig: core.ExecutorConfig{Type: "command"}},
{Name: "step2", ExecutorConfig: core.ExecutorConfig{Type: "hitl"}},
{Name: "step2", Approval: &core.ApprovalConfig{Prompt: "review"}},
},
expected: true,
},
{
name: "OnlyHITL",
name: "OnlyApproval",
steps: []core.Step{
{Name: "step1", ExecutorConfig: core.ExecutorConfig{Type: "hitl"}},
{Name: "step1", Approval: &core.ApprovalConfig{}},
},
expected: true,
},
@@ -883,7 +883,7 @@ func TestDAGHasHITLSteps(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
dag := &core.DAG{Steps: tt.steps}
result := dag.HasHITLSteps()
result := dag.HasApprovalSteps()
assert.Equal(t, tt.expected, result)
})
}
+7 -2
View File
@@ -21,18 +21,23 @@ type Node struct {
SubRuns []SubDAGRun `json:"children,omitempty"`
SubRunsRepeated []SubDAGRun `json:"childrenRepeated,omitempty"` // repeated sub DAG runs
OutputVariables *collections.SyncMap `json:"outputVariables,omitempty"`
// ApprovedAt records when this wait step was approved (HITL)
// ApprovedAt records when this wait step was approved
ApprovedAt string `json:"approvedAt,omitempty"`
// ApprovalInputs stores key-value parameters provided during approval
ApprovalInputs map[string]string `json:"approvalInputs,omitempty"`
// ApprovedBy records who approved this wait step (username)
ApprovedBy string `json:"approvedBy,omitempty"`
// RejectedAt records when this wait step was rejected (HITL)
// RejectedAt records when this wait step was rejected
RejectedAt string `json:"rejectedAt,omitempty"`
// RejectedBy records who rejected this wait step (username)
RejectedBy string `json:"rejectedBy,omitempty"`
// RejectionReason stores the optional reason for rejection
RejectionReason string `json:"rejectionReason,omitempty"`
// ApprovalIteration tracks how many times this step has been pushed back.
ApprovalIteration int `json:"approvalIteration,omitempty"`
// PushBackInputs stores the inputs from the last push-back.
// These are injected as environment variables when the step re-executes.
PushBackInputs map[string]string `json:"pushBackInputs,omitempty"`
// ChatMessages stores the session messages for chat/LLM steps.
// This field is populated during execution and synced via status updates
// in shared-nothing mode where workers don't have filesystem access.
+4 -4
View File
@@ -138,7 +138,7 @@ type handlerOn struct {
Success *step `yaml:"success,omitempty"` // Step to execute on success
Abort *step `yaml:"abort,omitempty"` // Step to execute on abort
Exit *step `yaml:"exit,omitempty"` // Step to execute on exit
Wait *step `yaml:"wait,omitempty"` // Step to execute when DAG enters wait status (HITL)
Wait *step `yaml:"wait,omitempty"` // Step to execute when DAG enters wait status (approval)
}
// smtpConfig defines the SMTP configuration.
@@ -531,12 +531,12 @@ func (d *dag) build(ctx BuildContext) (*core.DAG, error) {
errs = append(errs, err)
}
// Validate workerSelector compatibility with HITL steps
if len(result.WorkerSelector) > 0 && result.HasHITLSteps() {
// Validate workerSelector compatibility with approval steps
if len(result.WorkerSelector) > 0 && result.HasApprovalSteps() {
errs = append(errs, core.NewValidationError(
"worker_selector",
result.WorkerSelector,
fmt.Errorf("DAG with HITL steps cannot be dispatched to workers"),
fmt.Errorf("DAG with approval steps cannot be dispatched to workers"),
))
}
+7 -7
View File
@@ -2135,7 +2135,7 @@ func TestBuildLogOutput(t *testing.T) {
}
}
func TestBuildHITLStepsValidation(t *testing.T) {
func TestBuildApprovalStepsValidation(t *testing.T) {
t.Parallel()
tests := []struct {
@@ -2145,7 +2145,7 @@ func TestBuildHITLStepsValidation(t *testing.T) {
errContains string
}{
{
name: "NoHITLSteps",
name: "NoApprovalSteps",
dag: &dag{
Name: "test-dag",
WorkerSelector: map[string]string{"region": "us-west"},
@@ -2160,7 +2160,7 @@ func TestBuildHITLStepsValidation(t *testing.T) {
dag: &dag{
Name: "test-dag",
Steps: []any{
map[string]any{"name": "step1", "type": "hitl"},
map[string]any{"name": "step1", "command": "true", "approval": map[string]any{}},
},
},
expectErr: false,
@@ -2171,11 +2171,11 @@ func TestBuildHITLStepsValidation(t *testing.T) {
Name: "test-dag",
WorkerSelector: map[string]string{"region": "us-west"},
Steps: []any{
map[string]any{"name": "step1", "type": "hitl"},
map[string]any{"name": "step1", "command": "true", "approval": map[string]any{}},
},
},
expectErr: true,
errContains: "DAG with HITL steps cannot be dispatched to workers",
errContains: "DAG with approval steps cannot be dispatched to workers",
},
{
name: "ConflictMultipleSteps",
@@ -2184,12 +2184,12 @@ func TestBuildHITLStepsValidation(t *testing.T) {
WorkerSelector: map[string]string{"region": "us-west"},
Steps: []any{
map[string]any{"name": "step1", "script": "echo hello"},
map[string]any{"name": "step2", "type": "hitl"},
map[string]any{"name": "step2", "command": "true", "approval": map[string]any{}},
map[string]any{"name": "step3", "script": "echo done"},
},
},
expectErr: true,
errContains: "DAG with HITL steps cannot be dispatched to workers",
errContains: "DAG with approval steps cannot be dispatched to workers",
},
}
+37 -1
View File
@@ -6,6 +6,7 @@ import (
"math"
"reflect"
"regexp"
"slices"
"sort"
"strings"
"time"
@@ -106,6 +107,9 @@ type step struct {
// Only valid when type is "agent".
Agent *agentConfig `yaml:"agent,omitempty"`
// Approval configures a human approval gate after step execution.
Approval *approvalConfig `yaml:"approval,omitempty"`
// Router configuration (type: router)
// Value is the expression to evaluate for routing
Value string `yaml:"value,omitempty"`
@@ -113,6 +117,16 @@ type step struct {
Routes map[string][]string `yaml:"routes,omitempty"`
}
// approvalConfig defines the approval configuration for a step.
type approvalConfig struct {
// Prompt is the message displayed to the approver.
Prompt string `yaml:"prompt,omitempty"`
// Input is the list of expected input field names from the approver.
Input []string `yaml:"input,omitempty"`
// Required is the subset of Input fields that must be provided.
Required []string `yaml:"required,omitempty"`
}
// repeatPolicy defines the repeat policy for a step.
type repeatPolicy struct {
Repeat any `yaml:"repeat,omitempty"` // Flag to indicate if the step should be repeated, can be bool (legacy) or string ("while" or "until")
@@ -228,7 +242,7 @@ type agentConfig struct {
Prompt string `yaml:"prompt,omitempty"`
// MaxIterations is the maximum number of tool call rounds.
MaxIterations *int `yaml:"max_iterations,omitempty"`
// SafeMode enables command approval via HITL.
// SafeMode enables command approval via human review.
SafeMode *bool `yaml:"safe_mode,omitempty"`
// WebSearch configures provider-native web search for this agent step.
// Overrides the global agent web search setting.
@@ -379,6 +393,9 @@ func (s *step) build(ctx StepBuildContext) (*core.Step, error) {
if err := buildStepRouter(ctx, s, result); err != nil {
errs = append(errs, wrapTransformError("router", err))
}
if err := buildStepApproval(ctx, s, result); err != nil {
errs = append(errs, wrapTransformError("approval", err))
}
if err := buildStepCommand(ctx, s, result); err != nil {
errs = append(errs, wrapTransformError("command", err))
}
@@ -1722,6 +1739,25 @@ func validateAgent(result *core.Step) error {
return nil
}
// buildStepApproval parses the approval configuration for a step.
func buildStepApproval(_ StepBuildContext, s *step, result *core.Step) error {
if s.Approval == nil {
return nil
}
result.Approval = &core.ApprovalConfig{
Prompt: s.Approval.Prompt,
Input: s.Approval.Input,
Required: s.Approval.Required,
}
// Validate required fields are subset of input
for _, req := range result.Approval.Required {
if !slices.Contains(result.Approval.Input, req) {
return fmt.Errorf("required field %q is not in input list", req)
}
}
return nil
}
// buildStepSubDAG parses the child core.DAG definition and sets up the step to run a sub DAG.
func buildStepSubDAG(ctx StepBuildContext, s *step, result *core.Step) error {
name := strings.TrimSpace(s.Call)
+17 -5
View File
@@ -106,6 +106,9 @@ type Step struct {
// Agent contains the configuration for agent-type steps.
// Only used when type is "agent".
Agent *AgentStepConfig `json:"agent,omitempty"`
// Approval configures a human approval gate after step execution.
// When set, the step pauses in Waiting state after execution completes.
Approval *ApprovalConfig `json:"approval,omitempty"`
}
// String returns a formatted string representation of the step
@@ -325,6 +328,18 @@ type ContinueOn struct {
MarkSuccess bool `json:"markSuccess,omitempty"` // MarkSuccess is the flag to mark the step as success when the condition is met.
}
// ApprovalConfig configures the approval gate for a step.
// When a step has an ApprovalConfig, it pauses in Waiting state after execution
// completes, allowing a human to approve, push back (re-run with feedback), or reject.
type ApprovalConfig struct {
// Prompt is the message displayed to the approver.
Prompt string `json:"prompt,omitempty"`
// Input is the list of expected input field names from the approver.
Input []string `json:"input,omitempty"`
// Required is the subset of Input fields that must be provided.
Required []string `json:"required,omitempty"`
}
const (
// ExecutorTypeDAG is the executor type for a sub DAG.
ExecutorTypeDAG = "dag"
@@ -332,9 +347,6 @@ const (
// ExecutorTypeParallel is the executor type for parallel steps.
ExecutorTypeParallel = "parallel"
// ExecutorTypeHITL is the executor type for HITL (Human In The Loop) steps.
ExecutorTypeHITL = "hitl"
// ExecutorTypeRouter is the executor type for router steps.
ExecutorTypeRouter = "router"
@@ -359,7 +371,7 @@ type AgentStepConfig struct {
Prompt string `json:"prompt,omitempty"`
// MaxIterations is the maximum number of tool call rounds (default: 50).
MaxIterations int `json:"maxIterations,omitempty"`
// SafeMode enables command approval via HITL (default: true).
// SafeMode enables command approval via human review (default: true).
SafeMode bool `json:"safeMode"`
// WebSearch configures provider-native web search for this step.
// Overrides the global agent web search setting.
@@ -378,7 +390,7 @@ type AgentToolsConfig struct {
type AgentBashPolicy struct {
// DefaultBehavior is the default action when no rule matches ("allow" or "deny").
DefaultBehavior string `json:"defaultBehavior,omitempty"`
// DenyBehavior determines what happens when a command is denied ("block" or "hitl").
// DenyBehavior determines what happens when a command is denied ("block" or "ask_user").
DenyBehavior string `json:"denyBehavior,omitempty"`
// Rules is an ordered list of pattern-matching rules.
Rules []AgentBashRule `json:"rules,omitempty"`
+198 -4
View File
@@ -16,8 +16,8 @@ func TestWaitStepApproval(t *testing.T) {
type: graph
steps:
- name: wait-step
type: hitl
config:
command: "true"
approval:
prompt: "Please approve"
- name: after-wait
depends: [wait-step]
@@ -50,7 +50,8 @@ steps:
command: echo "before"
- name: wait-step
depends: [before-wait]
type: hitl
command: "true"
approval: {}
- name: after-wait-1
depends: [wait-step]
command: echo "after1"
@@ -87,7 +88,8 @@ steps:
depends: [branch-a-1]
command: echo "a2"
- name: wait-branch
type: hitl
command: "true"
approval: {}
- name: after-wait
depends: [wait-branch]
command: echo "after wait"
@@ -109,3 +111,195 @@ steps:
require.Equal(t, core.NodeNotStarted, dagRunStatus.Nodes[3].Status, "after-wait should not start")
})
}
func TestApprovalField(t *testing.T) {
t.Run("ApprovalFieldOnCommandStep", func(t *testing.T) {
th := test.Setup(t)
testDAG := th.DAG(t, `
type: graph
steps:
- name: review-step
command: echo "ready for review"
approval:
prompt: "Please review the output"
- name: after-review
depends: [review-step]
command: echo "approved"
`)
agent := testDAG.Agent()
err := agent.Run(agent.Context)
require.NoError(t, err)
testDAG.AssertLatestStatus(t, core.Waiting)
dagRunStatus, err := th.DAGRunMgr.GetLatestStatus(th.Context, testDAG.DAG)
require.NoError(t, err)
require.Len(t, dagRunStatus.Nodes, 2)
// The command step should have executed (produced stdout) then entered waiting
require.Equal(t, core.NodeWaiting, dagRunStatus.Nodes[0].Status, "review-step should be waiting")
require.NotEmpty(t, dagRunStatus.Nodes[0].Stdout, "review-step should have stdout from command execution")
require.Equal(t, core.NodeNotStarted, dagRunStatus.Nodes[1].Status, "after-review should not start")
})
t.Run("ApprovalFieldOnScriptStep", func(t *testing.T) {
th := test.Setup(t)
testDAG := th.DAG(t, `
type: graph
steps:
- name: script-step
script: |
echo "script output line 1"
echo "script output line 2"
approval:
prompt: "Review the script output"
`)
agent := testDAG.Agent()
err := agent.Run(agent.Context)
require.NoError(t, err)
testDAG.AssertLatestStatus(t, core.Waiting)
dagRunStatus, err := th.DAGRunMgr.GetLatestStatus(th.Context, testDAG.DAG)
require.NoError(t, err)
require.Len(t, dagRunStatus.Nodes, 1)
require.Equal(t, core.NodeWaiting, dagRunStatus.Nodes[0].Status, "script-step should be waiting")
require.NotEmpty(t, dagRunStatus.Nodes[0].Stdout, "script-step should have stdout")
})
t.Run("ApprovalFieldWithInputConfig", func(t *testing.T) {
th := test.Setup(t)
testDAG := th.DAG(t, `
type: graph
steps:
- name: review-step
command: echo "needs feedback"
approval:
prompt: "Please provide feedback"
input: [FEEDBACK, NOTES]
required: [FEEDBACK]
`)
agent := testDAG.Agent()
err := agent.Run(agent.Context)
require.NoError(t, err)
testDAG.AssertLatestStatus(t, core.Waiting)
dagRunStatus, err := th.DAGRunMgr.GetLatestStatus(th.Context, testDAG.DAG)
require.NoError(t, err)
require.Len(t, dagRunStatus.Nodes, 1)
require.Equal(t, core.NodeWaiting, dagRunStatus.Nodes[0].Status)
require.NotNil(t, dagRunStatus.Nodes[0].Step.Approval)
require.Equal(t, "Please provide feedback", dagRunStatus.Nodes[0].Step.Approval.Prompt)
require.Equal(t, []string{"FEEDBACK", "NOTES"}, dagRunStatus.Nodes[0].Step.Approval.Input)
require.Equal(t, []string{"FEEDBACK"}, dagRunStatus.Nodes[0].Step.Approval.Required)
})
t.Run("MultipleApprovalSteps", func(t *testing.T) {
th := test.Setup(t)
testDAG := th.DAG(t, `
type: graph
steps:
- name: step-a
command: echo "step a output"
approval:
prompt: "Approve step A"
- name: step-b
command: echo "step b output"
approval:
prompt: "Approve step B"
`)
agent := testDAG.Agent()
err := agent.Run(agent.Context)
require.NoError(t, err)
testDAG.AssertLatestStatus(t, core.Waiting)
dagRunStatus, err := th.DAGRunMgr.GetLatestStatus(th.Context, testDAG.DAG)
require.NoError(t, err)
require.Len(t, dagRunStatus.Nodes, 2)
require.Equal(t, core.NodeWaiting, dagRunStatus.Nodes[0].Status, "step-a should be waiting")
require.Equal(t, core.NodeWaiting, dagRunStatus.Nodes[1].Status, "step-b should be waiting")
})
t.Run("ApprovalStepWithDependency", func(t *testing.T) {
th := test.Setup(t)
testDAG := th.DAG(t, `
type: graph
steps:
- name: step-a
command: echo "upstream"
- name: step-b
depends: [step-a]
command: echo "needs approval"
approval:
prompt: "Review step-b"
- name: step-c
depends: [step-b]
command: echo "downstream"
`)
agent := testDAG.Agent()
err := agent.Run(agent.Context)
require.NoError(t, err)
testDAG.AssertLatestStatus(t, core.Waiting)
dagRunStatus, err := th.DAGRunMgr.GetLatestStatus(th.Context, testDAG.DAG)
require.NoError(t, err)
require.Len(t, dagRunStatus.Nodes, 3)
require.Equal(t, core.NodeSucceeded, dagRunStatus.Nodes[0].Status, "step-a should succeed")
require.Equal(t, core.NodeWaiting, dagRunStatus.Nodes[1].Status, "step-b should be waiting")
require.Equal(t, core.NodeNotStarted, dagRunStatus.Nodes[2].Status, "step-c should not start")
})
t.Run("ApprovalFieldOnCallStep", func(t *testing.T) {
th := test.Setup(t)
// Create the sub-DAG first
subDAG := th.DAG(t, `
type: graph
steps:
- name: sub-step
command: echo "sub-dag output"
`)
testDAG := th.DAG(t, `
type: graph
steps:
- name: call-step
call: "`+subDAG.Name+`"
approval:
prompt: "Review sub-DAG results"
- name: after-call
depends: [call-step]
command: echo "after call"
`)
agent := testDAG.Agent()
err := agent.Run(agent.Context)
require.NoError(t, err)
testDAG.AssertLatestStatus(t, core.Waiting)
dagRunStatus, err := th.DAGRunMgr.GetLatestStatus(th.Context, testDAG.DAG)
require.NoError(t, err)
require.Len(t, dagRunStatus.Nodes, 2)
require.Equal(t, core.NodeWaiting, dagRunStatus.Nodes[0].Status, "call-step should be waiting after sub-DAG completes")
require.Equal(t, core.NodeNotStarted, dagRunStatus.Nodes[1].Status, "after-call should not start")
})
}
+8 -4
View File
@@ -204,7 +204,8 @@ handler_on:
steps:
- name: wait-step
type: hitl
command: "true"
approval: {}
`,
setupFunc: func(t *testing.T, dag *core.DAG) {
require.NotNil(t, dag.HandlerOn.Wait)
@@ -228,7 +229,8 @@ handler_on:
steps:
- name: wait-step
type: hitl
command: "true"
approval: {}
`,
runFunc: func(_ *testing.T, ctx context.Context, agent *test.Agent) {
_ = agent.Run(ctx)
@@ -721,7 +723,8 @@ steps:
command: "true"
- name: wait-step
type: hitl
command: "true"
approval: {}
depends:
- first-step
`)
@@ -763,7 +766,8 @@ steps:
command: "true"
- name: approval-gate
type: hitl
command: "true"
approval: {}
depends:
- setup-step
`)
@@ -206,7 +206,7 @@ steps:
# bash, patch excluded = read-only agent
bash_policy:
default_behavior: deny
deny_behavior: block # or "hitl" for human approval
deny_behavior: block # or "ask_user" for human approval
rules:
- name: allow-ls
pattern: "^ls "
@@ -1,7 +1,12 @@
package agentstep
import (
"fmt"
"sort"
"strings"
"github.com/dagu-org/dagu/internal/agent"
"github.com/dagu-org/dagu/internal/core"
"github.com/dagu-org/dagu/internal/core/exec"
"github.com/dagu-org/dagu/internal/llm"
)
@@ -108,6 +113,36 @@ func contextToLLMHistory(msgs []exec.LLMMessage) []llm.Message {
return result
}
// formatPushBackFeedback creates a user message from push-back inputs,
// filtering to only declared approval input fields.
func formatPushBackFeedback(inputs map[string]string, approval *core.ApprovalConfig) string {
var sb strings.Builder
sb.WriteString("The reviewer has requested changes to your previous work.\n")
if len(inputs) > 0 && approval != nil {
// Filter to declared input fields only (consistent with env var allowlist).
allowed := make(map[string]struct{}, len(approval.Input))
for _, key := range approval.Input {
allowed[key] = struct{}{}
}
sb.WriteString("\nReviewer feedback:\n")
keys := make([]string, 0, len(inputs))
for k := range inputs {
if _, ok := allowed[k]; ok {
keys = append(keys, k)
}
}
sort.Strings(keys)
for _, k := range keys {
fmt.Fprintf(&sb, "- %s: %s\n", k, inputs[k])
}
}
sb.WriteString("\nPlease revise your response based on this feedback.")
return sb.String()
}
// convertToolResultMessages converts a user message with tool results
// into one exec.LLMMessage per tool result (Role=Tool).
func convertToolResultMessages(msg agent.Message) []exec.LLMMessage {
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/dagu-org/dagu/internal/agent"
"github.com/dagu-org/dagu/internal/core"
"github.com/dagu-org/dagu/internal/core/exec"
"github.com/dagu-org/dagu/internal/llm"
"github.com/stretchr/testify/assert"
@@ -178,3 +179,79 @@ func TestConvertMessage_UnknownType(t *testing.T) {
result := convertMessage(msg, testModelConfig())
assert.Nil(t, result)
}
func TestFormatPushBackFeedback_WithInputs(t *testing.T) {
t.Parallel()
inputs := map[string]string{
"REASON": "needs more error handling",
"NOTES": "also add logging",
}
approval := &core.ApprovalConfig{
Input: []string{"REASON", "NOTES"},
}
result := formatPushBackFeedback(inputs, approval)
assert.Contains(t, result, "requested changes")
assert.Contains(t, result, "- NOTES: also add logging")
assert.Contains(t, result, "- REASON: needs more error handling")
assert.Contains(t, result, "revise your response")
}
func TestFormatPushBackFeedback_EmptyInputs(t *testing.T) {
t.Parallel()
result := formatPushBackFeedback(nil, &core.ApprovalConfig{})
assert.Contains(t, result, "requested changes")
assert.Contains(t, result, "revise your response")
assert.NotContains(t, result, "Reviewer feedback")
}
func TestFormatPushBackFeedback_FiltersUndeclaredKeys(t *testing.T) {
t.Parallel()
inputs := map[string]string{
"REASON": "fix it",
"MALICIOUS": "should not appear",
}
approval := &core.ApprovalConfig{
Input: []string{"REASON"},
}
result := formatPushBackFeedback(inputs, approval)
assert.Contains(t, result, "- REASON: fix it")
assert.NotContains(t, result, "MALICIOUS")
}
func TestFormatPushBackFeedback_NilApproval(t *testing.T) {
t.Parallel()
inputs := map[string]string{"KEY": "value"}
result := formatPushBackFeedback(inputs, nil)
assert.Contains(t, result, "requested changes")
assert.NotContains(t, result, "KEY")
}
func TestFormatPushBackFeedback_DeterministicOrder(t *testing.T) {
t.Parallel()
inputs := map[string]string{
"ZZZ": "last",
"AAA": "first",
"MMM": "middle",
}
approval := &core.ApprovalConfig{
Input: []string{"ZZZ", "AAA", "MMM"},
}
// Run multiple times to verify deterministic ordering.
for range 10 {
result := formatPushBackFeedback(inputs, approval)
assert.Contains(t, result, "- AAA: first\n- MMM: middle\n- ZZZ: last")
}
}
+40 -10
View File
@@ -26,6 +26,7 @@ import (
var _ executor.Executor = (*Executor)(nil)
var _ executor.ChatMessageHandler = (*Executor)(nil)
var _ executor.PushBackAware = (*Executor)(nil)
func init() {
executor.RegisterExecutor(
@@ -38,13 +39,15 @@ func init() {
// Executor runs the agent loop as a workflow step.
type Executor struct {
step core.Step
stdout io.Writer
stderr io.Writer
mu sync.Mutex
cancelLoop context.CancelFunc
contextMessages []exec.LLMMessage
savedMessages []exec.LLMMessage
step core.Step
stdout io.Writer
stderr io.Writer
mu sync.Mutex
cancelLoop context.CancelFunc
contextMessages []exec.LLMMessage
savedMessages []exec.LLMMessage
pushBackInputs map[string]string
pushBackIteration int
}
func newAgentExecutor(_ context.Context, step core.Step) (executor.Executor, error) {
@@ -60,6 +63,12 @@ func (e *Executor) SetContext(msgs []exec.LLMMessage) { e.contextMessages = msgs
// GetMessages returns the collected messages after execution.
func (e *Executor) GetMessages() []exec.LLMMessage { return e.savedMessages }
// SetPushBackContext provides push-back feedback for iterative re-execution.
func (e *Executor) SetPushBackContext(inputs map[string]string, iteration int) {
e.pushBackInputs = inputs
e.pushBackIteration = iteration
}
func (e *Executor) Kill(_ os.Signal) error {
e.mu.Lock()
defer e.mu.Unlock()
@@ -170,6 +179,17 @@ func (e *Executor) Run(ctx context.Context) error {
// Generate system prompt.
systemPrompt := buildSystemPrompt(dagCtx, stepCfg, memoryContent, skillSummaries, skillCount, soul)
// Enhance system prompt for push-back re-execution.
if e.pushBackIteration > 0 {
systemPrompt += fmt.Sprintf(
"\n\n## Revision Context\n\nThis is a revision (iteration %d). "+
"Your previous conversation is included in the history. "+
"The reviewer's feedback follows as the next user message. "+
"Revise your work accordingly.\n",
e.pushBackIteration,
)
}
// Resolve safe mode and max iterations.
safeMode := true
maxIterations := 50
@@ -253,9 +273,19 @@ func (e *Executor) Run(ctx context.Context) error {
},
})
// Queue user messages.
for _, msg := range userMessages {
loop.QueueUserMessage(msg)
// Queue messages: either push-back feedback or original YAML messages.
if e.pushBackIteration > 0 {
// Push-back re-execution: previous conversation is already in history
// via contextMessages. Queue only the feedback message.
feedback := formatPushBackFeedback(e.pushBackInputs, e.step.Approval)
loop.QueueUserMessage(llm.Message{
Role: llm.RoleUser,
Content: feedback,
})
} else {
for _, msg := range userMessages {
loop.QueueUserMessage(msg)
}
}
// Run the loop. It returns context.Canceled when we cancel it (expected).
-1
View File
@@ -8,7 +8,6 @@ import (
_ "github.com/dagu-org/dagu/internal/runtime/builtin/dag"
_ "github.com/dagu-org/dagu/internal/runtime/builtin/docker"
_ "github.com/dagu-org/dagu/internal/runtime/builtin/gha"
_ "github.com/dagu-org/dagu/internal/runtime/builtin/hitl"
_ "github.com/dagu-org/dagu/internal/runtime/builtin/http"
_ "github.com/dagu-org/dagu/internal/runtime/builtin/jq"
_ "github.com/dagu-org/dagu/internal/runtime/builtin/mail"
+6 -6
View File
@@ -34,8 +34,8 @@ type dagExecutor struct {
// Errors for DAG executor
var (
ErrWorkingDirNotExist = fmt.Errorf("working directory does not exist")
ErrHITLStepsWithWorker = fmt.Errorf("sub-DAG with HITL steps cannot be dispatched to workers")
ErrWorkingDirNotExist = fmt.Errorf("working directory does not exist")
ErrApprovalStepsWithWorker = fmt.Errorf("sub-DAG with approval steps cannot be dispatched to workers")
)
func newDAGExecutor(ctx context.Context, step core.Step) (executor.Executor, error) {
@@ -48,9 +48,9 @@ func newDAGExecutor(ctx context.Context, step core.Step) (executor.Executor, err
return nil, err
}
// Validate: sub-DAGs with HITL steps cannot be dispatched to workers
if len(step.WorkerSelector) > 0 && child.DAG.HasHITLSteps() {
return nil, fmt.Errorf("%w: %s", ErrHITLStepsWithWorker, step.SubDAG.Name)
// Validate: sub-DAGs with approval steps cannot be dispatched to workers
if len(step.WorkerSelector) > 0 && child.DAG.HasApprovalSteps() {
return nil, fmt.Errorf("%w: %s", ErrApprovalStepsWithWorker, step.SubDAG.Name)
}
dir := runtime.GetEnv(ctx).WorkingDir
@@ -115,7 +115,7 @@ func (e *dagExecutor) DetermineNodeStatus() (core.NodeStatus, error) {
case core.PartiallySucceeded:
return core.NodePartiallySucceeded, nil
case core.Waiting:
// Sub-DAG is waiting for human approval (HITL)
// Sub-DAG is waiting for human approval
// Propagate the waiting status to the parent
return core.NodeWaiting, nil
case core.NotStarted, core.Running, core.Failed, core.Aborted, core.Queued:
+4 -4
View File
@@ -58,9 +58,9 @@ func newParallelExecutor(
return nil, err
}
// Validate: sub-DAGs with HITL steps cannot be dispatched to workers
if len(step.WorkerSelector) > 0 && child.DAG.HasHITLSteps() {
return nil, fmt.Errorf("%w: %s", ErrHITLStepsWithWorker, step.SubDAG.Name)
// Validate: sub-DAGs with approval steps cannot be dispatched to workers
if len(step.WorkerSelector) > 0 && child.DAG.HasApprovalSteps() {
return nil, fmt.Errorf("%w: %s", ErrApprovalStepsWithWorker, step.SubDAG.Name)
}
dir := runtime.GetEnv(ctx).WorkingDir
@@ -224,7 +224,7 @@ func (e *parallelExecutor) DetermineNodeStatus() (core.NodeStatus, error) {
case core.PartiallySucceeded:
partialSuccess = true
case core.Waiting:
// Sub-DAG is waiting for human approval (HITL)
// Sub-DAG is waiting for human approval
hasWaiting = true
default:
return core.NodeFailed, fmt.Errorf("sub DAG run %s is still in progress with status: %s", result.DAGRunID, result.Status)
-39
View File
@@ -1,39 +0,0 @@
package hitl
import (
"github.com/dagu-org/dagu/internal/core"
"github.com/go-viper/mapstructure/v2"
"github.com/google/jsonschema-go/jsonschema"
)
// Config holds the configuration for a HITL step.
type Config struct {
// Prompt is the message displayed to the approver.
Prompt string `mapstructure:"prompt"`
// Input is the list of expected input field names from the approver.
Input []string `mapstructure:"input"`
// Required is the subset of Input fields that must be provided.
Required []string `mapstructure:"required"`
}
func decodeConfig(dat map[string]any, cfg *Config) error {
md, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
WeaklyTypedInput: true,
ErrorUnused: false,
Result: cfg,
})
return md.Decode(dat)
}
var configSchema = &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"prompt": {Type: "string", Description: "Message displayed to the approver"},
"input": {Type: "array", Items: &jsonschema.Schema{Type: "string"}, Description: "List of expected input field names"},
"required": {Type: "array", Items: &jsonschema.Schema{Type: "string"}, Description: "Subset of Input fields that must be provided"},
},
}
func init() {
core.RegisterExecutorConfigSchema("hitl", configSchema)
}
-101
View File
@@ -1,101 +0,0 @@
package hitl
import (
"context"
"fmt"
"io"
"os"
"slices"
"github.com/dagu-org/dagu/internal/core"
"github.com/dagu-org/dagu/internal/runtime/executor"
)
var (
_ executor.Executor = (*hitlExecutor)(nil)
_ executor.NodeStatusDeterminer = (*hitlExecutor)(nil)
)
type hitlExecutor struct {
stdout io.Writer
stderr io.Writer
step core.Step
config Config
}
func newHITL(_ context.Context, step core.Step) (executor.Executor, error) {
var cfg Config
if step.ExecutorConfig.Config != nil {
if err := decodeConfig(step.ExecutorConfig.Config, &cfg); err != nil {
return nil, fmt.Errorf("failed to decode hitl config: %w", err)
}
}
return &hitlExecutor{
stdout: os.Stdout,
stderr: os.Stderr,
step: step,
config: cfg,
}, nil
}
func (e *hitlExecutor) SetStdout(out io.Writer) {
e.stdout = out
}
func (e *hitlExecutor) SetStderr(out io.Writer) {
e.stderr = out
}
func (*hitlExecutor) Kill(_ os.Signal) error {
return nil
}
// Run outputs the HITL step information and completes immediately.
// The actual waiting is handled by the runner which detects NodeWaiting status.
func (e *hitlExecutor) Run(_ context.Context) error {
_, _ = fmt.Fprintln(e.stdout, "Waiting for human approval...")
if e.config.Prompt != "" {
_, _ = fmt.Fprintln(e.stdout)
_, _ = fmt.Fprintln(e.stdout, "Prompt:")
_, _ = fmt.Fprintln(e.stdout, e.config.Prompt)
}
if len(e.config.Input) > 0 {
_, _ = fmt.Fprintln(e.stdout)
_, _ = fmt.Fprintf(e.stdout, "Expected inputs: %v\n", e.config.Input)
if len(e.config.Required) > 0 {
_, _ = fmt.Fprintf(e.stdout, "Required inputs: %v\n", e.config.Required)
}
}
return nil
}
// DetermineNodeStatus returns NodeWaiting to signal this step requires approval.
func (e *hitlExecutor) DetermineNodeStatus() (core.NodeStatus, error) {
return core.NodeWaiting, nil
}
func validateConfig(step core.Step) error {
var cfg Config
if step.ExecutorConfig.Config != nil {
if err := decodeConfig(step.ExecutorConfig.Config, &cfg); err != nil {
return fmt.Errorf("failed to decode hitl config: %w", err)
}
}
// Validate that all required fields are in input list
for _, req := range cfg.Required {
if !slices.Contains(cfg.Input, req) {
return fmt.Errorf("required field %q is not in input list", req)
}
}
return nil
}
func init() {
executor.RegisterExecutor("hitl", newHITL, validateConfig, core.ExecutorCapabilities{})
}
-160
View File
@@ -1,160 +0,0 @@
package hitl
import (
"bytes"
"context"
"testing"
"github.com/dagu-org/dagu/internal/core"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHITLExecutorRun(t *testing.T) {
t.Parallel()
tests := []struct {
name string
config map[string]any
expectPrompt string
expectInputs bool
expectRequired bool
}{
{
name: "Basic",
config: nil,
},
{
name: "WithPrompt",
config: map[string]any{
"prompt": "Please approve this deployment",
},
expectPrompt: "Please approve this deployment",
},
{
name: "WithInputs",
config: map[string]any{
"prompt": "Enter approval details",
"input": []string{"reason", "approver"},
"required": []string{"reason"},
},
expectPrompt: "Enter approval details",
expectInputs: true,
expectRequired: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
step := core.Step{
Name: "test-hitl",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
Config: tt.config,
},
}
exec, err := newHITL(context.Background(), step)
require.NoError(t, err)
stdout := &bytes.Buffer{}
exec.SetStdout(stdout)
err = exec.Run(context.Background())
require.NoError(t, err)
output := stdout.String()
assert.Contains(t, output, "Waiting for human approval")
if tt.expectPrompt != "" {
assert.Contains(t, output, tt.expectPrompt)
}
if tt.expectInputs {
assert.Contains(t, output, "Expected inputs")
}
if tt.expectRequired {
assert.Contains(t, output, "Required inputs")
}
})
}
}
func TestHITLExecutorDetermineNodeStatus(t *testing.T) {
t.Parallel()
step := core.Step{
Name: "test-hitl",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
},
}
exec, err := newHITL(context.Background(), step)
require.NoError(t, err)
determiner, ok := exec.(interface {
DetermineNodeStatus() (core.NodeStatus, error)
})
require.True(t, ok, "executor should implement NodeStatusDeterminer")
status, err := determiner.DetermineNodeStatus()
require.NoError(t, err)
assert.Equal(t, core.NodeWaiting, status)
}
func TestHITLValidateConfig(t *testing.T) {
t.Parallel()
tests := []struct {
name string
config map[string]any
expectErr bool
}{
{
name: "Nil",
config: nil,
},
{
name: "Empty",
config: map[string]any{},
},
{
name: "ValidRequired",
config: map[string]any{
"input": []string{"reason", "approver"},
"required": []string{"reason"},
},
},
{
name: "InvalidRequired",
config: map[string]any{
"input": []string{"reason"},
"required": []string{"approver"},
},
expectErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
step := core.Step{
Name: "test-hitl",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
Config: tt.config,
},
}
err := validateConfig(step)
if tt.expectErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
+9 -5
View File
@@ -70,19 +70,23 @@ type NodeState struct {
// ToolDefinitions stores the tool definitions that were available to the LLM during execution.
// This provides visibility into what tools/functions the LLM could call.
ToolDefinitions []exec.ToolDefinition
// ApprovalInputs stores key-value parameters provided during HITL approval.
// ApprovalInputs stores key-value parameters provided during approval.
// These are available as environment variables in subsequent steps.
ApprovalInputs map[string]string
// ApprovedAt is the time when the HITL step was approved.
// ApprovedAt is the time when the step was approved.
ApprovedAt string
// ApprovedBy is the username of the user who approved the HITL step.
// ApprovedBy is the username of the user who approved the step.
ApprovedBy string
// RejectedAt is the time when the HITL step was rejected.
// RejectedAt is the time when the step was rejected.
RejectedAt string
// RejectedBy is the username of the user who rejected the HITL step.
// RejectedBy is the username of the user who rejected the step.
RejectedBy string
// RejectionReason stores the optional reason for rejection.
RejectionReason string
// ApprovalIteration tracks how many times this step has been pushed back.
ApprovalIteration int
// PushBackInputs stores inputs from the last push-back for env var injection.
PushBackInputs map[string]string
}
// Parallel represents the evaluated parallel execution configuration for a node.
+6
View File
@@ -99,6 +99,12 @@ type ChatMessageHandler interface {
GetMessages() []exec.LLMMessage
}
// PushBackAware is implemented by executors that can incorporate
// push-back feedback into their conversation flow.
type PushBackAware interface {
SetPushBackContext(inputs map[string]string, iteration int)
}
// SubRunProvider is an interface for executors that spawn sub-DAG runs.
// This is used by executors like chat (with tools) to report sub-runs
// for UI drill-down functionality.
+20
View File
@@ -0,0 +1,20 @@
package runtime
import "context"
// SetupChatMessages exports setupChatMessages for testing.
func (r *Runner) SetupChatMessages(ctx context.Context, node *Node) {
r.setupChatMessages(ctx, node)
}
// SetupPushBackConversation exports setupPushBackConversation for testing.
func (r *Runner) SetupPushBackConversation(ctx context.Context, node *Node) {
r.setupPushBackConversation(ctx, node)
}
// SetApprovalIteration sets the approval iteration count for testing.
func (n *Node) SetApprovalIteration(iteration int) {
n.Data.mu.Lock()
defer n.Data.mu.Unlock()
n.inner.State.ApprovalIteration = iteration
}
+8
View File
@@ -199,6 +199,14 @@ func (n *Node) Execute(ctx context.Context) error {
}
}
// Pass push-back context to executors that support iterative feedback.
if pbHandler, ok := cmd.(executor.PushBackAware); ok {
state := n.State()
if state.ApprovalIteration > 0 {
pbHandler.SetPushBackContext(state.PushBackInputs, state.ApprovalIteration)
}
}
flusher := n.startOutputFlusher()
defer func() {
n.stopOutputFlusher(flusher)
+69 -2
View File
@@ -429,8 +429,27 @@ func (r *Runner) runNodeExecution(ctx context.Context, plan *Plan, node *Node, p
ctx = node.SetupEnv(ctx)
// Inject push-back inputs as environment variables for re-execution.
// Only declared input fields are allowed to prevent arbitrary env overwrite.
if approval := node.Step().Approval; approval != nil && len(node.State().PushBackInputs) > 0 {
env := GetEnv(ctx)
allowed := make(map[string]struct{}, len(approval.Input))
for _, key := range approval.Input {
allowed[key] = struct{}{}
}
for k, v := range node.State().PushBackInputs {
if _, ok := allowed[k]; !ok {
logger.Warn(ctx, "Ignoring unexpected push-back input", slog.String("input", k))
continue
}
env = env.WithEnvVars(k, v)
}
ctx = WithEnv(ctx, env)
}
// Setup chat messages from dependencies before execution
r.setupChatMessages(ctx, node)
r.setupPushBackConversation(ctx, node)
ExecRepeat: // repeat execution
for !r.isCanceled() {
@@ -466,13 +485,24 @@ ExecRepeat: // repeat execution
isRepetitive := node.Step().RepeatPolicy.RepeatMode != ""
if !isRepetitive && r.isCanceled() {
node.SetStatus(core.NodeAborted)
} else if node.Step().Approval != nil {
// Step has approval config — enter waiting state for human review.
// Push-back is human-controlled, no iteration limit.
node.SetStatus(core.NodeWaiting)
} else {
node.SetStatus(core.NodeSucceeded)
}
}
// Save chat messages after successful execution
if node.State().Status == core.NodeSucceeded {
// For executors that implement NodeStatusDeterminer (e.g. call/dag, parallel),
// the status may have been set to NodeSucceeded by the executor.
// If the step has an approval config, override to NodeWaiting.
if node.State().Status == core.NodeSucceeded && node.Step().Approval != nil {
node.SetStatus(core.NodeWaiting)
}
// Save chat messages after execution (including waiting steps for push-back continuity).
if node.State().Status == core.NodeSucceeded || node.State().Status == core.NodeWaiting {
r.saveChatMessages(ctx, node)
}
@@ -560,6 +590,43 @@ func (r *Runner) saveChatMessages(ctx context.Context, node *Node) {
}
}
// setupPushBackConversation loads the step's own previous conversation for
// agent steps being re-executed after push-back. This REPLACES any dependency
// messages (which are already embedded in the previous conversation from
// iteration 0). Non-agent steps are unaffected.
func (r *Runner) setupPushBackConversation(ctx context.Context, node *Node) {
if r.messagesHandler == nil {
return
}
step := node.Step()
if step.Approval == nil || !core.SupportsAgent(step.ExecutorConfig.Type) {
return
}
if node.State().ApprovalIteration == 0 {
return
}
ownMessages, err := r.messagesHandler.ReadStepMessages(ctx, step.Name)
if err != nil {
logger.Warn(ctx, "Failed to read own messages for push-back",
tag.Step(step.Name), tag.Error(err))
return
}
if len(ownMessages) == 0 {
return
}
if len(ownMessages) > 200 {
logger.Warn(ctx, "Large conversation history after push-back iterations",
tag.Step(step.Name), slog.Int("messageCount", len(ownMessages)),
slog.Int("iteration", node.State().ApprovalIteration))
}
// REPLACE (not merge) — dependencies are already embedded in the
// previous conversation from iteration 0.
node.SetChatMessages(ownMessages)
}
func (r *Runner) setupVariables(ctx context.Context, plan *Plan, node *Node) context.Context {
env := NewPlanEnv(ctx, node.Step(), plan)
+3 -6
View File
@@ -28,7 +28,7 @@ func failStep(name string, depends ...string) core.Step {
}
func waitStep(name string, depends ...string) core.Step {
return newStep(name, withDepends(depends...), withExecutor("hitl", nil))
return newStep(name, withDepends(depends...), withCommand("true"), withApproval(&core.ApprovalConfig{}))
}
type stepOption func(*core.Step)
@@ -110,12 +110,9 @@ func withID(id string) stepOption {
}
}
func withExecutor(executorType string, config map[string]any) stepOption {
func withApproval(approval *core.ApprovalConfig) stepOption {
return func(step *core.Step) {
step.ExecutorConfig = core.ExecutorConfig{
Type: executorType,
Config: config,
}
step.Approval = approval
}
}
+160 -4
View File
@@ -3081,6 +3081,161 @@ func TestRunner_ChatMessagesHandler(t *testing.T) {
})
}
func TestSetupPushBackConversation(t *testing.T) {
t.Run("LoadsOwnMessagesForPushedBackAgentStep", func(t *testing.T) {
t.Parallel()
handler := newMockMessagesHandler()
// Pre-populate the step's own previous messages.
handler.messages["agent1"] = []exec.LLMMessage{
{Role: exec.RoleSystem, Content: "be helpful"},
{Role: exec.RoleUser, Content: "original prompt"},
{Role: exec.RoleAssistant, Content: "previous response"},
}
// Also set dependency messages to verify they get replaced.
handler.messages["dep1"] = []exec.LLMMessage{
{Role: exec.RoleUser, Content: "dep message"},
}
r := setupRunner(t, withMessagesHandler(handler))
step := newStep("agent1",
withExecutorType(core.ExecutorTypeAgent),
withDepends("dep1"),
withApproval(&core.ApprovalConfig{
Prompt: "review this",
Input: []string{"FEEDBACK"},
}),
)
plan := r.newPlan(t, successStep("dep1"), step)
node := plan.GetNodeByName("agent1")
require.NotNil(t, node)
// Simulate push-back: set ApprovalIteration > 0
node.SetApprovalIteration(1)
ctx := context.Background()
// First, setupChatMessages sets dependency messages.
r.runner.SetupChatMessages(ctx, node)
msgs := node.GetChatMessages()
require.Len(t, msgs, 1)
assert.Equal(t, "dep message", msgs[0].Content)
// Then, setupPushBackConversation replaces with own messages.
r.runner.SetupPushBackConversation(ctx, node)
msgs = node.GetChatMessages()
require.Len(t, msgs, 3)
assert.Equal(t, "be helpful", msgs[0].Content)
assert.Equal(t, "original prompt", msgs[1].Content)
assert.Equal(t, "previous response", msgs[2].Content)
})
t.Run("NoOpForFirstExecution", func(t *testing.T) {
t.Parallel()
handler := newMockMessagesHandler()
handler.messages["agent1"] = []exec.LLMMessage{
{Role: exec.RoleUser, Content: "should not load"},
}
r := setupRunner(t, withMessagesHandler(handler))
step := newStep("agent1",
withExecutorType(core.ExecutorTypeAgent),
withApproval(&core.ApprovalConfig{}),
)
plan := r.newPlan(t, step)
node := plan.GetNodeByName("agent1")
// ApprovalIteration is 0 (default) — no push-back
ctx := context.Background()
r.runner.SetupPushBackConversation(ctx, node)
// Should not load any messages.
msgs := node.GetChatMessages()
assert.Empty(t, msgs)
})
t.Run("NoOpForNonAgentStep", func(t *testing.T) {
t.Parallel()
handler := newMockMessagesHandler()
handler.messages["cmd1"] = []exec.LLMMessage{
{Role: exec.RoleUser, Content: "should not load"},
}
r := setupRunner(t, withMessagesHandler(handler))
step := newStep("cmd1",
withCommand("echo hello"),
withApproval(&core.ApprovalConfig{}),
)
plan := r.newPlan(t, step)
node := plan.GetNodeByName("cmd1")
node.SetApprovalIteration(1)
ctx := context.Background()
r.runner.SetupPushBackConversation(ctx, node)
msgs := node.GetChatMessages()
assert.Empty(t, msgs)
})
t.Run("NoOpWithoutApproval", func(t *testing.T) {
t.Parallel()
handler := newMockMessagesHandler()
handler.messages["agent1"] = []exec.LLMMessage{
{Role: exec.RoleUser, Content: "should not load"},
}
r := setupRunner(t, withMessagesHandler(handler))
step := newStep("agent1",
withExecutorType(core.ExecutorTypeAgent),
)
plan := r.newPlan(t, step)
node := plan.GetNodeByName("agent1")
node.SetApprovalIteration(1)
ctx := context.Background()
r.runner.SetupPushBackConversation(ctx, node)
msgs := node.GetChatMessages()
assert.Empty(t, msgs)
})
t.Run("GracefulOnReadError", func(t *testing.T) {
t.Parallel()
handler := newMockMessagesHandler()
handler.readErr = fmt.Errorf("storage error")
r := setupRunner(t, withMessagesHandler(handler))
step := newStep("agent1",
withExecutorType(core.ExecutorTypeAgent),
withApproval(&core.ApprovalConfig{}),
)
plan := r.newPlan(t, step)
node := plan.GetNodeByName("agent1")
node.SetApprovalIteration(1)
ctx := context.Background()
// Should not panic on read error.
r.runner.SetupPushBackConversation(ctx, node)
msgs := node.GetChatMessages()
assert.Empty(t, msgs)
})
}
func TestWaitStep(t *testing.T) {
t.Run("WaitStepResultsInWaitStatus", func(t *testing.T) {
t.Parallel()
@@ -3167,10 +3322,11 @@ func TestWaitStep(t *testing.T) {
// Wait step with input configuration
waitWithInputs := newStep("wait-inputs",
withExecutor("hitl", map[string]any{
"prompt": "Please provide approval",
"input": []string{"reason", "approver"},
"required": []string{"reason"},
withCommand("true"),
withApproval(&core.ApprovalConfig{
Prompt: "Please provide approval",
Input: []string{"reason", "approver"},
Required: []string{"reason"},
}),
)
+47 -43
View File
@@ -26,27 +26,29 @@ func ToNode(n *exec.Node) *runtime.Node {
err = errors.New(n.Error)
}
return runtime.NewNode(n.Step, runtime.NodeState{
Status: n.Status,
Stdout: n.Stdout,
Stderr: n.Stderr,
StartedAt: startedAt,
FinishedAt: finishedAt,
RetriedAt: retriedAt,
RetryCount: n.RetryCount,
DoneCount: n.DoneCount,
Repeated: n.Repeated,
Error: err,
SubRuns: children,
SubRunsRepeated: childrenRepeated,
OutputVariables: n.OutputVariables,
ChatMessages: n.ChatMessages,
ToolDefinitions: n.ToolDefinitions,
ApprovalInputs: n.ApprovalInputs,
ApprovedAt: n.ApprovedAt,
ApprovedBy: n.ApprovedBy,
RejectedAt: n.RejectedAt,
RejectedBy: n.RejectedBy,
RejectionReason: n.RejectionReason,
Status: n.Status,
Stdout: n.Stdout,
Stderr: n.Stderr,
StartedAt: startedAt,
FinishedAt: finishedAt,
RetriedAt: retriedAt,
RetryCount: n.RetryCount,
DoneCount: n.DoneCount,
Repeated: n.Repeated,
Error: err,
SubRuns: children,
SubRunsRepeated: childrenRepeated,
OutputVariables: n.OutputVariables,
ChatMessages: n.ChatMessages,
ToolDefinitions: n.ToolDefinitions,
ApprovalInputs: n.ApprovalInputs,
ApprovedAt: n.ApprovedAt,
ApprovedBy: n.ApprovedBy,
RejectedAt: n.RejectedAt,
RejectedBy: n.RejectedBy,
RejectionReason: n.RejectionReason,
ApprovalIteration: n.ApprovalIteration,
PushBackInputs: n.PushBackInputs,
})
}
@@ -65,27 +67,29 @@ func newNode(node runtime.NodeData) *exec.Node {
childrenRepeated[i] = exec.SubDAGRun(child)
}
return &exec.Node{
Step: node.Step,
Stdout: node.State.Stdout,
Stderr: node.State.Stderr,
StartedAt: stringutil.FormatTime(node.State.StartedAt),
FinishedAt: stringutil.FormatTime(node.State.FinishedAt),
Status: node.State.Status,
RetriedAt: stringutil.FormatTime(node.State.RetriedAt),
RetryCount: node.State.RetryCount,
DoneCount: node.State.DoneCount,
Repeated: node.State.Repeated,
Error: errText,
SubRuns: children,
SubRunsRepeated: childrenRepeated,
OutputVariables: node.State.OutputVariables,
ChatMessages: node.State.ChatMessages,
ToolDefinitions: node.State.ToolDefinitions,
ApprovalInputs: node.State.ApprovalInputs,
ApprovedAt: node.State.ApprovedAt,
ApprovedBy: node.State.ApprovedBy,
RejectedAt: node.State.RejectedAt,
RejectedBy: node.State.RejectedBy,
RejectionReason: node.State.RejectionReason,
Step: node.Step,
Stdout: node.State.Stdout,
Stderr: node.State.Stderr,
StartedAt: stringutil.FormatTime(node.State.StartedAt),
FinishedAt: stringutil.FormatTime(node.State.FinishedAt),
Status: node.State.Status,
RetriedAt: stringutil.FormatTime(node.State.RetriedAt),
RetryCount: node.State.RetryCount,
DoneCount: node.State.DoneCount,
Repeated: node.State.Repeated,
Error: errText,
SubRuns: children,
SubRunsRepeated: childrenRepeated,
OutputVariables: node.State.OutputVariables,
ChatMessages: node.State.ChatMessages,
ToolDefinitions: node.State.ToolDefinitions,
ApprovalInputs: node.State.ApprovalInputs,
ApprovedAt: node.State.ApprovedAt,
ApprovedBy: node.State.ApprovedBy,
RejectedAt: node.State.RejectedAt,
RejectedBy: node.State.RejectedBy,
RejectionReason: node.State.RejectionReason,
ApprovalIteration: node.State.ApprovalIteration,
PushBackInputs: node.State.PushBackInputs,
}
}
+292 -30
View File
@@ -2,6 +2,7 @@ package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
@@ -635,7 +636,7 @@ func (a *API) UpdateDAGRunStepStatus(ctx context.Context, request api.UpdateDAGR
return &api.UpdateDAGRunStepStatus200Response{}, nil
}
// ApproveDAGRunStep approves a waiting step for HITL (Human-in-the-Loop).
// ApproveDAGRunStep approves a waiting step.
func (a *API) ApproveDAGRunStep(ctx context.Context, request api.ApproveDAGRunStepRequestObject) (api.ApproveDAGRunStepResponseObject, error) {
if err := a.isAllowed(config.PermissionRunDAGs); err != nil {
return nil, err
@@ -853,7 +854,7 @@ func (a *API) GetSubDAGRunStepMessages(ctx context.Context, request api.GetSubDA
}, nil
}
// RejectDAGRunStep rejects a waiting step for HITL (Human-in-the-Loop).
// RejectDAGRunStep rejects a waiting step.
func (a *API) RejectDAGRunStep(ctx context.Context, request api.RejectDAGRunStepRequestObject) (api.RejectDAGRunStepResponseObject, error) {
if err := a.isAllowed(config.PermissionRunDAGs); err != nil {
return nil, err
@@ -965,6 +966,183 @@ func (a *API) RejectSubDAGRunStep(ctx context.Context, request api.RejectSubDAGR
}, nil
}
// PushBackDAGRunStep pushes back a waiting step for re-execution with feedback.
func (a *API) PushBackDAGRunStep(ctx context.Context, request api.PushBackDAGRunStepRequestObject) (api.PushBackDAGRunStepResponseObject, error) {
if err := a.isAllowed(config.PermissionRunDAGs); err != nil {
return nil, err
}
if err := a.requireExecute(ctx); err != nil {
return nil, err
}
ref := exec.NewDAGRunRef(request.Name, request.DagRunId)
dagStatus, err := a.dagRunMgr.GetSavedStatus(ctx, ref)
if err != nil {
return &api.PushBackDAGRunStep404JSONResponse{
Code: api.ErrorCodeNotFound,
Message: fmt.Sprintf("dag-run ID %s not found for DAG %s", request.DagRunId, request.Name),
}, nil
}
stepIdx := findStepByName(dagStatus.Nodes, request.StepName)
if stepIdx < 0 {
return &api.PushBackDAGRunStep404JSONResponse{
Code: api.ErrorCodeNotFound,
Message: fmt.Sprintf("step %s not found in DAG %s", request.StepName, request.Name),
}, nil
}
node := dagStatus.Nodes[stepIdx]
if node.Status != core.NodeWaiting {
return &api.PushBackDAGRunStep400JSONResponse{
Code: api.ErrorCodeBadRequest,
Message: fmt.Sprintf("step %s is not waiting for approval (status: %s)", request.StepName, node.Status),
}, nil
}
if node.Step.Approval == nil {
return &api.PushBackDAGRunStep400JSONResponse{
Code: api.ErrorCodeBadRequest,
Message: fmt.Sprintf("step %s does not have approval configuration; push-back requires the approval field", request.StepName),
}, nil
}
if err := validatePushBackInputs(node.Step, request.Body); err != nil {
return &api.PushBackDAGRunStep400JSONResponse{
Code: api.ErrorCodeBadRequest,
Message: err.Error(),
}, nil
}
// Snapshot current state for rollback if resume fails.
snapshot, err := json.Marshal(dagStatus)
if err != nil {
return nil, fmt.Errorf("error serializing status for rollback: %w", err)
}
applyPushBack(ctx, node, dagStatus, request.Body)
if err := a.dagRunMgr.UpdateStatus(ctx, ref, *dagStatus); err != nil {
return nil, fmt.Errorf("error updating status: %w", err)
}
if err := a.resumeDAGRun(ctx, ref, request.DagRunId); err != nil {
logger.Error(ctx, "Failed to resume DAG after push-back, rolling back", tag.Error(err))
var original exec.DAGRunStatus
if unmarshalErr := json.Unmarshal(snapshot, &original); unmarshalErr == nil {
if rollbackErr := a.dagRunMgr.UpdateStatus(ctx, ref, original); rollbackErr != nil {
logger.Error(ctx, "Failed to rollback push-back state", tag.Error(rollbackErr))
}
}
return nil, fmt.Errorf("failed to resume DAG after push-back: %w", err)
}
logger.Info(ctx, "DAG resumed after push-back",
slog.String("dagRunId", request.DagRunId),
slog.String("step", request.StepName),
slog.Int("iteration", node.ApprovalIteration),
)
a.logStepPushBack(ctx, request.Name, request.DagRunId, "", request.StepName, node.ApprovalIteration, true)
return &api.PushBackDAGRunStep200JSONResponse{
DagRunId: request.DagRunId,
StepName: request.StepName,
ApprovalIteration: node.ApprovalIteration,
Resumed: true,
}, nil
}
// PushBackSubDAGRunStep pushes back a waiting step in a sub DAG-run for re-execution with feedback.
func (a *API) PushBackSubDAGRunStep(ctx context.Context, request api.PushBackSubDAGRunStepRequestObject) (api.PushBackSubDAGRunStepResponseObject, error) {
if err := a.isAllowed(config.PermissionRunDAGs); err != nil {
return nil, err
}
if err := a.requireExecute(ctx); err != nil {
return nil, err
}
rootRef := exec.NewDAGRunRef(request.Name, request.DagRunId)
dagStatus, err := a.dagRunMgr.FindSubDAGRunStatus(ctx, rootRef, request.SubDAGRunId)
if err != nil {
return &api.PushBackSubDAGRunStep404JSONResponse{
Code: api.ErrorCodeNotFound,
Message: fmt.Sprintf("sub DAG-run ID %s not found", request.SubDAGRunId),
}, nil
}
stepIdx := findStepByName(dagStatus.Nodes, request.StepName)
if stepIdx < 0 {
return &api.PushBackSubDAGRunStep404JSONResponse{
Code: api.ErrorCodeNotFound,
Message: fmt.Sprintf("step %s not found in sub DAG-run %s", request.StepName, request.SubDAGRunId),
}, nil
}
node := dagStatus.Nodes[stepIdx]
if node.Status != core.NodeWaiting {
return &api.PushBackSubDAGRunStep400JSONResponse{
Code: api.ErrorCodeBadRequest,
Message: fmt.Sprintf("step %s is not waiting for approval (status: %s)", request.StepName, node.Status),
}, nil
}
if node.Step.Approval == nil {
return &api.PushBackSubDAGRunStep400JSONResponse{
Code: api.ErrorCodeBadRequest,
Message: fmt.Sprintf("step %s does not have approval configuration; push-back requires the approval field", request.StepName),
}, nil
}
if err := validatePushBackInputs(node.Step, request.Body); err != nil {
return &api.PushBackSubDAGRunStep400JSONResponse{
Code: api.ErrorCodeBadRequest,
Message: err.Error(),
}, nil
}
// Snapshot current state for rollback if resume fails.
snapshot, err := json.Marshal(dagStatus)
if err != nil {
return nil, fmt.Errorf("error serializing status for rollback: %w", err)
}
applyPushBack(ctx, node, dagStatus, request.Body)
if err := a.dagRunMgr.UpdateStatus(ctx, rootRef, *dagStatus); err != nil {
return nil, fmt.Errorf("error updating sub DAG-run status: %w", err)
}
if err := a.resumeSubDAGRun(ctx, rootRef, request.SubDAGRunId); err != nil {
logger.Error(ctx, "Failed to resume sub DAG after push-back, rolling back", tag.Error(err))
var original exec.DAGRunStatus
if unmarshalErr := json.Unmarshal(snapshot, &original); unmarshalErr == nil {
if rollbackErr := a.dagRunMgr.UpdateStatus(ctx, rootRef, original); rollbackErr != nil {
logger.Error(ctx, "Failed to rollback push-back state", tag.Error(rollbackErr))
}
}
return nil, fmt.Errorf("failed to resume sub DAG after push-back: %w", err)
}
logger.Info(ctx, "Sub DAG resumed after push-back",
slog.String("subDagRunId", request.SubDAGRunId),
slog.String("step", request.StepName),
slog.Int("iteration", node.ApprovalIteration),
)
a.logStepPushBack(ctx, request.Name, request.DagRunId, request.SubDAGRunId, request.StepName, node.ApprovalIteration, true)
return &api.PushBackSubDAGRunStep200JSONResponse{
DagRunId: request.SubDAGRunId,
SubDAGRunId: &request.SubDAGRunId,
StepName: request.StepName,
ApprovalIteration: node.ApprovalIteration,
Resumed: true,
}, nil
}
// GetDAGRunDetails implements api.StrictServerInterface.
func (a *API) GetDAGRunDetails(ctx context.Context, request api.GetDAGRunDetailsRequestObject) (api.GetDAGRunDetailsResponseObject, error) {
resp, err := a.getDAGRunDetailsData(ctx, request.Name, request.DagRunId)
@@ -1850,44 +2028,128 @@ func hasWaitingSteps(nodes []*exec.Node) bool {
return false
}
func validateRequiredInputs(step core.Step, body *api.ApproveStepRequest) error {
if step.ExecutorConfig.Config == nil {
return nil
}
requiredFields, ok := step.ExecutorConfig.Config["required"]
if !ok {
return nil
}
required, ok := requiredFields.([]any)
if !ok || len(required) == 0 {
return nil
}
var providedInputs map[string]string
if body != nil && body.Inputs != nil {
providedInputs = *body.Inputs
}
// checkMissingInputs validates that all required fields are present in the provided inputs.
func checkMissingInputs(required []string, provided map[string]string) error {
var missing []string
for _, r := range required {
fieldName, ok := r.(string)
if !ok {
continue
}
if providedInputs == nil || providedInputs[fieldName] == "" {
for _, fieldName := range required {
if provided == nil || strings.TrimSpace(provided[fieldName]) == "" {
missing = append(missing, fieldName)
}
}
if len(missing) > 0 {
return fmt.Errorf("missing required inputs: %v", missing)
}
return nil
}
// requiredFieldsForStep returns the list of required input field names for a step.
func requiredFieldsForStep(step core.Step) []string {
if step.Approval != nil {
return step.Approval.Required
}
return nil
}
func validateRequiredInputs(step core.Step, body *api.ApproveStepRequest) error {
required := requiredFieldsForStep(step)
if len(required) == 0 {
return nil
}
var provided map[string]string
if body != nil && body.Inputs != nil {
provided = *body.Inputs
}
return checkMissingInputs(required, provided)
}
func validatePushBackInputs(step core.Step, body *api.PushBackStepRequest) error {
if step.Approval == nil || len(step.Approval.Required) == 0 {
return nil
}
var provided map[string]string
if body != nil && body.Inputs != nil {
provided = *body.Inputs
}
return checkMissingInputs(step.Approval.Required, provided)
}
func applyPushBack(_ context.Context, node *exec.Node, status *exec.DAGRunStatus, body *api.PushBackStepRequest) {
node.ApprovalIteration++
node.Status = core.NodeNotStarted
node.StartedAt = "-"
node.FinishedAt = "-"
node.Error = ""
if body != nil && body.Inputs != nil {
node.PushBackInputs = *body.Inputs
} else {
node.PushBackInputs = nil
}
// Clear downstream nodes so they re-execute after the push-back step
dependents := findDependentNodes(status.Nodes, node.Step.Name)
for _, dep := range dependents {
dep.Status = core.NodeNotStarted
dep.StartedAt = "-"
dep.FinishedAt = "-"
dep.Error = ""
}
}
// findDependentNodes returns all nodes that directly or transitively depend on the given step.
func findDependentNodes(nodes []*exec.Node, stepName string) []*exec.Node {
// Build a set of step names that depend on the given step
dependentNames := make(map[string]bool)
dependentNames[stepName] = true
// Iterate until no new dependents are found (transitive closure)
changed := true
for changed {
changed = false
for _, n := range nodes {
if dependentNames[n.Step.Name] {
continue
}
for _, dep := range n.Step.Depends {
if dependentNames[dep] {
dependentNames[n.Step.Name] = true
changed = true
break
}
}
}
}
// Collect dependent nodes (excluding the source step itself)
var result []*exec.Node
for _, n := range nodes {
if dependentNames[n.Step.Name] && n.Step.Name != stepName {
result = append(result, n)
}
}
return result
}
func (a *API) logStepPushBack(ctx context.Context, dagName, dagRunID, subDAGRunID, stepName string, iteration int, resumed bool) {
detailsMap := map[string]any{
"dag_name": dagName,
"dag_run_id": dagRunID,
"step_name": stepName,
"approval_iteration": iteration,
"resumed": resumed,
}
if subDAGRunID != "" {
detailsMap["sub_dag_run_id"] = subDAGRunID
}
action := "dag_step_push_back"
if subDAGRunID != "" {
action = "sub_dag_step_push_back"
}
a.logAudit(ctx, audit.CategoryDAG, action, detailsMap)
}
// SSE Data Methods for DAG Runs
// DAGRunLogsResponse represents the response for DAG run logs SSE.
@@ -213,8 +213,8 @@ func TestApproveDAGRunStep(t *testing.T) {
dagSpec := `type: graph
steps:
- name: wait-step
type: hitl
config:
command: "true"
approval:
prompt: "Please approve"
- name: after-wait
depends: [wait-step]
@@ -278,8 +278,8 @@ func TestApproveDAGRunStepWithInputs(t *testing.T) {
dagSpec := `type: graph
steps:
- name: wait-step
type: hitl
config:
command: "true"
approval:
prompt: "Please provide reason"
input:
- reason
@@ -350,8 +350,8 @@ func TestApproveDAGRunStepMissingRequired(t *testing.T) {
dagSpec := `type: graph
steps:
- name: wait-step
type: hitl
config:
command: "true"
approval:
prompt: "Please provide reason"
input:
- reason
@@ -437,8 +437,8 @@ func TestRejectDAGRunStep(t *testing.T) {
dagSpec := `type: graph
steps:
- name: wait-step
type: hitl
config:
command: "true"
approval:
prompt: "Please approve"
- name: after-wait
depends: [wait-step]
@@ -647,11 +647,11 @@ func TestExecuteDAGSyncTimeout(t *testing.T) {
func TestExecuteDAGSyncWithWaitingStatus(t *testing.T) {
server := test.SetupServer(t)
// Create a DAG with HITL step that will wait for approval
// Create a DAG with approval step that will wait for approval
dagSpec := `steps:
- name: wait-step
type: hitl
config:
command: "true"
approval:
prompt: "Approve this"`
_ = server.Client().Post("/api/v1/dags", api.CreateNewDAGJSONRequestBody{
+1 -1
View File
@@ -825,7 +825,7 @@ func (a *API) waitForDAGCompletion(
lastStatus = status
// Check if execution is complete (not active) or waiting for human approval.
// We return on "waiting" status because HITL (Human-In-The-Loop) workflows
// We return on "waiting" status because approval workflows
// require external intervention that would cause indefinite blocking otherwise.
// The client can poll the status endpoint or use callbacks to resume monitoring.
if !status.Status.IsActive() || status.Status.IsWaiting() {
+28 -18
View File
@@ -112,6 +112,14 @@ func toStep(obj core.Step) api.Step {
}
}
if obj.Approval != nil {
step.Approval = &api.ApprovalConfig{
Prompt: ptrOf(obj.Approval.Prompt),
Input: ptrOf(obj.Approval.Input),
Required: ptrOf(obj.Approval.Required),
}
}
if obj.Router != nil {
routes := make([]struct {
Pattern string `json:"pattern"`
@@ -215,24 +223,26 @@ func toNode(node *exec.Node) api.Node {
return api.Node{}
}
return api.Node{
DoneCount: node.DoneCount,
FinishedAt: node.FinishedAt,
Stdout: node.Stdout,
Stderr: node.Stderr,
RetryCount: node.RetryCount,
StartedAt: node.StartedAt,
Status: api.NodeStatus(node.Status),
StatusLabel: api.NodeStatusLabel(node.Status.String()),
Step: toStep(node.Step),
Error: ptrOf(node.Error),
SubRuns: ptrOf(toSubDAGRuns(node.SubRuns)),
SubRunsRepeated: ptrOf(toSubDAGRuns(node.SubRunsRepeated)),
ApprovedAt: ptrOf(node.ApprovedAt),
ApprovedBy: ptrOf(node.ApprovedBy),
ApprovalInputs: ptrOf(node.ApprovalInputs),
RejectedAt: ptrOf(node.RejectedAt),
RejectedBy: ptrOf(node.RejectedBy),
RejectionReason: ptrOf(node.RejectionReason),
DoneCount: node.DoneCount,
FinishedAt: node.FinishedAt,
Stdout: node.Stdout,
Stderr: node.Stderr,
RetryCount: node.RetryCount,
StartedAt: node.StartedAt,
Status: api.NodeStatus(node.Status),
StatusLabel: api.NodeStatusLabel(node.Status.String()),
Step: toStep(node.Step),
Error: ptrOf(node.Error),
SubRuns: ptrOf(toSubDAGRuns(node.SubRuns)),
SubRunsRepeated: ptrOf(toSubDAGRuns(node.SubRunsRepeated)),
ApprovedAt: ptrOf(node.ApprovedAt),
ApprovedBy: ptrOf(node.ApprovedBy),
ApprovalInputs: ptrOf(node.ApprovalInputs),
PushBackInputs: ptrOf(node.PushBackInputs),
RejectedAt: ptrOf(node.RejectedAt),
RejectedBy: ptrOf(node.RejectedBy),
RejectionReason: ptrOf(node.RejectionReason),
ApprovalIteration: ptrOf(node.ApprovalIteration),
}
}
@@ -19,7 +19,7 @@ func TestValidateRequiredInputs(t *testing.T) {
errMsg string
}{
{
name: "no config - always valid",
name: "no approval config - always valid",
step: core.Step{
Name: "test",
},
@@ -27,26 +27,11 @@ func TestValidateRequiredInputs(t *testing.T) {
expectErr: false,
},
{
name: "empty config - always valid",
name: "approval with no required fields - always valid",
step: core.Step{
Name: "test",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
Config: map[string]any{},
},
},
body: nil,
expectErr: false,
},
{
name: "no required fields - always valid",
step: core.Step{
Name: "test",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
Config: map[string]any{
"input": []any{"reason", "approver"},
},
Approval: &core.ApprovalConfig{
Input: []string{"reason", "approver"},
},
},
body: nil,
@@ -56,12 +41,9 @@ func TestValidateRequiredInputs(t *testing.T) {
name: "required fields provided",
step: core.Step{
Name: "test",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
Config: map[string]any{
"input": []any{"reason", "approver"},
"required": []any{"reason"},
},
Approval: &core.ApprovalConfig{
Input: []string{"reason", "approver"},
Required: []string{"reason"},
},
},
body: &api.ApproveStepRequest{
@@ -75,11 +57,8 @@ func TestValidateRequiredInputs(t *testing.T) {
name: "required fields missing - no body",
step: core.Step{
Name: "test",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
Config: map[string]any{
"required": []any{"reason"},
},
Approval: &core.ApprovalConfig{
Required: []string{"reason"},
},
},
body: nil,
@@ -90,11 +69,8 @@ func TestValidateRequiredInputs(t *testing.T) {
name: "required fields missing - empty inputs",
step: core.Step{
Name: "test",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
Config: map[string]any{
"required": []any{"reason", "approver"},
},
Approval: &core.ApprovalConfig{
Required: []string{"reason", "approver"},
},
},
body: &api.ApproveStepRequest{
@@ -107,11 +83,8 @@ func TestValidateRequiredInputs(t *testing.T) {
name: "partial required fields provided",
step: core.Step{
Name: "test",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
Config: map[string]any{
"required": []any{"reason", "approver"},
},
Approval: &core.ApprovalConfig{
Required: []string{"reason", "approver"},
},
},
body: &api.ApproveStepRequest{
@@ -126,11 +99,8 @@ func TestValidateRequiredInputs(t *testing.T) {
name: "all required fields provided with extras",
step: core.Step{
Name: "test",
ExecutorConfig: core.ExecutorConfig{
Type: "hitl",
Config: map[string]any{
"required": []any{"reason"},
},
Approval: &core.ApprovalConfig{
Required: []string{"reason"},
},
},
body: &api.ApproveStepRequest{
+209 -9
View File
@@ -911,7 +911,7 @@ export interface paths {
get?: never;
put?: never;
/**
* Approve a waiting step for HITL
* Approve a waiting step
* @description Approves a step that is in Waiting status, optionally providing input parameters that will be available as environment variables in subsequent steps
*/
post: operations["approveDAGRunStep"];
@@ -931,7 +931,7 @@ export interface paths {
get?: never;
put?: never;
/**
* Reject a waiting step for HITL
* Reject a waiting step
* @description Rejects a step that is in Waiting status, optionally providing a reason for rejection
*/
post: operations["rejectDAGRunStep"];
@@ -941,6 +941,26 @@ export interface paths {
patch?: never;
trace?: never;
};
"/dag-runs/{name}/{dagRunId}/steps/{stepName}/push-back": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Push back a waiting step for re-execution with feedback
* @description Pushes back a step that is in Waiting status, providing input parameters that will be injected as environment variables when the step re-executes. The step must have an approval configuration.
*/
post: operations["pushBackDAGRunStep"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}": {
parameters: {
query?: never;
@@ -1111,7 +1131,7 @@ export interface paths {
get?: never;
put?: never;
/**
* Approve a waiting step in a sub DAG-run for HITL
* Approve a waiting step in a sub DAG-run
* @description Approves a step that is in Waiting status within a sub DAG-run, optionally providing input parameters that will be available as environment variables in subsequent steps
*/
post: operations["approveSubDAGRunStep"];
@@ -1131,7 +1151,7 @@ export interface paths {
get?: never;
put?: never;
/**
* Reject a waiting step in a sub DAG-run for HITL
* Reject a waiting step in a sub DAG-run
* @description Rejects a step that is in Waiting status within a sub DAG-run, optionally providing a reason for rejection
*/
post: operations["rejectSubDAGRunStep"];
@@ -1141,6 +1161,26 @@ export interface paths {
patch?: never;
trace?: never;
};
"/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/push-back": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Push back a waiting step in a sub DAG-run for re-execution with feedback
* @description Pushes back a step that is in Waiting status within a sub DAG-run, providing input parameters that will be injected as environment variables when the step re-executes. The step must have an approval configuration.
*/
post: operations["pushBackSubDAGRunStep"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/queues": {
parameters: {
query?: never;
@@ -2507,6 +2547,35 @@ export interface components {
/** @description The rejected step name */
stepName: string;
};
/** @description Request body for pushing back a waiting step for re-execution with feedback */
PushBackStepRequest: {
/** @description Key-value parameters to provide as feedback. These will be injected as environment variables when the step re-executes. */
inputs?: {
[key: string]: string;
};
};
/** @description Response after pushing back a waiting step */
PushBackStepResponse: {
/** @description The DAG run ID */
dagRunId: string;
/** @description The pushed-back step name */
stepName: string;
/** @description The current approval iteration count after push-back */
approvalIteration: number;
/** @description Whether the DAG run was re-enqueued for execution */
resumed: boolean;
/** @description The sub-DAG run ID, present only for sub-DAG push-back operations */
subDAGRunId?: string;
};
/** @description Configuration for a human approval gate on a step */
ApprovalConfig: {
/** @description Message displayed to the approver */
prompt?: string;
/** @description List of expected input field names from the approver */
input?: string[];
/** @description Subset of input fields that must be provided */
required?: string[];
};
/** @description Generic error response object */
Error: {
code: components["schemas"]["ErrorCode"];
@@ -2959,20 +3028,26 @@ export interface components {
subRunsRepeated?: components["schemas"]["SubDAGRun"][];
/** @description Error message if the step failed */
error?: string;
/** @description RFC3339 timestamp when the HITL step was approved */
/** @description RFC3339 timestamp when the step was approved */
approvedAt?: string;
/** @description Username of who approved the HITL step */
/** @description Username of who approved the step */
approvedBy?: string;
/** @description Key-value inputs provided during HITL approval */
/** @description Key-value inputs provided during approval */
approvalInputs?: {
[key: string]: string;
};
/** @description RFC3339 timestamp when the HITL step was rejected */
/** @description RFC3339 timestamp when the step was rejected */
rejectedAt?: string;
/** @description Username of who rejected the HITL step */
/** @description Username of who rejected the step */
rejectedBy?: string;
/** @description Optional reason for rejection */
rejectionReason?: string;
/** @description Number of times this step has been pushed back for re-execution */
approvalIteration?: number;
/** @description Key-value inputs from the last push-back, injected as environment variables during re-execution */
pushBackInputs?: {
[key: string]: string;
};
};
/** @description Metadata for a sub DAG-run */
SubDAGRun: {
@@ -3056,6 +3131,7 @@ export interface components {
targets: string[];
}[];
};
approval?: components["schemas"]["ApprovalConfig"];
};
/** @description Individual search result item for a DAG */
SearchResultItem: {
@@ -7113,6 +7189,67 @@ export interface operations {
};
};
};
pushBackDAGRunStep: {
parameters: {
query?: {
/** @description name of the remote node */
remoteNode?: components["parameters"]["RemoteNode"];
};
header?: never;
path: {
/** @description name of the DAG */
name: components["parameters"]["DAGName"];
/** @description ID of the DAG-run or 'latest' to get the most recent DAG-run */
dagRunId: components["parameters"]["DAGRunId"];
/** @description name of the step */
stepName: components["parameters"]["StepName"];
};
cookie?: never;
};
requestBody?: {
content: {
"application/json": components["schemas"]["PushBackStepRequest"];
};
};
responses: {
/** @description Step pushed back successfully */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PushBackStepResponse"];
};
};
/** @description Step is not in Waiting status, missing required inputs, or step does not have approval config */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description DAG-run or step not found */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Generic error response */
default: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
getSubDAGRunDetails: {
parameters: {
query?: {
@@ -7673,6 +7810,69 @@ export interface operations {
};
};
};
pushBackSubDAGRunStep: {
parameters: {
query?: {
/** @description name of the remote node */
remoteNode?: components["parameters"]["RemoteNode"];
};
header?: never;
path: {
/** @description name of the DAG */
name: components["parameters"]["DAGName"];
/** @description ID of the DAG-run or 'latest' to get the most recent DAG-run */
dagRunId: components["parameters"]["DAGRunId"];
/** @description ID of the sub DAG-run containing the step to push back */
subDAGRunId: string;
/** @description name of the step */
stepName: components["parameters"]["StepName"];
};
cookie?: never;
};
requestBody?: {
content: {
"application/json": components["schemas"]["PushBackStepRequest"];
};
};
responses: {
/** @description Step pushed back successfully */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PushBackStepResponse"];
};
};
/** @description Step is not in Waiting status, missing required inputs, or step does not have approval config */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Sub DAG-run or step not found */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Generic error response */
default: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
listQueues: {
parameters: {
query?: {
@@ -16,9 +16,17 @@ import {
} from '@/components/ui/tooltip';
import dayjs from '@/lib/dayjs';
import ActionButton from '@/ui/ActionButton';
import { RefreshCw, Square, X } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/CustomDialog';
import { Ban, RefreshCw, Square, X } from 'lucide-react';
import React from 'react';
import { components, Status } from '../../../../api/v1/schema';
import { Button } from '@/components/ui/button';
import { components, NodeStatus, Status } from '../../../../api/v1/schema';
import { AppBarContext } from '../../../../contexts/AppBarContext';
import { useConfig } from '../../../../contexts/ConfigContext';
import { useClient } from '../../../../hooks/api';
@@ -63,6 +71,8 @@ function DAGRunActions({
const [isStopModal, setIsStopModal] = React.useState(false);
const [isRetryModal, setIsRetryModal] = React.useState(false);
const [isDequeueModal, setIsDequeueModal] = React.useState(false);
const [isRejectModal, setIsRejectModal] = React.useState(false);
const [rejectReason, setRejectReason] = React.useState('');
// Retry-as-new modal state
const [retryAsNew, setRetryAsNew] = React.useState(false);
@@ -80,15 +90,19 @@ function DAGRunActions({
}
};
const isWaiting = dagRun?.status === Status.Waiting;
const hasNodes = dagRun && 'nodes' in dagRun && Array.isArray((dagRun as components['schemas']['DAGRunDetails']).nodes);
// Determine which buttons should be enabled based on current status and root level
const buttonState = {
stop: isRootLevel && dagRun?.status === Status.Running, // Running and at root level
stop: isRootLevel && dagRun?.status === Status.Running,
reject: isRootLevel && isWaiting && hasNodes,
retry:
isRootLevel &&
dagRun?.status !== Status.Running &&
dagRun?.status !== Status.Queued &&
dagRun?.dagRunId !== '', // Not running, not queued, has dagRunId, and at root level
dequeue: isRootLevel && dagRun?.status === Status.Queued, // Queued and at root level
dagRun?.dagRunId !== '',
dequeue: isRootLevel && dagRun?.status === Status.Queued,
};
if (!dagRun || !config.permissions.runDags) {
@@ -100,29 +114,50 @@ function DAGRunActions({
<div
className={`flex items-center ${displayMode === 'compact' ? 'space-x-1' : 'space-x-2'}`}
>
{/* Stop Button */}
<Tooltip>
<TooltipTrigger asChild>
<span>
<ActionButton
label={displayMode !== 'compact'}
icon={<Square className="h-4 w-4" />}
disabled={!buttonState['stop']}
onClick={() => setIsStopModal(true)}
className="cursor-pointer"
>
Stop
</ActionButton>
</span>
</TooltipTrigger>
<TooltipContent>
<p>
{isRootLevel
? 'Stop DAGRun execution'
: 'Stop action only available at root dagRun level'}
</p>
</TooltipContent>
</Tooltip>
{/* Stop / Reject Button */}
{isWaiting && hasNodes ? (
<Tooltip>
<TooltipTrigger asChild>
<span>
<ActionButton
label={displayMode !== 'compact'}
icon={<Ban className="h-4 w-4" />}
disabled={!buttonState['reject']}
onClick={() => setIsRejectModal(true)}
className="cursor-pointer"
>
Reject
</ActionButton>
</span>
</TooltipTrigger>
<TooltipContent>
<p>Reject all waiting steps</p>
</TooltipContent>
</Tooltip>
) : (
<Tooltip>
<TooltipTrigger asChild>
<span>
<ActionButton
label={displayMode !== 'compact'}
icon={<Square className="h-4 w-4" />}
disabled={!buttonState['stop']}
onClick={() => setIsStopModal(true)}
className="cursor-pointer"
>
Stop
</ActionButton>
</span>
</TooltipTrigger>
<TooltipContent>
<p>
{isRootLevel
? 'Stop DAGRun execution'
: 'Stop action only available at root dagRun level'}
</p>
</TooltipContent>
</Tooltip>
)}
{/* Retry Button */}
<Tooltip>
@@ -365,6 +400,64 @@ function DAGRunActions({
</div>
</ConfirmModal>
{/* Reject Modal */}
<Dialog open={isRejectModal} onOpenChange={(open) => { if (!open) { setIsRejectModal(false); setRejectReason(''); } }}>
<DialogContent className="sm:max-w-[450px]">
<DialogHeader>
<DialogTitle>Reject DAG Run</DialogTitle>
</DialogHeader>
<div className="py-2">
<textarea
className="w-full px-3 py-2 text-sm border border-border rounded bg-background focus:outline-none focus:border-ring resize-none"
placeholder="Reason (optional)..."
rows={2}
value={rejectReason}
onChange={(e) => setRejectReason(e.target.value)}
/>
</div>
<DialogFooter>
<Button variant="ghost" size="sm" onClick={() => { setIsRejectModal(false); setRejectReason(''); }}>
<X className="h-4 w-4" /> Cancel
</Button>
<Button
variant="default"
size="sm"
onClick={async () => {
setIsRejectModal(false);
const details = dagRun as components['schemas']['DAGRunDetails'];
const waitingNodes = details.nodes.filter(n => n.status === NodeStatus.Waiting);
const errors: string[] = [];
for (const node of waitingNodes) {
const { error } = await client.POST(
'/dag-runs/{name}/{dagRunId}/steps/{stepName}/reject',
{
params: {
path: { name, dagRunId: dagRun!.dagRunId, stepName: node.step.name },
query: { remoteNode: appBarContext.selectedRemoteNode || 'local' },
},
body: { reason: rejectReason || undefined },
}
);
if (error) {
errors.push(node.step.name);
}
}
if (errors.length > 0) {
showError(
`Failed to reject ${errors.length} step(s)`,
`Failed to reject: ${errors.join(', ')}`
);
}
setRejectReason('');
reloadData();
}}
>
<Ban className="h-4 w-4" /> Reject
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Dequeue Confirmation Modal */}
<ConfirmModal
title="Confirmation"
+38 -2
View File
@@ -13,6 +13,7 @@ import {
MessageSquare,
MousePointerClick,
Package,
ShieldCheck,
} from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { useCookies } from 'react-cookie';
@@ -26,6 +27,7 @@ import BorderedBox from '../../../ui/BorderedBox';
import { DAGRunOutputs } from '../../dag-runs/components/dag-run-details';
import { DAGContext } from '../contexts/DAGContext';
import { getEventHandlers } from '../lib/getEventHandlers';
import { ApprovalTab } from './approval';
import { ChatHistoryTab } from './chat-history';
import { DAGStatusOverview, NodeStatusTable } from './dag-details';
import { DAGSpecReadOnly } from './dag-editor';
@@ -41,7 +43,7 @@ type Props = {
fileName: string;
};
type StatusTab = 'status' | 'timeline' | 'outputs' | 'chat' | 'spec';
type StatusTab = 'status' | 'timeline' | 'outputs' | 'chat' | 'spec' | 'approval';
/** Check if the current DAG run is a sub DAG-run (has a different root) */
function isSubDAGRun(dagRun: components['schemas']['DAGRunDetails']): boolean {
@@ -308,6 +310,12 @@ function DAGStatus({ dagRun, fileName }: Props) {
(node) => node.step.executorConfig?.type === 'chat'
);
// Check if there are any steps awaiting approval
const waitingStepCount = dagRun.nodes?.filter(
(node) => node.status === NodeStatus.Waiting
).length || 0;
const hasWaitingSteps = waitingStepCount > 0;
// Reset to status tab if selected tab is not available
useEffect(() => {
if (activeTab === 'timeline' && !showTimeline) {
@@ -316,7 +324,17 @@ function DAGStatus({ dagRun, fileName }: Props) {
if (activeTab === 'chat' && !hasChatSteps) {
setActiveTab('status');
}
}, [showTimeline, hasChatSteps, activeTab]);
if (activeTab === 'approval' && !hasWaitingSteps) {
setActiveTab('status');
}
}, [showTimeline, hasChatSteps, hasWaitingSteps, activeTab]);
// Auto-switch to approval tab when steps enter waiting state
useEffect(() => {
if (hasWaitingSteps) {
setActiveTab('approval');
}
}, [hasWaitingSteps]);
return (
<div className="space-y-4">
@@ -330,6 +348,19 @@ function DAGStatus({ dagRun, fileName }: Props) {
<ActivitySquare className="h-4 w-4" />
Status
</Tab>
{hasWaitingSteps && (
<Tab
isActive={activeTab === 'approval'}
onClick={() => setActiveTab('approval')}
className="flex items-center gap-2 cursor-pointer"
>
<ShieldCheck className="h-4 w-4" />
Approval
<span className="bg-warning/15 text-warning text-xs font-medium px-1.5 py-0.5 rounded-full">
{waitingStepCount}
</span>
</Tab>
)}
{showTimeline && (
<Tab
isActive={activeTab === 'timeline'}
@@ -466,6 +497,11 @@ function DAGStatus({ dagRun, fileName }: Props) {
</div>
)}
{/* Approval Tab Content */}
{activeTab === 'approval' && hasWaitingSteps && (
<ApprovalTab dagRun={dagRun} dagName={fileName} />
)}
{/* Timeline Tab Content */}
{activeTab === 'timeline' && showTimeline && (
<TimelineChart status={dagRun} />
@@ -0,0 +1,173 @@
import { Button } from '@/components/ui/button';
import { AppBarContext } from '@/contexts/AppBarContext';
import { useClient } from '@/hooks/api';
import { Check, RotateCcw } from 'lucide-react';
import React, { useState } from 'react';
import { components, NodeStatus, Stream } from '../../../../api/v1/schema';
import { InlineLogViewer } from '../common/InlineLogViewer';
import { StepReviewModal } from '../dag-execution/StepReviewModal';
type DAGRunDetails = components['schemas']['DAGRunDetails'];
type NodeData = components['schemas']['Node'];
interface ApprovalTabProps {
dagRun: DAGRunDetails;
dagName: string;
}
function ApprovalCard({
node,
dagRun,
dagName,
onAction,
}: {
node: NodeData;
dagRun: DAGRunDetails;
dagName: string;
onAction: (node: NodeData, action: 'approve' | 'retry') => void;
}) {
const step = node.step;
const prompt = step.approval?.prompt || step.description;
const iteration = node?.approvalIteration || 0;
return (
<div className="bg-surface border border-border rounded-lg p-4 space-y-3">
{/* Header + Action buttons */}
<div className="flex items-start justify-between gap-4">
<div className="space-y-1">
<div className="flex items-center gap-2">
<span className="text-sm font-semibold">{step.name}</span>
{iteration > 0 && (
<span className="text-xs font-normal text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
Iteration {iteration}
</span>
)}
</div>
{prompt && (
<div className="text-base whitespace-pre-wrap">
{prompt}
</div>
)}
</div>
<div className="flex shrink-0 gap-2">
{step.approval && (
<Button
size="sm"
variant="default"
onClick={() => onAction(node, 'retry')}
>
<RotateCcw className="h-4 w-4" />
Retry
</Button>
)}
<Button
size="sm"
variant="primary"
onClick={() => onAction(node, 'approve')}
>
<Check className="h-4 w-4" />
Approve
</Button>
</div>
</div>
{/* Step Output */}
<div>
<div className="text-xs font-medium text-muted-foreground mb-1">Step Output</div>
<div className="max-h-[400px] overflow-y-auto rounded border border-border">
<InlineLogViewer
dagName={dagName}
dagRunId={dagRun.dagRunId}
stepName={step.name}
stream={node.stdout ? Stream.stdout : Stream.stderr}
dagRun={dagRun}
/>
</div>
</div>
</div>
);
}
export function ApprovalTab({ dagRun, dagName }: ApprovalTabProps) {
const client = useClient();
const appBarContext = React.useContext(AppBarContext);
const remoteNode = appBarContext.selectedRemoteNode || 'local';
const [reviewState, setReviewState] = useState<{
node: NodeData;
action: 'approve' | 'retry';
} | null>(null);
const waitingNodes = dagRun.nodes?.filter(
(n) => n.status === NodeStatus.Waiting
) || [];
const isSubRun = !!(
dagRun.rootDAGRunId &&
dagRun.rootDAGRunName &&
dagRun.rootDAGRunId !== dagRun.dagRunId
);
const getPathParams = (stepName: string) => ({
name: isSubRun ? dagRun.rootDAGRunName : dagName,
dagRunId: isSubRun ? dagRun.rootDAGRunId : dagRun.dagRunId,
stepName,
...(isSubRun ? { subDAGRunId: dagRun.dagRunId } : {}),
});
const handleApprove = async (inputs: Record<string, string>) => {
if (!reviewState) return;
const endpoint = isSubRun
? '/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/approve'
: '/dag-runs/{name}/{dagRunId}/steps/{stepName}/approve';
const { error } = await client.POST(endpoint, {
params: { path: getPathParams(reviewState.node.step.name), query: { remoteNode } },
body: { inputs: Object.keys(inputs).length > 0 ? inputs : undefined },
});
if (error) throw new Error(error.message || 'Failed to approve step');
};
const handlePushBack = async (inputs: Record<string, string>) => {
if (!reviewState) return;
const endpoint = isSubRun
? '/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/push-back'
: '/dag-runs/{name}/{dagRunId}/steps/{stepName}/push-back';
const { error } = await client.POST(endpoint, {
params: { path: getPathParams(reviewState.node.step.name), query: { remoteNode } },
body: { inputs: Object.keys(inputs).length > 0 ? inputs : undefined },
});
if (error) throw new Error(error.message || 'Failed to retry step');
};
if (waitingNodes.length === 0) {
return (
<div className="text-center text-muted-foreground py-8 text-sm">
No steps awaiting approval.
</div>
);
}
return (
<div className="space-y-4">
{waitingNodes.map((node) => (
<ApprovalCard
key={`${node.step.name}-${node.approvalIteration || 0}`}
node={node}
dagRun={dagRun}
dagName={dagName}
onAction={(n, action) => setReviewState({ node: n, action })}
/>
))}
{reviewState && (
<StepReviewModal
visible={!!reviewState}
dismissModal={() => setReviewState(null)}
step={reviewState.node.step}
onApprove={reviewState.action === 'approve' ? handleApprove : undefined}
onPushBack={reviewState.action === 'retry' ? handlePushBack : undefined}
/>
)}
</div>
);
}
@@ -0,0 +1 @@
export { ApprovalTab } from './ApprovalTab';
@@ -17,9 +17,17 @@ import {
import dayjs from '@/lib/dayjs';
import ActionButton from '@/ui/ActionButton';
import StatusChip from '@/ui/StatusChip';
import { AlertTriangle, Play, RefreshCw, Square } from 'lucide-react'; // Import lucide icons
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/CustomDialog';
import { AlertTriangle, Ban, Play, RefreshCw, Square, X } from 'lucide-react';
import React from 'react';
import { components } from '../../../../api/v1/schema';
import { Button } from '@/components/ui/button';
import { components, NodeStatus } from '../../../../api/v1/schema';
import { AppBarContext } from '../../../../contexts/AppBarContext';
import { useConfig } from '../../../../contexts/ConfigContext';
import { useUnsavedChanges } from '../../../../contexts/UnsavedChangesContext';
@@ -74,6 +82,8 @@ function DAGActions({
const [isUnsavedChangesModal, setIsUnsavedChangesModal] = React.useState(false);
const [retryDagRunId, setRetryDagRunId] = React.useState<string>('');
const [stopAllRunning, setStopAllRunning] = React.useState(false);
const [isRejectModal, setIsRejectModal] = React.useState(false);
const [rejectReason, setRejectReason] = React.useState('');
// Retry-as-new modal state
const [retryAsNew, setRetryAsNew] = React.useState(false);
@@ -91,11 +101,15 @@ function DAGActions({
}
};
const isWaiting = status?.status == 7;
const hasNodes = status && 'nodes' in status && Array.isArray((status as components['schemas']['DAGRunDetails']).nodes);
// Determine which buttons should be enabled based on current status
const buttonState = {
enqueue: true, // Always allow enqueuing
enqueue: true,
stop: status?.status == 1,
retry: status?.status != 1 && status?.status != 5 && status?.dagRunId != '', // Disable when running (1) or queued (5)
reject: isWaiting && hasNodes,
retry: status?.status != 1 && status?.status != 5 && status?.dagRunId != '',
};
if (!dag || !config.permissions.runDags) {
@@ -131,23 +145,42 @@ function DAGActions({
</TooltipContent>
</Tooltip>
{/* Stop Button */}
<Tooltip>
<TooltipTrigger asChild>
<ActionButton
label={displayMode !== 'compact'}
icon={<Square className="h-4 w-4" />}
disabled={!buttonState['stop']}
onClick={() => setIsStopModal(true)}
className="cursor-pointer"
>
Stop
</ActionButton>
</TooltipTrigger>
<TooltipContent>
<p>Stop DAG execution</p>
</TooltipContent>
</Tooltip>
{/* Stop / Reject Button */}
{isWaiting && hasNodes ? (
<Tooltip>
<TooltipTrigger asChild>
<ActionButton
label={displayMode !== 'compact'}
icon={<Ban className="h-4 w-4" />}
disabled={!buttonState['reject']}
onClick={() => setIsRejectModal(true)}
className="cursor-pointer"
>
Reject
</ActionButton>
</TooltipTrigger>
<TooltipContent>
<p>Reject all waiting steps</p>
</TooltipContent>
</Tooltip>
) : (
<Tooltip>
<TooltipTrigger asChild>
<ActionButton
label={displayMode !== 'compact'}
icon={<Square className="h-4 w-4" />}
disabled={!buttonState['stop']}
onClick={() => setIsStopModal(true)}
className="cursor-pointer"
>
Stop
</ActionButton>
</TooltipTrigger>
<TooltipContent>
<p>Stop DAG execution</p>
</TooltipContent>
</Tooltip>
)}
{/* Retry Button */}
<Tooltip>
@@ -226,6 +259,64 @@ function DAGActions({
<p>Retry DAG execution</p>
</TooltipContent>
</Tooltip>
{/* Reject Modal */}
<Dialog open={isRejectModal} onOpenChange={(open) => { if (!open) { setIsRejectModal(false); setRejectReason(''); } }}>
<DialogContent className="sm:max-w-[450px]">
<DialogHeader>
<DialogTitle>Reject DAG Run</DialogTitle>
</DialogHeader>
<div className="py-2">
<textarea
className="w-full px-3 py-2 text-sm border border-border rounded bg-background focus:outline-none focus:border-ring resize-none"
placeholder="Reason (optional)..."
rows={2}
value={rejectReason}
onChange={(e) => setRejectReason(e.target.value)}
/>
</div>
<DialogFooter>
<Button variant="ghost" size="sm" onClick={() => { setIsRejectModal(false); setRejectReason(''); }}>
<X className="h-4 w-4" /> Cancel
</Button>
<Button
variant="default"
size="sm"
onClick={async () => {
setIsRejectModal(false);
const details = status as components['schemas']['DAGRunDetails'];
const waitingNodes = details.nodes.filter(n => n.status === NodeStatus.Waiting);
const errors: string[] = [];
for (const node of waitingNodes) {
const { error } = await client.POST(
'/dag-runs/{name}/{dagRunId}/steps/{stepName}/reject',
{
params: {
path: { name: status!.name, dagRunId: status!.dagRunId, stepName: node.step.name },
query: { remoteNode: appBarContext.selectedRemoteNode || 'local' },
},
body: { reason: rejectReason || undefined },
}
);
if (error) {
errors.push(node.step.name);
}
}
if (errors.length > 0) {
showError(
`Failed to reject ${errors.length} step(s)`,
`Failed to reject: ${errors.join(', ')}`
);
}
setRejectReason('');
reloadData();
}}
>
<Ban className="h-4 w-4" /> Reject
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<ConfirmModal
title="Confirmation"
buttonText="Stop"
@@ -0,0 +1,130 @@
import { AppBarContext } from '@/contexts/AppBarContext';
import { useQuery } from '@/hooks/api';
import { useContext } from 'react';
import { components, Stream } from '../../../../api/v1/schema';
/**
* ANSI color codes regex for stripping
*/
const ANSI_CODES_REGEX = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))',
].join('|');
/**
* Simple inline log viewer - no controls, just logs
*/
export function InlineLogViewer({
dagName,
dagRunId,
stepName,
stream,
dagRun,
}: {
dagName: string;
dagRunId: string;
stepName: string;
stream: components['schemas']['Stream'];
dagRun?: components['schemas']['DAGRunDetails'];
}) {
const appBarContext = useContext(AppBarContext);
const remoteNode = appBarContext.selectedRemoteNode || 'local';
// Determine if this is a sub DAG run - check both rootDAGRunId AND rootDAGRunName
const isSubDAGRun =
dagRun &&
dagRun.rootDAGRunId &&
dagRun.rootDAGRunName &&
dagRun.rootDAGRunId !== dagRun.dagRunId;
// Fetch sub-DAG-run step log (only when isSubDAGRun is true)
const subDAGQuery = useQuery(
'/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/log',
{
params: {
query: {
remoteNode,
stream,
tail: 100,
},
path: {
name: dagRun?.rootDAGRunName as string,
dagRunId: dagRun?.rootDAGRunId as string,
subDAGRunId: dagRun?.dagRunId as string,
stepName,
},
},
},
{
refreshInterval: 2000,
revalidateOnFocus: false,
isPaused: () => !isSubDAGRun,
}
);
// Fetch regular DAG-run step log (only when isSubDAGRun is false)
const dagRunQuery = useQuery(
'/dag-runs/{name}/{dagRunId}/steps/{stepName}/log',
{
params: {
query: {
remoteNode,
stream,
tail: 100,
},
path: {
name: dagName,
dagRunId,
stepName,
},
},
},
{
refreshInterval: 2000,
revalidateOnFocus: false,
isPaused: () => !!isSubDAGRun,
}
);
// Use the appropriate query based on whether this is a sub-DAG-run
const { data, isLoading } = isSubDAGRun ? subDAGQuery : dagRunQuery;
// Process log content
const content =
data?.content?.replace(new RegExp(ANSI_CODES_REGEX, 'g'), '') || '';
const lines = content ? content.split('\n') : [];
const totalLines = data?.totalLines || 0;
const lineCount = data?.lineCount || 0;
return (
<div className="bg-muted rounded overflow-hidden border border-border">
{isLoading && !data ? (
<div className="text-muted-foreground text-xs py-4 px-3">Loading logs...</div>
) : lines.length === 0 ? (
<div className="text-muted-foreground text-xs py-4 px-3">
&lt;No log output&gt;
</div>
) : (
<div className="overflow-x-auto max-h-[400px] overflow-y-auto">
<pre className="font-mono text-xs text-foreground p-2">
{lines.map((line, index) => {
const lineNumber = totalLines - lineCount + index + 1;
return (
<div key={index} className="flex px-1 py-0.5">
<span className="text-muted-foreground mr-3 select-none w-12 text-right flex-shrink-0">
{lineNumber}
</span>
<span className="whitespace-pre-wrap break-all flex-grow">
{line || ' '}
</span>
</div>
);
})}
</pre>
</div>
)}
</div>
);
}
export { ANSI_CODES_REGEX, Stream };
@@ -14,7 +14,7 @@ import {
TooltipTrigger,
} from '@/components/ui/tooltip';
import { AppBarContext } from '@/contexts/AppBarContext';
import { useClient, useQuery } from '@/hooks/api';
import { useClient } from '@/hooks/api';
import { getExecutorCommand } from '@/lib/executor-utils';
import dayjs from '@/lib/dayjs';
import { cn } from '@/lib/utils';
@@ -27,8 +27,6 @@ import {
} from '@/ui/CustomDialog';
import {
AlertCircle,
Ban,
Check,
ChevronDown,
ChevronRight,
Code,
@@ -47,8 +45,7 @@ import {
} from '../../../../api/v1/schema';
import StyledTableRow from '../../../../ui/StyledTableRow';
import { NodeStatusChip } from '../common';
import { ApprovalModal } from '../dag-execution/ApprovalModal';
import { RejectionModal } from '../dag-execution/RejectionModal';
import { InlineLogViewer } from '../common/InlineLogViewer';
import StatusUpdateModal from '../dag-execution/StatusUpdateModal';
import { SubDAGRunsList } from './SubDAGRunsList';
@@ -86,130 +83,6 @@ const formatTimestamp = (timestamp: string | undefined) => {
}
};
/**
* ANSI color codes regex for stripping
*/
const ANSI_CODES_REGEX = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))',
].join('|');
/**
* Simple inline log viewer - no controls, just logs
*/
function InlineLogViewer({
dagName,
dagRunId,
stepName,
stream,
dagRun,
}: {
dagName: string;
dagRunId: string;
stepName: string;
stream: components['schemas']['Stream'];
dagRun?: components['schemas']['DAGRunDetails'];
}) {
const appBarContext = useContext(AppBarContext);
const remoteNode = appBarContext.selectedRemoteNode || 'local';
// Determine if this is a sub DAG run - check both rootDAGRunId AND rootDAGRunName
const isSubDAGRun =
dagRun &&
dagRun.rootDAGRunId &&
dagRun.rootDAGRunName &&
dagRun.rootDAGRunId !== dagRun.dagRunId;
// Fetch sub-DAG-run step log (only when isSubDAGRun is true)
const subDAGQuery = useQuery(
'/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/log',
{
params: {
query: {
remoteNode,
stream,
tail: 100,
},
path: {
name: dagRun?.rootDAGRunName as string,
dagRunId: dagRun?.rootDAGRunId as string,
subDAGRunId: dagRun?.dagRunId as string,
stepName,
},
},
},
{
refreshInterval: 2000,
revalidateOnFocus: false,
isPaused: () => !isSubDAGRun,
}
);
// Fetch regular DAG-run step log (only when isSubDAGRun is false)
const dagRunQuery = useQuery(
'/dag-runs/{name}/{dagRunId}/steps/{stepName}/log',
{
params: {
query: {
remoteNode,
stream,
tail: 100,
},
path: {
name: dagName,
dagRunId,
stepName,
},
},
},
{
refreshInterval: 2000,
revalidateOnFocus: false,
isPaused: () => !!isSubDAGRun,
}
);
// Use the appropriate query based on whether this is a sub-DAG-run
const { data, isLoading } = isSubDAGRun ? subDAGQuery : dagRunQuery;
// Process log content
const content =
data?.content?.replace(new RegExp(ANSI_CODES_REGEX, 'g'), '') || '';
const lines = content ? content.split('\n') : [];
const totalLines = data?.totalLines || 0;
const lineCount = data?.lineCount || 0;
return (
<div className="bg-muted rounded overflow-hidden border border-border">
{isLoading && !data ? (
<div className="text-muted-foreground text-xs py-4 px-3">Loading logs...</div>
) : lines.length === 0 ? (
<div className="text-muted-foreground text-xs py-4 px-3">
&lt;No log output&gt;
</div>
) : (
<div className="overflow-x-auto max-h-[400px] overflow-y-auto">
<pre className="font-mono text-xs text-foreground p-2">
{lines.map((line, index) => {
const lineNumber = totalLines - lineCount + index + 1;
return (
<div key={index} className="flex px-1 py-0.5">
<span className="text-muted-foreground mr-3 select-none w-12 text-right flex-shrink-0">
{lineNumber}
</span>
<span className="whitespace-pre-wrap break-all flex-grow">
{line || ' '}
</span>
</div>
);
})}
</pre>
</div>
)}
</div>
);
}
/**
* Calculate duration between two timestamps
* If endTime is not provided, calculate duration from startTime to now (for running tasks)
@@ -279,10 +152,6 @@ function NodeStatusTableRow({
);
// State for status update modal
const [showStatusModal, setShowStatusModal] = useState(false);
// State for approval modal
const [showApprovalModal, setShowApprovalModal] = useState(false);
// State for rejection modal
const [showRejectionModal, setShowRejectionModal] = useState(false);
// Check if this is a sub dagRun node
// Include both regular and repeated sub runs
const allSubRuns = [...(node.subRuns || []), ...(node.subRunsRepeated || [])];
@@ -328,6 +197,8 @@ function NodeStatusTableRow({
return 'bg-success-muted';
case NodeStatus.Failed:
return 'bg-error-muted';
case NodeStatus.Waiting:
return 'bg-warning/5';
default:
return '';
}
@@ -491,82 +362,6 @@ function NodeStatusTableRow({
setShowStatusModal(false);
};
// Handle approval for wait steps
const handleApprove = async (inputs: Record<string, string>) => {
// Check if this is a sub DAG-run
const isSubDAGRun =
dagRun.rootDAGRunId &&
dagRun.rootDAGRunName &&
dagRun.rootDAGRunId !== dagRun.dagRunId;
// Define path parameters
const pathParams = {
name: isSubDAGRun ? dagRun.rootDAGRunName : dagName,
dagRunId: isSubDAGRun ? dagRun.rootDAGRunId : dagRunId || '',
stepName: node.step.name,
...(isSubDAGRun ? { subDAGRunId: dagRun.dagRunId } : {}),
};
// Use the appropriate endpoint
const endpoint = isSubDAGRun
? '/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/approve'
: '/dag-runs/{name}/{dagRunId}/steps/{stepName}/approve';
const { error } = await client.POST(endpoint, {
params: {
path: pathParams,
query: {
remoteNode,
},
},
body: {
inputs: Object.keys(inputs).length > 0 ? inputs : undefined,
},
});
if (error) {
throw new Error(error.message || 'Failed to approve step');
}
};
// Handle rejection for wait steps
const handleReject = async (reason: string) => {
// Check if this is a sub DAG-run
const isSubDAGRun =
dagRun.rootDAGRunId &&
dagRun.rootDAGRunName &&
dagRun.rootDAGRunId !== dagRun.dagRunId;
// Define path parameters
const pathParams = {
name: isSubDAGRun ? dagRun.rootDAGRunName : dagName,
dagRunId: isSubDAGRun ? dagRun.rootDAGRunId : dagRunId || '',
stepName: node.step.name,
...(isSubDAGRun ? { subDAGRunId: dagRun.dagRunId } : {}),
};
// Use the appropriate endpoint
const endpoint = isSubDAGRun
? '/dag-runs/{name}/{dagRunId}/sub-dag-runs/{subDAGRunId}/steps/{stepName}/reject'
: '/dag-runs/{name}/{dagRunId}/steps/{stepName}/reject';
const { error } = await client.POST(endpoint, {
params: {
path: pathParams,
query: {
remoteNode,
},
},
body: {
reason: reason || undefined,
},
});
if (error) {
throw new Error(error.message || 'Failed to reject step');
}
};
// Determine if logs are available
const hasStdout = !!node.stdout;
const hasStderr = !!node.stderr;
@@ -768,7 +563,7 @@ function NodeStatusTableRow({
{currentDuration}
</div>
)}
{/* Approval info for HITL steps */}
{/* Approval info */}
{node.approvedBy && (
<div className="text-xs text-muted-foreground leading-tight">
<span className="font-medium">Approved by:</span>{' '}
@@ -789,7 +584,7 @@ function NodeStatusTableRow({
</span>
</div>
)}
{/* Rejection info for rejected HITL steps */}
{/* Rejection info */}
{node.rejectedBy && (
<div className="text-xs text-muted-foreground leading-tight">
<span className="font-medium">Rejected by:</span>{' '}
@@ -907,33 +702,6 @@ function NodeStatusTableRow({
{dagRunId && (
<TableCell className="text-center">
<div className="flex items-center justify-center gap-1">
{/* Approve button for waiting steps */}
{node.status === NodeStatus.Waiting && (
<>
<Button
size="icon-sm"
className="btn-3d-secondary bg-warning/10 hover:bg-warning/20"
title="Approve this step"
onClick={(e) => {
e.stopPropagation();
setShowApprovalModal(true);
}}
>
<Check className="h-4 w-4 text-warning" />
</Button>
<Button
size="icon-sm"
className="btn-3d-secondary bg-error/10 hover:bg-error/20"
title="Reject this step"
onClick={(e) => {
e.stopPropagation();
setShowRejectionModal(true);
}}
>
<Ban className="h-4 w-4 text-error" />
</Button>
</>
)}
{/* Retry button - hidden for Waiting and Rejected steps */}
{node.status !== NodeStatus.Waiting &&
node.status !== NodeStatus.Rejected && (
@@ -1072,21 +840,6 @@ function NodeStatusTableRow({
onSubmit={handleStatusUpdate}
/>
{/* Approval Modal for wait steps */}
<ApprovalModal
visible={showApprovalModal}
dismissModal={() => setShowApprovalModal(false)}
step={node.step}
onApprove={handleApprove}
/>
{/* Rejection Modal for wait steps */}
<RejectionModal
visible={showRejectionModal}
dismissModal={() => setShowRejectionModal(false)}
step={node.step}
onReject={handleReject}
/>
</>
);
}
@@ -1239,7 +992,7 @@ function NodeStatusTableRow({
{currentDuration}
</div>
)}
{/* Approval info for HITL steps */}
{/* Approval info */}
{node.approvedBy && (
<div className="text-xs text-muted-foreground">
<span className="font-medium">Approved by:</span>{' '}
@@ -1260,7 +1013,7 @@ function NodeStatusTableRow({
</span>
</div>
)}
{/* Rejection info for rejected HITL steps */}
{/* Rejection info */}
{node.rejectedBy && (
<div className="text-xs text-muted-foreground">
<span className="font-medium">Rejected by:</span>{' '}
@@ -1361,25 +1114,6 @@ function NodeStatusTableRow({
{dagRunId && (
<div className="flex justify-end mt-4 gap-2">
{/* Approve and Reject buttons for waiting steps */}
{node.status === NodeStatus.Waiting && (
<>
<button
className="p-2 rounded-full hover:bg-warning/20 bg-warning/10"
title="Approve this step"
onClick={() => setShowApprovalModal(true)}
>
<Check className="h-6 w-6 text-warning" />
</button>
<button
className="p-2 rounded-full hover:bg-error/20 bg-error/10"
title="Reject this step"
onClick={() => setShowRejectionModal(true)}
>
<Ban className="h-6 w-6 text-error" />
</button>
</>
)}
{/* Retry button - hidden for Waiting and Rejected steps */}
{node.status !== NodeStatus.Waiting &&
node.status !== NodeStatus.Rejected && (
@@ -1422,21 +1156,6 @@ function NodeStatusTableRow({
</DialogContent>
</Dialog>
{/* Approval Modal for wait steps */}
<ApprovalModal
visible={showApprovalModal}
dismissModal={() => setShowApprovalModal(false)}
step={node.step}
onApprove={handleApprove}
/>
{/* Rejection Modal for wait steps */}
<RejectionModal
visible={showRejectionModal}
dismissModal={() => setShowRejectionModal(false)}
step={node.step}
onReject={handleReject}
/>
</div>
)}
</div>
@@ -1,122 +0,0 @@
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/CustomDialog';
import { Ban, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { components } from '../../../../api/v1/schema';
type Step = components['schemas']['Step'];
type Props = {
visible: boolean;
dismissModal: () => void;
step: Step;
onReject: (reason: string) => Promise<void>;
};
/**
* RejectionModal displays a form for rejecting a wait step with an optional reason.
*/
export function RejectionModal({ visible, dismissModal, step, onReject }: Props) {
const [reason, setReason] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Reset state when modal opens
useEffect(() => {
if (visible) {
setReason('');
setError(null);
setLoading(false);
}
}, [visible]);
const handleReject = async () => {
setLoading(true);
setError(null);
try {
await onReject(reason);
dismissModal();
} catch (e) {
const err = e as { message?: string };
setError(err.message || 'Failed to reject step');
} finally {
setLoading(false);
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey && !loading) {
e.preventDefault();
handleReject();
}
};
return (
<Dialog open={visible} onOpenChange={dismissModal}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle className="text-base">
Reject: {step.name}
</DialogTitle>
</DialogHeader>
<div className="py-2 space-y-4">
<div className="text-sm text-muted-foreground">
Are you sure you want to reject this step? Dependent steps will be aborted.
</div>
{/* Optional reason field */}
<div>
<label htmlFor="rejection-reason" className="block text-sm font-semibold mb-1">
Reason <span className="text-muted-foreground">(optional)</span>
</label>
<textarea
id="rejection-reason"
value={reason}
onChange={(e) => setReason(e.target.value)}
onKeyDown={handleKeyDown}
className="w-full px-3 py-2 text-sm border border-border rounded bg-background focus:outline-none focus:border-ring resize-none"
placeholder="Enter a reason for rejection..."
rows={3}
/>
</div>
{/* Error message */}
{error && (
<div className="text-sm text-error bg-error-muted p-2 rounded">
{error}
</div>
)}
</div>
<DialogFooter>
<Button
size="sm"
variant="ghost"
onClick={dismissModal}
disabled={loading}
>
<X className="h-4 w-4" />
Cancel
</Button>
<Button
size="sm"
onClick={handleReject}
disabled={loading}
className="bg-error hover:bg-error/90"
>
<Ban className="h-4 w-4" />
{loading ? 'Rejecting...' : 'Reject'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -6,40 +6,38 @@ import {
DialogHeader,
DialogTitle,
} from '@/ui/CustomDialog';
import { Check, X } from 'lucide-react';
import { Check, RotateCcw, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { components } from '../../../../api/v1/schema';
type Step = components['schemas']['Step'];
type WaitConfig = {
prompt?: string;
input?: string[];
required?: string[];
};
type Props = {
visible: boolean;
dismissModal: () => void;
step: Step;
onApprove: (inputs: Record<string, string>) => Promise<void>;
onApprove?: (inputs: Record<string, string>) => Promise<void>;
onPushBack?: (inputs: Record<string, string>) => Promise<void>;
};
/**
* ApprovalModal displays a form for approving a wait step with optional input fields.
*/
export function ApprovalModal({ visible, dismissModal, step, onApprove }: Props) {
export function StepReviewModal({
visible,
dismissModal,
step,
onApprove,
onPushBack,
}: Props) {
const [inputs, setInputs] = useState<Record<string, string>>({});
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Extract wait config from step's executorConfig
const waitConfig: WaitConfig = (step.executorConfig?.config as WaitConfig) || {};
const inputFields = waitConfig.input || [];
const requiredFields = waitConfig.required || [];
const prompt = waitConfig.prompt || step.description;
const inputFields = step.approval?.input || [];
const requiredFields = step.approval?.required || [];
const isValid = requiredFields.every(
(field) => inputs[field] && inputs[field].trim() !== ''
);
// Reset state when modal opens
useEffect(() => {
if (visible) {
setInputs({});
@@ -48,80 +46,76 @@ export function ApprovalModal({ visible, dismissModal, step, onApprove }: Props)
}
}, [visible]);
// Check if all required fields are filled
const isValid = requiredFields.every(
(field) => inputs[field] && inputs[field].trim() !== ''
);
const handleApprove = async () => {
const handleAction = async (
action: (inputs: Record<string, string>) => Promise<void>,
errorLabel: string
) => {
if (!isValid) {
setError('Please fill in all required fields');
return;
}
setLoading(true);
setError(null);
try {
await onApprove(inputs);
await action(inputs);
dismissModal();
} catch (e) {
const err = e as { message?: string };
setError(err.message || 'Failed to approve step');
setError(err.message || `Failed to ${errorLabel} step`);
} finally {
setLoading(false);
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey && isValid && !loading) {
e.preventDefault();
handleApprove();
const handleSubmit = () => {
if (onApprove) {
handleAction(onApprove, 'approve');
} else if (onPushBack) {
handleAction(onPushBack, 'retry');
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey && !loading) {
e.preventDefault();
handleSubmit();
}
};
const actionLabel = onApprove ? 'Approve' : 'Retry';
const actionIcon = onApprove
? <Check className="h-4 w-4" />
: <RotateCcw className="h-4 w-4" />;
const actionVariant = onApprove ? 'primary' as const : 'outline' as const;
return (
<Dialog open={visible} onOpenChange={dismissModal}>
<DialogContent className="sm:max-w-[500px]">
<DialogContent className="sm:max-w-[450px]">
<DialogHeader>
<DialogTitle className="text-base">
Approve: {step.name}
{actionLabel}: {step.name}
</DialogTitle>
</DialogHeader>
<div className="py-2 space-y-4">
{/* Prompt message */}
{prompt && (
<div className="text-sm text-muted-foreground whitespace-pre-wrap bg-muted p-3 rounded">
{prompt}
</div>
)}
{/* Input fields */}
<div className="py-2 space-y-3" onKeyDown={handleKeyDown}>
{inputFields.length > 0 && (
<div className="space-y-3">
{inputFields.map((field) => {
const isRequired = requiredFields.includes(field);
const fieldId = `approval-input-${field}`;
const fieldId = `review-input-${field}`;
return (
<div key={field}>
<label htmlFor={fieldId} className="block text-sm font-medium mb-1">
{field}
{isRequired && (
<span className="text-error ml-1">*</span>
)}
{isRequired && <span className="text-error ml-1">*</span>}
</label>
<input
id={fieldId}
type="text"
value={inputs[field] || ''}
onChange={(e) =>
setInputs((prev) => ({
...prev,
[field]: e.target.value,
}))
setInputs((prev) => ({ ...prev, [field]: e.target.value }))
}
onKeyDown={handleKeyDown}
className="w-full px-3 py-1 text-sm border border-border rounded bg-background focus:outline-none focus:border-ring"
placeholder={`Enter ${field}`}
/>
@@ -131,14 +125,6 @@ export function ApprovalModal({ visible, dismissModal, step, onApprove }: Props)
</div>
)}
{/* No input fields message */}
{inputFields.length === 0 && !prompt && (
<div className="text-sm text-muted-foreground">
Click Approve to continue the workflow execution.
</div>
)}
{/* Error message */}
{error && (
<div className="text-sm text-error bg-error-muted p-2 rounded">
{error}
@@ -158,12 +144,12 @@ export function ApprovalModal({ visible, dismissModal, step, onApprove }: Props)
</Button>
<Button
size="sm"
onClick={handleApprove}
variant={actionVariant}
onClick={handleSubmit}
disabled={loading || (!isValid && requiredFields.length > 0)}
className="bg-success hover:bg-success/90"
>
<Check className="h-4 w-4" />
{loading ? 'Approving...' : 'Approve'}
{actionIcon}
{loading ? `${actionLabel}...` : actionLabel}
</Button>
</DialogFooter>
</DialogContent>