Documentation
¶
Index ¶
- Constants
- Variables
- func AnimateMax(mood MaxMood, speech string)
- func AnimateMaxTransition(from, to MaxMood, speech string)
- func ApplyTheme(t Theme)
- func ClearBrowserAnimation()
- func DiffStat(ops []DiffLine) (added, removed int)
- func DisplayImage(path string, maxWidth int) error
- func DisplayImageFromBase64(data string, maxWidth int) error
- func EnsureTTYNewlines()
- func FormatScreenshotCompact(label string, url string) string
- func GetMaxArt(mood MaxMood, speech string) string
- func GetMaxError() string
- func GetMaxGreeting() string
- func GetMaxSuccess() string
- func GetMaxThought() string
- func IsImagePath(path string) bool
- func IsLargePastedText(text string, pasted bool) bool
- func PasteTextFromClipboard() (string, error)
- func PastedFilePrompt(path string, size int) string
- func RenderFileDiff(path, oldContent, newContent string) string
- func RenderScreenshotCompact(label string, url string)
- func RestoreTermMode(state *TermState)
- func SavePastedTextFile(text string) (string, error)
- func SaveTheme(c *api.Config, theme string) error
- func ShowBrowserAnimation(frame int)
- func ShowCloudSyncPicker(current *bool) (bool, bool)
- func ShowLiveFeedPicker(current bool) (bool, bool)
- func ShowSessionPicker(sessions []SessionPickerItem, activeID string) (string, bool)
- func ShowThemePicker(currentTheme string) (string, bool)
- func ThemeNames() []string
- func TruncateStr(s string, maxLen int) string
- type DiffLine
- type ImageAttachment
- type InputResult
- type MaxFrame
- type MaxMood
- type ModelPickerOpts
- type ModelPickerResult
- type OpenCodeModelEntry
- type PlanStep
- type ProgressBar
- type ProviderPickerItem
- type ProviderPickerResult
- type SessionPickerItem
- type SettingsPickerResult
- type SettingsRow
- type SettingsRowKind
- type SlashMenuItem
- type StatusInfo
- type TermState
- type Terminal
- func (t *Terminal) Close()
- func (t *Terminal) EndLine()
- func (t *Terminal) FinishMarkdown(fullText string)
- func (t *Terminal) PrintAssistant(text string)
- func (t *Terminal) PrintBanner(version string, ctx *api.SessionContext)
- func (t *Terminal) PrintCostSummary(usage api.TokenUsage, model string, plan *api.PlanWindow)
- func (t *Terminal) PrintError(msg string)
- func (t *Terminal) PrintFileDiff(path, oldContent, newContent string)
- func (t *Terminal) PrintPlan(steps []PlanStep)
- func (t *Terminal) PrintPlanWindow(plan *api.PlanWindow)
- func (t *Terminal) PrintStatusInfo(ctx *api.SessionContext, usage api.TokenUsage, model string, ...)
- func (t *Terminal) PrintSystem(msg string)
- func (t *Terminal) PrintTestResults(results []TestResult)
- func (t *Terminal) PrintTokenUsage(usage api.TokenUsage)
- func (t *Terminal) PrintToolIcon(name string)
- func (t *Terminal) PrintToolResult(name string, output string)
- func (t *Terminal) PrintToolStart(name string, input interface{})
- func (t *Terminal) Prompt() string
- func (t *Terminal) ReadConsent() (string, error)
- func (t *Terminal) ReadLine() (string, error)
- func (t *Terminal) SetSessionPrompt(sessionID string)
- func (t *Terminal) SetTurnActivity(text string) bool
- func (t *Terminal) SetUserTyping(v bool)
- func (t *Terminal) StartThinking()
- func (t *Terminal) Stderr() io.Writer
- func (t *Terminal) StopThinking()
- func (t *Terminal) StreamText(text string)
- func (t *Terminal) Write(p []byte) (int, error)
- type TestResult
- type Theme
- type TurnInputResult
Constants ¶
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 ¶
var SpinnerFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
SpinnerFrames for the waiting animation.
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 ¶
AnimateMax prints Max with a brief animation effect.
func AnimateMaxTransition ¶
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 DisplayImage ¶
DisplayImage renders an image in the terminal. Tries iTerm2 → Kitty → Sixel → half-block fallback.
func DisplayImageFromBase64 ¶
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 ¶
FormatScreenshotCompact returns the compact screenshot frame so callers can send it through a persistent terminal renderer instead of writing directly.
func GetMaxGreeting ¶
func GetMaxGreeting() string
GetMaxGreeting returns a random greeting from Max.
func IsImagePath ¶
IsImagePath returns true if the path looks like an image file.
func IsLargePastedText ¶
func PasteTextFromClipboard ¶
PasteTextFromClipboard returns the text content of the clipboard.
func PastedFilePrompt ¶
func RenderFileDiff ¶
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 ¶
RenderScreenshotCompact shows a framed screenshot label.
func RestoreTermMode ¶
func RestoreTermMode(state *TermState)
func SavePastedTextFile ¶
func SaveTheme ¶
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 ¶
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 ¶
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 ¶
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 ¶
TruncateStr limits a string to maxLen characters.
Types ¶
type DiffLine ¶
DiffLine is a single line of a file diff. T is "+", "-", or " " (context).
func ComputeDiff ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) 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 ¶
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 ¶
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 ¶
PrintError prints an error message.
func (*Terminal) PrintFileDiff ¶
PrintFileDiff shows a live code change under the current tool line. Renders nothing when the content is unchanged.
func (*Terminal) PrintPlan ¶
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 ¶
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 ¶
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 ¶
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 ¶
PrintToolStart shows a tool invocation with its input summary.
func (*Terminal) Prompt ¶
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 ¶
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 ¶
ReadLine reads a line of user input via readline (fallback, used by non-REPL code).
func (*Terminal) SetSessionPrompt ¶
SetSessionPrompt updates the prompt to include the session ID.
func (*Terminal) SetTurnActivity ¶
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 ¶
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 ¶
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 ¶
StreamText prints text as it arrives from the SSE stream (token-by-token).
type TestResult ¶
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 ¶
ThemeByName returns the named theme, defaulting to "historic".
type TurnInputResult ¶
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.