agenttui

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 25 Imported by: ? 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.

README

AgentTUI ⚡

A modern, responsive, and extensible Terminal User Interface (TUI) engine built with Bubble Tea v2, Lipgloss v2, and Glamour. Specifically engineered for AI Coding Assistants, LLM Chat CLIs, and Autonomous Agents.

Go Reference Go Report Card


✨ Features

  • 🎯 Slash Commands & Autocomplete: Floating command popup when typing /, arrow key navigation, tab completion, and argument usage hints.

  • 📎 @file & @mention Completion: Instant fuzzy file autocomplete when typing @ with rank prioritization and automatic XML attachment injection.

  • 🌊 Streaming Markdown & Spinner: Real-time token streaming with syntax highlighting, bullet points, headers, and thinking spinners without flickering.

  • 🎨 Theme Engine: Anthropic Claude Code aesthetic (warm terracotta & peach) and modern deep Devran aesthetic (violet & cyan) out of the box.

  • 📐 Responsive Sidebar & Split View: Adaptive layout automatically shows a rich context panel (modes, tools, stats, tokens) on wide screens and collapses gracefully on narrow viewports.

  • 📜 Proportional Viewport Scrollbar: Smooth vertical scrollbar track with dynamic thumb sizing.

  • 🛡️ Table-Safe Turn Banners: Horizontal divider banners (── ❯ You · 15:04 ── and ◈ <Title> · 15:04) that never corrupt markdown tables, code blocks, or ANSI codes.

  • 🔔 Toast Notifications & Statuses: Non-intrusive status alerts for clipboard actions, mode changes, and errors.

  • ⚡ Instant Shell Escapes: Run commands directly in chat via !cmd without interrupting conversational history.

  • ❓ Ask / Approval Prompts: app.Ask(ctx, agenttui.Question{...}) blocks a handler until the user picks an option or types an answer.

  • 🧩 Typed Event Stream: Config.StreamEvents reports text, thinking and tool start/end as separate events (no <think> tag parsing).

  • 💾 Session Store & Retry: optional Config.Store (Load/Save) for resume; /retry regenerates the last answer.


🚀 Installation

go get github.com/tevfik/agenttui

🛠️ Quickstart

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/tevfik/agenttui"
)

func main() {
	app := agenttui.New(agenttui.Config{
		Title:     "My Agent",
		ModelName: "qwen3.5:9b",
		Theme:     agenttui.ClaudeTheme(),
		Stream: func(ctx context.Context, prompt string, emit func(chunk string)) (int, error) {
			// Simulate LLM streaming
			emit("Thinking about: " + prompt + "\n\n")
			for i := 1; i <= 3; i++ {
				time.Sleep(100 * time.Millisecond)
				emit(fmt.Sprintf("- Point %d\n", i))
			}
			return 42, nil // returns tokens used
		},
	})

	// Register slash commands
	app.RegisterCommand(agenttui.SlashCommand{
		Name:        "clear",
		Description: "Clear conversation transcript",
		Handler: func(ctx context.Context, args []string, a *agenttui.App) (string, bool, error) {
			a.ClearMessages()
			return "Transcript cleared.", true, nil
		},
	})

	ctx := context.Background()
	if err := app.Run(ctx); err != nil {
		fmt.Printf("Error: %v\n", err)
	}
}

⌨️ Keyboard Shortcuts

Key Action
Enter Submit prompt / Execute selected slash command
Shift+Enter / Alt+Enter Insert new line
Tab Autocomplete selected command or @file
↑ / ↓ Navigate command popup or browse command history
Ctrl+Y Copy latest assistant response to system clipboard
Ctrl+M Toggle mouse capture (switch between wheel scroll & native terminal selection)
Ctrl+C / Esc Cancel streaming response or clear input

📄 License

MIT License. See LICENSE for details.

Agent-facing API

app := agenttui.New(agenttui.Config{
	Title: "My Agent",
	StreamEvents: func(ctx context.Context, prompt string, emit func(agenttui.Event)) (int, error) {
		emit(agenttui.Event{Kind: agenttui.EventThinking, Text: "checking the repo…"})
		emit(agenttui.Event{Kind: agenttui.EventToolStart, ToolID: "1", ToolName: "shell", ToolArgs: "ls"})
		ans, err := app.Ask(ctx, agenttui.Question{Text: "Run `rm -rf build`?", Options: []string{"yes", "no"}, Default: "no"})
		emit(agenttui.Event{Kind: agenttui.EventToolEnd, ToolID: "1", ToolOutput: ans, ToolOK: err == nil})
		emit(agenttui.Event{Kind: agenttui.EventText, Text: "Done."})
		return 0, nil
	},
})

Ask returns ErrAskCancelled on Esc/Ctrl+C and ErrNotRunning before Run. Implement Store to persist the transcript between runs.

Keyboard shortcuts & tmux

Keys Action
Ctrl+←/→ (or Alt+←/→) move by word
Ctrl+Backspace / Alt+Backspace / Ctrl+W delete word backward
Ctrl+Delete / Alt+D delete word forward
Home/End, Ctrl+A/E line start / end
Ctrl+Home/End input start / end
Ctrl+U / Ctrl+K delete to line start / end
Ctrl+B or F2 toggle sidebar

Works inside tmux/screen without touching their configuration: legacy ESC[5D/ESC[5C Ctrl+arrow sequences are translated, and the footer shows F2 instead of Ctrl+B there (Ctrl+B is tmux's prefix). Limits that only the multiplexer config can lift: without tmux's extended-keys, Ctrl+Backspace is indistinguishable from Backspace — use Alt+Backspace or Ctrl+W; and tmux's default escape-time delays a lone Esc.

Settings forms and long pick lists

app.Form(ctx, agenttui.Form{Title, Fields}) shows an inline settings panel (choice, number, bool and text fields) and returns the edited values on Enter, or ErrAskCancelled on Esc. Ask windows long option lists (8 visible, scrolling).

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrAskCancelled = errors.New("agenttui: question cancelled")

ErrAskCancelled is returned by App.Ask when the user dismisses the prompt.

View Source
var ErrNotRunning = errors.New("agenttui: app is not running")

ErrNotRunning is returned by App.Ask when the TUI is not running.

Functions

func AvailableThemes

func AvailableThemes() []string

AvailableThemes returns the identifiers of all built-in themes.

func ExtractCodeBlocks

func ExtractCodeBlocks(text string) string

ExtractCodeBlocks extracts the raw code within markdown fenced code blocks (```...```). If no code fences are found, the original text is returned.

func ResetTerminalBackground

func ResetTerminalBackground()

ResetTerminalBackground restores the terminal emulator window's default background color via OSC 111.

func SetTerminalBackground

func SetTerminalBackground(hexColor string)

SetTerminalBackground updates the terminal emulator window's background color via OSC 11. Most modern terminals (GNOME Terminal, Windows Terminal, Kitty, Alacritty, WezTerm, macOS Terminal, Foot, Ghostty) support this sequence to dynamically adapt their background to the active theme.

func ThemeHex

func ThemeHex(c color.Color) string

ThemeHex converts a color.Color (like lipgloss.Color) to a hex string format like "#000000".

Types

type App

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

App manages the chat application lifecycle and Bubble Tea program.

func New

func New(cfg Config) *App

New creates a new extensible Agent TUI instance.

func (*App) AddChangedFile

func (a *App) AddChangedFile(file string)

AddChangedFile appends a file to the changed files list.

func (*App) AddMessage

func (a *App) AddMessage(msg Message)

AddMessage appends a message to the conversation.

func (*App) Ask

func (a *App) Ask(ctx context.Context, q Question) (string, error)

Ask shows q and blocks until the user answers, dismisses it (ErrAskCancelled) or ctx is done. It is safe to call from stream and slash-command handlers, i.e. from any goroutine except the UI loop itself.

func (*App) ClearMessages

func (a *App) ClearMessages()

ClearMessages removes all messages from the conversation transcript.

func (*App) CopyToClipboard

func (a *App) CopyToClipboard(text string) bool

CopyToClipboard copies arbitrary text to the system clipboard.

func (*App) EmitToolEnd

func (a *App) EmitToolEnd(id, output string, success bool)

EmitToolEnd updates a tool execution with result.

func (*App) EmitToolStart

func (a *App) EmitToolStart(id, name, args string)

EmitToolStart logs a tool beginning execution in the stream.

func (*App) ExportSession

func (a *App) ExportSession(outDir, baseName string) (mdPath, htmlPath string, err error)

ExportSession writes the conversation history to both Markdown (.md) and standalone HTML (.html). Returns the absolute or relative paths to both generated files.

func (*App) Form

func (a *App) Form(ctx context.Context, f Form) ([]string, error)

Form shows f and blocks until the user saves it (Enter), dismisses it (ErrAskCancelled) or ctx is done. It returns the field values in order. Same calling rules as Ask: not from the UI goroutine.

func (*App) GetModelName

func (a *App) GetModelName() string

GetModelName returns the current active model identifier.

func (*App) GetTheme

func (a *App) GetTheme() Theme

GetTheme returns the active theme.

func (*App) GetWorkDir

func (a *App) GetWorkDir() string

GetWorkDir returns the active workspace path.

func (*App) Init

func (a *App) Init() tea.Cmd

Init implements tea.Model.

func (*App) IsSidebarHidden

func (a *App) IsSidebarHidden() bool

IsSidebarHidden reports whether the sidebar is currently hidden.

func (*App) Mode

func (a *App) Mode() string

Mode returns current mode.

func (*App) RegisterCommand

func (a *App) RegisterCommand(cmd SlashCommand)

RegisterCommand adds or updates a slash command in the registry without duplicates.

func (*App) ResetSession

func (a *App) ResetSession()

ResetSession clears all conversation messages, history, sidebar widgets, changed files, and resets session timer and context counters.

func (*App) RewindLastTurn

func (a *App) RewindLastTurn() (string, bool)

RewindLastTurn pops the last assistant response (and any associated tool calls) and the last user prompt from the conversation history, and restores that user prompt back into the input textarea so the user can easily revise and resubmit it.

func (*App) Run

func (a *App) Run(ctx context.Context) error

Run launches the Bubble Tea interactive TUI.

func (*App) ScanRepoFiles

func (a *App) ScanRepoFiles(root string)

ScanRepoFiles walks the workspace root and collects files for @file completion.

func (*App) SetChangedFiles

func (a *App) SetChangedFiles(files []string)

SetChangedFiles updates the list of changed files shown in the sidebar.

func (*App) SetContextTokens

func (a *App) SetContextTokens(used, max int)

SetContextTokens updates the context window usage indicator.

func (*App) SetMode

func (a *App) SetMode(mode string)

SetMode updates the active mode (e.g. "build", "plan").

func (*App) SetModelName

func (a *App) SetModelName(name string)

SetModelName updates the active model label in the status bar.

func (*App) SetNotification

func (a *App) SetNotification(msg string, ntype NotificationType) tea.Cmd

SetNotification sets a toast notification.

func (*App) SetRepoFiles

func (a *App) SetRepoFiles(files []string)

SetRepoFiles sets the cached list of workspace files for @file completion.

func (*App) SetSidebar

func (a *App) SetSidebar(w Widget)

SetSidebar attaches or replaces a sidecar widget.

func (*App) SetTheme

func (a *App) SetTheme(t Theme)

SetTheme dynamically updates the theme and refreshes the UI.

func (*App) SetWorkDir

func (a *App) SetWorkDir(dir string)

SetWorkDir updates the active workspace path.

func (*App) Submit

func (a *App) Submit(input string)

Submit feeds input to the app as if the user had typed it and pressed Enter (slash commands included). Safe to call from any goroutine; a no-op before Run.

func (*App) ToggleSidebar

func (a *App) ToggleSidebar() (*App, tea.Cmd)

ToggleSidebar switches sidebar visibility on and off. When hidden, chat text expands across full width, allowing clean terminal copy/selection without sidebars.

func (*App) Update

func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update implements tea.Model.

func (*App) View

func (a *App) View() tea.View

View implements tea.Model.

type Config

type Config struct {
	Title       string
	Subtitle    string
	ModelName   string
	WorkDir     string
	Mode        string // e.g. "build" or "plan"
	Placeholder string
	Theme       Theme
	Stream      StreamHandler
	// StreamEvents, when set, takes precedence over Stream.
	StreamEvents EventStreamHandler
	Store        Store    // optional session persistence
	IgnoreDirs   []string // extra directory names skipped by @file completion
	Commands     []SlashCommand
	Sidebar      Widget
	EnableMouse  bool
	ShowHeader   bool
	ShowFooter   bool

	// Presentation hooks, all optional.
	Banner         []string           // ASCII art shown on the empty-transcript welcome screen
	QuickActions   []QuickAction      // command list shown under the banner
	HideMode       bool               // hide the build/plan mode badge and info row
	HeaderInfo     func() string      // extra text shown before the model name in the header
	HeaderInfoWide func() string      // used instead of HeaderInfo while the sidebar is hidden (Ctrl+B) or the terminal is too narrow for it
	InfoRows       func() [][2]string // replaces the sidebar's built-in mode/model rows
	FooterHint     string             // replaces the default key-hint footer
	// OnKey sees every key press before the built-in handling (but not while a
	// question or form is open). Return true to consume it. It runs on the UI
	// goroutine: start a goroutine for anything that blocks, e.g. App.Form.
	OnKey func(key string, app *App) bool
}

Config holds initialization parameters for the Agent TUI.

type Event

type Event struct {
	Kind       EventKind
	Text       string
	ToolID     string
	ToolName   string
	ToolArgs   string
	ToolOutput string
	ToolOK     bool
}

Event is one typed item of an agent response stream.

type EventKind

type EventKind int

EventKind identifies the type of a streaming Event.

const (
	EventText      EventKind = iota // Text: a chunk of answer content
	EventThinking                   // Text: a chunk of reasoning
	EventToolStart                  // ToolID, ToolName, ToolArgs
	EventToolEnd                    // ToolID, ToolOutput, ToolOK
)

type EventStreamHandler

type EventStreamHandler func(ctx context.Context, prompt string, emit func(Event)) (tokens int, err error)

EventStreamHandler is the typed alternative to StreamHandler. Reasoning and tool calls are reported as separate events instead of being inferred from <think> tags in the text.

type Field

type Field struct {
	Label    string
	Kind     FieldKind
	Value    string
	Options  []string // FieldChoice; for FieldSlider the ordered preset values (first = min, last = max)
	Min, Max float64  // FieldNumber / numeric FieldSlider (ignored when Max <= Min for Number)
	Step     float64  // FieldNumber / numeric FieldSlider (default 1)
	Format   string   // numeric FieldSlider: printf format for the limits, default "%g"
	Hint     string   // one-line help shown while the field is focused
}

Field is one editable setting of a Form. Values are exchanged as strings: Bool uses "on"/"off", Number uses plain decimal notation.

type FieldKind

type FieldKind int

FieldKind selects how a Form field is edited.

const (
	FieldChoice FieldKind = iota // ←/→ cycles through Options
	FieldNumber                  // ←/→ changes the value by Step within [Min, Max]
	FieldBool                    // ←/→ or Space toggles "on"/"off"
	FieldText                    // Enter edits the value in the input box
	FieldSlider                  // like Choice/Number but drawn as a bar with its limits; ←/→ clamp at the ends
)

type Form

type Form struct {
	Title  string
	Fields []Field
	Note   string // optional read-only line shown under the fields
}

Form is a settings panel: a list of fields edited in place.

type Item

type Item struct {
	Text   string
	Status string // "pending", "in_progress", "done", "failed"
}

Item represents a generic item in a status list widget.

type KeyValWidget

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

KeyValWidget displays key-value pairs (e.g. system info, index stats).

func NewKeyValWidget

func NewKeyValWidget(title string, theme Theme) *KeyValWidget

NewKeyValWidget creates a key-value widget.

func (*KeyValWidget) Render

func (w *KeyValWidget) Render(width, height int) string

Render renders the key-value widget.

func (*KeyValWidget) SetPairs

func (w *KeyValWidget) SetPairs(pairs [][2]string)

SetPairs updates the key-value pairs.

func (*KeyValWidget) Title

func (w *KeyValWidget) Title() string

Title returns the widget title.

func (*KeyValWidget) Update

func (w *KeyValWidget) Update(msg tea.Msg) (Widget, tea.Cmd)

Update handles Bubble Tea messages.

func (*KeyValWidget) Visible

func (w *KeyValWidget) Visible() bool

Visible returns visibility status.

type Message

type Message struct {
	Role         Role          `json:"role"`
	Content      string        `json:"content"`
	Thinking     string        `json:"thinking,omitempty"`
	ThinkingOpen bool          `json:"thinking_open,omitempty"`
	ThinkingTime time.Duration `json:"thinking_time,omitempty"`
	Timestamp    time.Time     `json:"timestamp"`
	Tokens       int           `json:"tokens,omitempty"`
	Tool         *ToolCall     `json:"tool,omitempty"`
}

Message represents a message in the conversation.

type Notification

type Notification struct {
	Message string
	Type    NotificationType
	Expires time.Time
}

Notification represents a toast notification in the status bar.

type NotificationType

type NotificationType int

NotificationType defines the severity of a notification.

const (
	NotifyInfo NotificationType = iota
	NotifySuccess
	NotifyWarning
	NotifyError
)

type Question

type Question struct {
	Text    string
	Detail  string   // optional background shown under the question
	Options []string // empty means free-text answer
	Default string   // pre-selected option, or the text used on an empty free-text answer
}

Question is a prompt the agent puts to the user. With Options the user picks one (arrows, Enter, or the option number); without them the user types free text into the input box.

type QuickAction

type QuickAction struct {
	Cmd  string // e.g. "/settings"
	Desc string
}

QuickAction is one line of the welcome screen's command list.

type Role

type Role string

Role represents the role of a message participant.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleSystem    Role = "system"
	RoleTool      Role = "tool"
	RoleError     Role = "error"
)

type SlashCommand

type SlashCommand struct {
	Name        string // e.g. "help", "model", "clear"
	Description string // Short description shown in autocomplete popup
	Usage       string // Parameter usage info, e.g. "<model-name>"
	Handler     func(ctx context.Context, args []string, app *App) (result string, isLocal bool, err error)
}

SlashCommand defines an interactive command starting with '/'.

type StatusListWidget

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

StatusListWidget displays a vertical list of tasks/steps with status icons.

func NewStatusListWidget

func NewStatusListWidget(title string, theme Theme) *StatusListWidget

NewStatusListWidget creates a status list widget.

func (*StatusListWidget) Render

func (w *StatusListWidget) Render(width, height int) string

Render renders the widget into the given dimensions.

func (*StatusListWidget) SetItems

func (w *StatusListWidget) SetItems(items []Item)

SetItems updates the list items.

func (*StatusListWidget) SetVisible

func (w *StatusListWidget) SetVisible(v bool)

SetVisible controls widget visibility.

func (*StatusListWidget) Title

func (w *StatusListWidget) Title() string

Title returns the widget title.

func (*StatusListWidget) Update

func (w *StatusListWidget) Update(msg tea.Msg) (Widget, tea.Cmd)

Update handles Bubble Tea messages.

func (*StatusListWidget) Visible

func (w *StatusListWidget) Visible() bool

Visible returns whether the widget is visible.

type Store

type Store interface {
	Load() ([]Message, error)
	Save([]Message) error
}

Store persists the conversation so a session can be resumed. Load is called once by New; Save after every completed turn.

type StreamHandler

type StreamHandler func(ctx context.Context, prompt string, emit func(chunk string)) (tokens int, err error)

StreamHandler is a streaming function called when the user sends a prompt. It yields chunks via emit() and returns the total tokens or an error when done.

type Theme

type Theme struct {
	Name      string
	Primary   color.Color
	Secondary color.Color
	Accent    color.Color
	Success   color.Color
	Warning   color.Color
	Error     color.Color
	Info      color.Color
	Text      color.Color
	SubText   color.Color
	Muted     color.Color
	Border    color.Color
	BgDark    color.Color

	// Styles
	HeaderTitle lipgloss.Style
	HeaderSub   lipgloss.Style
	UserBubble  lipgloss.Style
	SystemText  lipgloss.Style
	ErrorText   lipgloss.Style
	ToolCard    lipgloss.Style
	StatusBar   lipgloss.Style
	Badge       lipgloss.Style
	PopupBox    lipgloss.Style
	PopupItem   lipgloss.Style
	PopupSel    lipgloss.Style
}

Theme defines the visual styling tokens for the TUI. Theme defines the visual styling tokens for the TUI.

func CatppuccinTheme

func CatppuccinTheme() Theme

CatppuccinTheme returns the soothing Catppuccin Mocha pastel aesthetic.

func ClaudeTheme

func ClaudeTheme() Theme

ClaudeTheme returns Anthropic Claude Code's signature warm aesthetic.

func DefaultTheme

func DefaultTheme() Theme

DefaultTheme returns the default theme (ClaudeTheme).

func DevranTheme

func DevranTheme() Theme

DevranTheme returns the modern deep violet & cyan theme.

func DraculaTheme

func DraculaTheme() Theme

DraculaTheme returns the classic gothic Dracula aesthetic.

func GruvboxTheme

func GruvboxTheme() Theme

GruvboxTheme returns the warm retro aesthetic of Gruvbox Dark.

func NordTheme

func NordTheme() Theme

NordTheme returns the arctic cold aesthetic of Nord.

func OpenCodeTheme

func OpenCodeTheme() Theme

OpenCodeTheme returns the signature OpenCode minimalist pitch black, crisp white, vibrant orange, and zinc gray aesthetic.

func ThemeByName

func ThemeByName(name string) Theme

ThemeByName returns the matching theme by name, defaulting to Claude.

func TokyoNightTheme

func TokyoNightTheme() Theme

TokyoNightTheme returns the neon cyber aesthetic of Tokyo Night.

type ToolCall

type ToolCall struct {
	ID        string     `json:"id"`
	Name      string     `json:"name"`
	Args      string     `json:"args"`
	Output    string     `json:"output,omitempty"`
	Status    ToolStatus `json:"status"`
	Duration  time.Duration
	Timestamp time.Time
}

ToolCall represents an invoked tool within the chat stream.

type ToolStatus

type ToolStatus int

ToolStatus represents the lifecycle of a tool invocation.

const (
	ToolStatusRunning ToolStatus = iota
	ToolStatusSuccess
	ToolStatusFailed
)

type Widget

type Widget interface {
	Title() string
	Render(width, height int) string
	Update(msg tea.Msg) (Widget, tea.Cmd)
	Visible() bool
}

Widget represents an optional sidecar or overlay panel (e.g. Plan Tracker, Memory Tree).

Directories

Path Synopsis
examples
basic command

Jump to

Keyboard shortcuts

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