tui

package
v1.5.31 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 76 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package tui hosts the full-screen terminal UI for golder's interactive mode (US-001). It is the alt-screen counterpart to the line-based REPL in internal/cli/repl: cmd/golder's dispatch launches it via Run when there is no prompt, stdout is a TTY, and --no-tui is not set; otherwise the REPL path is used. See tasks/spec-tui-agent.md (Sections 2.1, 4.2, 5.2) for the design.

This node is the skeleton: a root Model (Init/Update/View) built on Bubble Tea v2 (charm.land/bubbletea/v2) that renders an empty shell — a placeholder status bar, an empty transcript area, and an empty input line — starts on the alt-screen, and quits cleanly on Ctrl+C / Ctrl+D, restoring the terminal. Session assembly, the run bridge, tool cards, and slash-command completion land in downstream nodes; Options already mirrors repl.Options so those nodes can wire real behavior without changing the entry seam.

This file makes runSession satisfy cli.Host: the accessor and mutator methods let the /status command (and future /goal, /btw) read the session's live collaborators and mutable state through the cli.Host contract rather than the concrete aggregate — the same seam the REPL's replDeps implements. The compile-time assertion below fails the build if runSession drifts out of conformance.

This file wires the remote-control bridge (internal/remotecontrol, #442) into the full-screen TUI, the counterpart to internal/cli/repl/remotecontrol.go. It adds the "/remote-control" command that starts/stops an in-process HTTP+WebSocket server mirroring the session to a paired browser on the LAN, mirrors transcript output to that browser, surfaces browser-submitted prompts as a tea.Msg, and routes trust questions to the browser while a client is connected (see trustConfirm).

The non-remote path is unchanged: when no session is active the mirror is a no-op and waitRemoteInput returns a nil Cmd.

This file binds the full-screen TUI to the real agent run seam and the local session store (US-009, FR-16/17). It is the TUI counterpart to the REPL's replDeps + streamRun + cli.PersistTurn plumbing (internal/cli/repl): it assembles an AgentContext + RunConfig from the model's Options, feeds them to the event bridge (bridge.go's startRun → runtime.StartRun/DrainStream), and persists the growing conversation to ~/.golder/sessions after each turn.

It deliberately imports the SHARED lower-level packages the REPL also uses (session, runtime, provider, cli, cli/run, cli/headless, cli/ui) rather than the repl package itself, so the two entry paths share one store and one run-config shape without an import cycle (repl and tui are siblings; prompts imports tui, so tui must not reach back into repl/prompts).

This file is the TUI's half of the multiplexer reporting (see internal/hostcompat): the four moments the session knows about, plus the one the gates know about, wired onto the session the TUI already assembles.

It is deliberately thin. Every decision — what a state means, how it reaches tuios or herdr, what happens when a prompt and a turn overlap — lives in internal/hostcompat, so the REPL, headless and the TUI cannot drift apart on what the person's rail shows. What is here is only *when* the TUI knows.

This file implements slash-commands and their autocomplete popup for the full-screen TUI (US-008, FR-15). It is the TUI counterpart to the REPL's slash handling (internal/cli/repl/repl.go): both front-ends consult the SAME shared registry assembled by internal/cli/prompts.BuildSlashRegistry (#383), so /model, /help, user-declared templates (~/.golder/{commands,prompts}), config/CLI prompt templates, plugin commands and ~/.agents/skills /skill-name commands are identical across the two surfaces.

tui deliberately imports prompts/runtime/cli (the shared lower layers), never repl: prompts sits below both front-ends, so there is no import cycle.

The autocomplete popup (slashMenu) activates while the input buffer is a "/name" being typed (a leading "/" with no whitespace yet). It filters the registry by the typed prefix, is navigated with the arrow keys, completed with Tab, and run with Enter — the model intercepts those keys before delegating to the textarea (see model.handleKey).

This file wires the `!command` passthrough into the TUI: a locally run shell command (no model call, no approval, no sandbox) that opens its own card in the transcript while it streams and, once settled, joins the conversation as the same user-role <user_shell_command> record the REPL writes — so the model sees exactly what the user ran and what came back (codex parity). The model is the tea-side owner of the state; the command's blocking Wait runs inside a tea.Cmd goroutine and reports back through userShellDoneMsg.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(opts Options) (runErr error)

Run starts the full-screen TUI and blocks until the user quits (Ctrl+C / Ctrl+D) or the program errors. It is the alt-screen counterpart to repl.Run: cmd/golder's dispatch calls it on the (no prompt + TTY + no --no-tui) path and maps its error to the process exit code. The alt-screen is entered/left via the View returned by the root Model, so a clean return here restores the terminal to the user's prior scrollback.

func SetMarkdownDark

func SetMarkdownDark(dark bool)

SetMarkdownDark records whether the terminal has a dark background and drops the renderer cache so the next render rebuilds with the matching style.

This is the fix for the escape-sequence leak into the input box: glamour's WithAutoStyle() detects the palette by issuing its OWN synchronous OSC 11 background-color query and reading the reply straight from the tty. Under the alt-screen, bubbletea already owns the input reader, so that reply (\x1b]11;rgb:…\x07) races with — and is swallowed by — bubbletea's parser, which then leaks the unparsed tail (e.g. "1;rgb:0000/0000/0000" plus a stray SGR mouse report) into the textarea as literal text. We instead let bubbletea detect the background the parser-safe way (RequestBackgroundColor → BackgroundColorMsg) and feed the result here, then build glamour with a fixed WithStandardStyle so it never touches the terminal.

func TruncateToWidth

func TruncateToWidth(s string, width int) string

TruncateToWidth returns s clipped to at most width display columns, appending an ellipsis "…" when it removes content. Width is measured in terminal cells (CJK and emoji count as two) via ui.Width, and truncation happens on rune boundaries so a double-width character is never sliced. The returned string's display width is guaranteed to be <= width. A non-positive width yields the empty string.

func WrapToWidth

func WrapToWidth(s string, width int) string

WrapToWidth wraps s to at most width display columns per line, measuring width by terminal cells (CJK and emoji count as two) via ui.Width rather than byte length. It never splits inside a multi-byte rune or a double-width character: a rune that would overflow the current line starts a new line instead. Any existing newlines in s are preserved as hard breaks. A non-positive width is treated as "no wrapping" and s is returned unchanged.

func WrapToWidthWords added in v1.2.20

func WrapToWidthWords(s string, width int) string

WrapToWidthWords wraps s like WrapToWidth, but breaks at spaces in preference to breaking inside a word: prose that is wrapped for display ("show or switch the approval mode") must not come out as "re/ad-only", which is what a pure rune wrapper does to any word that straddles the column. A single word wider than the line still breaks by rune — the fallback that keeps a long path, a URL, or a run of CJK (which has no spaces at all) from overflowing. Existing newlines are hard breaks, and runs of spaces collapse to one, since the callers that need exact spacing (the transcript's own wrapping) use WrapToWidth.

Types

type Model

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

Model is the root Bubble Tea model for the full-screen TUI. It composes a scrolling transcript (US-005) with the persistent status bar (#386) and a minimal input line, and owns the run lifecycle: on prompt submit it starts an agent run through the event bridge (bridge.go) and pumps the resulting tea.Msg stream into the transcript one message at a time. Downstream nodes grow the input into a full textarea (#390), render tool cards (#389), and wire the real session/run assembly (#392); the Init/Update/View contract and the alt-screen + quit-key handling stay stable.

func NewModel

func NewModel(opts Options) Model

NewModel builds the root model from the assembled Options. It reads the current working directory (for the status bar's path display and git probe) and assembles the shared slash-command registry (#391), which reads the user prompt-template dirs (~/.golder/{commands,prompts}) and the pre-loaded skills; missing dirs are not an error. The registry is bound here to a live config derived from Options; withSession rebinds it to the session's live config so a /model switch reaches the run loop.

func (Model) Init

func (m Model) Init() tea.Cmd

Init implements tea.Model. It kicks off the async git probe so the status bar can show the branch/dirty state as soon as it resolves; the alt-screen is requested declaratively via the AltScreen field on the View returned by View.

func (Model) Update

func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update implements tea.Model. It tracks the terminal size, drives the minimal input line, starts runs on submit, and pumps bridged run events into the transcript and status bar. It quits on the standard exit keys (Ctrl+C / Ctrl+D).

func (Model) View

func (m Model) View() tea.View

View implements tea.Model. It renders the shell on the alt-screen: the scrolling transcript filling the top rows, then the autocomplete popup (when open) and the multi-line input editor, and finally the persistent status bar (#386) on the very bottom row — below the input, per the layout fix. Setting AltScreen on the returned View is how Bubble Tea v2 enters/leaves the alternate screen buffer, so the user's scrollback is restored on quit.

type Options

type Options struct {
	Model        string
	ProviderName string
	Provider     provider.Provider
	BaseURL      string
	APIKey       string
	Protocol     string
	// Version is the running build version (main.version), shown in the startup
	// banner. Empty or "dev"/"unknown" renders as-is with no update hint.
	Version string
	// NoAnimations settles the logo immediately, disables status-bar motion,
	// and keeps the working indicator static (elapsed stats still refresh).
	// GOLDER_NO_ANIMATIONS and SSH detection also enable this in NewModel.
	NoAnimations bool
	// ThinkingLevel is the resolved reasoning-effort level (US-023): it seeds the
	// live run config so every turn requests it, until a control command changes
	// it.
	ThinkingLevel agentcore.ThinkingLevel
	Tools         []agentcore.AgentTool
	SysPrompt     string

	// Prompt is the launch context SysPrompt was built from (user-authored base
	// and appends, working directory, skills, tools). A resumed session rebuilds
	// its prompt through it — see cli.ResumeSystemPrompt — so the guide and
	// environment come from THIS binary while the session's own user inputs are
	// preserved.
	Prompt runtime.PromptInputs

	// ResumeID, when non-empty, resumes an existing session: its messages seed
	// the context and replayed transcript. Otherwise a fresh session is created.
	ResumeID string

	// Approve, when true, grants the launch directory session trust before the
	// run so the first-launch trust prompt is skipped and side-effect tools run
	// without per-call confirmation (mirrors pi's --approve/-a).
	Approve bool
	// Skills is the pre-loaded skill set (loaded once by run.SetupEnv, shared with
	// prompt injection). Each is registered as a /skill-name command. Empty under
	// --no-skills, so nothing is registered.
	Skills []*runtime.Skill

	// Plugins holds the loaded plugin manager so the TUI can deliver lifecycle
	// events to subscribed plugins (US-017, #133). It may be nil (no plugins).
	Plugins    *plugin.Manager
	Extensions *extensions.Manager

	// ConfigPrompts holds prompt-template paths from the config.toml `prompts`
	// array (settings tier); each is a file or dir loaded non-recursively.
	ConfigPrompts []string
	// CliPrompts holds --prompt-template paths (CLI tier, repeatable).
	CliPrompts []string
	// NoPromptTemplates disables all prompt-template discovery (global, project,
	// settings, CLI); built-in slash commands are unaffected. Independent of
	// --no-skills.
	NoPromptTemplates bool

	// Permissions is the live approval mode shared with the tool set (created
	// by run.SetupEnv and wired into every BashTool). The /permissions command
	// mutates it in place; a nil value falls back to a private auto state.
	Permissions *permissions.State
	// ReviewNotes is the announcement sink for mode decisions (approvals,
	// sandbox routing, denials, read-only blocks), shared with the gates.
	// The TUI routes notes into the run's event channel so they render as
	// transcript cards.
	ReviewNotes *run.ReviewNotes
	// Budget is the session-scoped context-window budget (created by
	// run.SetupEnv) shared by every run of the session, so the low-budget
	// reminder ladder and the context tools stay consistent across prompts.
	// A nil value falls back to a run-local state.
	Budget *contextbudget.State

	// MaxContext is the resolved [compaction] max_context value: a token count
	// or window fraction that lowers the auto-compaction trigger point. The
	// zero value leaves the defaults. It is read on every run, so a "N%" form
	// follows a /model switch that changes the window.
	MaxContext config.MaxContext

	// HistoryPath is the global prompt-history file (history.jsonl) the model
	// lazily reads for cross-session ↑/↓ browsing and appends every submission
	// to. Empty disables the feature entirely (tests construct models without
	// touching disk); cmd/golder resolves it under the golder home directory.
	HistoryPath string
}

Options carries the resolved run configuration into Run. It deliberately mirrors repl.Options (see internal/cli/repl/interactive.go) field-for-field so cmd/golder's dispatch can map the same assembled environment to either path, and so downstream nodes can port the REPL's session/live/slash/trust wiring into the TUI without reshaping the entry seam. This skeleton node does not yet consume most fields — they are here to lock the contract.

type Theme

type Theme struct {
	// User styles the human's turns in the transcript.
	User lipgloss.Style
	// Assistant styles the model's turns in the transcript.
	Assistant lipgloss.Style
	// System styles system / meta notices (secondary gray).
	System lipgloss.Style
	// ToolVerb styles the "Running"/"Ran" verb of a tool invocation headline
	// (bold, terminal default color — codex renders its exec verb the same way;
	// the old all-blue headline read like a link).
	ToolVerb lipgloss.Style
	// ToolName styles the tool's name in the headline (cyan, codex's accent for
	// tool verbs like Read/Search).
	ToolName lipgloss.Style
	// ToolCmd styles the command/argument text of a headline and its `│ `
	// continuation lines (near-white, so a command reads as code, not as a
	// colored label).
	ToolCmd lipgloss.Style
	// ToolBody styles the body/output region of a tool card.
	ToolBody lipgloss.Style
	// TodoActive styles the text of the todo item currently in progress. It
	// borrows the card's tool-name cyan (the same color as the "todo" word in
	// the headline) so the active step reads as part of the card instead of
	// shouting in bright green.
	TodoActive lipgloss.Style
	// TodoDone styles completed todo rows: muted gray, dimmed so they recede
	// without a strikethrough running through the row.
	TodoDone lipgloss.Style
	// TodoPending styles not-yet-started todo rows (muted gray, same weight as
	// ToolBody so only the active step draws color).
	TodoPending lipgloss.Style
	// Toast styles the transient bottom-right notice (e.g. "↓ 8 new lines ·
	// Ctrl+E to jump"): a filled block that floats over the transcript and
	// fades on its own, deliberately outside the permanent status bar.
	Toast lipgloss.Style
	// StatusBar styles the persistent bottom status bar.
	StatusBar lipgloss.Style
	// Accent styles file names and other highlighted tokens (blue).
	Accent lipgloss.Style
	// Error styles failure messages (red).
	Error lipgloss.Style
	// Warn styles warnings (yellow).
	Warn lipgloss.Style
	// Success styles successful outcomes (green).
	Success lipgloss.Style
	// Approved styles an allow verdict line (near-white). An allow is a normal
	// outcome, not a warning; the marker and wording stay as they are.
	Approved lipgloss.Style
	// ScrollThumb styles the transcript scrollbar thumb (medium gray block).
	ScrollThumb lipgloss.Style
	// ScrollTrack styles the transcript scrollbar track (dim shaded column).
	ScrollTrack lipgloss.Style
	// Spinner styles the animated "working" indicator glyph + verb (warm coral).
	Spinner lipgloss.Style
	// MenuHeader styles the category headers in the slash-command popup (bold,
	// terminal default color, so the groups stand out above the dimmed rows).
	MenuHeader lipgloss.Style
	// DiffAdd styles added lines in a rendered diff (green).
	DiffAdd lipgloss.Style
	// DiffDel styles removed lines in a rendered diff (red).
	DiffDel lipgloss.Style
	// DiffHunk styles @@ hunk markers in a rendered diff (cyan).
	DiffHunk lipgloss.Style
	// DiffCtx styles unchanged context lines and file headers in a rendered
	// diff (dim gray).
	DiffCtx lipgloss.Style
}

Theme bundles the lipgloss styles for every visual element the TUI paints so the transcript, tool cards and status bar share one palette instead of each call site hand-rolling colors (see tasks/spec-tui-agent.md Sections 2.2, 5.1). The reference palette is: success green, error/warn red & yellow, file/accent blue, and gray for secondary chrome. Styles are plain value types, so a Theme is cheap to copy and safe to pass by value.

func DefaultTheme

func DefaultTheme() Theme

DefaultTheme returns the built-in palette described in the SPEC: success green, error/warn red & yellow, file/accent blue, and gray for secondary chrome. It performs no I/O and never panics, so callers can construct it eagerly at startup.

Jump to

Keyboard shortcuts

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