Documentation
¶
Overview ¶
Package tui implements the interactive terminal UI using Bubble Tea v2.
Index ¶
- Constants
- func BashEventKind(kind string) string
- func GenerateCommitMsgFunc(llm llmmodel.LLM) func(ctx context.Context, diffs string) (string, error)
- func RenderContextBreakdown(b ContextBreakdown, window int64, width int, p Palette) string
- func RenderMermaid(source string, width int, p Palette) string
- func RenderSidebar(in SidebarRenderInput) string
- func Run(ctx context.Context, cfg Config) error
- func SetupProgramOptions() []tea.ProgramOption
- type A2AAgentEntry
- type AgentMood
- type AgentSubEvent
- type ArtifactEntry
- type Breakpoint
- type ChatModel
- func (c *ChatModel) AppendError(text string)
- func (c *ChatModel) AppendMeta(text string)
- func (c *ChatModel) AppendNotice(text string)
- func (c *ChatModel) AppendWarning(text string)
- func (c *ChatModel) Clear()
- func (c *ChatModel) MaxScroll(height int) int
- func (c *ChatModel) PlainTranscript() string
- func (c *ChatModel) RefreshTheme() bool
- func (c *ChatModel) RenderMarkdown(text string) string
- func (c *ChatModel) RenderMessages(running bool) string
- func (c *ChatModel) ResetScroll()
- func (c *ChatModel) ScrollDown(n int)
- func (c *ChatModel) ScrollUp(n, height int)
- func (c *ChatModel) UpdateRenderer(width int)
- type ChecklistStep
- type CompactStatsProvider
- type CompleteResult
- type CompletionCandidate
- type CompletionType
- type Config
- type ContextBreakdown
- type ContextSegmentKind
- type FaceRenderer
- type Gate
- type GateResult
- type GateStatus
- type HistoryEntry
- type InitEvent
- type InitResult
- type InputModel
- func (im *InputModel) AllCommandNames() []string
- func (im *InputModel) AtFirstRow() bool
- func (im *InputModel) AtLastRow() bool
- func (im *InputModel) Clear()
- func (im *InputModel) Cursor() *tea.Cursor
- func (im *InputModel) HandleKey(msg tea.KeyPressMsg) tea.Cmd
- func (im *InputModel) InsertText(text string)
- func (im *InputModel) RefreshTheme() bool
- func (im *InputModel) ReloadSkills()
- func (im *InputModel) SetText(text string)
- func (im *InputModel) SetWidth(width int)
- func (im *InputModel) View(running bool) string
- type InputSubmitMsg
- type Layout
- type Palette
- type PlanPhase
- type SOPGraph
- type SearchItem
- type SetupConfig
- type SetupProvider
- type SetupResult
- type SetupWizard
- type SidebarRenderInput
- type StatusModel
- type StatusRenderInput
- type Theme
- type ThemeColors
- func (c ThemeColors) BaseColor() color.Color
- func (c ThemeColors) DiffAddedColor() color.Color
- func (c ThemeColors) DiffAddedTextColor() color.Color
- func (c ThemeColors) DiffRemovedColor() color.Color
- func (c ThemeColors) DiffRemovedTextColor() color.Color
- func (c ThemeColors) ErrorColor() color.Color
- func (c ThemeColors) InfoColor() color.Color
- func (c ThemeColors) PrimaryColor() color.Color
- func (c ThemeColors) SecondaryColor() color.Color
- func (c ThemeColors) SuccessColor() color.Color
- func (c ThemeColors) TextColor() color.Color
- func (c ThemeColors) ToolColor() color.Color
- func (c ThemeColors) WarningColor() color.Color
- type ThemeManager
- func (tm *ThemeManager) ClosestMatches(query string, max int) []string
- func (tm *ThemeManager) Colors() ThemeColors
- func (tm *ThemeManager) Current() Theme
- func (tm *ThemeManager) CurrentName() string
- func (tm *ThemeManager) HasTheme(name string) bool
- func (tm *ThemeManager) IsDark() bool
- func (tm *ThemeManager) List() []Theme
- func (tm *ThemeManager) SetTheme(name string) error
- func (tm *ThemeManager) ThemeCount() int
- type TokenTracker
- type ToolDisplayModel
Constants ¶
const DefaultThemeName = "tokyo-night"
DefaultThemeName is the default theme when none is configured.
const SidebarWidth = 23
SidebarWidth is the fixed width of the right sidebar.
23 is the 18 it used to be, widened by 5: the sidebar's rows are short labels and counts, so the columns it gives back to the chat panel are worth more than the slack it keeps. Every consumer reads this constant — mainWidth, the render-integrity test's column check — so the whole frame follows from it.
Variables ¶
This section is empty.
Functions ¶
func BashEventKind ¶ added in v0.0.53
BashEventKind namespaces a live shell-command event so it can share the subagent event channel without being mistaken for subagent activity. Producers outside this package must route bash events through it rather than hard-coding the prefix.
func GenerateCommitMsgFunc ¶
func GenerateCommitMsgFunc(llm llmmodel.LLM) func(ctx context.Context, diffs string) (string, error)
GenerateCommitMsgFunc creates a function that generates commit messages using the given LLM.
func RenderContextBreakdown ¶ added in v0.0.48
func RenderContextBreakdown(b ContextBreakdown, window int64, width int, p Palette) string
RenderContextBreakdown renders the legend panel: a header with the headline percentage, the segmented bar, then one row per section.
func RenderMermaid ¶ added in v0.0.83
RenderMermaid renders mermaid source as terminal art styled with the pane's palette, wrapped to width. It returns "" when the source is not a diagram this renderer models, which is the caller's signal to fall back to showing the original fence.
Width is a fill target, not a hard cap — the layout engine will exceed it for a graph that genuinely needs more columns — so the result is measured and rejected if it overflows. A diagram wider than the pane is worse than no diagram: the terminal cannot scroll sideways, so it renders as ragged, truncated lines with no way to see the rest.
func RenderSidebar ¶ added in v0.0.11
func RenderSidebar(in SidebarRenderInput) string
RenderSidebar renders the right sidebar panel.
The body is a sequence of independent sections, each contributing its own lines (nil when hidden); sidebarFrame then pads, clamps and boxes the result to the requested width and height.
func SetupProgramOptions ¶ added in v0.2.4
func SetupProgramOptions() []tea.ProgramOption
SetupProgramOptions returns the terminal options a standalone program should use for the wizard: the same environment and color-profile negotiation the main TUI performs, so color detection is consistent between the two.
Types ¶
type A2AAgentEntry ¶ added in v0.0.87
type A2AAgentEntry struct {
Name string
}
A2AAgentEntry is one row in the A2A Agents sidebar section.
type AgentMood ¶ added in v0.0.11
type AgentMood int
AgentMood represents the current emotional state of the agent.
type AgentSubEvent ¶
type AgentSubEvent struct {
AgentID string
Kind string // "tool_call", "tool_result", "text_delta", etc.
Content string
PipelineID string // groups agents in same call
Mode string // "single", "parallel", "chain"
Step int // 1-based position in pipeline
Total int // total agents in pipeline
}
AgentSubEvent carries a subagent event from the agent tool to the TUI.
type ArtifactEntry ¶ added in v0.0.46
ArtifactEntry is one row in the Artifacts sidebar section. Filename is the ADK artifact key (e.g. "screenshot.png"). Size is the byte count of the stored part. Mime is optional; entries with an "image/*" MIME get a frame icon, everything else gets a paperclip.
type Breakpoint ¶ added in v0.0.10
type Breakpoint int
Breakpoint represents terminal width categories.
const ( BreakpointNarrow Breakpoint = iota // < 60 cols BreakpointNormal // 60-100 cols BreakpointWide // > 100 cols )
type ChatModel ¶ added in v0.0.10
type ChatModel struct {
Messages []message
Scroll int // scroll offset from bottom
Streaming string
Thinking string
Renderer *glamour.TermRenderer
TraceLog []traceEntry
Width int
ToolDisplay ToolDisplayModel
// Palette is the resolved theme palette, set each frame by the model before
// rendering. Zero means the dark default.
Palette Palette
// contains filtered or unexported fields
}
ChatModel manages the conversation message display, scrolling, and markdown rendering.
func NewChatModel ¶ added in v0.0.10
func NewChatModel(renderer *glamour.TermRenderer) ChatModel
NewChatModel creates a ChatModel with the given markdown renderer.
func (*ChatModel) AppendError ¶ added in v0.0.46
AppendError adds an error message styled with red text. Errors that end a run must be impossible to miss: the plain assistant bubble reads like part of the model's answer, which is how provider failures used to slip past.
func (*ChatModel) AppendMeta ¶ added in v0.0.74
AppendMeta adds a dim, single-line metadata note to the transcript (e.g. the per-turn token summary). It is deliberately low-contrast: it must read as chrome around the reply, not as content.
func (*ChatModel) AppendNotice ¶ added in v0.2.0
AppendNotice adds a system notice to the transcript — a skipped MCP server, a blocked skill, an LSP hook warning — styled as an ordinary reply.
It exists rather than reusing AppendWarning because a notice is not a warning: "compaction ran" and "update available" carry no ⚠, and dressing them in the warning color would make every benign startup message read as a problem.
What it does share with the other appenders is closing the block. A notice carries role "assistant" so it sits in the reply column, which means an unflagged one is indistinguishable from a reply still being streamed: the next text delta appends into it and overwrites the notice before it is ever painted. The repaint the notice triggers is not the problem — painting a message that the next delta erases is.
func (*ChatModel) AppendWarning ¶ added in v0.0.11
AppendWarning adds a warning message styled with yellow text.
func (*ChatModel) Clear ¶ added in v0.0.10
func (c *ChatModel) Clear()
Clear removes all messages and resets scroll.
func (*ChatModel) MaxScroll ¶ added in v0.0.10
MaxScroll returns the maximum scroll offset for the given terminal height.
func (*ChatModel) PlainTranscript ¶ added in v0.0.37
PlainTranscript returns the conversation as copy-friendly plain text.
func (*ChatModel) RefreshTheme ¶ added in v0.0.57
RefreshTheme rebuilds the markdown renderer when the palette has changed since the renderer was built, and reports whether it did.
The glamour stylesheet is baked into the TermRenderer, so it is invisible to renderKey — a theme switch that only swapped the palette would repaint the lipgloss chrome and leave the transcript in the old theme. Callers that change the palette (the /theme command, terminal background detection) call this to bring the transcript with them.
func (*ChatModel) RenderMarkdown ¶ added in v0.0.10
RenderMarkdown renders text as markdown using the glamour renderer. It first expands markdown links (like [text](url)) into inline format when the link has both a display name and an actual file:// or http:// URL.
Closed ```mermaid fences are drawn as terminal art instead of being printed as source. The art is spliced in after glamour has run on the prose around it: glamour treats escape bytes as literal text, so anything already carrying ANSI has to bypass it.
func (*ChatModel) RenderMessages ¶ added in v0.0.10
RenderMessages renders all messages into a string for display.
func (*ChatModel) ResetScroll ¶ added in v0.0.10
func (c *ChatModel) ResetScroll()
ResetScroll resets the scroll offset to bottom.
func (*ChatModel) ScrollDown ¶ added in v0.0.10
ScrollDown scrolls down by n lines, clamped to 0.
func (*ChatModel) UpdateRenderer ¶ added in v0.0.10
UpdateRenderer recreates the glamour renderer for the given terminal width.
type ChecklistStep ¶ added in v0.0.14
ChecklistStep represents a single step from the plan.md checklist.
type CompactStatsProvider ¶ added in v0.0.4
type CompactStatsProvider interface {
FormatStats() string
}
CompactStatsProvider provides compaction statistics for TUI display.
type CompleteResult ¶
type CompleteResult struct {
Candidates []CompletionCandidate
Selected int
Type CompletionType
}
CompleteResult holds all completion results.
func Complete ¶
func Complete(input string, skills []extension.Skill, workDir string) *CompleteResult
Complete returns completion candidates for the given input. It analyzes the input and returns all matching options for commands, skills, and specs.
func CompleteMention ¶ added in v0.0.10
func CompleteMention(prefix string, workDir string) *CompleteResult
CompleteMention returns file completion candidates for the given prefix.
func (*CompleteResult) ApplySelection ¶
func (r *CompleteResult) ApplySelection(index int) string
ApplySelection returns the text of the candidate at the given index.
func (*CompleteResult) CycleSelection ¶
func (r *CompleteResult) CycleSelection(dir int)
CycleSelection moves the selection index in the given direction. dir should be 1 for next, -1 for previous.
func (*CompleteResult) SelectedCandidate ¶
func (r *CompleteResult) SelectedCandidate() *CompletionCandidate
SelectedCandidate returns the currently selected candidate.
type CompletionCandidate ¶
type CompletionCandidate struct {
Text string
Description string
Type CompletionType
}
CompletionCandidate represents a single completion option.
type CompletionType ¶
type CompletionType int
CompletionType identifies what kind of completion to perform.
const ( CompletionTypeNone CompletionType = iota CompletionTypeCommand CompletionTypeSkill CompletionTypeSpec CompletionTypeFile )
type Config ¶
type Config struct {
Agent *agent.Agent
LLM llmmodel.LLM // The active LLM, used by /ping.
SessionID string
AppVersion string
ModelName string
ProviderName string
// ThinkingLevel is the configured reasoning effort: "none", "low",
// "medium", "high" or "max", or empty for the provider's own default.
//
// It is read at startup by the CLI, which threads it into
// provider.NewLLM, and shown by the sidebar under the model name. The two
// are deliberately separate: this field reports what was configured, while
// a provider that ignores the level still accepts it, so the row describes
// the request rather than a guarantee.
ThinkingLevel string
ActiveRole string
Roles map[string]config.RoleConfig
SessionService *pisession.FileService
WorkDir string
Orchestrator *subagent.Orchestrator
// GenerateCommitMsg is called by /commit to generate a conventional commit message from diffs.
// If nil, /commit is disabled.
GenerateCommitMsg func(ctx context.Context, diffs string) (string, error)
// Logger is the session logger. If nil, logging is disabled.
Logger *logger.Logger
// Skills is loaded from skill directories for command completion.
Skills []extension.Skill
// SkillDirs are the directories to re-scan for skills on each completion.
SkillDirs []string
// AgentEventCh receives subagent events from the agent tool for live display.
AgentEventCh <-chan AgentSubEvent
// SystemNoticeCh receives short system messages that must be shown in the
// chat — auto-compaction outcomes, for instance. Compaction discards
// history, so it must never happen silently.
SystemNoticeCh <-chan string
// ContextBreakdown attributes fixed context overhead (system prompt, tool
// definitions, rules, skills, MCP tools, subagents) to its origins, so the
// gauge can show what is filling the window rather than only how much.
// Nil renders the gauge in a single severity color.
ContextBreakdown *ContextBreakdown
// TokenTracker tracks daily token usage and enforces limits. May be nil.
TokenTracker TokenTracker
// CompactMetrics tracks output compaction statistics. May be nil.
CompactMetrics CompactStatsProvider
// ThemeName is the configured theme name from config. Empty or "default" uses tokyo-night.
ThemeName string
// PlanAutoFix enables the automatic plan-repair loop: when a /plan session
// ends with a spec that fails the PDD contract, the blocking findings are
// fed back to the planner as its next prompt instead of waiting for a human
// turn. Bounded by maxPlanFixCycles.
PlanAutoFix bool
// GoalTool is the shared state of the goal_complete tool, or nil when the
// tool was not registered. The /goal loop reads the completions the agent
// reports through it and publishes the running cycle back, so the two agree on
// which turn is running without either reaching into the other's structure.
GoalTool *tools.GoalController
// BaseInstruction is the system instruction the session was configured with,
// before any goal section was appended. The /goal loop rebuilds the agent's
// instruction each cycle and must rebuild it from this rather than from
// agent.SystemInstruction: --system replaces the built-in outright, so reloading
// the default would discard the user's own prompt the first time a goal was set
// and never put it back. Empty falls back to the default.
BaseInstruction string
// LifecycleHooks are shell-command hooks fired on agent lifecycle events
// (turn_complete, user_input_required). Each carries the event name and a
// small data payload as JSON on stdin. Nil disables lifecycle hooks.
LifecycleHooks []extension.HookConfig
// DeferredInit, if non-nil, is a channel of InitEvent messages.
// When set, the TUI starts immediately in loading state and receives
// initialization progress updates. The final event carries the fully
// initialized subsystems in its Result field.
DeferredInit <-chan InitEvent
// MCPToolsets holds the live MCP toolsets, used by /mcp to show status.
MCPToolsets []adktool.Toolset
// MCPServers holds the configured MCP server definitions.
MCPServers []extension.MCPServerConfig
// A2A holds the configured A2A agent endpoints, shown in the sidebar.
A2A *config.A2AConfig
// ModelSwitcher creates a new LLM instance for the given model name,
// updates the token tracker's context window size, and returns the
// wrapped LLM, resolved model name, and provider. Used by /model <name>.
// If nil, model switching via /model is disabled.
ModelSwitcher func(ctx context.Context, modelName string) (llmmodel.LLM, string, string, error)
}
Config holds configuration for the TUI.
type ContextBreakdown ¶ added in v0.0.48
type ContextBreakdown struct {
// Fixed per-session overhead, in tokens.
SystemPrompt int64
ToolDefs int64
Rules int64
Skills int64
MCPTools int64
Subagents int64
// Conversation is everything else in the window: messages, tool calls and
// tool results. Derived, not measured directly.
Conversation int64
}
ContextBreakdown attributes context usage to its origins. The fixed sections are measured once at startup; Conversation is derived per-render from the provider's reported prompt size.
func (ContextBreakdown) FixedTotal ¶ added in v0.0.48
func (b ContextBreakdown) FixedTotal() int64
FixedTotal is the overhead present before a single message is exchanged.
func (ContextBreakdown) Tokens ¶ added in v0.0.48
func (b ContextBreakdown) Tokens(k ContextSegmentKind) int64
Tokens returns one segment's size.
func (ContextBreakdown) Total ¶ added in v0.0.48
func (b ContextBreakdown) Total() int64
Total is the whole window in use.
type ContextSegmentKind ¶ added in v0.0.48
type ContextSegmentKind int
ContextSegmentKind identifies a category of context consumption. The order of these constants is the order segments are drawn, fixed overhead first, so the bar reads left-to-right from "cost you pay every turn" to "the session".
const ( SegSystemPrompt ContextSegmentKind = iota SegToolDefs SegRules SegSkills SegMCPTools SegSubagents SegConversation )
func (ContextSegmentKind) Color ¶ added in v0.0.48
func (k ContextSegmentKind) Color(p Palette) color.Color
Color returns the segment's swatch. The palette is chosen so adjacent segments never share a hue and the whole set stays legible on the theme's background; Conversation is warmest because it is the one that grows.
func (ContextSegmentKind) Label ¶ added in v0.0.48
func (k ContextSegmentKind) Label() string
Label is the human-readable name shown in the legend.
type FaceRenderer ¶ added in v0.0.11
type FaceRenderer struct {
// contains filtered or unexported fields
}
FaceRenderer tracks the agent's current mood (thread-safe).
func NewFaceRenderer ¶ added in v0.0.11
func NewFaceRenderer() *FaceRenderer
NewFaceRenderer creates a new face renderer with default idle mood.
func (*FaceRenderer) Eyes ¶ added in v0.0.11
func (f *FaceRenderer) Eyes() string
Eyes returns the eyes string for the current mood.
func (*FaceRenderer) GetMood ¶ added in v0.0.11
func (f *FaceRenderer) GetMood() AgentMood
GetMood returns the current mood.
func (*FaceRenderer) Mascot ¶ added in v0.0.17
func (f *FaceRenderer) Mascot() string
Mascot returns the full mascot face for the current mood.
func (*FaceRenderer) SetMood ¶ added in v0.0.11
func (f *FaceRenderer) SetMood(mood AgentMood)
SetMood changes the agent's current mood.
type GateResult ¶
type GateResult struct {
Name string
Command string
Passed bool // true only for GatePass; kept as the summary predicate
Status GateStatus
Output string
Elapsed time.Duration
}
GateResult holds the result of running a single gate command.
type GateStatus ¶ added in v0.0.82
type GateStatus string
GateStatus is the outcome of one gate command. It is three-valued on purpose: a gate that never returns is not a gate that passed.
pi-go has a documented case of this — tests that bind a local listener hang under the sandbox (AGENTS.md, "Two environment traps"). Session trajectories show coordinators backgrounding such a run, killing it, and reporting success. Collapsing "hang" into either "pass" or "fail" is what let that happen: reported as a pass it merges unverified work, reported as a fail it burns the retry budget re-running something that will hang again.
const ( GatePass GateStatus = "pass" GateFail GateStatus = "fail" GateHang GateStatus = "hang" )
type HistoryEntry ¶ added in v0.0.10
type HistoryEntry struct {
Text string `json:"text"`
Mentions []string `json:"mentions,omitempty"`
}
HistoryEntry stores a single prompt with its full input state.
type InitEvent ¶ added in v0.0.11
type InitEvent struct {
Item string // subsystem name (e.g. "lsp", "memory", "mcp")
Done bool // true when this item finished loading
Total int // planned subsystem count when known; 0 means derive from seen items
Result *InitResult // set on the final event when all init is complete
Err error // fatal initialization error
}
InitEvent reports progress from deferred initialization.
type InitResult ¶ added in v0.0.11
type InitResult struct {
Agent *agent.Agent
SessionID string
// SessionTitle is the default title the agent applied to the new session
// (git repo name, or CWD basename). The TUI seeds its terminal window/tab
// title with it so the user sees a label before the first user prompt
// arrives. Empty if the agent has no title namer or no CWD to derive from.
SessionTitle string
// Resumed reports that SessionID names an existing session rather than one
// created for this run, so the TUI knows to rebuild its transcript from the
// session's events instead of opening on the welcome splash.
Resumed bool
SessionService *pisession.FileService
Orchestrator *subagent.Orchestrator
Logger *logger.Logger
Skills []extension.Skill
SkillDirs []string
GenerateCommitMsg func(context.Context, string) (string, error)
AgentEventCh <-chan AgentSubEvent
SystemNoticeCh <-chan string
ContextBreakdown *ContextBreakdown
TokenTracker TokenTracker
CompactMetrics CompactStatsProvider
GitBranch string
DiffAdded int
DiffRemoved int
// GoalTool is the shared goal_complete controller, nil when the tool was not
// registered. It is handed over on the same deferred-init path as the other
// late-built subsystems, because the tool is built alongside the tool set.
GoalTool *tools.GoalController
// BaseInstruction is the system instruction the session was configured with,
// before any goal or skill section was appended. The /goal loop rebuilds the
// agent's instruction each cycle, and it has to rebuild it from this rather
// than from agent.SystemInstruction: --system replaces the built-in outright, so
// reloading the default would silently discard the user's own prompt the first
// time a goal was set, and never put it back.
BaseInstruction string
// MCPToolsets holds the live MCP toolsets for /mcp status display.
MCPToolsets []adktool.Toolset
// MCPServers holds the configured MCP server definitions.
MCPServers []extension.MCPServerConfig
}
InitResult holds the fully initialized subsystems delivered by deferred init.
type InputModel ¶ added in v0.0.10
type InputModel struct {
Text string
CursorPos int // character position (not byte offset)
History []HistoryEntry
// Dependencies (set by root model).
Skills []extension.Skill
SkillDirs []string
WorkDir string
// Palette is the resolved theme palette, set each frame by the model before
// rendering. Zero means the dark default.
Palette Palette
// contains filtered or unexported fields
}
InputModel wraps Bubble Tea's textarea component with history and slash-command support. All completion/mention state has been removed; the textarea library handles cursor movement and editing directly.
Enter submits. Shift+Enter, Alt+Enter and Ctrl+J insert a newline, and a multi-line paste keeps its line breaks. Text and CursorPos stay flat (a rune offset into the whole value, newlines included) so callers need not know the input is multi-line.
History is recorded here but not navigated here: the root model binds Up to the history window (see handleKey), so the input never sees arrow keys.
func NewInputModel ¶ added in v0.0.10
func NewInputModel(history []HistoryEntry, skills []extension.Skill, skillDirs []string, workDir string) InputModel
NewInputModel creates an InputModel with initial state.
func (*InputModel) AllCommandNames ¶ added in v0.0.10
func (im *InputModel) AllCommandNames() []string
AllCommandNames returns a sorted list of all command names: built-in + skills.
func (*InputModel) AtFirstRow ¶ added in v0.3.1
func (im *InputModel) AtFirstRow() bool
AtFirstRow reports whether the cursor is on the first visual row, so Up has nowhere to go inside the text and may be used for history instead.
func (*InputModel) AtLastRow ¶ added in v0.3.1
func (im *InputModel) AtLastRow() bool
AtLastRow reports whether the cursor is on the last visual row.
func (*InputModel) Clear ¶ added in v0.0.10
func (im *InputModel) Clear()
Clear resets the input text and cursor.
func (*InputModel) Cursor ¶ added in v0.0.32
func (im *InputModel) Cursor() *tea.Cursor
Cursor returns the real Bubble Tea cursor for the input's current position.
func (*InputModel) HandleKey ¶ added in v0.0.10
func (im *InputModel) HandleKey(msg tea.KeyPressMsg) tea.Cmd
HandleKey processes a key press for the input area. Returns a tea.Cmd (InputSubmitMsg on submit, nil otherwise).
func (*InputModel) InsertText ¶ added in v0.0.10
func (im *InputModel) InsertText(text string)
InsertText inserts pasted or programmatic text at cursor position.
func (*InputModel) RefreshTheme ¶ added in v0.0.57
func (im *InputModel) RefreshTheme() bool
RefreshTheme repaints the input's prompt and cursor when the palette has changed since they were built, and reports whether it did.
func (*InputModel) ReloadSkills ¶ added in v0.0.10
func (im *InputModel) ReloadSkills()
ReloadSkills re-scans skill directories from disk and updates the cached list.
func (*InputModel) SetText ¶ added in v0.0.32
func (im *InputModel) SetText(text string)
SetText replaces the input text and moves the cursor to the end.
func (*InputModel) SetWidth ¶ added in v0.0.32
func (im *InputModel) SetWidth(width int)
SetWidth sets the visible width of the editable input text, excluding the prompt.
func (*InputModel) View ¶ added in v0.0.10
func (im *InputModel) View(running bool) string
View renders the input area.
type InputSubmitMsg ¶ added in v0.0.10
InputSubmitMsg is emitted when the user presses Enter with non-empty input.
type Layout ¶ added in v0.0.10
type Layout struct {
Width int
Height int
Breakpoint Breakpoint
}
Layout holds terminal dimensions and the computed breakpoint.
func (Layout) ChatWidth ¶ added in v0.0.10
ChatWidth returns the available width for chat message content.
func (Layout) MaxPathLen ¶ added in v0.0.10
MaxPathLen returns the maximum path display length for the current breakpoint.
func (Layout) SeparatorWidth ¶ added in v0.0.10
SeparatorWidth returns the width for horizontal separators.
func (Layout) StatusWidth ¶ added in v0.0.10
StatusWidth returns the available width for the status bar content.
type Palette ¶ added in v0.0.56
type Palette struct {
Valid bool
// IsLight reports whether this palette is meant for a light terminal
// background. Renderers that must pick a whole foreign stylesheet — the
// glamour markdown style, the chroma syntax style — branch on this rather
// than sniffing Background, which only worked while every light theme
// collapsed to one palette.
IsLight bool
// Text roles.
Text color.Color // primary text
Subtext color.Color // secondary text
Dim color.Color // muted text (thinking, separators)
Faint color.Color // faintest (line numbers, very muted)
// Semantic accents.
Primary color.Color // blue — prompts, user labels, links
Accent color.Color // violet — reply bullets
Tool color.Color // green — tool names
Success color.Color // green
Error color.Color // red
Warning color.Color // yellow
// Extended hues.
Blue color.Color
Cyan color.Color
Teal color.Color
Green color.Color
Yellow color.Color
Peach color.Color // orange
Red color.Color
Pink color.Color
Mauve color.Color
Sky color.Color
Sapphire color.Color
Lavender color.Color
// Surfaces.
Surface color.Color // rules, separators (surface2)
Surface1 color.Color
Overlay color.Color
Overlay2 color.Color
Background color.Color
Surface0 color.Color
Overlay0 color.Color
Overlay1 color.Color
White color.Color // deliberately outside the gauge vocabulary
Control color.Color // controls that must sit outside a gauge's color vocabulary
Transparent color.Color
}
Palette is the resolved set of colors the renderers draw with. It is the bridge between the theme system and the renderers: the theme manager picks a Theme, and paletteFor turns it into a Palette the renderers can read.
Before this existed every renderer hardcoded Catppuccin Mocha (dark) hex values, so switching to a light theme changed nothing on screen — the dark foregrounds were invisible on a light terminal background. Threading a Palette through the render inputs is what makes light themes actually render.
Valid distinguishes a real palette from the zero value, so renderers that receive an unset Palette (e.g. in tests) fall back to the dark palette and keep their existing output byte-for-byte.
func PaletteForName ¶ added in v0.2.4
PaletteForName resolves the palette for a configured theme name, falling back to the dark default for an unknown or empty name. It exists for entry points that run outside a chat session — `pi setup` — which have no ThemeManager and should still draw in the user's colors rather than always in the default.
type PlanPhase ¶ added in v0.0.82
type PlanPhase struct {
Name string // short label, e.g. "Requirements"
Done bool // the artifact carries real content, not just a skeleton
}
PlanPhase is one PDD phase in the plan-mode sidebar checklist.
type SOPGraph ¶ added in v0.0.82
SOPGraph is the compiled SOP the sidebar draws underneath the stage list: the stages in order, the edges between them, and each stage's status. Nil hides the diagram.
type SearchItem ¶ added in v0.0.32
type SearchItem struct {
Text string // the command or history text
Description string // for commands: the description
}
SearchItem represents an item in the search popup (command or history entry).
type SetupConfig ¶ added in v0.2.4
type SetupConfig struct {
Providers []SetupProvider
// Candidates maps a provider name to the model IDs offered for selection.
// An empty or missing entry means free-text entry only, which is the
// honest answer for a provider pi-go has no offline catalog for.
Candidates map[string][]string
// InitialProvider preselects the configured provider, so re-running setup
// is an edit rather than a reset.
InitialProvider string
Theme string
}
SetupConfig is everything the wizard needs before it can draw a frame.
type SetupProvider ¶ added in v0.2.4
type SetupProvider struct {
Name string // provider key as config.json spells it, e.g. "anthropic"
Label string // human name shown in the list
EnvVar string // environment variable / .env key
NeedsKey bool // false for a local daemon that authenticates nothing
KeyURL string // where the user gets a key, empty when NeedsKey is false
// OptionalKey shows the key step without requiring an answer. It is for a
// provider that runs without a credential by default but can be put
// behind one — agentgateway with an apiKey policy — where skipping the
// step would leave no way to configure the protected case, and requiring
// it would block the common open one. Ignored when NeedsKey is set.
OptionalKey bool
}
SetupProvider describes one provider the setup wizard can configure.
The wizard deliberately carries its own small description of a provider rather than deriving it from internal/provider: that package answers "which backend serves this model", while this answers "what does a user have to paste, and from where". Keeping the credential URL next to the env var is what lets the wizard tell someone exactly which page to open.
type SetupResult ¶ added in v0.2.4
SetupResult is the choice the user confirmed, or Canceled.
The wizard returns data instead of writing it: persistence lives in the CLI, so the UI stays free of I/O and a test can drive the whole flow in memory.
type SetupWizard ¶ added in v0.2.4
type SetupWizard struct {
// contains filtered or unexported fields
}
SetupWizard is a standalone Bubble Tea program for configuring a provider.
It is separate from the main TUI on purpose. `pi setup` runs before any session exists — there is no agent, no logger and no config to reload — so hosting it inside the chat model would mean standing up that whole machine to collect three strings.
func NewSetupWizard ¶ added in v0.2.4
func NewSetupWizard(cfg SetupConfig, p Palette) *SetupWizard
NewSetupWizard builds the wizard with its first step ready.
func (*SetupWizard) Init ¶ added in v0.2.4
func (w *SetupWizard) Init() tea.Cmd
Init starts the wizard with the first step's input focused.
func (*SetupWizard) Result ¶ added in v0.2.4
func (w *SetupWizard) Result() SetupResult
Result reports the confirmed choice. It is only meaningful once the program has exited; anything other than an explicit confirmation returns Canceled.
func (*SetupWizard) View ¶ added in v0.2.4
func (w *SetupWizard) View() tea.View
View renders the current step.
type SidebarRenderInput ¶ added in v0.0.11
type SidebarRenderInput struct {
Width int
Height int
Eyes string
Mascot string // full 3-line mascot face (mutually exclusive with Eyes)
Mode string
ProviderName string
ModelName string
// ThinkingLevel is the configured reasoning effort ("none", "low", "medium",
// "high", "max"), shown under the model name. Empty hides the row, which is
// what an unset level means — the provider's own default applies.
//
// It is the configured value, not a capability report. Several providers
// (OpenAI, Azure, Gemini, agentgateway) never receive it, so a level can be
// displayed on a model that ignores it. Reporting that here would mean
// duplicating internal/provider.NewLLM's provider switch into the sidebar,
// which is a worse trade than a row that occasionally describes an unheeded
// request.
ThinkingLevel string
GitBranch string
DiffAdded int
DiffRemoved int
Running bool
TokenTracker TokenTracker
AppVersion string
HostName string
FolderName string
Messages []message
ActiveTool string
LoadingItems map[string]bool
RunChecklist []ChecklistStep // steps from plan.md during /run
RunPhase string // current /run phase (empty if not running)
RunSpec string // spec name during /run
RunCycle int // current retry cycle
RunMaxCycle int // max retries
PlanPhases []PlanPhase // PDD phase checklist shown in plan mode; nil/empty = hidden
Graph *SOPGraph // compiled SOP drawn under the stage list; nil = hidden
MatrixLines string // pre-rendered matrix rain (2 lines)
StatusLine string // status text shown above matrix
Orchestrator *subagent.Orchestrator // may be nil — for agents section
Skills []extension.Skill // skills section; nil = hidden
MCPTools []extension.MCPToolEntry // MCP tools section; nil = hidden
// Goal is the session's /goal objective, nil when none is set. The loop
// spends a billed agent turn per cycle, so how far into the budget it has
// got belongs on screen while it happens rather than in the transcript
// afterwards.
Goal *pisession.Goal
GoalMaxCycles int // resolved loop budget, 0 when no goal
GoalStopped bool // loop stopped without the goal's status changing (Esc, budget)
A2AAgents []A2AAgentEntry // A2A agents section; nil = hidden
MemoryStatus *palace.PalaceStatus // memory palace status; nil = hidden
Artifacts []ArtifactEntry // artifacts section; nil/empty = hidden
Palette Palette // resolved theme palette; zero = dark default
// contains filtered or unexported fields
}
SidebarRenderInput provides data needed by the sidebar.
type StatusModel ¶ added in v0.0.10
type StatusModel struct {
// GitBranch is the current git branch (detected at startup).
GitBranch string
// ActiveTool is the name of the currently executing tool (single).
ActiveTool string
// ActiveTools tracks parallel tool execution: name → start time.
ActiveTools map[string]time.Time
// ToolStart is when the current single tool started.
ToolStart time.Time
// Width is the terminal width for rendering.
Width int
}
StatusModel manages the status bar display at the bottom of the TUI.
func (*StatusModel) Render ¶ added in v0.0.10
func (s *StatusModel) Render(in StatusRenderInput) string
Render renders the status bar string.
The bar is a list of fields joined by a separator, and each statusXxxField helper below owns exactly one of them. A helper returns nil when its field is not shown this frame, so appending with "..." keeps the separator bookkeeping here and out of every field.
type StatusRenderInput ¶ added in v0.0.10
type StatusRenderInput struct {
ProviderName string
ModelName string
Running bool
Pending int // prompts waiting behind the active response
Mode string // "chat" or "plan"
Eyes string // mood eyes e.g. "◕ ◕"
Messages []message // for context estimate
TokenTracker TokenTracker // may be nil
DiffAdded int
DiffRemoved int
RunCycle *runCycleInfo // may be nil
FolderName string // current working directory basename
HostName string // local hostname
LoadingItems map[string]bool // item -> done; nil means not loading
Flash string // transient notice ("Copied!"); empty when none
Palette Palette // resolved theme palette; zero = dark default
}
StatusRenderInput provides data from other models needed by the status bar.
type Theme ¶ added in v0.0.10
type Theme struct {
Name string `json:"name"`
DisplayName string `json:"displayName"`
ThemeType string `json:"themeType"`
Colors ThemeColors `json:"colors"`
}
Theme represents a loaded color theme.
type ThemeColors ¶ added in v0.0.10
type ThemeColors struct {
Text string `json:"text"`
Base string `json:"base"`
Primary string `json:"primary"`
Tool string `json:"tool"`
Success string `json:"success"`
Error string `json:"error"`
Secondary string `json:"secondary"`
Info string `json:"info"`
Warning string `json:"warning"`
DiffAdded string `json:"diffAdded"`
DiffRemoved string `json:"diffRemoved"`
DiffAddedText string `json:"diffAddedText"`
DiffRemovedText string `json:"diffRemovedText"`
}
ThemeColors holds the 13 color roles used throughout the TUI. Colors are stored as hex strings and converted to color.Color via lipgloss.Color().
func (ThemeColors) BaseColor ¶ added in v0.0.10
func (c ThemeColors) BaseColor() color.Color
func (ThemeColors) DiffAddedColor ¶ added in v0.0.10
func (c ThemeColors) DiffAddedColor() color.Color
func (ThemeColors) DiffAddedTextColor ¶ added in v0.0.10
func (c ThemeColors) DiffAddedTextColor() color.Color
func (ThemeColors) DiffRemovedColor ¶ added in v0.0.10
func (c ThemeColors) DiffRemovedColor() color.Color
func (ThemeColors) DiffRemovedTextColor ¶ added in v0.0.10
func (c ThemeColors) DiffRemovedTextColor() color.Color
func (ThemeColors) ErrorColor ¶ added in v0.0.10
func (c ThemeColors) ErrorColor() color.Color
func (ThemeColors) InfoColor ¶ added in v0.0.10
func (c ThemeColors) InfoColor() color.Color
func (ThemeColors) PrimaryColor ¶ added in v0.0.10
func (c ThemeColors) PrimaryColor() color.Color
func (ThemeColors) SecondaryColor ¶ added in v0.0.10
func (c ThemeColors) SecondaryColor() color.Color
func (ThemeColors) SuccessColor ¶ added in v0.0.10
func (c ThemeColors) SuccessColor() color.Color
func (ThemeColors) TextColor ¶ added in v0.0.10
func (c ThemeColors) TextColor() color.Color
func (ThemeColors) ToolColor ¶ added in v0.0.10
func (c ThemeColors) ToolColor() color.Color
func (ThemeColors) WarningColor ¶ added in v0.0.10
func (c ThemeColors) WarningColor() color.Color
type ThemeManager ¶ added in v0.0.10
type ThemeManager struct {
// contains filtered or unexported fields
}
ThemeManager manages theme loading, selection, and color access.
func NewThemeManager ¶ added in v0.0.10
func NewThemeManager() *ThemeManager
NewThemeManager creates a ThemeManager with all embedded themes loaded. Falls back to pi-classic if the embedded JSON is corrupt.
func NewThemeManagerFromJSON ¶ added in v0.0.10
func NewThemeManagerFromJSON(data []byte) (*ThemeManager, error)
NewThemeManagerFromJSON creates a ThemeManager from custom JSON data.
func (*ThemeManager) ClosestMatches ¶ added in v0.0.10
func (tm *ThemeManager) ClosestMatches(query string, max int) []string
ClosestMatches returns theme names that contain the given substring, useful for suggesting alternatives when a theme isn't found.
func (*ThemeManager) Colors ¶ added in v0.0.10
func (tm *ThemeManager) Colors() ThemeColors
Colors returns the current theme's color palette.
func (*ThemeManager) Current ¶ added in v0.0.10
func (tm *ThemeManager) Current() Theme
Current returns the active theme.
func (*ThemeManager) CurrentName ¶ added in v0.0.10
func (tm *ThemeManager) CurrentName() string
CurrentName returns the name of the active theme.
func (*ThemeManager) HasTheme ¶ added in v0.0.10
func (tm *ThemeManager) HasTheme(name string) bool
HasTheme returns true if a theme with the given name exists.
func (*ThemeManager) IsDark ¶ added in v0.0.10
func (tm *ThemeManager) IsDark() bool
IsDark returns true if the current theme is a dark theme.
func (*ThemeManager) List ¶ added in v0.0.10
func (tm *ThemeManager) List() []Theme
List returns all available themes sorted by name.
func (*ThemeManager) SetTheme ¶ added in v0.0.10
func (tm *ThemeManager) SetTheme(name string) error
SetTheme changes the active theme. Returns an error if the theme doesn't exist.
func (*ThemeManager) ThemeCount ¶ added in v0.0.10
func (tm *ThemeManager) ThemeCount() int
ThemeCount returns the number of loaded themes.
type TokenTracker ¶ added in v0.0.4
type TokenTracker interface {
Limit() int64
Remaining() int64 // -1 if unlimited
PercentUsed() float64 // 0-100+
TotalUsed() int64 // total tokens consumed today
// Session context window tracking.
LastPromptTokens() int64 // most recent prompt tokens from LLM response
ContextWindowSize() int64 // model's context window size (0 = unknown)
ContextPercentUsed() float64 // context window usage 0-100+
// SetLastPromptTokens overrides the last-prompt baseline. Compaction
// passes call this with the post-pass token count so the context gauge
// reflects the new window immediately rather than waiting for the next
// LLM response. Implementations also reset the cached-prefix baseline
// (the new window has a new prefix by definition).
SetLastPromptTokens(n int64)
// ResetContextWindow zeroes the per-window baselines (last prompt,
// cached-prefix and last-cached counts) so the gauge reads empty. /clear
// calls this after the session's events are gone. SetLastPromptTokens(0)
// is deliberately not a substitute: it keeps a non-zero prompt count on
// purpose, so it can never empty the gauge. Daily usage totals are not
// affected — clearing a conversation does not un-spend tokens.
ResetContextWindow()
// Prompt-cache tracking. Prompt tokens are billed at a steep discount when
// served from cache, so LastPromptTokens alone overstates cost.
LastCachedTokens() int64 // cache reads on the most recent response
CachedTokensToday() int64 // cache reads accumulated today
CacheHitRateToday() float64 // share of today's prompt tokens cached, 0-100
BodyTokens() int64 // tokens accumulated after the cached prefix
CachePrefixTokens() int64 // stable cached prefix for this window
}
TokenTracker provides read access to daily token usage for the status bar.
type ToolDisplayModel ¶ added in v0.0.10
type ToolDisplayModel struct {
// Width is the terminal width for rendering.
Width int
// CompactTools when true shows one-line summaries instead of full output.
CompactTools bool
// Palette is the resolved theme palette, set each frame by the model before
// rendering. Zero means the dark default.
Palette Palette
// BlinkOn is the current phase of the pending-tool bullet blink, set each
// frame by the model. A tool card with no result yet blinks its ◉ bullet on
// and off so an active tool is visible at a glance; finished cards render
// the bullet solid.
BlinkOn bool
}
ToolDisplayModel manages the formatting and rendering of tool call/result messages in the chat view. It owns per-tool formatters, syntax highlighting, and summary generation.
func (*ToolDisplayModel) RenderToolMessage ¶ added in v0.0.10
func (t *ToolDisplayModel) RenderToolMessage(msg message) string
RenderToolMessage renders a tool message (role=="tool") into a styled string. It handles both agent/subagent tools (with event streams) and regular tools (with syntax-highlighted output). When CompactTools is true, renders a one-line summary instead of full output.
Source Files
¶
- agent_loop.go
- bar.go
- chat.go
- collapse.go
- commands.go
- commit.go
- completion.go
- context_breakdown.go
- context_rule.go
- create_skill.go
- drain_unix.go
- face.go
- goal.go
- grounding_display.go
- history.go
- input.go
- layout.go
- login.go
- matrix.go
- memory.go
- mermaid.go
- minimap.go
- model_price_refresh.go
- palette.go
- ping.go
- plan.go
- plan_validate.go
- prautofix.go
- run.go
- run_preflight.go
- selection.go
- session_restore.go
- setup_wizard.go
- sidebar.go
- sop_graph.go
- sop_status.go
- spinner.go
- status.go
- terminal_compat.go
- terminal_prepare.go
- terminal_title.go
- theme.go
- theme_preview.go
- tool_display.go
- tui.go
- types.go