ui

package
v0.11.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: EUPL-1.2 Imports: 23 Imported by: 0

Documentation

Overview

Package ui provides user interface components for the AWF CLI.

The ui package implements output formatting, interactive prompts, input collection, and visual presentation for the command-line interface.

Output Formatting

The package supports multiple output formats (text, JSON, table, quiet) via OutputWriter, which handles workflow listings, execution status, validation results, and error display:

writer := ui.NewOutputWriter(os.Stdout, ui.FormatTable)
writer.WriteExecution(executionInfo)
writer.WriteError(err)

Color System

Colorizer provides semantic color coding with automatic detection of terminal capabilities:

c := ui.NewColorizer()
fmt.Println(c.Success("Workflow completed"))
fmt.Println(c.Error("Step failed"))

Interactive Prompts

CLIPrompt implements step-by-step interactive execution with step details, context display, and action selection (execute/skip/abort):

prompt := ui.NewCLIPrompt()
prompt.ShowStepDetails(step)
action, err := prompt.PromptAction()

Input Collection

CLIInputCollector handles runtime input prompts with type coercion and validation:

collector := ui.NewCLIInputCollector(schema)
values, err := collector.PromptForInput()

Dry Run Formatting

DryRunFormatter generates human-readable previews of workflow execution without running commands:

formatter := ui.NewDryRunFormatter()
formatter.Format(workflow)

The package integrates with the CLI layer to provide consistent visual presentation across all AWF commands.

Index

Constants

This section is empty.

Variables

View Source
var (
	NewHumanErrorFormatter = errfmt.NewHumanErrorFormatter
)

Factory functions for error formatters

Functions

func RenderEvents added in v0.11.2

func RenderEvents(w io.Writer, events []display.DisplayEvent, mode display.DisplayMode)

RenderEvents writes the displayable content of events to w according to mode. Default mode emits text content only; verbose mode also emits tool-use markers in the form [tool: Name(Arg)].

Types

type CLIInputCollector

type CLIInputCollector struct {
	// contains filtered or unexported fields
}

CLIInputCollector implements InputCollector for terminal-based input collection. It uses bufio.Reader for stdin interaction with support for:

  • Enum display as numbered lists (1-9)
  • Validation with error messages and retry
  • Optional input skipping with default values
  • Type coercion (string → int, bool)
  • Graceful cancellation (Ctrl+C, EOF)

func NewCLIInputCollector

func NewCLIInputCollector(reader io.Reader, writer io.Writer, colorizer *Colorizer) *CLIInputCollector

NewCLIInputCollector creates a new CLI input collector with the given I/O streams. The colorizer parameter controls terminal color output for prompts and errors.

func (*CLIInputCollector) PromptForInput

func (c *CLIInputCollector) PromptForInput(ctx context.Context, input *workflow.Input) (any, error)

PromptForInput prompts the user to provide a value for a single workflow input.

Behavior:

  • Display input metadata (name, type, description, required status)
  • Show numbered list (1-9) for enum inputs with <= 9 options
  • Show freetext prompt for other inputs or enums with >9 options
  • Validate input values against workflow.InputValidation constraints
  • Re-prompt on validation errors with specific error messages
  • Handle empty input: error for required, default/nil for optional
  • Apply type coercion based on input.Type (string/integer/boolean)
  • Detect EOF (Ctrl+D) and return cancellation error

type CLIPrompt

type CLIPrompt struct {
	// contains filtered or unexported fields
}

CLIPrompt implements InteractivePrompt for terminal-based interaction.

func NewCLIPrompt

func NewCLIPrompt(reader io.Reader, writer io.Writer, colorEnabled bool) *CLIPrompt

NewCLIPrompt creates a new CLI prompt with the given I/O streams.

func (*CLIPrompt) EditInput

func (p *CLIPrompt) EditInput(ctx context.Context, name string, current any) (any, error)

EditInput prompts the user to edit an input value.

func (*CLIPrompt) PromptAction

func (p *CLIPrompt) PromptAction(ctx context.Context, hasRetry bool) (workflow.InteractiveAction, error)

PromptAction prompts the user for an action and returns their choice.

func (*CLIPrompt) ShowAborted

func (p *CLIPrompt) ShowAborted()

ShowAborted displays a message indicating workflow was aborted.

func (*CLIPrompt) ShowCompleted

func (p *CLIPrompt) ShowCompleted(status workflow.ExecutionStatus)

ShowCompleted displays a message indicating workflow completed.

func (*CLIPrompt) ShowContext

func (p *CLIPrompt) ShowContext(ctx *workflow.RuntimeContext)

ShowContext displays the current runtime context.

func (*CLIPrompt) ShowError

func (p *CLIPrompt) ShowError(err error)

ShowError displays an error message.

func (*CLIPrompt) ShowExecuting

func (p *CLIPrompt) ShowExecuting(stepName string)

ShowExecuting displays a message indicating step execution is in progress.

func (*CLIPrompt) ShowHeader

func (p *CLIPrompt) ShowHeader(workflowName string)

ShowHeader displays the interactive mode header with workflow name.

func (*CLIPrompt) ShowSkipped

func (p *CLIPrompt) ShowSkipped(stepName, nextStep string)

ShowSkipped displays a message indicating step was skipped.

func (*CLIPrompt) ShowStepDetails

func (p *CLIPrompt) ShowStepDetails(info *workflow.InteractiveStepInfo)

ShowStepDetails displays step information before execution.

func (*CLIPrompt) ShowStepResult

func (p *CLIPrompt) ShowStepResult(state *workflow.StepState, nextStep string)

ShowStepResult displays the outcome of step execution.

type CapabilityEntry added in v0.5.0

type CapabilityEntry struct {
	Type   string `json:"type"`
	Name   string `json:"name"`
	Plugin string `json:"plugin"`
}

CapabilityEntry represents a unified capability for --details listing.

type Colorizer

type Colorizer struct {
	// contains filtered or unexported fields
}

Colorizer provides colored output for CLI.

func NewColorizer

func NewColorizer(enabled bool) *Colorizer

NewColorizer creates a new colorizer.

Color enablement is set per *color.Color instance rather than through the fatih/color package global (color.NoColor). Mutating that global here raced with concurrent Sprint reads from the facade execution goroutine and the event projector (both build/use colorizers on the shared run path). Pinning each instance's state via Enable/DisableColor makes Sprint read the per-instance flag and never touch the package global.

func (*Colorizer) Bold

func (c *Colorizer) Bold(s string) string

Bold formats text as bold.

func (*Colorizer) Dim

func (c *Colorizer) Dim(s string) string

Dim formats text as dimmed.

func (*Colorizer) Error

func (c *Colorizer) Error(s string) string

Error formats text as error (red).

func (*Colorizer) Info

func (c *Colorizer) Info(s string) string

Info formats text as info (cyan).

func (*Colorizer) Status

func (c *Colorizer) Status(status, text string) string

Status formats text based on execution status.

func (*Colorizer) Success

func (c *Colorizer) Success(s string) string

Success formats text as success (green).

func (*Colorizer) Warning

func (c *Colorizer) Warning(s string) string

Warning formats text as warning (yellow).

type DryRunFormatter

type DryRunFormatter struct {
	// contains filtered or unexported fields
}

DryRunFormatter formats dry-run execution plans for display.

func NewDryRunFormatter

func NewDryRunFormatter(out io.Writer, useColor bool) *DryRunFormatter

NewDryRunFormatter creates a new DryRunFormatter.

func NewDryRunFormatterWithWriter

func NewDryRunFormatterWithWriter(out io.Writer, useColor bool) *DryRunFormatter

NewDryRunFormatterWithWriter creates a DryRunFormatter with custom writer (for testing).

func (*DryRunFormatter) Format

func (f *DryRunFormatter) Format(plan *workflow.DryRunPlan) error

Format renders the dry-run plan to the output writer.

func (*DryRunFormatter) FormatCapture

func (f *DryRunFormatter) FormatCapture(capture *workflow.DryRunCapture) error

FormatCapture formats capture configuration.

func (*DryRunFormatter) FormatFieldIfPresent

func (f *DryRunFormatter) FormatFieldIfPresent(label, value string) error

FormatFieldIfPresent formats a configuration field if value is non-empty.

func (*DryRunFormatter) FormatIntFieldIfPositive

func (f *DryRunFormatter) FormatIntFieldIfPositive(label string, value int, unit string) error

FormatIntFieldIfPositive formats an integer field if value is positive.

func (*DryRunFormatter) FormatRetry

func (f *DryRunFormatter) FormatRetry(retry *workflow.DryRunRetry) error

FormatRetry formats retry configuration.

type ErrorFormatter

type ErrorFormatter = ports.ErrorFormatter

Type aliases for error formatting interfaces

type ErrorResponse

type ErrorResponse struct {
	Error     string `json:"error"`
	Code      int    `json:"code"`
	ErrorCode string `json:"error_code,omitempty"` // Hierarchical error code (e.g., "USER.INPUT.MISSING_FILE")
}

ErrorResponse is the JSON structure for errors.

type ExecutionInfo

type ExecutionInfo struct {
	WorkflowID   string     `json:"workflow_id"`
	WorkflowName string     `json:"workflow_name"`
	Status       string     `json:"status"`
	CurrentStep  string     `json:"current_step,omitempty"`
	StartedAt    string     `json:"started_at,omitempty"`
	CompletedAt  string     `json:"completed_at,omitempty"`
	DurationMs   int64      `json:"duration_ms"`
	Steps        []StepInfo `json:"steps,omitempty"`
}

ExecutionInfo is the JSON structure for status command.

type FormatOptions

type FormatOptions struct {
	Verbose bool
	Quiet   bool
	NoColor bool
}

FormatOptions configures formatter behavior.

type Formatter

type Formatter struct {
	// contains filtered or unexported fields
}

Formatter handles CLI output formatting.

func NewFormatter

func NewFormatter(out io.Writer, opts FormatOptions) *Formatter

NewFormatter creates a new formatter.

func (*Formatter) Colorizer

func (f *Formatter) Colorizer() *Colorizer

Colorizer returns the underlying colorizer.

func (*Formatter) Debug

func (f *Formatter) Debug(msg string)

Debug writes a debug message (only in verbose mode).

func (*Formatter) Error

func (f *Formatter) Error(msg string)

Error writes an error message (always shown).

func (*Formatter) Info

func (f *Formatter) Info(msg string)

Info writes an info message (suppressed in quiet mode).

func (*Formatter) Printf

func (f *Formatter) Printf(format string, args ...any)

Printf writes formatted output.

func (*Formatter) Println

func (f *Formatter) Println(args ...any)

Println writes a line.

func (*Formatter) StatusLine

func (f *Formatter) StatusLine(label, status, detail string)

StatusLine writes a status line with colored status.

func (*Formatter) StepSuccess

func (f *Formatter) StepSuccess(stepID string)

StepSuccess displays success feedback for steps with no output. Hidden in quiet mode.

func (*Formatter) Success

func (f *Formatter) Success(msg string)

Success writes a success message.

func (*Formatter) Table

func (f *Formatter) Table(headers []string, rows [][]string)

Table renders data as a formatted table.

func (*Formatter) Warning

func (f *Formatter) Warning(msg string)

Warning writes a warning message.

type InputInfo

type InputInfo struct {
	Name        string
	Type        string
	Required    bool
	Default     string
	Description string
}

InputInfo represents workflow input for table output.

type OperationEntry

type OperationEntry struct {
	Name   string `json:"name"`
	Plugin string `json:"plugin"`
}

OperationEntry represents an operation for operation listing.

type OutputFormat

type OutputFormat int

OutputFormat defines the output format for CLI commands.

const (
	FormatText  OutputFormat = iota // default: human-readable
	FormatJSON                      // JSON output
	FormatTable                     // tabular output
	FormatQuiet                     // minimal: IDs/names only
)

func ParseOutputFormat

func ParseOutputFormat(s string) (OutputFormat, error)

ParseOutputFormat parses a string to OutputFormat.

func (OutputFormat) String

func (f OutputFormat) String() string

type OutputWriter

type OutputWriter struct {
	// contains filtered or unexported fields
}

OutputWriter handles structured output for different formats.

func NewOutputWriter

func NewOutputWriter(out, errOut io.Writer, format OutputFormat, noColor, noHints bool) *OutputWriter

NewOutputWriter creates a writer for the specified format.

func (*OutputWriter) IsJSONFormat

func (w *OutputWriter) IsJSONFormat() bool

IsJSONFormat returns true if the output format is JSON.

func (*OutputWriter) Out

func (w *OutputWriter) Out() io.Writer

Out returns the output writer.

func (*OutputWriter) WriteCapabilities added in v0.5.0

func (w *OutputWriter) WriteCapabilities(entries []CapabilityEntry) error

WriteCapabilities outputs unified capability list (--details).

func (*OutputWriter) WriteDryRun

func (w *OutputWriter) WriteDryRun(plan *workflow.DryRunPlan, formatter *DryRunFormatter) error

WriteDryRun outputs the dry-run execution plan.

func (*OutputWriter) WriteError

func (w *OutputWriter) WriteError(err error, code int) error

WriteError outputs an error in the appropriate format. Detects StructuredError and uses formatters for enhanced error output. When err wraps multiple errors via errors.Join, each nested StructuredError is rendered individually so the user sees all validation failures at once.

func (*OutputWriter) WriteExecution

func (w *OutputWriter) WriteExecution(exec *ExecutionInfo) error

WriteExecution outputs execution status.

func (*OutputWriter) WriteJSON

func (w *OutputWriter) WriteJSON(v any) error

WriteJSON outputs any value as JSON.

func (*OutputWriter) WriteOperations

func (w *OutputWriter) WriteOperations(operations []OperationEntry) error

WriteOperations outputs operation list.

func (*OutputWriter) WritePlugins

func (w *OutputWriter) WritePlugins(plugins []PluginInfo) error

WritePlugins outputs plugin list.

func (*OutputWriter) WritePrompts

func (w *OutputWriter) WritePrompts(prompts []PromptInfo) error

WritePrompts outputs prompt file list.

func (*OutputWriter) WriteResumableList

func (w *OutputWriter) WriteResumableList(infos []ResumableInfo) error

WriteResumableList outputs a list of resumable workflows.

func (*OutputWriter) WriteRunResult

func (w *OutputWriter) WriteRunResult(result *RunResult) error

WriteRunResult outputs run command result.

func (*OutputWriter) WriteStepTypes added in v0.5.0

func (w *OutputWriter) WriteStepTypes(entries []OperationEntry) error

WriteStepTypes outputs step type list (--step-types).

func (*OutputWriter) WriteValidation

func (w *OutputWriter) WriteValidation(result ValidationResult) error

WriteValidation outputs validation result.

func (*OutputWriter) WriteValidationTable

func (w *OutputWriter) WriteValidationTable(result *ValidationResultTable) error

WriteValidationTable outputs validation result with detailed table.

func (*OutputWriter) WriteValidators added in v0.5.0

func (w *OutputWriter) WriteValidators(entries []ValidatorEntry) error

WriteValidators outputs validator plugin list (--validators).

func (*OutputWriter) WriteWorkflowPacks added in v0.11.2

func (w *OutputWriter) WriteWorkflowPacks(packs []WorkflowPackInfo) error

WriteWorkflowPacks outputs workflow pack list.

func (*OutputWriter) WriteWorkflows

func (w *OutputWriter) WriteWorkflows(workflows []WorkflowInfo) error

WriteWorkflows outputs workflow list.

type PluginInfo

type PluginInfo struct {
	Name         string   `json:"name"`
	Type         string   `json:"type,omitempty"`
	Version      string   `json:"version,omitempty"`
	Description  string   `json:"description,omitempty"`
	Status       string   `json:"status"`
	Enabled      bool     `json:"enabled"`
	Capabilities []string `json:"capabilities,omitempty"`
	Operations   []string `json:"operations,omitempty"`
	StepTypes    []string `json:"step_types,omitempty"`
	Source       string   `json:"source,omitempty"`
}

PluginInfo represents a plugin for list plugins command.

type PrefixType

type PrefixType int

PrefixType indicates stdout or stderr prefixing.

const (
	PrefixStdout PrefixType = iota
	PrefixStderr
)

type PrefixedWriter

type PrefixedWriter struct {
	// contains filtered or unexported fields
}

PrefixedWriter wraps an io.Writer and prefixes each line.

func NewPrefixedWriter

func NewPrefixedWriter(out io.Writer, prefix PrefixType, stepName string, colorizer *Colorizer) *PrefixedWriter

NewPrefixedWriter creates a new prefixed writer.

func (*PrefixedWriter) Flush

func (w *PrefixedWriter) Flush()

Flush writes any remaining buffered content.

func (*PrefixedWriter) Write

func (w *PrefixedWriter) Write(p []byte) (n int, err error)

Write implements io.Writer with line prefixing.

type PromptInfo

type PromptInfo struct {
	Name    string `json:"name"`
	Source  string `json:"source"`
	Path    string `json:"path"`
	Size    int64  `json:"size"`
	ModTime string `json:"mod_time,omitempty"`
}

PromptInfo represents a prompt file for list prompts command.

type ResumableInfo

type ResumableInfo struct {
	WorkflowID   string `json:"workflow_id"`
	WorkflowName string `json:"workflow_name"`
	Status       string `json:"status"`
	CurrentStep  string `json:"current_step"`
	UpdatedAt    string `json:"updated_at"`
	Progress     string `json:"progress"`
}

ResumableInfo contains information for resumable workflow display.

type RunResult

type RunResult struct {
	WorkflowID string     `json:"workflow_id"`
	Status     string     `json:"status"`
	DurationMs int64      `json:"duration_ms"`
	Error      string     `json:"error,omitempty"`
	Steps      []StepInfo `json:"steps,omitempty"`
}

RunResult is the JSON structure for run command.

type StdinInputReader added in v0.11.2

type StdinInputReader struct {
	// contains filtered or unexported fields
}

StdinInputReader implements UserInputReader for terminal-based conversation input.

func NewStdinInputReader added in v0.11.2

func NewStdinInputReader(r io.Reader, w io.Writer) *StdinInputReader

NewStdinInputReader creates a StdinInputReader reading from r and writing the prompt to w.

func (*StdinInputReader) PreflightInput added in v0.11.4

func (s *StdinInputReader) PreflightInput(ctx context.Context) error

PreflightInput rejects unusable CLI stdin without reading or waiting on a pipe. Explicit in-memory readers remain supported for scripted input and tests.

func (*StdinInputReader) ReadInput added in v0.11.2

func (s *StdinInputReader) ReadInput(ctx context.Context) (string, error)

ReadInput prints "> " and reads one line from stdin. Returns empty string when the user submits no input (signals conversation end). Returns error on context cancellation or I/O failure.

type StepInfo

type StepInfo struct {
	Name        string `json:"name"`
	Status      string `json:"status"`
	Output      string `json:"output,omitempty"`
	Stderr      string `json:"stderr,omitempty"`
	ExitCode    int    `json:"exit_code,omitempty"`
	StartedAt   string `json:"started_at,omitempty"`
	CompletedAt string `json:"completed_at,omitempty"`
	Error       string `json:"error,omitempty"`
}

StepInfo is the JSON structure for step status.

type StepSummary

type StepSummary struct {
	Name string
	Type string
	Next string
}

StepSummary represents a workflow step summary for table output.

type SyncWriter added in v0.11.2

type SyncWriter struct {
	// contains filtered or unexported fields
}

SyncWriter serializes concurrent writes to an underlying io.Writer.

The facade run path (F107) executes a workflow on a background goroutine while the main goroutine drains and renders the session's events. Both sides write to the same stdout sink: the background side through the injected logger/Formatter (and per-step PrefixedWriters), the main side through the event projector. Those writes are otherwise unsynchronized and the race detector flags them as a data race on the shared buffer.

Wrapping the shared sink in a single SyncWriter — and routing every writer in the run path through that one instance — makes the writes mutually exclusive. Because fmt.Fprint/Fprintln emit each message in a single Write call, locking at the Write boundary preserves line-level output without interleaving partial lines.

func NewSyncWriter added in v0.11.2

func NewSyncWriter(w io.Writer) *SyncWriter

NewSyncWriter wraps w so that concurrent Write calls are serialized. Passing an already-synchronized writer is harmless (the extra lock is uncontended).

func (*SyncWriter) Write added in v0.11.2

func (s *SyncWriter) Write(p []byte) (int, error)

Write writes p to the underlying writer while holding the mutex, so concurrent callers never interleave their bytes.

type ValidationResult

type ValidationResult struct {
	Valid    bool     `json:"valid"`
	Workflow string   `json:"workflow"`
	Errors   []string `json:"errors,omitempty"`
	Warnings []string `json:"warnings,omitempty"`
}

ValidationResult is the JSON structure for validate command.

type ValidationResultTable

type ValidationResultTable struct {
	Valid    bool
	Workflow string
	Inputs   []InputInfo
	Steps    []StepSummary
	Errors   []string
	Warnings []string
}

ValidationResultTable is the structure for validate command table output.

type ValidatorEntry added in v0.5.0

type ValidatorEntry struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

ValidatorEntry represents a validator plugin for --validators listing.

type WorkflowInfo

type WorkflowInfo struct {
	Name        string `json:"name"`
	Source      string `json:"source"`
	Version     string `json:"version,omitempty"`
	Description string `json:"description,omitempty"`
}

WorkflowInfo is the JSON structure for list command.

type WorkflowPackInfo added in v0.11.2

type WorkflowPackInfo struct {
	Name      string   `json:"name"`
	Version   string   `json:"version,omitempty"`
	Source    string   `json:"source,omitempty"`
	Enabled   bool     `json:"enabled"`
	Workflows []string `json:"workflows,omitempty"`
}

WorkflowPackInfo represents a workflow pack for pack listing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL