ui

package
v0.0.0-beta Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package ui provides interfaces and event types for user interaction. It defines a common event stream protocol used by both simple and TUI implementations.

Index

Constants

This section is empty.

Variables

View Source
var (
	UserStyle       = color.New(color.FgBlue, color.Bold)
	AssistantStyle  = color.New(color.FgYellow, color.Bold)
	ContentStyle    = color.New(color.FgWhite)
	ThinkingStyle   = color.New(color.Faint)
	ToolStyle       = color.New(color.FgCyan, color.Faint)
	ToolResultStyle = color.New(color.Faint)
	ErrorStyle      = color.New(color.FgRed, color.Bold)
	SyntheticStyle  = color.New(color.FgBlue)
)

Shared terminal styles used by Simple and Headless backends.

Functions

func DrainEvents

func DrainEvents(events <-chan Event)

DrainEvents processes remaining events after context cancellation. It unblocks any pending response channels (Flush.Done, ToolConfirmRequired.Response, AskRequired.Response) to prevent goroutine deadlocks, then returns when the channel is empty.

func RenderPartAdded

func RenderPartAdded(d Delta, p part.Part, verbose bool, prompt string)

RenderPartAdded renders a newly added part to stdout (thinking/content/tool-header).

func RenderPartUpdated

func RenderPartUpdated(d Delta, p part.Part, verbose bool, prompt string)

RenderPartUpdated renders an updated part to stdout (thinking/content/tool-result).

func ResolveAskResponse

func ResolveAskResponse(text string, options []AskOption, multiSelect bool) string

ResolveAskResponse parses the user's text input against ask options, converting numbered selections to labels and handling multi-select.

Types

type Action

type Action interface {
	// contains filtered or unexported methods
}

Action represents a UI-triggered action (keybinding, etc).

type AskOption

type AskOption struct {
	Label       string
	Description string
}

AskOption represents a selectable choice in an ask prompt.

type AskRequired

type AskRequired struct {
	Question    string
	Options     []AskOption
	MultiSelect bool
	Response    chan<- string
}

AskRequired signals the LLM needs user input before proceeding.

func (AskRequired) Tag

func (AskRequired) Tag() EventTag

type AssistantDone

type AssistantDone struct {
	Error     error
	Cancelled bool // True if cancelled via ESC
}

AssistantDone signals the assistant has finished processing.

func (AssistantDone) Tag

func (AssistantDone) Tag() EventTag

type CommandResult

type CommandResult struct {
	Command string
	Message string
	Error   error
	Level   Level // Styling hint (zero value = LevelInfo)
	Clear   bool  // when true, UI clears all displayed messages first
	Inline  bool  // when true, multi-line messages print inline instead of opening a pager
}

CommandResult signals the result of a slash command.

func (CommandResult) Tag

func (CommandResult) Tag() EventTag

type ConfirmAction

type ConfirmAction int

ConfirmAction is the user's response to a tool confirmation prompt.

const (
	// ConfirmAllow approves the command once.
	ConfirmAllow ConfirmAction = iota
	// ConfirmAllowSession approves all matching commands for this session (in-memory only).
	ConfirmAllowSession
	// ConfirmAllowPatternProject persists the pattern to project-scoped approval rules.
	ConfirmAllowPatternProject
	// ConfirmAllowPatternGlobal persists the pattern to global-scoped approval rules.
	ConfirmAllowPatternGlobal
	// ConfirmDeny blocks the command.
	ConfirmDeny
)

type ConfirmOnce

type ConfirmOnce struct{}

ConfirmOnce signals the user approved a single command execution.

type ConfirmPatternGlobal

type ConfirmPatternGlobal struct{}

ConfirmPatternGlobal signals the user approved all matching commands (global scope).

type ConfirmPatternProject

type ConfirmPatternProject struct{}

ConfirmPatternProject signals the user approved all matching commands (project scope).

type ConfirmReject

type ConfirmReject struct{}

ConfirmReject signals the user denied the command.

type ConfirmSession

type ConfirmSession struct{}

ConfirmSession signals the user approved all matching commands for this session.

type CycleThink

type CycleThink struct{}

CycleThink cycles through: off → on → low → medium → high → off.

type Delta

type Delta struct {
	// Text is the incremental text to display (empty for tool parts).
	Text string
	// SectionBreak is true when transitioning between different part types.
	SectionBreak bool
	// PartType is the type of the incoming part.
	PartType part.Type
	// First is true when this is the first chunk for this part type
	// (the relevant counter was 0 before this call).
	First bool
}

Delta holds the result of a single tracking computation.

type DisplayHints

type DisplayHints struct {
	Verbose bool
	Auto    bool
}

DisplayHints holds UI-specific display preferences.

type DisplayHintsChanged

type DisplayHintsChanged struct {
	Hints DisplayHints
}

DisplayHintsChanged is emitted when UI display preferences change.

func (DisplayHintsChanged) Tag

type Event

type Event interface {
	Tag() EventTag
	// contains filtered or unexported methods
}

Event is a marker interface for all events sent through the UI event channel.

type EventTag

type EventTag int

EventTag categorizes events into semantic groups.

const (
	TagMessage EventTag = iota // Message lifecycle (Added, Started, PartAdded, PartUpdated, Finalized)
	TagStatus                  // System state (StatusChanged, AssistantDone, WaitingForInput, UserMessagesProcessed, SpinnerMessage, SyntheticInjected)
	TagTool                    // Tool execution (ToolOutputDelta, ToolConfirmRequired)
	TagDialog                  // User interaction (AskRequired, TodoEditRequested)
	TagSession                 // Session/command (SessionRestored, SlashCommandHandled, CommandResult)
	TagControl                 // UI control (PickerOpen, Flush)
)

func (EventTag) String

func (t EventTag) String() string

String returns the tag name.

type Flush

type Flush struct {
	Done chan struct{}
}

Flush signals the UI to process all pending events before continuing.

func (Flush) Tag

func (Flush) Tag() EventTag

type Level

type Level int

Level indicates the severity of a CommandResult for UI styling.

const (
	LevelInfo    Level = iota // Default — gray, auto-clears after 5s
	LevelSuccess              // Green, auto-clears after 5s
	LevelWarn                 // Yellow, auto-clears after 5s
	LevelError                // Red, persists until next input
)

type MessageAdded

type MessageAdded struct {
	Message message.Message
}

MessageAdded signals a complete message was added.

func (MessageAdded) Tag

func (MessageAdded) Tag() EventTag

type MessageFinalized

type MessageFinalized struct {
	Message message.Message
}

MessageFinalized signals the current message is complete.

func (MessageFinalized) Tag

func (MessageFinalized) Tag() EventTag

type MessagePartAdded

type MessagePartAdded struct {
	MessageID string
	Part      part.Part
}

MessagePartAdded signals a new part was added to the current message.

func (MessagePartAdded) Tag

func (MessagePartAdded) Tag() EventTag

type MessagePartUpdated

type MessagePartUpdated struct {
	MessageID string
	PartIndex int
	Part      part.Part
}

MessagePartUpdated signals an existing part was updated.

func (MessagePartUpdated) Tag

type MessageStarted

type MessageStarted struct {
	MessageID string
}

MessageStarted signals a new assistant message is beginning.

func (MessageStarted) Tag

func (MessageStarted) Tag() EventTag

type NextAgent

type NextAgent struct{}

NextAgent cycles to the next available agent.

type NextMode

type NextMode struct{}

NextMode cycles to the next available mode.

type PartTracker

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

PartTracker computes streaming deltas for content and thinking parts. It tracks the last-seen text length and part type, returning incremental text for display. All three non-TUI UIs (Simple, Headless, Web) embed this instead of maintaining their own tracking fields.

func (*PartTracker) Added

func (t *PartTracker) Added(p part.Part) Delta

Added processes a newly added part. Call on MessagePartAdded events.

func (*PartTracker) Reset

func (t *PartTracker) Reset()

Reset zeroes all counters. Call on MessageStarted and MessageFinalized.

func (*PartTracker) Updated

func (t *PartTracker) Updated(p part.Part) Delta

Updated processes an update to an existing part. Call on MessagePartUpdated events.

type PickerItem

type PickerItem struct {
	Group       string // Section header (provider name, category, etc.)
	Label       string // Main display text (model name, command usage, etc.)
	Description string // Secondary text rendered faint (optional)
	Icons       string // Capability markers (optional)
	Current     bool   // Highlight as currently active
	Disabled    bool   // Unreachable/non-selectable placeholder
	Action      Action // What to dispatch on selection
}

PickerItem represents a single selectable item in a picker overlay.

type PickerOpen

type PickerOpen struct {
	Title string // Picker title (e.g. "Select model:", "Commands:")
	Items []PickerItem
}

PickerOpen signals the TUI should open a picker overlay.

func (PickerOpen) Display

func (p PickerOpen) Display() string

Display returns a formatted text representation of the picker for non-TUI output.

func (PickerOpen) Tag

func (PickerOpen) Tag() EventTag

type ResumeSession

type ResumeSession struct {
	SessionID string
}

ResumeSession resumes a saved session by ID.

type RunCommand

type RunCommand struct {
	Name string
}

RunCommand executes a slash command by name (e.g. "/info", "/model").

type SelectModel

type SelectModel struct {
	Provider string
	Model    string
}

SelectModel switches to a specific provider/model.

type SessionRestored

type SessionRestored struct {
	Messages message.Messages
}

SessionRestored carries restored conversation messages for UI display after resume.

func (SessionRestored) Tag

func (SessionRestored) Tag() EventTag

type SlashCommandHandled

type SlashCommandHandled struct {
	Text string
}

SlashCommandHandled signals a slash command was processed (no streaming follows).

func (SlashCommandHandled) Tag

type SpinnerMessage

type SpinnerMessage struct {
	Text string
}

SpinnerMessage updates the spinner text during streaming.

func (SpinnerMessage) Tag

func (SpinnerMessage) Tag() EventTag

type Status

type Status struct {
	Agent    string
	Mode     string
	Provider string
	Model    string
	Think    thinking.Value
	Tokens   struct {
		Used    int
		Max     int
		Percent float64
	}
	Sandbox struct {
		Enabled   bool
		Requested bool
	}
	Snapshots bool // snapshot tracking enabled
	Steps     struct {
		Current int // iteration within the turn (0 = idle)
		Max     int // configured max steps
	}
}

Status holds the current assistant status for display.

func (Status) AssistantPrompt

func (s Status) AssistantPrompt() string

AssistantPrompt returns a rich role label for assistant output (e.g. "Aura (model, 🧠 high, edit): ").

func (Status) ContextDisplay

func (s Status) ContextDisplay(msgCount int) string

ContextDisplay returns context stats like "Context: 12.4k / 131k tokens (10%), 42 messages".

func (Status) Prompt

func (s Status) Prompt() string

Prompt returns a formatted prompt string for the simple UI.

func (Status) StatusLine

func (s Status) StatusLine(hints DisplayHints) string

StatusLine returns the full status bar string with all parts joined by " • ".

func (Status) TokensDisplay

func (s Status) TokensDisplay() string

TokensDisplay returns a formatted token usage string (e.g. "tokens: 12.4k/131k (10%)").

func (Status) UserPrompt

func (s Status) UserPrompt() string

UserPrompt returns a rich role label for user messages (e.g. "You (model, edit): ").

func (Status) WelcomeInfo

func (s Status) WelcomeInfo() string

WelcomeInfo returns a multi-line welcome block with arrow bullets.

func (Status) WindowDisplay

func (s Status) WindowDisplay() string

WindowDisplay returns the context window size like "Context window: 131k tokens".

type StatusChanged

type StatusChanged struct {
	Status Status
}

StatusChanged signals the status bar should update.

func (StatusChanged) Tag

func (StatusChanged) Tag() EventTag

type SyntheticInjected

type SyntheticInjected struct {
	Header  string // e.g. "[SYNTHETIC user]: loop_detection"
	Content string // Truncated message content for display
	Role    string // "user", "assistant", "system"
}

SyntheticInjected signals that a synthetic message was injected into the conversation.

func (SyntheticInjected) Tag

type TodoEditRequested

type TodoEditRequested struct {
	Content string // Serialized todo list text
}

TodoEditRequested signals the UI should open $EDITOR for todo list editing.

func (TodoEditRequested) Tag

type TodoEdited

type TodoEdited struct {
	Text string
}

TodoEdited carries the raw text from $EDITOR back to the assistant for parsing.

type ToggleAuto

type ToggleAuto struct{}

ToggleAuto toggles the Auto mode on/off.

type ToggleSandbox

type ToggleSandbox struct{}

ToggleSandbox toggles sandbox enforcement on/off.

type ToggleThink

type ToggleThink struct{}

ToggleThink toggles thinking off ↔ on (true).

type ToggleVerbose

type ToggleVerbose struct{}

ToggleVerbose toggles visibility of thinking content.

type ToolConfirmRequired

type ToolConfirmRequired struct {
	ToolName    string               // Tool name (e.g. "Bash", "Write", "mcp__server__tool")
	Description string               // What the tool does (from tool.Description())
	Detail      string               // Context for display: command for Bash, file path for Write, etc.
	DiffPreview string               // Unified diff preview (empty for non-file tools)
	Pattern     string               // Derived persistence pattern (e.g. "Bash:git commit*", "Write")
	Response    chan<- ConfirmAction // User's decision
}

ToolConfirmRequired signals that a tool call needs user approval before execution.

func (ToolConfirmRequired) Tag

type ToolOutputDelta

type ToolOutputDelta struct {
	ToolName string
	Line     string
}

ToolOutputDelta carries a single line of incremental tool output during execution.

func (ToolOutputDelta) Tag

func (ToolOutputDelta) Tag() EventTag

type UI

type UI interface {
	Run(ctx context.Context) error
	Events() chan<- Event
	Input() <-chan UserInput
	Actions() <-chan UserAction
	Cancel() <-chan struct{}
	SetHintFunc(func(string) string)
	SetWorkdir(string)
}

UI defines the interface for user interaction.

type UndoExecute

type UndoExecute struct {
	Hash         string
	MessageIndex int
	Mode         string // "code", "messages", or "both"
}

UndoExecute is dispatched when the user selects a rewind mode (code/messages/both).

type UndoSnapshot

type UndoSnapshot struct {
	Hash         string
	MessageIndex int
}

UndoSnapshot is dispatched when the user selects a snapshot from the /undo picker. Triggers the second picker asking what to rewind.

type UserAction

type UserAction struct {
	Action Action
}

UserAction represents a UI-triggered action (not from text input).

type UserInput

type UserInput struct {
	Text string
}

UserInput contains text submitted by the user.

type UserMessagesProcessed

type UserMessagesProcessed struct {
	Texts []string
}

UserMessagesProcessed signals the backend has started processing user messages.

func (UserMessagesProcessed) Tag

type WaitingForInput

type WaitingForInput struct{}

WaitingForInput signals the UI should accept user input.

func (WaitingForInput) Tag

func (WaitingForInput) Tag() EventTag

Directories

Path Synopsis
Package headless provides a UI that prints events to stdout without user input.
Package headless provides a UI that prints events to stdout without user input.
Package simple provides a readline-based TUI implementation.
Package simple provides a readline-based TUI implementation.
tui
Package tui implements a terminal user interface using bubbletea.
Package tui implements a terminal user interface using bubbletea.
autocomplete
Package autocomplete provides directive name and path completions for the TUI.
Package autocomplete provides directive name and path completions for the TUI.
Package web provides a browser-based UI that streams HTML fragments over SSE.
Package web provides a browser-based UI that streams HTML fragments over SSE.

Jump to

Keyboard shortcuts

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