chatui

package
v0.54.8 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package chatui contains the reusable terminal chat controls used by suga and other clients. It deliberately depends only on public packages so hosts do not need access to suga's internal application layers.

Components

Streaming text and markdown: LiveText (a model message's streamed text, fed with StreamEvent values), MDTerm (line-by-line markdown rendering), CodeBlock.

Approval questions: ApprovalPrompt, PersistPrompt and the matching ParseApprovalReply / ParsePersistReply for the one-line answers.

Tool lines: a host describes one tool call or result as a ToolEvent and prints it with ToolCallLine / ToolResultLine. ToolCallArgs is the argument summary on its own. Arguments and results pass through redaction, paths are made relative to the workdir argument (empty keeps them absolute) and the line is cut to CallArgsLimit / ResultSummaryLimit. ToolFamilyOf maps a tool name to its ToolFamily, which decides the symbol and color.

Palette: NewPalette(theme, settings) resolves the chat.colors block (settings keys: ColorsKeyMode, ColorsKeyStyle and one key per element or family name) into SGR styles. It is built once per chat so the terminal's color depth is asked once; WithColor(false) returns a plain copy, and an unknown key or color is an error. Pass the palette to ToolCallLine / ToolResultLine and use Paint / PaintDim / OKInk / ErrInk / DimInk for the host's own lines.

Waiting line: NewSpinner(SpinnerConfig) shows "thinking" while the host waits for the model. With a StatusSetter (the *lineedit.Terminal itself has SetStatus) the line lives on the status row above the input line; with nil Status it owns a line of Out. Start / Stop bracket the wait, SetLabel switches the text (ToolLabel(t, name) is the label for a running tool), Suspend / Resume hand the screen to something else for a while. Enabled=false makes every method a no-op. Now and Ticks are injection points for tests.

Translator: every text the package writes goes through the host's Translator (T(key, args...)); nil selects the built-in Chinese text, so a host without a catalog needs nothing.

Input

Package lineedit is the line editor and package lineedit/pump the byte pump it reads through; see the pump package documentation.

Minimal host

Example_minimalHost (example_test.go) is the smallest wiring for a host with no steering (xhen style): pump.DefaultHooks + pump.NewPump + Bind + pump.WatchSize for input, ToolCallLine for a tool call and NewSpinner for the wait. The longer description lives in docs/usage/chatui.md.

Example (MinimalHost)

Example_minimalHost is the smallest wiring for a host without steering (xhen style): one input line read through the byte pump, a tool call printed as one line, and the waiting line while the model works. In a real host in is os.Stdin, out is os.Stdout and fd is the terminal descriptor; here the input is a string and fd is -1 (nothing to watch), so the example is deterministic.

package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"strings"
	"time"

	"github.com/inhere/suga/pkg/chatui"
	"github.com/inhere/suga/pkg/chatui/lineedit"
	"github.com/inhere/suga/pkg/chatui/lineedit/pump"
)

// rw joins the pump (what the editor reads) and an output writer into the
// io.ReadWriter lineedit.NewTerminal takes.
type rw struct {
	io.Reader
	io.Writer
}

// Example_minimalHost is the smallest wiring for a host without steering (xhen
// style): one input line read through the byte pump, a tool call printed as one
// line, and the waiting line while the model works. In a real host in is os.Stdin,
// out is os.Stdout and fd is the terminal descriptor; here the input is a string and
// fd is -1 (nothing to watch), so the example is deterministic.
func main() {
	in := strings.NewReader("hello\r")
	var screen bytes.Buffer
	fd := -1 // int(os.Stdin.Fd()) on a terminal

	// 1. Hooks: DefaultHooks needs no steer logic. Wait is the byte-ready wait of
	// the platform, which the pump needs to tell Alt+Enter and pasted newlines
	// from keys; EscActive nil means a lone Esc is never a key of its own.
	hooks := &pump.DefaultHooks{
		Wait: func(d time.Duration) bool { return pump.WaitTerminalInput(fd, d) },
	}

	// 2. The pump is built before the terminal (NewTerminal takes the reader) and
	// bound to it afterwards.
	p := pump.NewPump(in, hooks)
	term := lineedit.NewTerminal(rw{p, &screen}, "> ")
	p.Bind(term)

	// 3. Follow the window size: the editor wraps at the size it was last given.
	// stop is a no-op without a terminal.
	stop := pump.WatchSize(term, fd, func(width, height int) {})
	defer stop()

	// 4. Read one line. ResetFirstByte arms the first-byte handshake of this read.
	p.ResetFirstByte()
	line, err := term.ReadLine()
	fmt.Println(line, err)

	// 5. Print a tool call as one line. A nil Translator uses the built-in text;
	// "off" colors keep the output plain.
	pal, err := chatui.NewPalette("", map[string]string{chatui.ColorsKeyMode: chatui.ColorModeOff})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(chatui.ToolCallLine(nil, pal, chatui.ToolEvent{
		Name: "file_read",
		Args: map[string]any{"path": "main.go"},
	}, ""))

	// 6. The waiting line. With a StatusSetter (the terminal itself) it lives on
	// the row above the input line; with nil Status it owns a line of Out.
	spin := chatui.NewSpinner(chatui.SpinnerConfig{Enabled: false, Out: os.Stdout, Status: term})
	spin.Start()
	spin.SetLabel(chatui.ToolLabel(nil, "file_read"))
	spin.Stop()

}
Output:
hello <nil>
▸ file_read main.go

Index

Examples

Constants

View Source
const (
	StreamTextDelta   = "text_delta"
	StreamMessageStop = "message_stop"
	StreamRetry       = "retry"
)
View Source
const (
	ColorsKeyMode  = "mode"
	ColorsKeyStyle = "style"

	ColorModeAuto = "auto"
	ColorModeANSI = "ansi"
	ColorMode256  = "256"
	ColorModeTrue = "truecolor"
	ColorModeOff  = "off"

	// ColorStyleSymbol paints the family symbol only, ColorStyleName the symbol and
	// the tool name (the default), ColorStyleLine the whole call line.
	ColorStyleSymbol = "symbol"
	ColorStyleName   = "name"
	ColorStyleLine   = "line"

	ThemeLight = "light"
)

The keys of the chat.colors block: style is how much of a tool line the family color covers, mode is the color depth chat writes, and every other key names one color. A color is a 16 color name (blue, bright-cyan, purple), 256:NNN, #rrggbb or default for the terminal's own foreground.

View Source
const (
	// SpinnerSpeed is the interval between two frames of the waiting line.
	// It is cliui's default spinner speed: fast enough to look alive, slow
	// enough not to flood the terminal.
	SpinnerSpeed = 100 * time.Millisecond
	// SpinnerClear moves the cursor to the start of the line and erases it:
	// the overwrite sequence cliui's progress widgets use for a dynamic line.
	// Every frame starts with it (the elapsed seconds change anyway) and Stop
	// writes it once more, so the output that follows starts at column 0 with
	// no trace of the hint left on screen.
	SpinnerClear = "\r\x1b[2K"
)
View Source
const (
	// ResultSummaryLimit caps the one-line tool result summary, in runes.
	ResultSummaryLimit = 100
	// CallArgsLimit caps the tool_call argument text on screen, in runes.
	CallArgsLimit = 120
)

Variables

View Source
var FamilyNames = [FamilyCount]string{"read", "write", "shell", "net", "agent", "meta"}

FamilyNames are the chat.colors keys of the families, in the same order.

View Source
var FamilySymbols = [FamilyCount]string{"▸", "✎", "$", "⇄", "◆", "✦"}

FamilySymbols are the markers of the tool lines, one per family, in FamilyRead.. FamilyMeta order. They carry the distinction without colors too: a NO_COLOR terminal, a log file, a recording or a person who cannot tell these hues apart still reads a write apart from a read. A read tool keeps a triangle and not the record symbol ⏺ a call used to be marked with: many terminal fonts draw that one as a filled square, which is the answer's own marker ▣, so a tool line and an answer were told apart by their color alone.

View Source
var SpinnerChars = []rune("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")

SpinnerChars is cliui's dots loading theme (progress.CharsThemes[20]): the animation of the waiting line.

Functions

func ApprovalPrompt

func ApprovalPrompt(tool, scopeDescription string, allowAlways bool) string

ApprovalPrompt builds the compact answer line. allowAlways is false for an unsafe shell command: a deny scope is still useful, but an allow scope must never bypass the command safety matcher. Without a translator it falls back to the Chinese texts.

func ApprovalPromptWithTranslator

func ApprovalPromptWithTranslator(t Translator, tool, scopeDescription string, allowAlways bool) string

ApprovalPromptWithTranslator builds the compact answer line with the injected host UI translator; the compatibility wrapper above keeps older callers in zh. It accepts the host's minimal translation contract (Translator).

func PersistPrompt

func PersistPrompt(action string) string

PersistPrompt is explicit about the safe default: an empty answer keeps the rule in the current session, while only u/p request a file writeback.

func PersistPromptWithTranslator

func PersistPromptWithTranslator(t Translator, action string) string

PersistPromptWithTranslator builds the rule writeback question using the injected translator while retaining the safe session-only default.

func ToolCallArgs added in v0.53.0

func ToolCallArgs(t Translator, name, text string, full map[string]any, workspace string) string

ToolCallArgs returns what a tool line shows after "▸ <name>": the tool's own summary when there is one, the compact JSON of the call arguments otherwise. The workspace makes the paths inside it relative, and secrets are redacted like everywhere else in chat.

func ToolCallLine added in v0.53.0

func ToolCallLine(t Translator, p *Palette, ev ToolEvent, workdir string) string

ToolCallLine is the one-line display of a tool call: the symbol and the name of its family, then the arguments dim. Paths inside workdir are shown relative to it; with an empty workdir every path stays as the call wrote it.

func ToolLabel added in v0.53.0

func ToolLabel(t Translator, name string) string

ToolLabel is what the status line says while a tool of the turn runs: the tool's name in between ("执行 shell_exec…" / "running shell_exec…"), the elapsed seconds follow it.

func ToolResultLine added in v0.53.0

func ToolResultLine(t Translator, p *Palette, ev ToolEvent) string

ToolResultLine is the one-line display of a tool result: the ok label (or the error line) and the redacted, cut summary of the result text.

func TruncateLine added in v0.53.0

func TruncateLine(s string, limit int) string

TruncateLine collapses whitespace (one display line), removes terminal controls, and cuts to limit runes.

Types

type ApprovalReply

type ApprovalReply uint8

ApprovalReply is the decision made from the one-line answer to an approval question. The wiring layer turns the two persistent replies into session rules.

const (
	ReplyDeny ApprovalReply = iota
	ReplyAllow
	ReplyAllowAlways
	ReplyDenyAlways
)

func ParseApprovalReply

func ParseApprovalReply(answer string) ApprovalReply

ParseApprovalReply accepts the stable answer aliases used by chat. Empty and unknown answers stay deny, preserving the old fail-closed behavior.

type CodeBlock

type CodeBlock struct {
	Lang   string
	Lines  []string
	Folded int
}

CodeBlock is one fenced code block of a rendered message: the language of its fence, every line as the model wrote it and how many lines the fold limit hid (chat.code_max_lines). chat's :code command shows one of them again in full.

type LiveText

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

LiveText owns one model message's streamed text, line buffering and optional markdown rendering. It has no dependency on suga's engine or application layers.

func NewLiveText

func NewLiveText(w io.Writer) *LiveText

func NewPrefixedLiveText

func NewPrefixedLiveText(w io.Writer, prefix string) *LiveText

func (*LiveText) Answer

func (l *LiveText) Answer(text string)

func (*LiveText) CodeBlocks

func (l *LiveText) CodeBlocks() []CodeBlock

func (*LiveText) Finish

func (l *LiveText) Finish() bool

func (*LiveText) Handle

func (l *LiveText) Handle(event StreamEvent) bool

Handle writes deltas and closes a model message. It returns true for stream events.

func (*LiveText) SetCode

func (l *LiveText) SetCode(highlight bool, maxLines, width int)

func (*LiveText) SetMarkdown

func (l *LiveText) SetMarkdown(color bool)

func (*LiveText) SetMarkdownTheme

func (l *LiveText) SetMarkdownTheme(theme string)

func (*LiveText) SetTranslator

func (l *LiveText) SetTranslator(tr Translator)

func (*LiveText) SetWholeLines

func (l *LiveText) SetWholeLines(on bool)

type MDTerm

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

MDTerm renders markdown text line by line to a terminal writer. Zero value is not usable; call NewMDTerm.

func NewMDTerm

func NewMDTerm(w io.Writer, color bool) *MDTerm

NewMDTerm returns an MDTerm writing rendered lines to w; color styles them, with the dark theme's palette (SetTheme switches it).

func (*MDTerm) CodeBlocks

func (t *MDTerm) CodeBlocks() []CodeBlock

CodeBlocks returns the code blocks of the most recent message that had one, in the order they appeared (:code).

func (*MDTerm) Flush

func (t *MDTerm) Flush()

Flush renders the buffered, still incomplete line and ends the message: a code block left open does not carry into the next message.

func (*MDTerm) Print

func (t *MDTerm) Print(text string)

Print renders text that arrives as one piece (a final answer that was not streamed) and ends it on a line of its own. Empty text only ends the line its prefix was written on.

func (*MDTerm) SetCode

func (t *MDTerm) SetCode(highlight bool, maxLines int)

SetCode configures fenced code blocks: highlight colors them by their language (chat.code_highlight; it needs color) and maxLines folds a block after that many lines (chat.code_max_lines, 0: no fold).

func (*MDTerm) SetLinePrefix

func (t *MDTerm) SetLinePrefix(prefix string)

SetLinePrefix sets the text printed at the start of every message's first line ("" removes it).

func (*MDTerm) SetTheme

func (t *MDTerm) SetTheme(name string)

SetTheme switches the palette the elements are painted with (chat.theme, "dark" or "light"); an unknown name keeps the previous one.

func (*MDTerm) SetTranslator

func (t *MDTerm) SetTranslator(tr Translator)

SetTranslator installs the host UI catalog of the lines the renderer writes itself (the folded-code notice); nil keeps the historical Chinese text.

func (*MDTerm) SetWidth

func (t *MDTerm) SetWidth(width int)

SetWidth sets the terminal width used to leave a too wide table as it came (0: any width is accepted).

func (*MDTerm) Write

func (t *MDTerm) Write(text string)

Write takes the next chunk of markdown text and prints every line it completes; the rest waits in the buffer for its newline.

type Palette added in v0.53.0

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

Palette is the resolved styling of chat's own lines for this terminal: one SGR prefix per element, "" printing the terminal's default foreground. It is built once per chat, so the terminal's color depth is asked once.

func NewPalette added in v0.53.0

func NewPalette(theme string, settings map[string]string) (*Palette, error)

NewPalette resolves chat.colors for one chat: the defaults of theme (empty: the dark ones), overridden by the block's own values. An unknown key, style, mode or color is an error - a typo would otherwise silently leave a line as it was.

func (*Palette) DimInk added in v0.53.0

func (p *Palette) DimInk() string

func (*Palette) ErrInk added in v0.53.0

func (p *Palette) ErrInk() string

func (*Palette) FamilyInk added in v0.53.0

func (p *Palette) FamilyInk(family ToolFamily) string

FamilyInk is the SGR prefix of one tool family.

func (*Palette) OKInk added in v0.53.0

func (p *Palette) OKInk() string

OKInk, ErrInk and DimInk are the SGR prefixes of the ok label, the error line and the dim arguments.

func (*Palette) Paint added in v0.53.0

func (p *Palette) Paint(sgr, s string) string

Paint paints s with one resolved chat.colors style (an SGR prefix, "" for the terminal's default foreground). Like the paint() above it writes no SGR when the color library is off for this process (NO_COLOR, a terminal without colors, a test that pins plain text).

func (*Palette) PaintDim added in v0.53.0

func (p *Palette) PaintDim(s string) string

PaintDim dims a line (the arguments and the notices around a tool call) on a colored terminal.

func (*Palette) Style added in v0.53.0

func (p *Palette) Style() string

Style is how much of a tool line the family color covers (ColorStyleSymbol, ColorStyleName or ColorStyleLine).

func (*Palette) WithColor added in v0.53.0

func (p *Palette) WithColor(on bool) *Palette

WithColor returns a copy of the palette that paints (true) or writes plain text (false). The tool lines of a host that has no colored terminal keep their symbols and drop the SGR.

type PersistReply

type PersistReply uint8

PersistReply identifies the requested persistence destination. The wiring layer performs the writeback after the session rule has been installed in memory.

const (
	PersistSession PersistReply = iota
	PersistUser
	PersistProject
)

func ParsePersistReply

func ParsePersistReply(answer string) PersistReply

ParsePersistReply keeps Enter as the safe default and recognizes only the explicit destinations shown in the follow-up question.

type Spinner added in v0.53.0

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

Spinner shows one self-updating line while chat waits for the model ("⠋ 思考中… 3s", dimmed on a colored terminal), or what the turn does right now while a tool runs ("⠋ 执行 shell_exec… 3s"). The model is asked for its next message at every turn start and after every tool result; the line ends with the model's first output or the first line chat prints itself.

Where the line goes depends on the input line: a terminal chat keeps one on screen for the whole turn (chat.steering), so the frames go to the row above it (status); without one they overwrite a row of their own (SpinnerClear).

It does not use cliui's progress.SpinnerFactory (Spinner/LoadingSpinner): that widget renders from a goroutine it owns with an internal time.Sleep, so a test cannot drive its clock, Stop returns without waiting for that goroutine (a frame could land between the erase and the renderer's next line) and nothing reports that the goroutine is gone. This type keeps cliui's animation (progress.LoadingWidget) and its overwrite convention but owns the frame loop.

func NewSpinner added in v0.53.0

func NewSpinner(cfg SpinnerConfig) *Spinner

NewSpinner builds a spinner; its first label is the catalog's thinking line (status.spinner.thinking).

func (*Spinner) Resume added in v0.53.0

func (s *Spinner) Resume()

Resume is the counterpart of Suspend.

func (*Spinner) Running added in v0.53.0

func (s *Spinner) Running() bool

Running reports whether the frame goroutine is alive: a stopped spinner has closed its done channel, one that never started has none.

func (*Spinner) SetLabel added in v0.53.0

func (s *Spinner) SetLabel(label string)

SetLabel switches what the line says: the model is thinking (status.spinner.thinking) or a tool runs right now (ToolLabel). The elapsed seconds count from there on (the line reports how long the current state lasts), and a line that is already up changes in place. A no-op without a status line (the line of its own only ever says 思考中…) and while the line is not running.

func (*Spinner) Start added in v0.53.0

func (s *Spinner) Start()

Start shows the waiting line. It does nothing while the spinner is off (not a terminal, NO_COLOR or chat.spinner: false) or the line is already shown, so it may be called again after every tool result.

func (*Spinner) StatusRow added in v0.53.0

func (s *Spinner) StatusRow() bool

StatusRow reports whether the line goes to the row above the input line (chat.steering) instead of onto a row of its own (chat.spinner without an input line): what the renderer's writes have to do about the line depends on it.

func (*Spinner) Stop added in v0.53.0

func (s *Spinner) Stop()

Stop erases the waiting line and waits for the frame goroutine to be gone, so its caller can print immediately afterwards knowing that nothing will overwrite it and no goroutine is left behind. It is safe to call when nothing is shown.

func (*Spinner) Suspend added in v0.53.0

func (s *Spinner) Suspend()

Suspend takes the status line off screen while another part of chat owns the input line (an approval question asks on it): the frames of the running turn stop drawing until Resume, which shows the line again with what the turn waits for. Both are no-ops without a status line.

type SpinnerConfig added in v0.53.0

type SpinnerConfig struct {
	Enabled bool
	Out     io.Writer
	Status  StatusSetter
	Paint   func(string) string
	Speed   time.Duration
	Now     func() time.Time
	Ticks   func(time.Duration) (<-chan time.Time, func())
	// Translator renders the line's text; nil takes the built-in Chinese fallback
	// (spinnerText), like every other unwired chat text.
	Translator Translator
}

SpinnerConfig configures a Spinner.

type StatusSetter added in v0.53.0

type StatusSetter interface{ SetStatus(s string) }

StatusSetter is where the waiting line goes while chat keeps an input line on screen (chat.steering): the row above it (lineedit.Terminal.SetStatus), which the line editor clears and redraws around every write of its own - a line of its own would fight that input line for the row it is on (r3 M1). nil without a status line.

type StreamEvent

type StreamEvent struct {
	Kind string
	Text string
}

StreamEvent is the smallest event contract needed by the streaming text area. Hosts adapt their engine-specific event type at the application boundary.

type ToolEvent added in v0.53.0

type ToolEvent struct {
	Name    string
	Args    map[string]any
	Text    string
	IsError bool
}

ToolEvent is the host-neutral description of one tool call or tool result. Args is the whole argument map when the host has it (nil: Text is decoded instead); Text is the compact JSON of the arguments for a call and the result text for a result.

type ToolFamily added in v0.53.0

type ToolFamily uint8

ToolFamily groups the tools by what a call does, so one tool line says at a glance whether it read, wrote, ran or fetched something. A tool without an entry in toolFamilies (an MCP tool) gets FamilyMeta.

const (
	FamilyRead  ToolFamily = iota // reads the workspace
	FamilyWrite                   // writes or removes a file
	FamilyShell                   // runs a command
	FamilyNet                     // reaches the network
	FamilyAgent                   // runs a sub-agent
	FamilyMeta                    // session, memory, skills, plans
	FamilyCount = 6
)

func ToolFamilyOf added in v0.53.0

func ToolFamilyOf(name string) ToolFamily

ToolFamilyOf returns the family of a tool name; an unknown tool (an MCP tool, a tool a plugin added) keeps the neutral one.

type Translator

type Translator interface {
	T(key string, args ...map[string]any) string
}

Translator is the minimal host translation contract used by chat rendering.

Directories

Path Synopsis
Package lineedit is a copy of the VT100 line editor (Terminal) from golang.org/x/term v0.29.0 (terminal.go), made display-width aware.
Package lineedit is a copy of the VT100 line editor (Terminal) from golang.org/x/term v0.29.0 (terminal.go), made display-width aware.
pump
Package pump is the byte pump a line editor (lineedit.Terminal) reads through, plus the terminal helpers around it (platform input wait, input flush, output flags, window size watching).
Package pump is the byte pump a line editor (lineedit.Terminal) reads through, plus the terminal helpers around it (platform input wait, input flush, output flags, window size watching).
Package termtext removes terminal control sequences from text that came from a model, a tool or another external source before chat writes it to a terminal.
Package termtext removes terminal control sequences from text that came from a model, a tool or another external source before chat writes it to a terminal.

Jump to

Keyboard shortcuts

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