tui

package
v1.40.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ColorReset   = "\033[0m"
	ColorBold    = "\033[1m"
	ColorDim     = "\033[2m"
	ColorRed     = "\033[31m"
	ColorGreen   = "\033[32m"
	ColorYellow  = "\033[33m"
	ColorBlue    = "\033[34m"
	ColorMagenta = "\033[35m"
	ColorCyan    = "\033[36m"
)

ANSI color codes (kept for prompt and readline which don't use lipgloss)

Variables

View Source
var SpinnerFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}

SpinnerFrames for the waiting animation.

View Source
var (

	// ThemeIsDark exposes the active theme's background polarity.
	ThemeIsDark = true
)

Package-level vars for theme-driven ANSI colors used in the prompt and banner. Initialized to historic defaults; ApplyTheme overwrites them.

Functions

func AnimateMax

func AnimateMax(mood MaxMood, speech string)

AnimateMax prints Max with a brief animation effect.

func AnimateMaxTransition

func AnimateMaxTransition(from, to MaxMood, speech string)

AnimateMaxTransition shows Max changing from one mood to another.

func ApplyTheme

func ApplyTheme(t Theme)

ApplyTheme rebuilds all lipgloss styles and ANSI prompt vars from t. Must be called before NewTerminal() and ShowModelPicker().

func ClearBrowserAnimation

func ClearBrowserAnimation()

ClearBrowserAnimation clears the browser animation from terminal.

func DiffStat

func DiffStat(ops []DiffLine) (added, removed int)

DiffStat returns the added and removed line counts for a diff.

func DisplayImage

func DisplayImage(path string, maxWidth int) error

DisplayImage renders an image in the terminal. Tries iTerm2 → Kitty → Sixel → half-block fallback.

func DisplayImageFromBase64

func DisplayImageFromBase64(data string, maxWidth int) error

DisplayImageFromBase64 renders a base64-encoded image.

func EnsureTTYNewlines

func EnsureTTYNewlines()

EnsureTTYNewlines turns output-postprocessing back on so '\n' returns the cursor to column 0. A previous process that died in full raw mode (Bubble Tea) can leave OPOST/ONLCR off, which makes every later line staircase.

func FormatScreenshotCompact

func FormatScreenshotCompact(label string, url string) string

FormatScreenshotCompact returns the compact screenshot frame so callers can send it through a persistent terminal renderer instead of writing directly.

func GetMaxArt

func GetMaxArt(mood MaxMood, speech string) string

GetMaxArt returns ASCII art for the given mood with an optional speech line.

func GetMaxError

func GetMaxError() string

GetMaxError returns a random error reaction.

func GetMaxGreeting

func GetMaxGreeting() string

GetMaxGreeting returns a random greeting from Max.

func GetMaxSuccess

func GetMaxSuccess() string

GetMaxSuccess returns a random success message.

func GetMaxThought

func GetMaxThought() string

GetMaxThought returns a random thinking message.

func IsImagePath

func IsImagePath(path string) bool

IsImagePath returns true if the path looks like an image file.

func IsLargePastedText

func IsLargePastedText(text string, pasted bool) bool

func PasteTextFromClipboard

func PasteTextFromClipboard() (string, error)

PasteTextFromClipboard returns the text content of the clipboard.

func PastedFilePrompt

func PastedFilePrompt(path string, size int) string

func RenderFileDiff

func RenderFileDiff(path, oldContent, newContent string) string

RenderFileDiff renders a compact colored diff for the transcript: a header line ("path +A −R") followed by capped +/-/context lines. Returns "" when the contents are identical.

func RenderScreenshotCompact

func RenderScreenshotCompact(label string, url string)

RenderScreenshotCompact shows a framed screenshot label.

func RestoreTermMode

func RestoreTermMode(state *TermState)

func SavePastedTextFile

func SavePastedTextFile(text string) (string, error)

func SaveTheme

func SaveTheme(c *api.Config, theme string) error

SaveTheme validates and persists the selected theme name on the config. Empty value clears the preference (restoring the default). Lives here, not on (*api.Config), so config.go has no dep on theme.go's name list.

func ShowBrowserAnimation

func ShowBrowserAnimation(frame int)

ShowBrowserAnimation displays an ASCII browser frame (for test execution).

func ShowCloudSyncPicker

func ShowCloudSyncPicker(current *bool) (bool, bool)

ShowCloudSyncPicker opens a small TUI to toggle cloud session sync. `current` is the present setting (nil = unset). Returns (chosen, ok); ok=false means the user cancelled and the current value should be preserved.

func ShowLiveFeedPicker

func ShowLiveFeedPicker(current bool) (bool, bool)

ShowLiveFeedPicker opens a small TUI to toggle the live browser feed. Returns (chosen, ok); ok=false means the user cancelled and the current value should be preserved.

func ShowSessionPicker

func ShowSessionPicker(sessions []SessionPickerItem, activeID string) (string, bool)

ShowSessionPicker opens the interactive session picker TUI. Returns the selected session ID and whether the user confirmed.

func ShowThemePicker

func ShowThemePicker(currentTheme string) (string, bool)

ShowThemePicker opens the live-preview theme picker TUI. Returns the chosen theme name and whether it was confirmed. On cancel the original theme is automatically restored by the picker.

func ThemeNames

func ThemeNames() []string

ThemeNames returns available theme names in display order.

func TruncateStr

func TruncateStr(s string, maxLen int) string

TruncateStr limits a string to maxLen characters.

Types

type DiffLine

type DiffLine struct {
	T string
	S string
}

DiffLine is a single line of a file diff. T is "+", "-", or " " (context).

func ComputeDiff

func ComputeDiff(oldContent, newContent string) []DiffLine

ComputeDiff produces a line-level diff between old and new content. Common prefix/suffix are trimmed first (most edits are local); the middle is matched with an LCS when small enough. Runs of unchanged lines longer than two collapse into an ellipsis marker line ("⋯ N unchanged") emitted as a context DiffLine with T "…".

type ImageAttachment

type ImageAttachment struct {
	MediaType string // "image/png", "image/jpeg", etc.
	Data      string // base64-encoded
	FileName  string // original filename (for display)
}

ImageAttachment holds a base64-encoded image to send with a message. Lives here (not in agent.go) because media.go produces it from clipboard, disk, and screenshot capture; agent.go only consumes it as a parameter.

func CaptureScreenshot

func CaptureScreenshot() (*ImageAttachment, error)

CaptureScreenshot takes a screenshot using macOS screencapture and returns it as an attachment.

func DetectAndLoadImages

func DetectAndLoadImages(input string) (string, []ImageAttachment)

DetectAndLoadImages checks if the input contains file paths to images. Returns the cleaned text (without paths) and any loaded images.

func LoadImageFromFile

func LoadImageFromFile(path string) (*ImageAttachment, error)

LoadImageFromFile reads an image file and returns an ImageAttachment.

func PasteImageFromClipboard

func PasteImageFromClipboard() (*ImageAttachment, error)

PasteImageFromClipboard checks if the clipboard has an image and returns it.

type InputResult

type InputResult struct {
	Text         string
	CtrlC        bool
	Pasted       bool
	OutputToggle bool
}

InputResult holds the result of a ReadInput call.

func ReadInput

func ReadInput(prompt string, history []string, outputVerbose bool, status *StatusInfo) InputResult

ReadInput runs the bubbletea input widget and returns the submitted text. status is optional session metrics rendered below the input box (nil hides them).

type MaxFrame

type MaxFrame struct {
	Art    string
	Speech string
}

MaxFrame holds one ASCII art frame with a speech line.

type MaxMood

type MaxMood int

MaxMood represents Max's emotional state.

const (
	MoodNeutral MaxMood = iota
	MoodHappy
	MoodThinking
	MoodConfused
	MoodSad
	MoodProud
	MoodSleeping
	MoodAlert
	MoodExcited
	MoodWaving
)

type ModelPickerOpts

type ModelPickerOpts struct {
	CurrentBackend string // "" | "cc" | "codex" | "ollama" | "cerebras" — drives initial cursor position
	CurrentModelID string // specific model ID currently active, or ""
	Effort         string // "low" | "medium" | "high"; empty defaults to "high"
	OllamaURL      string // currently configured Ollama endpoint; "" hides the section
	OllamaModel    string // currently configured Ollama model; "" hides the section
	CCInstalled    bool   // pre-resolved (don't shell out from picker.View per frame)
	CodexInstalled bool
	AgyInstalled   bool
	CerebrasKeySet bool // true when a Cerebras API key is configured (drives the section status dot)

	OpenCodeInstalled bool                 // true when the opencode CLI is present
	OpenCodeModels    []OpenCodeModelEntry // models from enabled+entitled providers; empty hides the section
}

ModelPickerOpts collects the inputs to ShowModelPicker. Lives as a struct rather than positional args so new fields can land without a signature break, and so the boolean flags don't read as mystery true/false at the call site.

type ModelPickerResult

type ModelPickerResult struct {
	Backend   string // "cc" | "codex" | ""
	ModelID   string // specific model, or "" for default
	Effort    string // "low" | "medium" | "high"
	Confirmed bool
}

ModelPickerResult is returned after the TUI closes.

func ShowModelPicker

func ShowModelPicker(opts ModelPickerOpts) ModelPickerResult

ShowModelPicker opens the unified model + effort TUI. Returns the result; Confirmed=false means the user cancelled.

type OpenCodeModelEntry

type OpenCodeModelEntry struct {
	ProviderID   string // e.g. "groq"
	ProviderName string // e.g. "Groq"
	ModelID      string // full "provider/model" passed via --model
	Label        string // display name (model portion)
}

OpenCodeModelEntry is one model offered by an enabled opencode provider. The caller resolves these dynamically (via `opencode models <provider>`) and passes only enabled+entitled providers, so the picker shows exactly what the user opted into — never the full opencode catalogue.

type PlanStep

type PlanStep struct {
	Title  string
	Status string // pending | in_progress | done
}

PlanStep is one entry of an agent task plan, in the shape PrintPlan renders. Kept here (not imported from agent) because agent imports tui, not vice versa.

type ProgressBar

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

ProgressBar renders an animated progress bar in the terminal.

func NewProgressBar

func NewProgressBar(label string, width int) *ProgressBar

NewProgressBar creates a new progress bar.

func (*ProgressBar) Finish

func (p *ProgressBar) Finish(success bool, message string)

Finish marks the progress bar as complete.

func (*ProgressBar) Update

func (p *ProgressBar) Update(percent int, message string)

Update redraws the progress bar with new progress (0-100).

type ProviderPickerItem

type ProviderPickerItem struct {
	ID          string
	DisplayName string
	Status      string // "available", "enabled", "enabled (no key)", "not entitled"
	Enabled     bool
	Allowed     bool
}

ProviderPickerItem is one opt-in opencode provider shown by /providers.

type ProviderPickerResult

type ProviderPickerResult struct {
	ID        string
	Confirmed bool
}

ProviderPickerResult is returned after the /providers TUI closes.

func ShowProviderPicker

func ShowProviderPicker(items []ProviderPickerItem) ProviderPickerResult

ShowProviderPicker opens the /providers TUI. Confirmed=false means cancel.

type SessionPickerItem

type SessionPickerItem struct {
	ID        string
	UpdatedAt time.Time
	Turns     int
	Tokens    int
	ProjectID int
	Model     string
}

SessionPickerItem is the row data the picker needs to render. Defined here (not as session.SessionSummary) so the TUI doesn't import the session persistence package — caller maps from whatever real type they hold.

type SettingsPickerResult

type SettingsPickerResult struct {
	Confirmed bool
	Changes   map[string]string
}

SettingsPickerResult reports what the user changed. Changes holds only rows whose value differs from the initial one, keyed by SettingsRow.Key.

func ShowSettingsPicker

func ShowSettingsPicker(rows []SettingsRow) SettingsPickerResult

ShowSettingsPicker opens the settings editor. It never fails: a program error is reported as a plain cancellation.

type SettingsRow

type SettingsRow struct {
	Key     string
	Label   string
	Kind    SettingsRowKind
	Value   string
	Options []string
	Hint    string
	Display func(value string) string
}

SettingsRow describes one editable setting. Value is the CURRENT value: "true"/"false" for toggles, one of Options for cycles, raw text otherwise. Display may override how Value renders (e.g. "" → "none") without changing what is committed.

type SettingsRowKind

type SettingsRowKind int
const (
	SettingsToggle SettingsRowKind = iota
	SettingsCycle
	SettingsText
)

type SlashMenuItem

type SlashMenuItem struct {
	Cmd  string
	Desc string
}

SlashMenuItem represents a selectable command.

type StatusInfo

type StatusInfo struct {
	Backend        string // "cc" | "codex" | "opencode" | "cerebras" | "ollama" | "" (direct API)
	Model          string // active model ID; "" = backend default
	Effort         string // "low" | "medium" | "high" (CLI backends)
	PermissionMode string // autonomy mode, or "codex policy" for Codex-owned policy
	OutputVerbose  bool
	Task           string        // what the agent is working on (latest user prompt)
	TokensIn       int           // session input tokens
	TokensOut      int           // session output tokens
	ContextUsed    int           // tokens occupying the model context after the last turn
	ContextWindow  int           // assumed context window of the active model
	LastTurnDur    time.Duration // wall-clock duration of the previous agent turn
	SessionStarted time.Time     // used to keep the session timer live while typing

	// Subscription coding-plan usage window (cc / codex / opencode backends).
	// PlanActive is false for non-plan backends and before the first turn, in
	// which case the plan segment is omitted from the status line.
	PlanActive    bool
	PlanRemaining time.Duration // time until the plan window resets
	PlanTurns     int           // turns used in the current window
	PlanExhausted bool          // provider reported the plan limit was hit
}

StatusInfo carries session metrics rendered around the input box: token counts, context-window fill, timing, and the mode/task bottom bar. Zero values are omitted from the display, so backends that can't report a given metric simply don't show it.

type TermState

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

func EnableRawMode

func EnableRawMode() (*TermState, error)

type Terminal

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

Terminal handles all user-facing I/O with colors, glamour, and personality.

func NewTerminal

func NewTerminal() *Terminal

NewTerminal creates a new interactive terminal with markdown rendering.

func (*Terminal) Close

func (t *Terminal) Close()

Close cleans up the terminal.

func (*Terminal) EndLine

func (t *Terminal) EndLine()

EndLine completes an output line through whichever renderer currently owns the terminal. CLI backends use it instead of writing directly to stdout.

func (*Terminal) FinishMarkdown

func (t *Terminal) FinishMarkdown(fullText string)

FinishMarkdown is called when a text block is complete. Re-renders the streamed text with glamour so headers, bold/italic, lists, inline code, and fenced code blocks display formatted instead of as raw markdown syntax. Previously this only happened when the text contained a fenced code block; now every finished block gets the same treatment, since raw "**bold**"/backtick syntax is just as unreadable without one.

func (*Terminal) PrintAssistant

func (t *Terminal) PrintAssistant(text string)

PrintAssistant prints the agent's text response with markdown rendering. Used in non-streaming mode.

func (*Terminal) PrintBanner

func (t *Terminal) PrintBanner(version string, ctx *api.SessionContext)

PrintBanner shows the startup banner — fun, geeky, and cat-themed.

func (*Terminal) PrintCostSummary

func (t *Terminal) PrintCostSummary(usage api.TokenUsage, model string, plan *api.PlanWindow)

PrintCostSummary shows detailed cost info for /cost command. When plan is non-nil and a coding-plan window is open, its usage is appended.

func (*Terminal) PrintError

func (t *Terminal) PrintError(msg string)

PrintError prints an error message.

func (*Terminal) PrintFileDiff

func (t *Terminal) PrintFileDiff(path, oldContent, newContent string)

PrintFileDiff shows a live code change under the current tool line. Renders nothing when the content is unchanged.

func (*Terminal) PrintPlan

func (t *Terminal) PrintPlan(steps []PlanStep)

PrintPlan renders the agent's task plan (from update_plan) as a checklist with a done/total progress line. Marks: ✓ done, ▸ in_progress, ◦ pending. Restarts the thinking spinner on exit, mirroring PrintToolResult.

func (*Terminal) PrintPlanWindow

func (t *Terminal) PrintPlanWindow(plan *api.PlanWindow)

PrintPlanWindow renders the subscription coding-plan usage window (the rolling 5-hour limit shared by cc / codex / opencode backends). It is a no-op when plan is nil or no window has opened yet, so it is safe to call unconditionally from /plan, /cost, and /status.

func (*Terminal) PrintStatusInfo

func (t *Terminal) PrintStatusInfo(ctx *api.SessionContext, usage api.TokenUsage, model string, plan *api.PlanWindow)

PrintStatusInfo shows qmax status and session info for /status command.

func (*Terminal) PrintSystem

func (t *Terminal) PrintSystem(msg string)

PrintSystem prints a system message.

func (*Terminal) PrintTestResults

func (t *Terminal) PrintTestResults(results []TestResult)

PrintTestResults shows a colored pass/fail table of test results.

func (*Terminal) PrintTokenUsage

func (t *Terminal) PrintTokenUsage(usage api.TokenUsage)

PrintTokenUsage shows token usage in dim text after a response.

func (*Terminal) PrintToolIcon

func (t *Terminal) PrintToolIcon(name string)

PrintToolIcon shows a tool icon when a tool_use block starts streaming. Consecutive tool calls render as a tight group: only the first tool after text/system output gets a separating blank line.

func (*Terminal) PrintToolResult

func (t *Terminal) PrintToolResult(name string, output string)

PrintToolResult shows tool output with smart formatting for known result types. Restarts the thinking spinner on exit so it runs while the agent processes the result.

func (*Terminal) PrintToolStart

func (t *Terminal) PrintToolStart(name string, input interface{})

PrintToolStart shows a tool invocation with its input summary.

func (*Terminal) Prompt

func (t *Terminal) Prompt() string

Prompt returns the current rendered prompt string. Callers (notably the REPL using tui.ReadInput) need this to redraw the prompt after the bubbletea input session takes over the terminal.

func (*Terminal) ReadConsent

func (t *Terminal) ReadConsent() (string, error)

ReadConsent temporarily clears the readline prompt and reads one line. Used for consent questions that print their own prompt text via fmt, avoiding the raw-mode conflict that arises when using bufio.NewReader(os.Stdin) while readline already owns the terminal.

func (*Terminal) ReadLine

func (t *Terminal) ReadLine() (string, error)

ReadLine reads a line of user input via readline (fallback, used by non-REPL code).

func (*Terminal) SetSessionPrompt

func (t *Terminal) SetSessionPrompt(sessionID string)

SetSessionPrompt updates the prompt to include the session ID.

func (*Terminal) SetTurnActivity

func (t *Terminal) SetTurnActivity(text string) bool

SetTurnActivity updates an ephemeral activity line above the persistent input panel. It returns false when no turn viewport is active so callers can fall back to their legacy terminal animation.

func (*Terminal) SetUserTyping

func (t *Terminal) SetUserTyping(v bool)

SetUserTyping tells the active spinner to pause (true) or resume (false) its line rewrites so typed characters are not overwritten.

func (*Terminal) StartThinking

func (t *Terminal) StartThinking()

StartThinking shows an animated spinner with a funny cat-themed message. Safe to call even if a spinner is already running (replaces it).

func (*Terminal) Stderr

func (t *Terminal) Stderr() io.Writer

Stderr returns the writer used for diagnostic / debug log lines that the readline instance steers around the prompt. Callers in other packages need this to emit verbose messages without corrupting the readline buffer.

func (*Terminal) StopThinking

func (t *Terminal) StopThinking()

StopThinking stops the spinner and erases it from the terminal. Idempotent — safe to call when no spinner is active.

func (*Terminal) StreamText

func (t *Terminal) StreamText(text string)

StreamText prints text as it arrives from the SSE stream (token-by-token).

func (*Terminal) Write

func (t *Terminal) Write(p []byte) (int, error)

Write makes Terminal an io.Writer so subprocess diagnostics can be routed through the renderer that currently owns the terminal.

type TestResult

type TestResult struct {
	Name     string
	Passed   bool
	Duration float64
	Error    string
}

TestResult represents a single test result for visualization.

type Theme

type Theme struct {
	Name string
	Dark bool // true = optimized for dark terminal background

	// Semantic color roles — 256-color ANSI palette strings for lipgloss.
	Accent  string // tools, badges, star, filter — primary accent
	Brand   string // Claude icon, system msgs, selection highlight
	Success string // pass/success states
	Error   string // error states

	// Text hierarchy
	TextBright string // selected/focused text
	TextNormal string // normal label text
	TextDim    string // secondary/dimmed text
	TextSubtle string // hints, footers, usage

	// Surfaces
	SurfaceDark   string // status bar background
	SurfaceSelect string // row selection background
	SurfaceBorder string // box border
	SurfaceSep    string // section dividers

	// Icon colors
	IconCodex string // Codex section icon
	IconAPI   string // Direct API icon
	MenuItem  string // slash menu item color

	// ANSI escape sequences for readline prompt and banner (not lipgloss).
	ANSIPromptName  string // "qmax" text in prompt
	ANSIPromptArrow string // ">" arrow in prompt
	ANSIBanner      string // ASCII art banner color
	ANSICatArt      string // Max cat art color
	ANSIStatus      string // ▸ status lines in banner
}

Theme defines the full color palette for the terminal UI.

func ThemeByName

func ThemeByName(name string) Theme

ThemeByName returns the named theme, defaulting to "historic".

type TurnInputResult

type TurnInputResult struct {
	Text     string
	Pasted   bool
	Canceled bool
}

TurnInputResult is input collected while an agent turn is running. A submitted line is queued by the REPL and also interrupts the active turn.

func RunTurnViewport

func RunTurnViewport(term *Terminal, prompt string, status *StatusInfo, cancelFn func(), run func()) TurnInputResult

RunTurnViewport keeps a Bubble Tea-owned input/status region active while run emits streaming output through Terminal. It returns only after run exits.

Jump to

Keyboard shortcuts

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