tui

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: MIT Imports: 70 Imported by: 0

Documentation

Overview

Package tui implements the interactive terminal UI using Bubble Tea v2.

Index

Constants

View Source
const DefaultThemeName = "tokyo-night"

DefaultThemeName is the default theme when none is configured.

View Source
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

func BashEventKind(kind string) string

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

func RenderMermaid(source string, width int, p Palette) string

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 Run

func Run(ctx context.Context, cfg Config) error

Run starts the interactive TUI.

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.

const (
	MoodIdle       AgentMood = iota // Default waiting state
	MoodThinking                    // Processing/reasoning
	MoodProcessing                  // Tool execution
	MoodToolCall                    // About to call a tool
	MoodSpeaking                    // Producing text output
	MoodHappy                       // Task completed successfully
	MoodSad                         // Error or task failed
)

func (AgentMood) Eyes added in v0.0.11

func (m AgentMood) Eyes() string

Eyes returns the eyes string for this mood.

func (AgentMood) Mascot added in v0.0.17

func (m AgentMood) Mascot() string

Mascot returns the full mascot face for this mood.

func (AgentMood) String added in v0.0.11

func (m AgentMood) String() string

String returns a human-readable name for the mood.

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

type ArtifactEntry struct {
	Filename string
	Size     int64
	Mime     string
}

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

func (c *ChatModel) AppendError(text string)

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

func (c *ChatModel) AppendMeta(text string)

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) AppendWarning added in v0.0.11

func (c *ChatModel) AppendWarning(text string)

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

func (c *ChatModel) MaxScroll(height int) int

MaxScroll returns the maximum scroll offset for the given terminal height.

func (*ChatModel) PlainTranscript added in v0.0.37

func (c *ChatModel) PlainTranscript() string

PlainTranscript returns the conversation as copy-friendly plain text.

func (*ChatModel) RefreshTheme added in v0.0.57

func (c *ChatModel) RefreshTheme() bool

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

func (c *ChatModel) RenderMarkdown(text string) string

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

func (c *ChatModel) RenderMessages(running bool) string

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

func (c *ChatModel) ScrollDown(n int)

ScrollDown scrolls down by n lines, clamped to 0.

func (*ChatModel) ScrollUp added in v0.0.10

func (c *ChatModel) ScrollUp(n, height int)

ScrollUp scrolls up by n lines, clamped to max.

func (*ChatModel) UpdateRenderer added in v0.0.10

func (c *ChatModel) UpdateRenderer(width int)

UpdateRenderer recreates the glamour renderer for the given terminal width.

type ChecklistStep added in v0.0.14

type ChecklistStep struct {
	Title string
	Done  bool
}

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  string // "none", "low", "medium", "high", "max" — drives sidebar indicator
	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
	// 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

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

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 Gate

type Gate struct {
	Name    string
	Command string
}

Gate represents a validation command parsed from the ## Gates section of PROMPT.md.

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 (CLAUDE.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
	// 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 standard textinput component with history and slash-command support. All completion/mention state has been removed; the textinput library handles cursor movement and editing directly.

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) 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

type InputSubmitMsg struct {
	Text     string
	Mentions []string // file paths referenced via @path
}

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 NewLayout added in v0.0.10

func NewLayout(w, h int) Layout

NewLayout creates a Layout from terminal dimensions.

func (Layout) ChatWidth added in v0.0.10

func (l Layout) ChatWidth() int

ChatWidth returns the available width for chat message content.

func (Layout) IsNarrow added in v0.0.10

func (l Layout) IsNarrow() bool

IsNarrow returns true if the terminal is in narrow mode.

func (Layout) MaxPathLen added in v0.0.10

func (l Layout) MaxPathLen() int

MaxPathLen returns the maximum path display length for the current breakpoint.

func (Layout) SeparatorWidth added in v0.0.10

func (l Layout) SeparatorWidth() int

SeparatorWidth returns the width for horizontal separators.

func (Layout) StatusWidth added in v0.0.10

func (l Layout) StatusWidth() int

StatusWidth returns the available width for the status bar content.

func (Layout) TruncatePath added in v0.0.10

func (l Layout) TruncatePath(path string, max int) string

TruncatePath shortens a file path to fit within max characters. It preserves the filename and as much of the leading path as possible, inserting "..." when truncation is needed.

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.

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

type SOPGraph struct {
	Order  []string
	Edges  []sop.GraphEdge
	Status map[string]stageStatus
}

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 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
	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
	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.

Directories

Path Synopsis
Package refs implements context reference expansion for the TUI.
Package refs implements context reference expansion for the TUI.

Jump to

Keyboard shortcuts

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