tui

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2026 License: MIT Imports: 71 Imported by: 0

Documentation

Overview

file_view.go is the drill-in view for a touched file, opened from the FILES sidebar section (files_panel.go). It reuses the subchat pattern: while active, the chat column's body swaps to this file's content — the sidebar, composer, and scroll engine keep working unchanged (transcriptBodyItems is the single source the viewport, renderer, and hit-testers all read, so swapping there keeps every consumer consistent). Two modes:

diff (default) — the file's edit cards from this session, full-depth
full           — the file as it stands on disk, syntax highlighted, with
                 gutter markers on the lines this session's diffs added

d/f switch modes (with an empty composer), Esc returns to the chat at the scroll position it was left at.

files_git_sweep.go fills the FILES sidebar's blind spot: mutations that bypass the file tools entirely — bash/exec_command scaffolding (npm create, go generate, heredoc writes) and subagents editing the shared workspace. None of those produce a changedFiles-carrying tool result, so the transcript-derived roster (files_panel.go) never sees them. The sweep asks git instead: a baseline `git status --porcelain` snapshot is taken at startup (Init), and a re-run after each command tool result / turn end reports any NEWLY dirty paths, which merge into the roster with a diffstat from `git diff --numstat`. Pre-existing dirty state stays in the baseline and never shows; a non-git workspace fails the first command and the sweep silently stays off.

files_panel.go renders the FILES section of the right context sidebar: the workspace files this session has touched, newest first, with an A/M badge and a +added/−removed diffstat per file, plus a pulsing row for the file whose write is streaming right now. Like the swarm roster (sidebar.go), the touched set is not separate model state — it is recovered on demand from the transcript's tool-result rows (their changedFiles), so it survives resume for free and can never drift from what the chat shows.

Interaction (see handleTranscriptSelectionMouse): the first click on a row SELECTS the file — its edit cards tint in the chat and the transcript scrolls to the most recent one; a second click (or a click while the drill-in is already open) opens the file view (file_view.go). Esc clears the selection.

keybinding_help.go renders the `?` keyboard-shortcut overlay. Zero has a rich set of chord bindings (Ctrl+T effort, Ctrl+P plan, drill-in subchat, Shift+Tab permission mode, …) that are otherwise invisible — only learnable by reading the source. A single-key `?` overlay (opened on an empty composer) lists them grouped, so the keymap is discoverable the way the reference TUIs do it. The list is declarative and hand-curated to match the real handlers in model.go's Update switch; keep them in sync when a binding changes.

Configurable bindings (toggleDetailed, toggleMouse, cycleReasoning, togglePlan, toggleSidebar) pull their key label from m.keyBindings so a user who remaps them in config.json sees the actual chords, not the defaults.

plan_panel.go renders the sticky plan panel for the Zero TUI. The panel surfaces the in-progress task plan produced by the update_plan tool: a one-line header with a live spinner and progress count, a text progress bar, and (while running or expanded) the per-step list with status icons and timings. planPanelState tracks per-step start/completion timestamps across the tool's full-replacement updates so durations stay stable as steps transition between pending, in_progress, completed, and failed.

plan_step_detail.go makes the context-sidebar plan steps clickable: each step records the file mutations made while it was in_progress ("what was built"), and clicking a step drops a transcript card listing them. The work is captured from tool-result rows as they stream; the click maps a sidebar y-coordinate to a step, mirroring sidebarAgentSelectables' offset accounting.

Provider manager: the list-first /provider surface. It shares providerWizardState (steps providerWizardStepManage / EditMenu / EditValue) so the existing overlay gating, key routing, and mouse plumbing that check m.providerWizard cover it without touching those call sites.

UX contract: the list IS the home screen — Enter activates the selected provider, `a` opens the add wizard, `e` opens a field-level editor, `d` asks inline and deletes. Esc walks back one level and closes from the list.

ripple.go adds a slow cosine "breathing" colour wave for the working status line: each character cycles through a dim→lime ramp blended from the brand accent, and the wave travels across the text one character per phase tick. The phase is sourced from the shared spinner clock (m.spinnerPhase, advanced by the existing spinner.TickMsg handler) so the ripple and the braille spinner animate in lock-step with no extra ticker.

sidebar.go renders the right-hand context sidebar for the two-column chat layout (alt-screen managed mode only). The sidebar surfaces three sections — the spawned AGENTS and their live working detail, the live PLAN (the same data the pinned plan panel reads), and a token/context readout at the bottom — so the chat column stays focused on the conversation. It is a set of pure helpers: the layout in transcriptView renders the chat at a reduced width via the existing scroll engine, builds a sidebar block of the same height here, and joins the two columns row-by-row through joinColumns.

specialist_card.go renders specialist/subagent cards in the transcript.

A specialist card summarises one spawned sub-agent (worker, explorer, code review, ...): its name, task description, elapsed time, tool-call count, and token usage. The SpecialistTracker holds the live state that the transcript view consults each render; the session store feeds it via start/complete/ incrementToolCount/addTokens as specialist events arrive.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetLocalDiffStats

func GetLocalDiffStats(baseBranch string) (additions int, deletions int, err error)

func Run

func Run(ctx context.Context, options Options) int

Run starts the Zero Bubble Tea shell and returns a process-style exit code.

func ValidThemeArg

func ValidThemeArg(s string) bool

ValidThemeArg reports whether s is an acceptable --theme / ZERO_THEME value (`auto` or a registered theme name). Exported so the CLI flag validator shares this one source of truth instead of hardcoding the theme list.

func WatchPRState

func WatchPRState(service *PrService, onChange func(PrState)) func()

func WatchPRStateContext

func WatchPRStateContext(ctx context.Context, service *PrService, onChange func(PrState)) func()

Types

type Color

type Color string
const (
	ColorDefault Color = "default"
	ColorAccent  Color = "accent"
	ColorGreen   Color = "green"
	ColorRed     Color = "red"
)

type CompactRequest

type CompactRequest struct {
	SessionID             string
	ModelName             string
	ContextWindow         int
	SessionEventCount     int
	EstimatedTokens       int
	VisibleTranscriptRows int
	CompactRequests       int
}

type CompactResult

type CompactResult struct {
	Compacted    bool
	BeforeTokens int
	AfterTokens  int
	Summary      string
}

type MCPCommandResult

type MCPCommandResult struct {
	Config   config.MCPConfig
	Output   string
	Error    string
	ExitCode int
}

type MCPOAuthServerView

type MCPOAuthServerView struct {
	ServerName      string
	Configured      bool
	HasToken        bool
	HasRefreshToken bool
	TokenType       string
	Scopes          []string
	ExpiresAt       time.Time
	Expired         bool
}

type MCPOAuthSummary

type MCPOAuthSummary struct {
	Servers []MCPOAuthServerView
}

type MCPPermissionGrantView

type MCPPermissionGrantView struct {
	Target     string
	Autonomy   string
	ApprovedAt string
}

type MCPPermissionSummary

type MCPPermissionSummary struct {
	Mode         string
	GrantCount   int
	ServerGrants int
	ToolGrants   int
	PromptCount  int
	DeniedCount  int
	Grants       []MCPPermissionGrantView
}

type MCPServerView

type MCPServerView struct {
	Name      string
	Transport string
	State     string
	Target    string
	Auth      string
	ToolCount int
}

type MCPStateOptions

type MCPStateOptions struct {
	Config          config.MCPConfig
	Registry        *tools.Registry
	PermissionStore *mcp.PermissionStore
	TokenStore      *mcp.TokenStore
	PermissionMode  string
	PromptCount     int
	DeniedCount     int
}

type MCPToolView

type MCPToolView struct {
	ServerName   string
	Name         string
	RegistryName string
	SideEffect   string
	Permission   string
	Description  string
}

type MCPViewState

type MCPViewState struct {
	Servers     []MCPServerView
	Tools       []MCPToolView
	Permissions MCPPermissionSummary
	OAuth       MCPOAuthSummary
}

func BuildMCPViewState

func BuildMCPViewState(options MCPStateOptions) MCPViewState

type Options

type Options struct {
	Cwd                         string
	Version                     string // CLI build version, shown on the home screen; empty hides it
	UserConfigPath              string
	DoctorUserConfigPath        string
	ProjectConfigPath           string
	ProviderName                string
	ModelName                   string
	ProviderProfile             config.ProviderProfile
	SavedProviders              []config.ProviderProfile // all configured providers, for the /model multi-provider list
	FavoriteModels              []string
	RecentModels                []config.RecentModelEntry
	RecapsEnabled               bool
	Provider                    zeroruntime.Provider
	NewProvider                 func(config.ProviderProfile) (zeroruntime.Provider, error)
	ProbeProviderHealth         func(context.Context, providerhealth.Options) providerhealth.Result
	DiscoverProviderModels      func(context.Context, config.ProviderProfile) ([]providermodeldiscovery.Model, error)
	DiscoverOllamaContextWindow func(ctx context.Context, baseURL string, model string) (int, error)
	RuntimeMessageSink          func(tea.Msg)
	PrepareRunCompletionWarning func()
	RunCompletionWarning        func() string
	Registry                    *tools.Registry
	SessionStore                *sessions.Store
	SandboxStore                *sandbox.GrantStore
	MCPConfig                   config.MCPConfig
	MCPPermissionStore          *mcp.PermissionStore
	MCPTokenStore               *mcp.TokenStore
	MCPCommand                  func(context.Context, []string) MCPCommandResult
	SandboxSetupCommand         func(context.Context) SandboxSetupCommandResult
	UsageTracker                *usage.Tracker
	SessionCompactor            SessionCompactor
	PrService                   *PrService

	AgentOptions agent.Options
	// LoadSkills returns the installed skills (default skills dir merged with any
	// plugin skill roots), bodies included, for /skills and direct /<skill-name>
	// invocation. Called lazily per use so newly installed skills are picked up
	// without a restart. Nil means the session has no skills wiring (skills stay
	// model-pulled via the skill tool only).
	LoadSkills      func() []skills.Skill
	PermissionMode  agent.PermissionMode
	ReasoningEffort modelregistry.ReasoningEffort
	ResponseStyle   string
	// Theme is the operator's palette preference: "auto" (default), a built-in
	// ("dark"/"light"), or a registered color theme. Set from the --theme flag;
	// falls back to ZERO_THEME, then the persisted SavedTheme, then auto.
	Theme string
	// SavedTheme is the theme persisted in user config (Preferences.Theme). Applied
	// at startup below --theme and ZERO_THEME, so a /theme choice survives restart.
	SavedTheme string
	UserAgent  string

	// Notify configures completion / awaiting-input notifications.
	Notify config.NotifyConfig

	// KeyBindings configures remappable TUI keybindings. An empty/zero
	// KeyBindingsConfig means "use built-in defaults" for each action.
	KeyBindings config.KeyBindingsConfig

	// STT configures speech-to-text dictation (§ docs/dictation.md).
	STT config.STTConfig
	// BuildDictationTranscriber constructs the transcriber for the current STT
	// config. It lives in the CLI layer because it resolves provider API keys
	// (credstore + env) and base URLs; the TUI only calls it when a recording
	// starts. preferStreaming asks for the streaming backend; the returned
	// `streaming` bool reports whether streaming is actually available (false
	// falls the caller back to the batch pipeline). Nil disables dictation (the
	// keybinding shows a "not configured" hint). cfg is passed each call (not
	// captured) so a mid-session config change — e.g. the auto-download writing
	// localModelPath — takes effect on the next recording.
	BuildDictationTranscriber func(cfg config.STTConfig, preferStreaming bool) (t Transcriber, streaming bool, err error)

	// ShutdownDictationServer tears down the warm sherpa-onnx streaming server (if
	// one was started), called alongside the LSP manager's shutdown on exit. Nil
	// when dictation is not wired.
	ShutdownDictationServer func(context.Context) error

	// STTDownloadRoot is where the auto-download stores the sherpa-onnx engine
	// and model (e.g. ~/.config/zero/stt). Empty disables auto-download (the F9
	// setup message then only points at manual setup / cloud providers).
	STTDownloadRoot string

	// STTKeyStatus reports whether an API key is already resolvable for a cloud
	// STT provider ("groq"/"openai"/"deepgram"). Nil disables the inline key
	// prompt (dictation then just shows the "run zero auth" setup error).
	STTKeyStatus func(provider string) bool
	// SaveSTTKey stores an API key for a cloud STT provider in the credential
	// store, so the inline prompt can capture and persist it.
	SaveSTTKey func(provider, key string) error

	// AltScreen tells the model it is running inside Bubble Tea's alternate
	// screen. Run sets this for the interactive app; tests can leave it false
	// to exercise the native scrollback renderer.
	AltScreen bool

	// Setup configures the first-run/setup takeover. It is shown before the
	// normal chat surface when Visible is true.
	Setup SetupOptions
}

Options configures the reusable Zero terminal UI shell.

type PrProvider

type PrProvider string
const (
	ProviderGitHub PrProvider = "github"
	ProviderGitLab PrProvider = "gitlab"
)

type PrSegment

type PrSegment struct {
	Text  string
	Color Color
	Bold  bool
	URL   string
}

func BuildPRSegments

func BuildPRSegments(state PrState, useNerdFont bool) []PrSegment

type PrService

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

func NewPrService

func NewPrService(cwdValues ...string) *PrService

func (*PrService) GetState

func (s *PrService) GetState() PrState

func (*PrService) Refresh

func (s *PrService) Refresh()

func (*PrService) Subscribe

func (s *PrService) Subscribe(fn func(PrState)) func()

type PrState

type PrState struct {
	Status    PrStatus
	PrURL     string
	PrNumber  string
	Provider  PrProvider
	Additions int
	Deletions int
}

type PrStatus

type PrStatus string
const (
	PrIdle     PrStatus = "idle"
	PrLoading  PrStatus = "loading"
	PrFound    PrStatus = "found"
	PrNotFound PrStatus = "notfound"
)

type Recorder added in v0.3.0

type Recorder = dictation.Recorder

Transcriber and Recorder are re-exported so Options and the model can refer to the dictation interfaces without importing the package everywhere.

type SandboxSetupCommandResult

type SandboxSetupCommandResult struct {
	Output   string
	Error    string
	ExitCode int
}

type SessionCompactor

type SessionCompactor interface {
	CompactSession(context.Context, CompactRequest) (CompactResult, error)
}

type SetupOptions

type SetupOptions struct {
	Visible    bool
	Required   bool
	ConfigPath string
	Providers  []SetupProviderOption
	Save       func(SetupSelection) (SetupResult, error)
}

SetupOptions configures the guided first-run provider setup takeover.

type SetupProviderOption

type SetupProviderOption struct {
	ID           string
	Name         string
	DefaultModel string
	EnvVar       string
	RequiresAuth bool
	Local        bool
	Recommended  bool
}

SetupProviderOption is one provider choice offered by the setup takeover.

type SetupResult

type SetupResult struct {
	ConfigPath string
	Provider   config.ProviderProfile
}

SetupResult describes a completed setup write.

type SetupSelection

type SetupSelection struct {
	CatalogID string
	Name      string
	BaseURL   string
	Model     string
	APIKey    string
}

SetupSelection is the user's setup choice.

type Transcriber added in v0.3.0

type Transcriber = dictation.Transcriber

Transcriber and Recorder are re-exported so Options and the model can refer to the dictation interfaces without importing the package everywhere.

Jump to

Keyboard shortcuts

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