tui

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 69 Imported by: 0

Documentation

Overview

Package tui provides Pi-compatible terminal rendering, input, components, keybindings, and screen lifecycle management.

Ports packages/coding-agent/src/modes/interactive/theme/theme.ts.

Index

Constants

View Source
const (
	// Scoped SGR resets mirror upstream Pi's theme helpers:
	// foreground styles close with 39m and background styles close with 49m.
	// Avoid using SGRResetAll inside bg-painted content because it also clears
	// background color and creates visual gaps/stripes.
	SGRResetAll       = "\x1b[0m"
	SGRFgReset        = "\x1b[39m"
	SGRBgReset        = "\x1b[49m"
	SGRBoldDimReset   = "\x1b[22m"
	SGRItalicReset    = "\x1b[23m"
	SGRUnderlineReset = "\x1b[24m"
	SGRInverseReset   = "\x1b[27m"
	SGRStrikeReset    = "\x1b[29m"
)
View Source
const (
	// Deprecated: use TerminalColorModeTrueColor.
	ColorModeTrueColor = TerminalColorModeTrueColor
	// Deprecated: use TerminalColorMode256.
	ColorMode256 = TerminalColorMode256
)
View Source
const DefaultHiddenThinkingLabel = "Thinking..."

DefaultHiddenThinkingLabel is the label that stands in for a hidden thinking run (interactive-mode.ts defaultHiddenThinkingLabel).

View Source
const DefaultLoaderIntervalMs = 80

DefaultLoaderIntervalMs is upstream's DEFAULT_INTERVAL_MS.

View Source
const InMemoryThemeName = "<in-memory>"

InMemoryThemeName is the name of a theme set directly from an instance (theme.ts setThemeInstance's currentThemeName).

View Source
const ProgramStatusQuery = "\x1b]7501;?\x1b\\"

ProgramStatusQuery is the feature detection query. A supporting terminal replies with the same body.

View Source
const SystemThemeName = "system"

SystemThemeName is the reserved name of the theme generated from the terminal's own colors.

View Source
const TUICrashLogName = "pi-tui-crash.log"

TUICrashLogName is the upstream crash-log filename for over-wide rows that reach the main-screen differential renderer.

Variables

View Source
var DefaultSpinnerFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}

DefaultSpinnerFrames is the Braille spinner used by upstream.

View Source
var Key = KeyHelper{
	Escape: "escape", Esc: "esc", Enter: "enter", Return: "return", Tab: "tab", Space: "space", Backspace: "backspace",
	Delete: "delete", Insert: "insert", Clear: "clear", Home: "home", End: "end", PageUp: "pageUp", PageDown: "pageDown",
	Up: "up", Down: "down", Left: "left", Right: "right",
	F1: "f1", F2: "f2", F3: "f3", F4: "f4", F5: "f5", F6: "f6", F7: "f7", F8: "f8", F9: "f9", F10: "f10", F11: "f11", F12: "f12",

	Backtick: "`", Hyphen: "-", Equals: "=", Leftbracket: "[", Rightbracket: "]", Backslash: "\\", Semicolon: ";", Quote: "'",
	Comma: ",", Period: ".", Slash: "/", Exclamation: "!", At: "@", Hash: "#", Dollar: "$", Percent: "%", Caret: "^",
	Ampersand: "&", Asterisk: "*", Leftparen: "(", Rightparen: ")", Underscore: "_", Plus: "+", Pipe: "|", Tilde: "~",
	Leftbrace: "{", Rightbrace: "}", Colon: ":", Lessthan: "<", Greaterthan: ">", Question: "?",
}

Key is upstream's Key helper object. Key.Escape and Key.Ctrl("c") produce the identifiers MatchesKeyID and the keybinding tables take.

KeybindingPlatforms lists every platform column in inventory order.

TUIKeybindingOrder lists the TUI_KEYBINDINGS ids in declaration order (keybindings.ts), the order the generated keybindings schema uses.

TUIKeybindings is upstream TUI_KEYBINDINGS, the table getKeybindings() uses until an application installs its own. It has no platform column: the Windows and WSL keys are coding-agent KEYBINDINGS overrides, which the coding agent installs through its own manager. The Linux column carries none of those overrides.

View Source
var ViewOverridableTokens = []string{
	"accent", "muted", "dim", "text", "border", "borderAccent", "borderMuted",
	"success", "warning", "error", "selectedBg", "customMessageBg",
}

ViewOverridableTokens are the theme tokens a frontend view may override (extension component kit spec §6).

Functions

func ActionKeyDisplayText

func ActionKeyDisplayText(action string) string

ActionKeyDisplayText formats every key the registry binds to action, capitalized and joined by "/", or "" when none is bound. Mirrors upstream keyDisplayText (coding-agent keybinding-hints.ts).

func ActionKeyDisplayTextOr

func ActionKeyDisplayTextOr(action, fallback string) string

ActionKeyDisplayTextOr is ActionKeyDisplayText for an action that may not be registered (app actions outside the interactive mode, such as in component tests), falling back to the upstream default keys.

func ActionKeyText

func ActionKeyText(action string) string

ActionKeyText formats every key the registry binds to action, joined by "/", or "" when none is bound. Mirrors upstream keyText (coding-agent keybinding-hints.ts:34); ActionKeyDisplayText is keyDisplayText, its capitalized form.

func AllocateImageID

func AllocateImageID() int

func AppKeyText

func AppKeyText(action, fallback string) string

AppKeyText formats the resolved keys for an app-level keybinding, falling back to the provided default raw key text when no resolver is installed. An action the user unbound resolves to "", as upstream keyText formats an empty key list (keybinding-hints.ts formatKeys).

func BackgroundAnsi

func BackgroundAnsi(color Color, mode TerminalColorMode) string

BackgroundAnsi is the SGR sequence that selects color as the background.

func BgClose

func BgClose() string

func BgSeq

func BgSeq(c color.RGBA, trueColor bool) string

BgSeq returns the SGR background sequence for c (see FgSeq).

func BuildTerminalTitle

func BuildTerminalTitle(sessionName, cwd string) string

BuildTerminalTitle formats the pig terminal title from a session name (may be empty) and a cwd path. Matches upstream interactive-mode.ts pattern using APP_TITLE semantics.

func CalculateImageRows

func CalculateImageRows(imageDimensions ImageDimensions, targetWidthCells int, dims CellDimensions) int

func CapturesSelectPageInput

func CapturesSelectPageInput(component Component) bool

CapturesSelectPageInput reports whether component handles selection page keys.

func ColorToHex

func ColorToHex(color Color) string

ColorToHex formats any color as `#rrggbb`.

func CompositeTuiLine

func CompositeTuiLine(baseLine, overlayLine string, startCol, overlayWidth, totalWidth int) string

CompositeTuiLine ports upstream compositeTuiLine (tui.ts): overlay a child's line onto a base line at startCol, padding to keep column alignment and clipping to totalWidth. Image base lines pass through untouched.

func CropKittyImageLine

func CropKittyImageLine(line string, hiddenRows, visibleRows int) string

CropKittyImageLine rewrites a Kitty image line to show only rows [hiddenRows, hiddenRows+visibleRows) of the source image, adjusting the y/h/r controls. Returns the line unchanged when it carries no registered image or the crop is a no-op. Mirrors upstream cropKittyImageLine.

func CustomMessageText

func CustomMessageText(cm *CustomMessage) string

CustomMessageText extracts text from a CustomMessage's Content field the way upstream CustomMessageComponent does: a string is shown as is, and an array's text blocks are joined with newlines. Content from an extension is JSON-decoded ([]any of map[string]any); typed block slices from Go callers are read through the same JSON shape.

func DecodeKittyPrintable

func DecodeKittyPrintable(data string) (string, bool)

DecodeKittyPrintable decodes a printable Kitty CSI-u sequence into the corresponding character. Mirrors upstream decodeKittyPrintable().

func DecodePrintableKey

func DecodePrintableKey(data string) (string, bool)

DecodePrintableKey decodes printable terminal sequences from either Kitty CSI-u or xterm modifyOtherKeys formats.

func DeleteAllKittyImages

func DeleteAllKittyImages() string

func DeleteAllKittyPlacements

func DeleteAllKittyPlacements() string

DeleteAllKittyPlacements removes every Kitty image placement (visible renderings) while leaving the transmitted image data intact. Mirrors upstream deleteAllKittyPlacements.

func DeleteKittyImage

func DeleteKittyImage(imageID int) string

func DetectTheme deprecated

func DetectTheme()

DetectTheme activates the built-in theme for the terminal's appearance.

Deprecated: use SetThemeSettingPresence; without a setting it selects the system theme.

func EncodeITerm2

func EncodeITerm2(base64Data string, options ITerm2Options) string

EncodeITerm2 includes the decoded payload byte length in OSC 1337 metadata.

func EncodeKitty

func EncodeKitty(base64Data string, columns, rows, imageID int, moveCursor ...bool) string

func EnterRawMode

func EnterRawMode() (restore func(), err error)

EnterRawMode puts stdin into raw mode and returns a restore function.

This preserves pig's main-buffer rendering model from `tui.go`: no alternate screen, no hidden terminal reader, and callers continue to own the input loop.

func EnterRawModeForHandoff

func EnterRawModeForHandoff() (restore func(), err error)

EnterRawModeForHandoff enters raw mode with a restore closure that leaves unread input for the next terminal owner. The caller must join its reader before restoring and drain late releases separately on final shutdown.

func EnterRawModeWithDrain

func EnterRawModeWithDrain() (restore func(), drain func() error, err error)

EnterRawModeWithDrain separates process-shutdown input draining from cooked-mode restoration. A renderer drains first, stops while output is still raw, then restores cooked mode. Temporary terminal handoffs call only restore. drain returns DrainInput's error, so a caller can treat a terminal that went away as Pi's stdin error handler does.

func ExpandedEditorText

func ExpandedEditorText(editor EditorComponent) string

ExpandedEditorText returns the editor's text with markers expanded, falling back to Text when the editor has no expanded form.

upstream: editor-component.ts:42 (getExpandedText "Falls back to getText() if not implemented")

func FgClose

func FgClose(prefix string) string

FgClose is the sequence that ends a foreground opened by prefix, a Theme.Fg result: a dim token sets faint too, so it closes both (theme.ts fg of a dim token, `\x1b[2m...\x1b[22;39m`).

func FgSeq

func FgSeq(c color.RGBA, trueColor bool) string

FgSeq returns the SGR foreground sequence for c: 24-bit (38;2) when trueColor, else the nearest 256-color (38;5). BgSeq is the background equivalent.

func FindWordBackward

func FindWordBackward(text string, cursor int, options ...WordNavigationOptions) int

FindWordBackward skips trailing whitespace, then one word-like or atomic segment or a non-word run. Offsets count UTF-16 units.

func FindWordForward

func FindWordForward(text string, cursor int, options ...WordNavigationOptions) int

FindWordForward skips leading whitespace, then one word-like or atomic segment or a non-word run. Offsets count UTF-16 units.

func ForegroundAnsi

func ForegroundAnsi(color Color, mode TerminalColorMode) string

ForegroundAnsi is the SGR sequence that selects color as the foreground.

func FormatAuthSelectorProviderStatus

func FormatAuthSelectorProviderStatus(p OAuthProvider) string

FormatAuthSelectorProviderStatus is upstream formatAuthSelectorProviderStatus (oauth-selector.ts:36-53): the themed suffix describing whether and how a login option is configured, for example " ✓ configured".

func FormatAuthSelectorProviderType

func FormatAuthSelectorProviderType(authType string, subscription ...bool) string

FormatAuthSelectorProviderType mirrors upstream formatAuthSelectorProviderType(authType, subscription?) (oauth-selector.ts:27-33): an OAuth sign-in is a "subscription" unless subscription is false, which makes it an "account". Omitting subscription is Pi's undefined.

func FormatBashHeader

func FormatBashHeader(raw json.RawMessage) string

FormatBashHeader returns the styled `$ command` header for bash tool calls.

func FormatBuiltinToolHeader

func FormatBuiltinToolHeader(toolName string, args json.RawMessage, cwd string) string

FormatBuiltinToolHeader dispatches to the per-tool header formatter matching upstream's renderCall functions. cwd resolves relative paths to absolute file:// URLs for the OSC-8 hyperlink. Returns "" if the tool has no custom header format (falls back to FormatToolArgs).

func FormatCompactReadHeader

func FormatCompactReadHeader(raw json.RawMessage, cwd string) string

FormatCompactReadHeader is upstream read.ts formatCompactReadCall for the collapsed read card, or "" when the path has no compact classification.

func FormatEditHeader

func FormatEditHeader(raw json.RawMessage, cwd string) string

FormatEditHeader returns the styled `edit <path>` header for edit tool calls. Mirrors upstream renderers/edit.ts formatEditCall.

func FormatFindHeader

func FormatFindHeader(raw json.RawMessage) string

FormatFindHeader returns the styled find call. Mirrors upstream renderers/find.ts formatFindCall.

func FormatGrepHeader

func FormatGrepHeader(raw json.RawMessage) string

FormatGrepHeader returns the styled grep call. Mirrors upstream renderers/grep.ts formatGrepCall: bold toolTitle `grep`, accent `/pattern/`, toolOutput ` in <path>` ($HOME shortened, "." by default), then optional ` (glob)` and ` limit N` suffixes. Non-string pattern or path arguments render as the invalid-arg marker.

func FormatKeyText

func FormatKeyText(key string, capitalize bool) string

FormatKeyText formats a raw key string for UI display. It mirrors upstream formatKeyText by splitting alternate combos on "/" and combo parts on "+", mapping alt → option on macOS, and optionally capitalizing each part.

func FormatLsHeader

func FormatLsHeader(raw json.RawMessage, cwd string) string

FormatLsHeader returns the styled ls call. Mirrors upstream renderers/ls.ts formatLsCall: renderToolPath with emptyFallback ".".

func FormatProgramStatus

func FormatProgramStatus(status ProgramStatus) string

FormatProgramStatus encodes a status report. Terminals discard reports whose text contains control characters, so they are replaced.

func FormatReadHeader

func FormatReadHeader(raw json.RawMessage, cwd string) string

FormatReadHeader returns the styled `read <path>` header for read tool calls. Mirrors upstream read.ts formatReadCall: bold toolTitle `read`, the path via renderToolPath (accent + ~/ + OSC-8 link, or the invalid-arg marker for a non-string path), and a warning-colored `:start-end` line range.

func FormatReadLineRange

func FormatReadLineRange(offset, limit any) string

FormatReadLineRange is upstream render-utils.ts formatReadLineRange: `:start` or `:start-end` from finite numbers or numeric strings, nothing when both are null or absent or either is malformed. A zero end line prints no end, as the template's falsy check does.

func FormatShellHeader

func FormatShellHeader(raw json.RawMessage, prompt string) string

FormatShellHeader renders a shell tool call. Mirrors upstream formatShellCall: the whole `<prompt> <command>` is toolTitle-colored and bold, followed by a muted ` (timeout Ns)` suffix when the timeout argument is truthy. A non-string command renders as the error-colored invalid-arg marker; an empty or missing command renders as a toolOutput "...".

func FormatToolArgs

func FormatToolArgs(raw json.RawMessage) string

FormatToolArgs renders a JSON object as a compact `key:val, key:val` preview suitable for the tool-call header. Falls back to the raw JSON for non-object inputs. Long string values are truncated with "\u2026" so the header never overflows the terminal width.

Examples:

{"path":"x","limit":10}                \u2192  path:"x", limit:10
{"command":"git status --porcelain"}    \u2192  command:"git status \u2026"
[]                                      \u2192  []

func FormatToolCallWithArgs

func FormatToolCallWithArgs(title string, args json.RawMessage, theme *Theme, expanded bool) string

FormatToolCallWithArgs is the generic tool call header: the title followed by the arguments. Collapsed, they are `key=value` pairs on the title line, cut to 100 characters. Expanded, each is a `key: value` line below the title, with strings shown raw and continuation lines indented.

func FormatToolDuration

func FormatToolDuration(d time.Duration) string

FormatToolDuration mirrors upstream renderers/bash.ts formatDuration over the integer milliseconds Date.now() differences produce: seconds with one decimal under a minute, then "Xm Ys", then "Xh Ym Zs".

func FormatWriteHeader

func FormatWriteHeader(raw json.RawMessage, cwd string) string

FormatWriteHeader returns the styled `write <path>` header for write tool calls. Mirrors upstream write.ts formatWriteCall.

func FormatWriteHeaderArgs

func FormatWriteHeaderArgs(args map[string]any, cwd string) string

FormatWriteHeaderArgs is FormatWriteHeader of arguments that are already decoded.

func FuzzyFilter

func FuzzyFilter[T any](items []T, query string, getText func(T) string) []T

FuzzyFilter sorts items best-match-first and drops non-matchers. Tokens (separated by whitespace or `/`, upstream `split(/[\s/]+/)`) AND together: each token must match, so "openai-codex/gpt-5.5" matches the reordered text "gpt-5.5 openai-codex". Empty/whitespace-only query returns items unchanged.

func GetAltScreenSearchMatchKey

func GetAltScreenSearchMatchKey(match AltScreenSearchMatch) string

GetAltScreenSearchMatchKey identifies a match by its first and last cells. Mirrors upstream getAltScreenSearchMatchKey.

func GetDefaultTheme deprecated

func GetDefaultTheme() string

GetDefaultTheme is the built-in theme name for the terminal's appearance, "dark" or "light".

Deprecated: the default theme is SystemThemeName; use GetTerminalTheme for the appearance.

func GetKittyImagePlacementRows

func GetKittyImagePlacementRows(line string) (int, bool)

GetKittyImagePlacementRows reads the number of rows an image placement covers without scanning its payload: the explicit `r=` control, else the registered image's rows. Mirrors upstream getKittyImagePlacementRows.

func GetModelSearchText

func GetModelSearchText(item ModelSearchItem) string

GetModelSearchText mirrors upstream getModelSearchText: the bare id leads, followed by the provider, the provider/id pair, provider and id again, and the name when present.

func GetModelSelectorSearchText

func GetModelSelectorSearchText(item ModelSearchItem) string

GetModelSelectorSearchText mirrors upstream getModelSelectorSearchText. The /model selector search should rank exact provider-prefixed queries before proxy-provider IDs like openrouter/openai/gpt-5, so the bare model ID stays out of the leading position.

func HasBuiltInToolRenderers

func HasBuiltInToolRenderers(toolName string) bool

HasBuiltInToolRenderers reports whether upstream createAllToolRenderers has an entry for toolName. withBuiltInRenderers falls back to that entry for a registered definition (for example an extension override of a built-in name) that supplies no renderCall or renderResult of its own.

func HeaderForTool

func HeaderForTool(name string, args json.RawMessage, cwd string) string

HeaderForTool returns the fully styled call header for any tool: the builtin per-tool formatter when one matches, otherwise the upstream default of a bold toolTitle tool name followed by its compact args (tool-execution.ts:136 / formatToolExecution). The returned string is self-styled; renderHeaderInner emits it verbatim.

func Highlight

func Highlight(code string, options HighlightOptions) (string, error)

Highlight highlights code with highlight.js and renders its scopes with the theme. An error is an exception highlight.js throws, such as an unknown language.

func HighlightCode

func HighlightCode(code, lang string) []string

HighlightCode highlights code for the active theme and returns its lines, as theme.ts highlightCode does. Code in a language highlight.js does not support takes the mdCodeBlock color; code highlight.js fails on stays unstyled.

func HighlightCodeFor

func HighlightCodeFor(th *Theme, code, lang string, markdown bool) []string

HighlightCodeFor is highlightCode of pi-coding-agent's theme.ts, or getMarkdownTheme().highlightCode when markdown is set (a failed highlight then takes the mdCodeBlock color too), drawn with th rather than the active theme.

func Hyperlink(text, url string) string

func ImageFallback

func ImageFallback(mimeType string, dimensions *ImageDimensions, filename string) string

ImageFallback shortens home-prefixed paths and links absolute paths when the terminal supports hyperlinks.

func ImageTranscoderRegistered

func ImageTranscoderRegistered() bool

ImageTranscoderRegistered reports whether an image transcoder is registered.

func IsAppleTerminalSession

func IsAppleTerminalSession() bool

IsAppleTerminalSession mirrors terminal.ts isAppleTerminalSession.

func IsFocusable

func IsFocusable(component Component) bool

IsFocusable mirrors isFocusable (tui.ts:186): a component is focusable when it can hold the TUI focus flag. Upstream tests `"focused" in component`; a Go component carries the flag behind SetFocused, so it is focusable when it implements Focusable. A nil component is not focusable.

func IsImageLine

func IsImageLine(line string) bool

IsImageLine reports whether the line contains Kitty or iTerm2 image protocol bytes. Mirrors upstream terminal-image.ts isImageLine().

func IsKeyRelease

func IsKeyRelease(data string) bool

IsKeyRelease reports whether a raw input chunk is a Kitty key-release event (flag 2, ":3" variants). Bracketed-paste content is never treated as a release even when it contains ":3" byte patterns. Mirrors upstream isKeyRelease.

Prefer ShouldDeliverKey when routing input to a focused component; call this directly only from a raw-input consumer.

func IsKeyRepeat

func IsKeyRepeat(data string) bool

IsKeyRepeat reports whether a raw input chunk is a Kitty key-repeat event (flag 2, ":2" variants). Bracketed-paste content is never treated as a repeat even when it contains ":2" byte patterns. Mirrors upstream isKeyRepeat.

func IsKittyProtocolActive

func IsKittyProtocolActive() bool

IsKittyProtocolActive reports whether a Kitty protocol response was seen during the current raw-mode session.

func IsNativeModifierPressed

func IsNativeModifierPressed(key ModifierKey) bool

IsNativeModifierPressed mirrors upstream native-modifiers.ts isNativeModifierPressed: it asks the operating system whether a modifier key is held right now, and reports false when no helper is available.

func IsOsc11BackgroundColorResponse

func IsOsc11BackgroundColorResponse(data string) bool

IsOsc11BackgroundColorResponse recognizes a complete OSC 11 reply, even when its color payload cannot be parsed.

func IsProgramStatusReply

func IsProgramStatusReply(sequence string) bool

IsProgramStatusReply reports whether sequence is the reply to ProgramStatusQuery. Later spec revisions may add pairs after the `?`.

func IsShellTool

func IsShellTool(toolName string) bool

IsShellTool reports whether toolName uses the shared shell renderers.

func IsTerminalColorReply

func IsTerminalColorReply(data string) bool

IsTerminalColorReply reports whether data has the shape of a reply to QueryTerminalColors: an OSC 10, 11, or 4 color reply or a DA1 reply. Callers that must hop to the owner loop before ConsumeTerminalColorResponse use it to skip that hop for ordinary input.

func IsViewportTUI

func IsViewportTUI(renderer TUI) bool

IsViewportTUI mirrors isViewportTUI (tui.ts:491): it reports whether the renderer owns a scrollable viewport, which only the alt-screen renderer does.

func JSNumberString

func JSNumberString(v float64) string

JSNumberString mirrors JavaScript Number.prototype.toString() for finite values: the shortest round-trip digits, in plain notation for magnitudes in [1e-6, 1e21) and exponent notation (e.g. "1e-7", "1e+21") outside it. The integers 0 to 255, every RGB channel a color sequence prints, come from byteDecimals without formatting or allocating; -0 prints "0" as in JS.

func KeyDisplayText

func KeyDisplayText(key string) string

KeyDisplayText formats a raw key string in display form.

func KeyHint

func KeyHint(key, description string) string

KeyHint formats a display key and description with foreground-only resets, preserving enclosing text styles.

func LanguageFromPath

func LanguageFromPath(path string) string

LanguageFromPath returns the highlight language for a file path, or "" when none maps, as theme.ts getLanguageFromPath does: the extension is the text after the path's last dot, or the whole path when it has none, lowercased as String.prototype.toLowerCase does.

func LoadAllHighlightLanguages

func LoadAllHighlightLanguages()

LoadAllHighlightLanguages registers every highlight.js language, as loadAllHighlightLanguages does, and returns when they are available. It runs once; later calls wait for that load. Highlighted code cached before the load is discarded, because more languages now highlight.

func LoadThemeDir

func LoadThemeDir(dir string) (map[string]*Theme, error)

LoadThemeDir scans a directory for .json theme files and returns a map of name → *Theme. Mirrors upstream theme discovery.

func MarkTerminalColorsPending

func MarkTerminalColorsPending()

MarkTerminalColorsPending renders the system theme in grayscale until SetTerminalColors reports the terminal's colors.

func MatchesKeyID

func MatchesKeyID(data, keyID string) bool

MatchesKeyID checks if raw terminal data matches a key identifier string like "ctrl+c", "ctrl+shift+z", "enter", etc. Exported for use by extension shortcut dispatch in interactive mode.

func NormalizeAppleTerminalInput

func NormalizeAppleTerminalInput(data string, isAppleTerminal, isShiftPressed bool) string

NormalizeAppleTerminalInput mirrors terminal.ts normalizeAppleTerminalInput.

func NormalizeNativeShiftEnterInput

func NormalizeNativeShiftEnterInput(data string, shouldDetectNativeShiftEnter, isShiftPressed bool) string

NormalizeNativeShiftEnterInput mirrors terminal.ts normalizeNativeShiftEnterInput: a plain Return read while the native Shift key is held becomes the enhanced Shift+Enter sequence.

func NormalizeProcessInputSequence

func NormalizeProcessInputSequence(sequence string) string

NormalizeProcessInputSequence applies the input normalization of upstream ProcessTerminal.forwardInputSequence to one complete StdinBuffer sequence. Apple Terminal (and the Windows console) can send plain Return for Shift+Enter even with enhanced key reporting requested, so Pi asks the local OS whether Shift is held. Pig's input loops split sequences outside ProcessTerminal, so each loop calls this before dispatch.

func ObserveActiveTheme

func ObserveActiveTheme(observe func()) func()

ObserveActiveTheme registers observe to run after the active theme is replaced, which is what theme.ts reports through onThemeChange (theme.ts:698-731, 780), or after the terminal's reported colors change. Upstream's `ctx.ui.theme` is the global theme, read at every use, so an owner that hands a copy of the palette to a runtime reports each change through this. observe runs on the goroutine that replaced the theme, with the theme mutation lock held: it must return at once and must not select a theme. The returned function removes it and can be called repeatedly.

func OklabToOkhslLightness

func OklabToOkhslLightness(x float64) float64

OklabToOkhslLightness converts Oklab lightness to OKHSL lightness.

func OutputTerminalHungUp

func OutputTerminalHungUp() bool

OutputTerminalHungUp reports whether the terminal the process writes to has been hung up, as when the master side of its pseudo-terminal closed. Such a terminal can still answer TIOCGWINSZ while its hang-up completes.

func PageSelectionIndex

func PageSelectionIndex(kb *TUIKeybindingsManager, data string, selectedIndex, itemCount, pageSize int) (int, bool)

PageSelectionIndex is getPageSelectionIndex of Pi PR #7680 (packages/tui/src/selection-navigation.ts): the index a tui.select.pageUp or tui.select.pageDown key moves a selection to, clamped to the list without wrapping, and false when data is neither key.

pig divergence (D155): Pi 1.1.0 handles these keys in only some selection lists (Pi #7629).

func ParseAutoThemeSetting

func ParseAutoThemeSetting(themeSetting string) (lightTheme, darkTheme string, ok bool)

ParseAutoThemeSetting parses "lightTheme/darkTheme", trimming ECMAScript whitespace around each name. Empty or malformed values are not automatic.

func ParseKey

func ParseKey(data string) (string, bool)

ParseKey parses terminal input into Pi's canonical key identifier. The bool is false when the input is not one recognized key.

func RGBTo256

func RGBTo256(c color.RGBA) uint8

RGBTo256 maps a 24-bit color to the nearest xterm-256 palette index, choosing between the 6x6x6 color cube (16-231) and the 24-step grayscale ramp (232-255) by squared RGB distance, so near-gray colors use the finer gray ramp rather than a coarse cube step.

func RawKeyHint

func RawKeyHint(key, description string) string

RawKeyHint formats a raw key string without going through a keybinding registry. Mirrors upstream's rawKeyHint which skips the keybinding lookup.

func ReadInputChunk

func ReadInputChunk(r io.Reader) ([]byte, error)

ReadInputChunk reads one unframed terminal chunk. The input-loop owner passes it to TerminalInput so negotiation is handled after sequence framing.

func ReadInputStream

func ReadInputStream(ctx context.Context, source io.Reader, onInput func([]byte)) error

ReadInputStream delivers raw reads synchronously until EOF, a read error, or cancellation. The callback must return when ctx is cancelled. Files stay open for the next terminal owner. Other ReadClosers are closed on cancellation to interrupt Read; non-closable readers must complete each Read without waiting for external input.

func ReadInputStreamUntil

func ReadInputStreamUntil(ctx context.Context, source io.Reader, next func() time.Time, onInput func([]byte), expired func()) error

ReadInputStreamUntil is ReadInputStream for a reader that also owns input deadlines, such as TerminalInput's NextDeadline: while next reports a deadline, a terminal-file wait ends there and calls expired instead of waiting for input, as the framing timers' setTimeout fires on Pi's event loop between stdin reads. A nil next never ends a wait; other sources ignore deadlines.

func RedactSecretInput

func RedactSecretInput(text, value string) string

RedactSecretInput removes a submitted input and its trimmed credential form from an authentication diagnostic. It does not modify credentials or persist the input.

func RefreshActiveThemeColorMode

func RefreshActiveThemeColorMode()

RefreshActiveThemeColorMode re-activates the active theme in the color mode the terminal supports now. Upstream re-creates the theme from settings after applying capability overrides on reload.

func RegisterKittyImageMetadata

func RegisterKittyImageMetadata(metadata KittyImageMetadata)

RegisterKittyImageMetadata records metadata for a transmitted Kitty image, evicting the oldest entry past the cap. Mirrors upstream registerKittyImageMetadata.

func RenderDiff

func RenderDiff(diffText string, _ ...RenderDiffOptions) string

RenderDiff renders a diff string with colored lines and intra-line highlighting, as upstream renderDiff does: each row is theme.fg of the toolDiffContext, toolDiffRemoved or toolDiffAdded token.

func RenderHighlightedHtml

func RenderHighlightedHtml(html string, theme HighlightTheme) string

RenderHighlightedHtml renders highlight.js HTML as text: each run of text takes the formatter of its innermost mapped scope, or the theme's default, and HTML character references are decoded.

func RenderImage

func RenderImage(base64Data string, imageDimensions ImageDimensions, options ImageRenderOptions) *renderedImage

RenderImage preserves aspect ratio and permits Kitty cursor movement unless explicitly disabled in options.

func RenderIntraLineDiff

func RenderIntraLineDiff(oldContent, newContent string) (removedLine, addedLine string)

RenderIntraLineDiff is diff.ts renderIntraLineDiff: the word-level diff of the two lines (jsdiff's diffWords), with inverse on the changed parts and the leading whitespace of the first removed and first added part left outside the highlight.

func ResetCapabilitiesCache

func ResetCapabilitiesCache()

func ResolveEscapeTimeoutMs

func ResolveEscapeTimeoutMs(getenv func(string) string) float64

ResolveEscapeTimeoutMs returns how long, in milliseconds, input handling waits for the rest of an escape sequence before dispatching a lone ESC as the Escape key. PI_TUI_ESC_TIMEOUT wins when it is a finite positive number; SSH sessions default to 100ms because legacy Alt+key input is ESC plus another byte and high-latency transports split them. Mirrors upstream resolveEscapeTimeoutMs (terminal.ts).

func ResolveThemeSetting deprecated

func ResolveThemeSetting(themeSetting string, terminalTheme TerminalTheme) (string, bool)

ResolveThemeSetting resolves a stored theme setting to the concrete theme name for the detected terminal appearance.

Deprecated: use ResolveThemeSettingPresence; an empty string means no setting.

func ResolveThemeSettingPresence

func ResolveThemeSettingPresence(themeSetting *string, terminalTheme TerminalTheme) (string, bool)

ResolveThemeSettingPresence resolves a theme setting to the concrete theme name for the detected terminal appearance. A nil setting and a malformed slash value resolve to nothing; any other string, including an empty one, is a fixed name that resolves to itself.

func RestoreTerminalFromSignal

func RestoreTerminalFromSignal() bool

RestoreTerminalFromSignal returns the terminal to the mode it had before pig took it over, and reports whether there was anything to restore.

This is the subset of raw-mode teardown that is safe to run from a signal goroutine: it disables the extended-key protocols in a single write and then runs one tcsetattr against a state captured at startup. It deliberately skips the rest of the normal teardown, which drains stdin for up to a second, because that would race the input reader and the render loop.

Without the tcsetattr, exiting on a signal leaves the terminal raw: ISIG stays off, so the user's shell has no working Ctrl+C until they run `reset`. Without the protocol disable, the Kitty flags pig pushed stay on the terminal's stack after pig is gone, so the shell that inherits the terminal receives CSI-u encoded keys it does not understand.

func RestoreTerminalOnExit

func RestoreTerminalOnExit()

RestoreTerminalOnExit is Pi's process 'exit' handler: last-resort restore for exit paths that skip Stop, such as a direct os.Exit (#11170). It writes, synchronously and exactly once per started terminal, the mode resets (mouse tracking, focus reporting, Kitty keyboard protocol, bracketed paste, alternate screen) and puts the terminal back in cooked mode, which Node's libuv does at exit and Go does not. Idempotent, and a no-op after a normal Stop. Never panics.

func SGRColor

func SGRColor(prefix string) func(string) string

SGRColor is the color function for an SGR escape prefix: it writes prefix before the text and resets the foreground after it. An empty prefix leaves the text as it is.

func SecretInputPreview

func SecretInputPreview(value string) (string, int)

SecretInputPreview returns a bounded masked preview and the number of user-perceived characters. Inputs shorter than five characters reveal no suffix.

func SetAppKeyTextResolver

func SetAppKeyTextResolver(resolver func(action string) string)

SetAppKeyTextResolver installs a resolver for app-level keybinding IDs (for example, `app.tree.foldOrUp`) used by TUI components that can't import the codingagent package directly.

func SetCapabilities

func SetCapabilities(caps TerminalCapabilities)

SetCapabilities overrides the cached capabilities. Mirrors upstream setCapabilities.

func SetCapabilityOverrides

func SetCapabilityOverrides(overrides CapabilityOverrides)

SetCapabilityOverrides mirrors upstream setCapabilityOverrides: it replaces the overrides and drops the cache only when a field changed.

func SetCellDimensions

func SetCellDimensions(dims CellDimensions)

func SetCompactReadClassifier

func SetCompactReadClassifier(classify func(rawPath, cwd string) (CompactReadClassification, bool))

SetCompactReadClassifier installs the classifier FormatCompactReadHeader uses. Nil turns compact read headers off.

func SetImageTranscoder

func SetImageTranscoder(transcoder ImageTranscoder)

SetImageTranscoder registers the converter used for non-PNG images on Kitty-protocol terminals, which only accept PNG. Without one, such images render as text fallbacks. It clears the shared conversions. upstream: packages/tui/src/components/image.ts:setImageTranscoder

func SetImageTranscoderLoader

func SetImageTranscoderLoader(loader func(onRegistered func()))

SetImageTranscoderLoader installs the host function that registers the PNG transcoder for Kitty-protocol terminals (coding-agent utils/image-convert.ts ensurePngTranscoder). A tool card calls it when it shows a non-PNG image, so the transcoder is available in any host. The loader runs onRegistered once the transcoder is newly registered, and not when it was already registered or cannot load. Set it at start-up, before a card renders.

func SetKeybindings

func SetKeybindings(kb *TUIKeybindingsManager)

SetKeybindings mirrors upstream setKeybindings().

func SetKittyProtocolActive

func SetKittyProtocolActive(active bool)

SetKittyProtocolActive mirrors upstream keys.ts global Kitty state.

func SetProgramStatusElsewhere

func SetProgramStatusElsewhere(elsewhere bool)

SetProgramStatusElsewhere turns the process terminal's own OSC 7501 support detection and reports off, before raw mode starts for a run a frontend session may draw, or back on once no session draws. Turned back on in raw mode, it queries support then, as raw mode would have.

func SetTUIKeybindings

func SetTUIKeybindings(kb *TUIKeybindingsManager)

SetTUIKeybindings sets the global TUI keybinding manager.

func SetTerminalColorScheme

func SetTerminalColorScheme(scheme TerminalTheme)

SetTerminalColorScheme records the terminal's light/dark report, the fallback for terminals that do not report their background. An empty scheme clears it.

func SetTerminalColors

func SetTerminalColors(colors TerminalColors)

SetTerminalColors records the terminal's reported colors. Themes use the default colors for tokens set to "" (terminal default); the system theme is generated from all of them. It ends the pending state.

func SetTerminalProgramStatus

func SetTerminalProgramStatus(status ProgramStatus)

SetTerminalProgramStatus reports program status (OSC 7501) on the process terminal.

func SetTerminalProgress

func SetTerminalProgress(active bool)

SetTerminalProgress toggles the OSC 9;4 terminal progress indicator.

func SetTerminalTitle

func SetTerminalTitle(title string)

SetTerminalTitle writes an OSC 0 sequence to stdout to update the terminal window title. An empty title clears back to terminal default.

func SetTheme

func SetTheme(name string, enableWatcher ...bool)

SetTheme switches the active built-in theme. enableWatcher restarts the owned watcher; previews leave the current watch registration unchanged.

func SetThemeByName

func SetThemeByName(name string, enableWatcher ...bool)

SetThemeByName activates a registered theme, or the system theme when it is absent or invalid (theme.ts setTheme). enableWatcher restarts the interactive owner's watch after a successful selection; it defaults to false for previews.

func SetThemeByNameChecked

func SetThemeByNameChecked(name string, enableWatcher ...bool) error

SetThemeByNameChecked is SetThemeByName that reports why a theme could not be activated; the system theme is active then (theme.ts setTheme's `{ success: false, error }`).

func SetThemeInstance

func SetThemeInstance(theme *Theme)

SetThemeInstance makes theme the active theme as it is (theme.ts:795 setThemeInstance stores the instance it is given). Only a theme loaded or selected by name is created for the terminal's color depth (theme.ts createTheme); an instance keeps the mode it was created in, so putting back the theme that was active leaves it as it was. An instance has no file to watch, so the owned watcher selects nothing for it.

func SetThemeRegistry

func SetThemeRegistry(r *ThemeRegistry)

SetThemeRegistry sets the global theme registry.

func SetThemeSetting deprecated

func SetThemeSetting(themeSetting string)

SetThemeSetting applies a stored theme setting.

Deprecated: use SetThemeSettingPresence; an empty string means no setting.

func SetThemeSettingPresence

func SetThemeSettingPresence(themeSetting *string)

SetThemeSettingPresence applies a theme setting before the terminal answers: the theme it resolves to for the terminal's appearance so far, or the system theme when there is no setting or it is malformed (theme.ts initTheme, interactive-mode.ts initTheme). A name that is not registered also selects the system theme.

func ShellToolPrompt

func ShellToolPrompt(toolName string) (prompt string, ok bool)

ShellToolPrompt returns the prompt upstream createAllToolRenderers assigns to a built-in shell tool: createShellRenderers("$") for bash and createShellRenderers("PS>") for powershell. ok is false for other tools.

func ShouldDeliverKey

func ShouldDeliverKey(component Component, data string) bool

ShouldDeliverKey reports whether a raw input chunk may be handed to a focused component's HandleInput. Kitty key releases are dropped unless the component implements KeyReleaseReceiver and opts in.

This is the single decision point for focused-component key delivery, and every such handoff must route through it. A component that acts on a release fires each keystroke twice, because extendedKeyInit pushes \x1b[>7u, whose flag 2 makes the terminal report press, repeat, and release. Scattering the check across dispatch sites is what let extension dialogs move a selector cursor two rows per arrow press: the filter existed, but an earlier return bypassed it.

Raw-input consumers are a different contract and must not use this: terminal input listeners, alt-screen viewport handling, and extension shortcut listeners all see unfiltered input by design, matching upstream's addInputListener and handleViewportInput.

Mirrors upstream tui.ts:887 (isKeyRelease(data) && !wantsKeyRelease -> drop).

func StyleText

func StyleText(text string, style TextStyle, mode TerminalColorMode) string

StyleText wraps text in the SGR sequences for style, closing them in reverse order.

func StyleTextWithAnsi

func StyleTextWithAnsi(text, fgAnsi, bgAnsi string, attributes TextAttributes) string

StyleTextWithAnsi is StyleText with precomputed color sequences, e.g. cached theme colors; an empty sequence is unset.

func SupportsLanguage

func SupportsLanguage(name string) bool

SupportsLanguage reports whether highlight.js has a language or alias of that name.

func SupportsTrueColor

func SupportsTrueColor() bool

SupportsTrueColor reports whether the terminal advertises 24-bit color via the COLORTERM hint (truecolor/24bit) or Windows Terminal, matching the probe in DetectTerminalCapabilities. Terminals without the hint (Apple Terminal.app, plain xterm-256color) are treated as 256-color so callers downsample instead of emitting 24-bit SGR the terminal ignores, which would otherwise render the half-block art as a single default color.

func ThemeFg

func ThemeFg(token string) func(string) string

ThemeFg is `(text) => theme.fg(token, text)`, the color function upstream's callers pass: it styles with the active theme when it is called.

func ThemeHexBg

func ThemeHexBg(hex string) string

ThemeHexBg returns the active theme's background escape for a fixed hex color, in the theme's color mode.

func ThemeHexFg

func ThemeHexFg(hex string) string

ThemeHexFg returns the active theme's foreground escape for a fixed hex color, in the theme's color mode.

func ToolErrorBgOpen

func ToolErrorBgOpen() string

func ToolPendingBgOpen

func ToolPendingBgOpen() string

func ToolSuccessBgOpen

func ToolSuccessBgOpen() string

func TranscriptNodes

func TranscriptNodes(c Component, width int, streaming bool, toolDiff func(string, map[string]any, any) *frontend.Diff) []frontend.Node

TranscriptNodes returns the nodes the main transcript reports for c laid out at width: a user message's MarkdownText, an assistant message's parts (streaming marks it as being generated), or a tool card's ToolCard, with toolDiff the session's ToolDiff hook. Another component has none. An extension's view of Pi's conversation components (D107) carries them.

func TreeVisibleLines

func TreeVisibleLines(terminalHeight int) int

NewTreeSelectorComponent builds the flattened view from the given root. Root itself is not rendered; only its children.

Indent + connector rules mirror upstream tree-selector.ts:143-260 (flattenTree) and :631-666 (per-row prefix construction). Single-child chains stay at the same indent and skip the connector glyph; only branch points (parent with > 1 children) bump indent and draw `├─`/`└─`. TreeVisibleLines is upstream TreeSelectorComponent's row budget for a terminal of the given height.

func UseWindowsKeybindings

func UseWindowsKeybindings(goos string, getenv func(string) string) bool

UseWindowsKeybindings reports whether Windows default keys apply: native Windows, or Linux under WSL. WT_SESSION alone does not count, because Windows Terminal also hosts SSH sessions to other machines. Mirrors upstream useWindowsKeybindings(platform, env) in core/keybindings.ts; goos uses Go's runtime.GOOS names.

func UserMessageBgOpen

func UserMessageBgOpen() string

Convenience accessors for component code that paints backgrounds. These read from the active theme so dark/light mode works automatically.

func ValidateThemeJSON

func ValidateThemeJSON(label string, data []byte) error

ValidateThemeJSON validates one theme document (JSON text without a BOM) and returns an error naming the offending tokens, or nil. Mirrors upstream validateThemeJson (theme-schema.ts): a name containing "/" is rejected before the schema runs.

func WcagContrast

func WcagContrast(first, second RgbColor) float64

WcagContrast is the WCAG 2 contrast ratio, 1-21.

func WrapText

func WrapText(s string, width int) []string

WrapText wraps text at width, preserving ANSI escape codes across line breaks. Exported for use by tool renderers.

Types

type AltScreenFlashContainer

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

AltScreenFlashContainer holds transient reverse-video messages composited by the alternate-screen renderer. Ports pi-tui's AltScreenFlashContainer.

Forced Go mechanic: upstream's single-loop setTimeout(...).unref() removal is an owned time.AfterFunc guarded by a mutex, because each timer fires on its own goroutine and races Render/Flash/Dispose. The per-entry id is the identity guard: a fired-but-already-removed callback finds its id gone and no-ops. The requestRender callback runs after the lock is released so slow render work never holds the mutex. Go timers never keep the process alive, so unref() has no Go counterpart; Dispose stops every timer to avoid a goroutine leak.

func NewAltScreenFlashContainer

func NewAltScreenFlashContainer(requestRender func()) *AltScreenFlashContainer

NewAltScreenFlashContainer constructs a flash container that calls requestRender whenever the visible set changes.

func (*AltScreenFlashContainer) Dispose

func (c *AltScreenFlashContainer) Dispose()

Dispose stops all pending timers and clears the visible set.

func (*AltScreenFlashContainer) Flash

func (c *AltScreenFlashContainer) Flash(message string, durationMs int)

Flash shows message in reverse video for durationMs, then removes it. The caller supplies altScreenFlashDefaultDurationMS for the optional upstream default; an explicit zero or negative duration is clamped to zero like Math.max(0, durationMs).

func (*AltScreenFlashContainer) Invalidate

func (i *AltScreenFlashContainer) Invalidate()

func (*AltScreenFlashContainer) IsDirty

func (i *AltScreenFlashContainer) IsDirty() bool

func (*AltScreenFlashContainer) NeedsRedraw

func (i *AltScreenFlashContainer) NeedsRedraw() bool

func (*AltScreenFlashContainer) Render

func (c *AltScreenFlashContainer) Render(width int) []string

Render returns one reverse-video line per active flash, each padded-spaced and truncated to width. Mirrors upstream render.

type AltScreenSearchComponent

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

AltScreenSearchComponent is the transcript search box: an input, a result counter, and previous/next buttons in its bottom border. Mirrors upstream AltScreenSearchComponent. Navigation directions are -1 (previous), 1 (next), and 0 (none, upstream undefined).

func NewAltScreenSearchComponent

func NewAltScreenSearchComponent(onQueryChange func(query string), navigationButtonStyle func(text string, hovered bool) string) *AltScreenSearchComponent

NewAltScreenSearchComponent creates the search box. A nil navigationButtonStyle leaves the buttons unstyled.

func (*AltScreenSearchComponent) Focused

func (c *AltScreenSearchComponent) Focused() bool

Focused reports the Focusable state. Mirrors upstream get focused.

func (*AltScreenSearchComponent) GetNavigationDirectionAt

func (c *AltScreenSearchComponent) GetNavigationDirectionAt(row, column int) int

GetNavigationDirectionAt returns the button under a component-local cell.

func (*AltScreenSearchComponent) HandleInput

func (c *AltScreenSearchComponent) HandleInput(data string)

HandleInput edits the query and reports a changed query.

func (*AltScreenSearchComponent) Invalidate

func (c *AltScreenSearchComponent) Invalidate()

Invalidate invalidates the input.

func (*AltScreenSearchComponent) Render

func (c *AltScreenSearchComponent) Render(width int) []string

Render draws the box: top border, input row, and a bottom border carrying the navigation buttons. Mirrors upstream AltScreenSearchComponent.render.

func (*AltScreenSearchComponent) SetFocused

func (c *AltScreenSearchComponent) SetFocused(value bool)

SetFocused updates the Focusable state and forwards it to the input.

func (*AltScreenSearchComponent) SetHoveredNavigationDirection

func (c *AltScreenSearchComponent) SetHoveredNavigationDirection(direction int) bool

SetHoveredNavigationDirection records the hovered button and reports whether it changed.

func (*AltScreenSearchComponent) SetResult

func (c *AltScreenSearchComponent) SetResult(index, count int)

SetResult sets the displayed match index (-1 for none) and count.

type AltScreenSearchIndex

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

AltScreenSearchIndex caches the searchable corpus and matches while the rendered transcript lines remain unchanged. Mirrors upstream AltScreenSearchIndex.

func (*AltScreenSearchIndex) Search

func (i *AltScreenSearchIndex) Search(lines []string, query string) (matches []AltScreenSearchMatch, changed bool)

Search returns the matches for query over lines and whether they changed since the previous call. Mirrors upstream AltScreenSearchIndex.search.

type AltScreenSearchMatch

type AltScreenSearchMatch struct {
	Segments []AltScreenSearchSegment
}

AltScreenSearchMatch is one match, possibly spanning rows. Mirrors upstream AltScreenSearchMatch.

func FindAltScreenSearchMatches

func FindAltScreenSearchMatches(lines []string, query string) []AltScreenSearchMatch

FindAltScreenSearchMatches searches lines for query without caching. Mirrors upstream findAltScreenSearchMatches.

type AltScreenSearchSegment

type AltScreenSearchSegment struct {
	Row      int
	StartCol int
	EndCol   int
}

AltScreenSearchSegment is one row-local cell range of a match. Mirrors upstream AltScreenSearchSegment.

type AssistantContentBlock

type AssistantContentBlock struct {
	Type     string
	Text     string
	Thinking string
}

AssistantContentBlock is one content block of an AssistantMessage: Type "text" carries Text, "thinking" carries Thinking, and any other type (upstream "toolCall") is an invisible boundary between thinking runs.

type AssistantMessage

type AssistantMessage struct {
	Content      []AssistantContentBlock
	StopReason   string
	ErrorMessage string
}

AssistantMessage is the message argument of upstream assistant-message.ts updateContent: the ordered content blocks and the terminal stop reason ("length", "aborted", "error", ...) with its error message. tui cannot import the ai package, so it owns this copy.

type AssistantMessageComponent

type AssistantMessageComponent struct {
	Container
	// contains filtered or unexported fields
}

AssistantMessageComponent renders ordered text/thinking content, terminal diagnostics, and OSC 133 zones for one assistant turn. Ports packages/coding-agent/src/modes/interactive/components/assistant-message.ts.

func NewAssistantMessageComponent

func NewAssistantMessageComponent(message *AssistantMessage, hideThinkingBlock bool, markdownTheme *MarkdownTheme, hiddenThinkingLabel string, outputPad *int, markdownTransformers []MarkdownTransformer) *AssistantMessageComponent

NewAssistantMessageComponent is upstream's constructor (assistant-message.ts:26-49): a block that renders message when it is non-nil, with the thinking blocks hidden when hideThinkingBlock is true (Ctrl+T). A nil markdownTheme is the active theme's (getMarkdownTheme()), an empty hiddenThinkingLabel is "Thinking...", and a nil outputPad is 1 (any given value is kept, as in assistant-message.ts; only the settings layer limits it to 0 or 1). markdownTransformers rewrite the text and the visible thinking of the block, in order, with the block's streaming flag (markdown-transform.ts createMarkdownTransform); a host with a live transformer list uses SetMarkdownTransform and SetThinkingMarkdownTransform instead.

func (*AssistantMessageComponent) Dispose

func (b *AssistantMessageComponent) Dispose()

Dispose releases this block's Markdown generations without allowing a late publication.

func (*AssistantMessageComponent) FinishStreaming

func (b *AssistantMessageComponent) FinishStreaming()

FinishStreaming tells the block that its message is complete: its Markdown drops the memos that only speed up the render of the next streamed delta. The rows are unchanged. A hidden thinking run shows its label, so its Markdown does not render again and drops them now (Markdown.FinishStreaming keeps them for an undrawn text's next render).

func (*AssistantMessageComponent) Invalidate

func (b *AssistantMessageComponent) Invalidate()

Invalidate rebuilds the content so theme-baked colors follow the active theme (assistant-message.ts invalidate).

func (*AssistantMessageComponent) IsDirty

func (i *AssistantMessageComponent) IsDirty() bool

func (*AssistantMessageComponent) IsStreaming

func (b *AssistantMessageComponent) IsStreaming() bool

IsStreaming reports the isStreaming flag of the last UpdateContent.

func (*AssistantMessageComponent) NeedsRedraw

func (i *AssistantMessageComponent) NeedsRedraw() bool

func (*AssistantMessageComponent) Render

func (b *AssistantMessageComponent) Render(width int) []string

Render adds the OSC 133 zone boundaries around non-tool-call messages. Empty content with no terminal diagnostic has no rows.

func (*AssistantMessageComponent) SetAsyncMarkdownTransforms

func (b *AssistantMessageComponent) SetAsyncMarkdownTransforms(text, thinking *AsyncMarkdownTransform)

SetAsyncMarkdownTransforms installs separately contextualized text and thinking rewrites. Each retained segment owns its replaceable worker generation.

func (*AssistantMessageComponent) SetContent

func (b *AssistantMessageComponent) SetContent(content []AssistantSegment)

SetContent replaces text/thinking content in message order for streaming or redraw. Blocks are trimmed, empty ones skipped, and consecutive thinking blocks form one run joined by a blank line. An empty text segment preserves an invisible boundary such as a tool call.

func (*AssistantMessageComponent) SetHasToolCalls

func (b *AssistantMessageComponent) SetHasToolCalls(v bool)

SetHasToolCalls records that the assistant message contains tool calls. When true, the abort/error section is suppressed: tool execution components show their own error state. Mirrors upstream assistant-message.ts:128: `if (!hasToolCalls) { ... }`.

func (*AssistantMessageComponent) SetHiddenThinkingLabel

func (b *AssistantMessageComponent) SetHiddenThinkingLabel(label string)

SetHiddenThinkingLabel sets the label that stands in for a hidden thinking run (assistant-message.ts setHiddenThinkingLabel).

func (*AssistantMessageComponent) SetHideThinkingBlock

func (b *AssistantMessageComponent) SetHideThinkingBlock(hidden bool)

SetHideThinkingBlock controls all thinking runs and clears individual click overrides (assistant-message.ts setHideThinkingBlock).

func (*AssistantMessageComponent) SetMarkdownTransform

func (b *AssistantMessageComponent) SetMarkdownTransform(fn func(markdown string, width int) string)

SetMarkdownTransform installs a display-only rewrite applied to the text section at its render width, before markdown parsing. Mirrors upstream MarkdownOptions.transform threaded through createMarkdownTransform in assistant-message.ts:112. Used for the built-in Mermaid transformer.

func (*AssistantMessageComponent) SetMarkdownTransformState

func (b *AssistantMessageComponent) SetMarkdownTransformState(fn func() string)

SetMarkdownTransformState declares the external state the installed transform reads, so a change to it re-renders instead of serving the cached lines. Required whenever the transform is not a pure function of (markdown, width).

func (*AssistantMessageComponent) SetOutputPad

func (b *AssistantMessageComponent) SetOutputPad(padding int)

SetOutputPad changes the horizontal content padding.

func (*AssistantMessageComponent) SetTerminalError

func (b *AssistantMessageComponent) SetTerminalError(stopReason, errorMessage string)

SetTerminalError records length/error/abort state after partial assistant content. An empty error message renders "Unknown error"; tool calls suppress abort/error but not length diagnostics.

func (*AssistantMessageComponent) SetTextDelta

func (b *AssistantMessageComponent) SetTextDelta(delta string)

SetTextDelta appends to the current text block, or starts one after thinking.

func (*AssistantMessageComponent) SetThinkingDelta

func (b *AssistantMessageComponent) SetThinkingDelta(delta string)

SetThinkingDelta appends to the current thinking block, or starts one after text.

func (*AssistantMessageComponent) SetThinkingMarkdownTransform

func (b *AssistantMessageComponent) SetThinkingMarkdownTransform(fn func(markdown string, width int) string)

SetThinkingMarkdownTransform installs the display-only rewrite for visible thinking, separate from the assistant-text transform context. Hidden thinking does not invoke it.

func (*AssistantMessageComponent) Text

Text returns concatenated untrimmed text blocks, without display transformations.

func (*AssistantMessageComponent) Thinking

func (b *AssistantMessageComponent) Thinking() string

Thinking returns the accumulated thinking content.

func (*AssistantMessageComponent) UpdateContent

func (b *AssistantMessageComponent) UpdateContent(message AssistantMessage, isStreaming ...bool)

UpdateContent renders message, upstream assistant-message.ts:91 updateContent(message, isStreaming = this.isStreaming): the text and thinking blocks in order, consecutive thinking blocks as one run, tool calls as invisible boundaries, and the length/aborted/error diagnostic after the content (suppressed for aborted/error when the message has tool calls). The optional isStreaming replaces the retained flag; IsStreaming reports it.

type AssistantSegment

type AssistantSegment struct {
	Thinking bool
	Text     string
}

AssistantSegment is one text or thinking content block of a complete assistant message, in message order.

type AsyncAutocompleteProvider

type AsyncAutocompleteProvider struct {
	TriggerCharacters           []string
	GetSuggestions              func(context.Context, []string, int, int, bool) (*AutocompleteSuggestions, error)
	ApplyCompletion             func(context.Context, []string, int, int, AutocompleteItem, string) ([]string, int, int, error)
	ShouldTriggerFileCompletion func(context.Context, []string, int, int) (bool, error)
}

AsyncAutocompleteProvider runs a complete provider chain off the editor loop. Provider columns are byte offsets; the native editor converts its UTF-16 positions at this boundary.

type AsyncFileSearcher

type AsyncFileSearcher interface {
	FileSearchTask(lines []string, cursorLine, cursorCol int) (prefix string, run func(context.Context) []AutocompleteItem, ok bool)
}

AsyncFileSearcher is an optional capability of the local autocomplete provider: it returns a deferred fd-backed @-file search that the editor runs off the input thread with cancellation. Mirrors upstream's async getFuzzyFileSuggestions (autocomplete.ts:717) so a deep directory walk cannot block keystrokes. When ok is false the editor falls back to the synchronous GetSuggestions result.

type AsyncMarkdownTransform

type AsyncMarkdownTransform struct {
	Context    context.Context
	Start      func(func())
	Invalidate func()
	Prepare    func(markdown string, width int) func(context.Context) string
	// Queue preserves render admission order across components belonging to one owner. A nil queue keeps work local to the component.
	Queue *MarkdownTransformQueue
}

AsyncMarkdownTransform prepares an owned, cancellable display rewrite. Prepare runs on the UI loop and snapshots mutable inputs; its returned function runs off-loop. Start joins that work at owner shutdown. Invalidate requests a paint without mutating UI state. pig additive (D19): subprocess callbacks execute outside the host render loop.

type AsyncSuggestionPlanner

type AsyncSuggestionPlanner interface {
	SuggestionTask([]string, int, int, bool) (string, func(context.Context) ([]AutocompleteItem, error), bool)
}

AsyncSuggestionPlanner captures the awaited branch of a local provider without executing that branch on the owner loop.

type AuthCheck

type AuthCheck interface {
	AuthCheckType() string
	AuthCheckSource() string
}

AuthCheck reports that a provider's auth is configured: its type ("oauth" or "api_key") and, when known, where it comes from (an ai.AuthCheck).

type AuthInfoLink struct{ URL, Label string }

AuthInfoLink is a provider-owned documentation link shown in a login dialog.

type AuthMethod

type AuthMethod interface {
	AuthMethodName() string
}

AuthMethod is an auth method of a provider option: an ai.APIKeyAuth or ai.OAuthAuth.

type AuthURL

type AuthURL struct {
	Container
	// contains filtered or unexported fields
}

AuthURL is a sign-in URL with a click hint and a copy hint. Hosts call AuthURL.Copy when `app.message.copy` is pressed, since a long URL wraps and often cannot be selected or clicked as a whole (SSH, tmux).

func NewAuthURL

func NewAuthURL(url string, copyText func(text string) error, requestRender func()) *AuthURL

NewAuthURL returns the component for url. copyText writes the system clipboard; requestRender repaints after a copy finishes. Either may be nil.

func (*AuthURL) Copy

func (a *AuthURL) Copy() <-chan struct{}

Copy copies the URL to the clipboard on an owned goroutine and shows the outcome in the hint, as upstream's unawaited `copy()`. The returned channel closes when the hint shows the outcome.

func (*AuthURL) Invalidate

func (i *AuthURL) Invalidate()

func (*AuthURL) IsDirty

func (i *AuthURL) IsDirty() bool

func (*AuthURL) Lines

func (a *AuthURL) Lines() []string

Lines returns the hyperlinked URL and the hint line, each indented by one column as upstream's Text(…, 1, 0).

func (*AuthURL) NeedsRedraw

func (i *AuthURL) NeedsRedraw() bool

func (*AuthURL) URL

func (a *AuthURL) URL() string

URL returns the sign-in URL.

type AutocompleteItem

type AutocompleteItem struct {
	Value       string // text inserted at cursor on accept
	Label       string // displayed primary text
	Description string // optional secondary text (dim)
}

AutocompleteItem is one popup row.

type AutocompleteProvider

type AutocompleteProvider interface {
	// GetSuggestions returns suggestions for the given buffer state.
	// Return nil when no popup should be shown (no match, wrong context).
	GetSuggestions(ctx context.Context, lines []string, cursorLine, cursorCol int, options AutocompleteSuggestionOptions) *AutocompleteSuggestions

	// ApplyCompletion edits the buffer to insert `item.Value` in place
	// of the trailing `prefix`. Returns the new buffer + cursor.
	ApplyCompletion(lines []string, cursorLine, cursorCol int, item AutocompleteItem, prefix string) (newLines []string, newLine, newCol int)
}

AutocompleteProvider supplies the local synchronous portion of a query. Deferred callbacks and filesystem searches are captured by AsyncSuggestionPlanner and AsyncFileSearcher; extension chains use AsyncAutocompleteProvider.

type AutocompleteSuggestionOptions

type AutocompleteSuggestionOptions struct {
	// Force is Tab completion with the popup closed: naked path completion is offered even when the prefix does not look path-like yet.
	Force bool
}

AutocompleteSuggestionOptions is the `{ signal, force }` options bag of upstream getSuggestions (autocomplete.ts:281); the signal is the context.

type AutocompleteSuggestions

type AutocompleteSuggestions struct {
	Items  []AutocompleteItem
	Prefix string
}

AutocompleteSuggestions is the provider return shape. Prefix is the buffer slice the popup is matching against: applyCompletion uses its length to know how many chars to replace.

type AutocompleteWork

type AutocompleteWork func(context.Context) (func(), error)

AutocompleteWork runs off-loop and returns a mutation to execute on the owner loop. The host holds subsequent input while input work is pending.

type BaseComponent

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

BaseComponent is the exported equivalent of invalidatable for components living in other packages.

func (*BaseComponent) Invalidate

func (i *BaseComponent) Invalidate()

func (*BaseComponent) IsDirty

func (i *BaseComponent) IsDirty() bool

func (*BaseComponent) NeedsRedraw

func (i *BaseComponent) NeedsRedraw() bool

type BashExecutionComponent

type BashExecutionComponent struct {
	Container
	// contains filtered or unexported fields
}

BashExecutionComponent displays a `!cmd` invocation with streaming output, top/bottom borders, and expand/collapse support.

func NewBashExecutionComponent

func NewBashExecutionComponent(command string, ui TUI, excludeFromContext bool, outputPad int) *BashExecutionComponent

NewBashExecutionComponent returns a freshly-constructed bash-execution component in the running state (bash-execution.ts constructor(command, ui, excludeFromContext = false, outputPad = 1)). ui is the TUI the running Loader asks for a render after each spinner change; nil asks for none.

func (*BashExecutionComponent) AppendOutput

func (b *BashExecutionComponent) AppendOutput(chunk string)

AppendOutput streams a chunk into the block. It strips ANSI codes and normalizes line endings first (bash-execution.ts:appendOutput), so output that bypassed the bash executor, such as a user_bash extension result, renders the same. Text the executor already cleaned passes through without a copy.

func (*BashExecutionComponent) ContextOutput

func (b *BashExecutionComponent) ContextOutput() string

ContextOutput is Pi's truncateTail(getOutput(), { maxLines: DEFAULT_MAX_LINES, maxBytes: DEFAULT_MAX_BYTES }).content: the output the block draws (bash-execution.ts updateDisplay). Pi's getOutput returns the whole stream; the block keeps only this window (D176).

func (*BashExecutionComponent) GetCommand

func (b *BashExecutionComponent) GetCommand() string

GetCommand returns the command that was executed (bash-execution.ts:getCommand).

func (*BashExecutionComponent) Invalidate

func (b *BashExecutionComponent) Invalidate()

Invalidate rebuilds the content so theme-baked colors follow the active theme (bash-execution.ts invalidate).

func (*BashExecutionComponent) IsDirty

func (b *BashExecutionComponent) IsDirty() bool

IsDirty reports whether the block needs re-rendering. While running it embeds an animated Loader spinner advanced by the 100ms tick loop, but the tick ticks the loader without Invalidating this block. Reporting dirty while running keeps the per-child render cache from freezing the spinner.

func (*BashExecutionComponent) Loader

func (b *BashExecutionComponent) Loader() *Loader

Loader returns the embedded spinner when the block is still running, nil otherwise. The animation driver ticks it to advance the spinner.

func (*BashExecutionComponent) NeedsRedraw

func (i *BashExecutionComponent) NeedsRedraw() bool

func (*BashExecutionComponent) Render

func (b *BashExecutionComponent) Render(width int) []string

Render rebuilds the content when it changed, then renders the children. Commands and output wrap to the current terminal width, and collapsed previews retain the last previewLines visual rows.

func (*BashExecutionComponent) SetComplete

func (b *BashExecutionComponent) SetComplete(exitCode *int, cancelled bool, truncationResult *TruncationResult, fullOutputPath string)

SetComplete transitions the block out of the running state (bash-execution.ts setComplete(exitCode, cancelled, truncationResult?, fullOutputPath?)). A non-nil truncationResult with Truncated set marks the output as truncated; fullOutputPath is the file holding the untruncated output and, with a truncated result, adds the "Output truncated. Full output: <path>" row. The output already streamed into the block is kept; SetCompleteWithOutput replaces it with the durable output.

func (*BashExecutionComponent) SetCompleteWithOutput

func (b *BashExecutionComponent) SetCompleteWithOutput(exitCode *int, cancelled, truncated bool, output, fullOutputPath string)

SetCompleteWithOutput replaces the streaming preview with the durable truncated output and records its full-output path before completing the block.

func (*BashExecutionComponent) SetExpanded

func (b *BashExecutionComponent) SetExpanded(expanded bool)

SetExpanded forces the body open (true) or collapsed-to-preview (false). Driven by the global Ctrl+O toggle so all bash blocks land in the same state as their tool-execution peers.

func (*BashExecutionComponent) SetOutputPad

func (b *BashExecutionComponent) SetOutputPad(outputPad int)

SetOutputPad is Pi's setOutputPad(outputPad): the padding of the command header, output and status rows, rebuilt at once (bash-execution.ts:73).

func (*BashExecutionComponent) SurfaceLive

func (b *BashExecutionComponent) SurfaceLive() bool

pig additive (D91): SurfaceLive reports that the spinner, which ticks without invalidating the block, draws in it.

type BorderedLoader

type BorderedLoader struct {
	*Container

	// OnAbort is called after the cancellable loader is aborted; ignored for a
	// non-cancellable loader (upstream `set onAbort`).
	OnAbort func()
	// contains filtered or unexported fields
}

BorderedLoader extends Container (upstream BorderedLoader extends Container): its children are a border, the loader, an optional cancel hint and a border.

func NewBorderedLoader

func NewBorderedLoader(ui TUI, theme *Theme, message string, options ...BorderedLoaderOptions) *BorderedLoader

NewBorderedLoader is bordered-loader.ts constructor(tui, theme, message, options?): the loader asks ui to render on every frame and takes its colours from theme. Unless options set Cancellable to false, an Esc cancel hint is shown and HandleInput cancels on Esc. The theme is required, as in Pi.

func (*BorderedLoader) CancellableContext

func (bl *BorderedLoader) CancellableContext() *CancellableLoader

CancellableContext returns the cancellable loader's context, or nil.

func (*BorderedLoader) Dispose

func (bl *BorderedLoader) Dispose()

Dispose is upstream dispose() (bordered-loader.ts:61): a CancellableLoader is disposed, a plain Loader is stopped.

func (*BorderedLoader) HandleInput

func (bl *BorderedLoader) HandleInput(data string)

HandleInput delegates to the cancellable loader if present.

func (BorderedLoader) Invalidate

func (i BorderedLoader) Invalidate()

func (BorderedLoader) IsDirty

func (i BorderedLoader) IsDirty() bool

func (*BorderedLoader) Loader

func (bl *BorderedLoader) Loader() *Loader

Loader returns the loader the bordered loader draws.

func (BorderedLoader) NeedsRedraw

func (i BorderedLoader) NeedsRedraw() bool

func (*BorderedLoader) NextFrame

func (bl *BorderedLoader) NextFrame()

NextFrame advances the spinner animation.

type BorderedLoaderOptions

type BorderedLoaderOptions struct{ Cancellable *bool }

BorderedLoaderOptions is upstream's `{ cancellable?: boolean }`: a nil Cancellable is cancellable.

type Box

type Box struct {
	PaddingX int
	PaddingY int
	BgFn     func(string) string
	// contains filtered or unexported fields
}

Box component - a container that applies padding and background to children.

func NewBox

func NewBox() *Box

func NewPaddedBox

func NewPaddedBox(paddingX, paddingY int, bgFn func(string) string) *Box

func (*Box) AddChild

func (b *Box) AddChild(component Component)

AddChild, RemoveChild and Clear drop the render cache and mark the box dirty; they do not invalidate the children (box.ts addChild, removeChild, clear call only invalidateCache).

func (*Box) Clear

func (b *Box) Clear()

func (*Box) HandleMouse

func (b *Box) HandleMouse(event TuiMouseEvent) *TuiMouseDispatchResult

HandleMouse forwards an event inside the padded content area to the child under the pointer. Mirrors upstream Box.handleMouse.

func (*Box) Invalidate

func (b *Box) Invalidate()

func (*Box) IsDirty

func (i *Box) IsDirty() bool

func (*Box) NeedsRedraw

func (i *Box) NeedsRedraw() bool

func (*Box) RemoveChild

func (b *Box) RemoveChild(component Component)

func (*Box) Render

func (b *Box) Render(width int) []string

func (*Box) SetBgFn

func (b *Box) SetBgFn(bgFn func(string) string)

func (*Box) SetPaddingX

func (b *Box) SetPaddingX(paddingX int)

SetPaddingX sets the horizontal padding and drops the render cache (box.ts setPaddingX).

type BranchSummaryMessage

type BranchSummaryMessage struct {
	Summary string
}

BranchSummaryMessage is the part of Pi's BranchSummaryMessage (coding-agent core/messages.ts:55) that BranchSummaryMessageComponent renders: the LLM-generated markdown summarising the abandoned branch.

type BranchSummaryMessageComponent

type BranchSummaryMessageComponent struct {
	*Box
	// contains filtered or unexported fields
}

BranchSummaryMessageComponent renders a branch-summary boundary marker in the chat transcript. Like upstream's `extends Box`, it embeds the Box (padding 1, 1 and the customMessageBg background), so the Box members are inherited; each display update clears the Box and adds one mouse region.

upstream: packages/coding-agent/src/modes/interactive/components/branch-summary-message.ts

func NewBranchSummaryMessageComponent

func NewBranchSummaryMessageComponent(message BranchSummaryMessage, markdownTheme *MarkdownTheme, outputPad int) *BranchSummaryMessageComponent

NewBranchSummaryMessageComponent is Pi's constructor(message, markdownTheme = getMarkdownTheme(), outputPad = 1) (branch-summary-message.ts:15). The expanded body renders the summary with markdownTheme (nil selects the active theme's markdown theme) and the Box pads its rows by outputPad columns.

func (*BranchSummaryMessageComponent) Expanded

func (c *BranchSummaryMessageComponent) Expanded() bool

Expanded reports the component's expanded state, which a click toggles.

func (*BranchSummaryMessageComponent) Invalidate

func (c *BranchSummaryMessageComponent) Invalidate()

Invalidate invalidates the Box and rebuilds the display, which bakes theme colors into its text.

func (BranchSummaryMessageComponent) IsDirty

func (i BranchSummaryMessageComponent) IsDirty() bool

func (BranchSummaryMessageComponent) NeedsRedraw

func (i BranchSummaryMessageComponent) NeedsRedraw() bool

func (*BranchSummaryMessageComponent) SetExpanded

func (c *BranchSummaryMessageComponent) SetExpanded(expanded bool)

SetExpanded opens or collapses the component body. InteractiveMode calls it from the global Ctrl+O toggle.

func (*BranchSummaryMessageComponent) SetOutputPad

func (c *BranchSummaryMessageComponent) SetOutputPad(outputPad int)

SetOutputPad is Pi's setOutputPad(outputPad): the horizontal padding of the Box is the outputPad setting.

type CancellableLoader

type CancellableLoader struct {
	Loader

	OnAbort func()
	// contains filtered or unexported fields
}

CancellableLoader extends Loader with Esc-key cancellation.

func NewCancellableLoader

func NewCancellableLoader(ui TUI, spinnerColorFn, messageColorFn func(string) string, message string, indicator *LoaderIndicatorOptions) *CancellableLoader

NewCancellableLoader is `new CancellableLoader(ui, spinnerColorFn, messageColorFn, message, indicator)` (components/cancellable-loader.ts, which inherits Loader's constructor).

func (*CancellableLoader) Aborted

func (cl *CancellableLoader) Aborted() bool

Aborted returns true if cancelled.

func (*CancellableLoader) Context

func (cl *CancellableLoader) Context() context.Context

Context returns the cancellation context.

func (*CancellableLoader) Dispose

func (cl *CancellableLoader) Dispose()

Dispose is upstream dispose() (cancellable-loader.ts:37): it stops the animation timer. The abort state and OnAbort are untouched.

func (*CancellableLoader) HandleInput

func (cl *CancellableLoader) HandleInput(data string)

HandleInput cancels on the registry-bound tui.select.cancel key.

func (*CancellableLoader) IsDirty

func (i *CancellableLoader) IsDirty() bool

func (*CancellableLoader) NeedsRedraw

func (i *CancellableLoader) NeedsRedraw() bool

func (*CancellableLoader) Signal

func (cl *CancellableLoader) Signal() context.Context

Signal returns the underlying cancellation context.

type CapabilityOverrides

type CapabilityOverrides struct {
	Images     *ImageProtocol
	TrueColor  *bool
	Hyperlinks *bool
}

CapabilityOverrides mirrors upstream Partial<TerminalCapabilities> as passed to setCapabilityOverrides. A nil field is absent. Images points at "" for upstream's null (no image protocol).

type CellDimensions

type CellDimensions struct {
	WidthPx  int
	HeightPx int
}

func GetCellDimensions

func GetCellDimensions() CellDimensions

type Clickable

type Clickable interface {
	// ClickArea reports the cells of the lines last rendered that take a
	// click, and false when none do.
	ClickArea() (frontend.Area, bool)
}

Clickable is a component that takes a click on part of the lines it draws, which a TuiSurface reports as its node's Click area.

type Color

type Color interface {

	// Kind is upstream's `kind` discriminator: "indexed", "rgb" or "oklch" (colors.ts:5,10,17).
	Kind() string
	// contains filtered or unexported methods
}

Color is a concrete color: IndexedColor, RgbColorValue, or OklchColorValue. Every Color converts to sRGB, so color math never fails. Upstream's `Color` union is closed; the unexported method seals it.

func MixColors

func MixColors(first, second Color, amount float64, space ColorMixSpace) (Color, error)

MixColors interpolates two colors; upstream defaults `space` to oklch, so pass ColorMixSpaceOklch for the default.

func ParseColor

func ParseColor[T ColorValue](value T) (Color, error)

ParseColor mirrors `parseColor`. A number is an ANSI palette index and must be an integer from 0 to 255; a string is `#rgb`, `#rrggbb`, `oklch()`, or `okhsl()`.

type ColorMixSpace

type ColorMixSpace string

ColorMixSpace selects the space MixColors interpolates in.

const (
	ColorMixSpaceOklch ColorMixSpace = "oklch"
	ColorMixSpaceSrgb  ColorMixSpace = "srgb"
)

type ColorMode deprecated

type ColorMode = TerminalColorMode

ColorMode is the terminal color mode a theme resolves its colors for.

Deprecated: use TerminalColorMode; upstream unified the theme and terminal color modes.

type ColorValue

type ColorValue interface {
	string | int | float64
}

ColorValue is upstream's `string | number` parseColor argument.

type CombinedProvider

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

CombinedProvider handles both slash-command and @-file autocomplete. Mirrors upstream CombinedAutocompleteProvider (autocomplete.ts:238).

func NewCombinedProvider

func NewCombinedProvider(cmds []SlashCommand, baseDir, fdPath string) *CombinedProvider

NewCombinedProvider creates a provider for slash commands, attachment search, and direct paths. An empty fdPath disables attachment suggestions without affecting direct path completion.

func (*CombinedProvider) ApplyCompletion

func (p *CombinedProvider) ApplyCompletion(lines []string, cursorLine, cursorCol int, item AutocompleteItem, prefix string) ([]string, int, int)

ApplyCompletion preserves path prefixes and surrounding text, consumes an existing closing quote, and leaves directory cursors inside quotes. Only slash commands and file attachments append a space.

func (*CombinedProvider) FileSearchTask

func (p *CombinedProvider) FileSearchTask(lines []string, cursorLine, cursorCol int) (string, func(context.Context) []AutocompleteItem, bool)

FileSearchTask returns a deferred, cancellable fd-backed @-file search for the cursor's @-prefix, or ok=false when async file search is disabled, fd is unavailable, or the buffer-before-cursor is not an @ query. The returned run closure executes fd under the caller's context so the editor can abort it on the next keystroke, mirroring upstream's async getFuzzyFileSuggestions + AbortSignal (autocomplete.ts:717).

func (*CombinedProvider) GetSuggestions

func (p *CombinedProvider) GetSuggestions(ctx context.Context, lines []string, cursorLine, cursorCol int, options AutocompleteSuggestionOptions) *AutocompleteSuggestions

GetSuggestions implements upstream command, attachment and path matching. The Editor decides which contexts trigger queries automatically.

options.Force is upstream's {force: true}: Tab outside a slash-command-name context forces naked path completion even when the prefix does not look path-like yet. The signal is ctx; the file search that honors it runs through FileSearchTask.

func (*CombinedProvider) SetAsyncFileSearch

func (p *CombinedProvider) SetAsyncFileSearch(v bool)

SetAsyncFileSearch enables deferred, cancellable fd-backed @-file search. Interactive mode enables this so a slow tree walk cannot block keystrokes.

func (*CombinedProvider) ShouldTriggerFileCompletion

func (p *CombinedProvider) ShouldTriggerFileCompletion(lines []string, cursorLine, cursorCol int) bool

ShouldTriggerFileCompletion reports whether Tab may force file completion at the cursor: it may not while the text before the cursor is a slash-command name (a trimmed leading "/" with no space), where the command list answers instead (upstream autocomplete.ts shouldTriggerFileCompletion). cursorCol is a byte offset into the line.

func (*CombinedProvider) SuggestionTask

func (p *CombinedProvider) SuggestionTask(lines []string, line, col int, force bool) (string, func(context.Context) ([]AutocompleteItem, error), bool)

SuggestionTask defers filesystem access and awaited command arguments while preserving the combined provider's branch precedence.

type CompactReadClassification

type CompactReadClassification struct {
	Kind  string // "docs", "resource" or "skill"
	Label string
}

CompactReadClassification is upstream read.ts CompactReadClassification: a read of a skill file, the agent's own docs, or a context file draws a short label while the card is collapsed.

type CompactionSummaryMessage

type CompactionSummaryMessage struct {
	Summary      string
	TokensBefore int
}

CompactionSummaryMessage is the part of Pi's CompactionSummaryMessage (coding-agent core/messages.ts:62) that CompactionSummaryMessageComponent renders: the summary markdown and the context token count before compaction.

type CompactionSummaryMessageComponent

type CompactionSummaryMessageComponent struct {
	*Box
	// contains filtered or unexported fields
}

CompactionSummaryMessageComponent renders a collapsible compaction marker. Like upstream's `extends Box`, it embeds the Box (padding 1, 1 and the customMessageBg background), so the Box members are inherited; each display update clears the Box and adds one mouse region.

upstream: packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts

func NewCompactionSummaryMessageComponent

func NewCompactionSummaryMessageComponent(message CompactionSummaryMessage, markdownTheme *MarkdownTheme, outputPad ...int) *CompactionSummaryMessageComponent

NewCompactionSummaryMessageComponent is Pi's constructor(message, markdownTheme = getMarkdownTheme(), outputPad = 1) (compaction-summary-message.ts:15). The expanded body renders the summary with markdownTheme; nil selects the active theme's markdown theme. outputPad is the horizontal padding; absent it is 1.

func (*CompactionSummaryMessageComponent) Expanded

Expanded reports the component's expanded state, which a click toggles.

func (*CompactionSummaryMessageComponent) Invalidate

func (c *CompactionSummaryMessageComponent) Invalidate()

Invalidate invalidates the Box and rebuilds the display, which bakes theme colors into its text.

func (CompactionSummaryMessageComponent) IsDirty

func (i CompactionSummaryMessageComponent) IsDirty() bool

func (CompactionSummaryMessageComponent) NeedsRedraw

func (i CompactionSummaryMessageComponent) NeedsRedraw() bool

func (*CompactionSummaryMessageComponent) SetExpanded

func (c *CompactionSummaryMessageComponent) SetExpanded(expanded bool)

SetExpanded opens or collapses the component body. InteractiveMode calls it from the global Ctrl+O toggle.

func (*CompactionSummaryMessageComponent) SetOutputPad

func (c *CompactionSummaryMessageComponent) SetOutputPad(outputPad int)

SetOutputPad is Pi's setOutputPad(outputPad): the horizontal padding of the Box is the outputPad setting.

type Component

type Component interface {
	Render(width int) []string
	// Invalidate marks the component as needing a redraw on the next tick.
	Invalidate()
}

Component is the base interface all TUI widgets implement. Render returns a slice of ANSI-annotated lines (no trailing newlines). Width is the available terminal columns.

type ConfigSelectorComponent

type ConfigSelectorComponent struct {
	Container

	OnCancel   func()
	OnExit     func()
	OnToggle   func(item *ResourceItem, enabled bool)
	OnOverride func(item *ResourceItem, state string) error
	// contains filtered or unexported fields
}

ConfigSelectorComponent manages the resource configuration overlay.

func NewConfigSelector

func NewConfigSelector(groups []*ResourceGroup, terminalRows int) *ConfigSelectorComponent

NewConfigSelector creates a config selector from resolved resource groups.

func NewScopedConfigSelector

func NewScopedConfigSelector(global, project []*ResourceGroup, terminalRows int, writeScope string, projectModeAvailable bool) *ConfigSelectorComponent

NewScopedConfigSelector creates the global/project selector used by pig config.

func (*ConfigSelectorComponent) CapturesSelectPageInput

func (cs *ConfigSelectorComponent) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the selector handles tui.select.pageUp and tui.select.pageDown.

func (*ConfigSelectorComponent) HandleInput

func (cs *ConfigSelectorComponent) HandleInput(data string)

HandleInput processes keyboard input.

func (*ConfigSelectorComponent) Invalidate

func (i *ConfigSelectorComponent) Invalidate()

func (*ConfigSelectorComponent) IsDirty

func (i *ConfigSelectorComponent) IsDirty() bool

func (*ConfigSelectorComponent) NeedsRedraw

func (i *ConfigSelectorComponent) NeedsRedraw() bool

func (*ConfigSelectorComponent) SetTerminalRows

func (cs *ConfigSelectorComponent) SetTerminalRows(rows int)

SetTerminalRows updates the selector's view budget to track terminal height.

type Container

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

Container stacks child components vertically.

func NewContainer

func NewContainer(children ...Component) *Container

func (*Container) Add

func (c *Container) Add(comp Component)

func (*Container) AddChild

func (c *Container) AddChild(comp Component)

AddChild appends a child. upstream: packages/tui/src/tui.ts:351 Container.addChild

func (*Container) CapturesSelectPageInput

func (c *Container) CapturesSelectPageInput() bool

CapturesSelectPageInput reports whether any child captures selection page keys, as Pi's Container does.

func (*Container) ChildCount

func (c *Container) ChildCount() int

func (*Container) Children

func (c *Container) Children() []Component

Children returns a snapshot of the mounted child identities in insertion order. Callers can invoke child methods without holding the container lock. upstream: packages/tui/src/tui.ts:Container

func (*Container) Clear

func (c *Container) Clear()

Clear removes every child component. Used by /clear and /new.

func (*Container) HandleMouse

func (c *Container) HandleMouse(event TuiMouseEvent) *TuiMouseDispatchResult

HandleMouse forwards an event to the child under the pointer. Mirrors upstream Container.handleMouse. Upstream also rewrites a focus result's focusTarget to the container when a Container subclass handles keyboard input; Go embedding has no subclass identity, so a type that embeds Container and handles input must override HandleMouse to do the same.

func (*Container) InsertBefore

func (c *Container) InsertBefore(ref, comp Component) bool

InsertBefore adds comp immediately before ref and reports whether ref was a child. Pi splices into Container.children for this (interactive-mode.ts:3836-3839).

func (*Container) Invalidate

func (i *Container) Invalidate()

func (*Container) IsDirty

func (i *Container) IsDirty() bool

func (*Container) IsEmpty

func (c *Container) IsEmpty() bool

IsEmpty reports whether the container currently has no children.

func (*Container) LastTwoChildren

func (c *Container) LastTwoChildren() (Component, Component)

func (*Container) NeedsRedraw

func (i *Container) NeedsRedraw() bool

func (*Container) Remove

func (c *Container) Remove(comp Component)

func (*Container) RemoveChild

func (c *Container) RemoveChild(comp Component)

RemoveChild removes the first child identical to comp and ignores an absent one. upstream: packages/tui/src/tui.ts:355 Container.removeChild

func (*Container) Render

func (c *Container) Render(width int) []string

Render returns a fresh slice, matching upstream Container.render's observable array ownership. It builds into a new array and copies it under the lock, so a call on another goroutine neither writes into nor reads an array that a parent container or the renderer borrowed. Package renderers use renderBorrowed to read the immutable cached concatenation without copying settled transcript history every frame.

func (*Container) Replace

func (c *Container) Replace(oldComp, newComp Component) bool

Replace swaps oldComp with newComp at the same child index. Returns true if oldComp was found.

func (*Container) SetChildren

func (c *Container) SetChildren(children ...Component)

SetChildren atomically replaces all children. The children it keeps at the start and the end keep their cached lines, which their dirty flags invalidate as for any child, so replacing a few children renders only those again.

func (*Container) SetMaxLines

func (c *Container) SetMaxLines(n int)

SetMaxLines caps how many lines Render() returns. When n>0, only the last n lines of all children's output are returned. When n==0 (default), all lines are returned. Used by the /tree selector to keep the chat scrolled to a minimum context window. pig-specific: upstream controls the full viewport; this cap is not needed there.

type ConvertedImage

type ConvertedImage struct {
	Data     string
	MimeType string
}

ConvertedImage is a base64 image and its MIME type, the result of upstream image-convert.ts convertToPng.

type CountdownTimer

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

CountdownTimer counts down from a duration, calling OnTick each second and OnExpire when it reaches zero.

func NewCountdownTimer

func NewCountdownTimer(timeout time.Duration, dispatch func(func()), onTick func(int), onExpire func()) *CountdownTimer

NewCountdownTimer creates a timer. It calls onTick immediately with the initial seconds value, then starts a 1-second ticker.

Upstream's interval callback runs on the event loop that owns the dialog, so dispatch runs each second's decrement, onTick and expiry together on the owner loop. A nil dispatch runs them on the ticker goroutine. Dispose stops every later second, including one already dispatched.

func (*CountdownTimer) Dispose

func (ct *CountdownTimer) Dispose()

Dispose stops the timer.

type CustomMessage

type CustomMessage struct {
	CustomType string
	Content    any // string or []ContentBlock
}

CustomMessage holds the data for a custom message entry. Mirrors the upstream CustomMessage<T> shape.

type CustomMessageComponent

type CustomMessageComponent struct {
	Container
	// contains filtered or unexported fields
}

CustomMessageComponent renders a custom message entry from extensions with distinct styling. Mirrors upstream CustomMessageComponent extends Container (custom-message.ts:13).

func NewCustomMessageComponent

func NewCustomMessageComponent(message *CustomMessage, customRenderer MessageRenderer, markdownTheme *MarkdownTheme, outputPad int) *CustomMessageComponent

NewCustomMessageComponent mirrors the upstream constructor (custom-message.ts:23): customRenderer may be nil, a nil markdownTheme selects the active theme's, and outputPad is the horizontal padding handed to customRenderer (upstream default 1).

func (*CustomMessageComponent) Expanded

func (c *CustomMessageComponent) Expanded() bool

Expanded reports the component's expanded state (upstream _expanded).

func (*CustomMessageComponent) Invalidate

func (c *CustomMessageComponent) Invalidate()

Invalidate rebuilds the content, so a theme change reaches the box colors (custom-message.ts:55).

func (*CustomMessageComponent) IsDirty

func (c *CustomMessageComponent) IsDirty() bool

IsDirty reports a renderer component whose output changed on its own (an extension renderer proxy whose lines arrive after the first frame), so the parent container that caches this component re-renders it.

func (*CustomMessageComponent) NeedsRedraw

func (i *CustomMessageComponent) NeedsRedraw() bool

func (*CustomMessageComponent) SetExpanded

func (c *CustomMessageComponent) SetExpanded(expanded bool)

SetExpanded rebuilds the content when the expansion state changes (custom-message.ts:41).

func (*CustomMessageComponent) SetOutputPad

func (c *CustomMessageComponent) SetOutputPad(outputPad int)

SetOutputPad rebuilds the content when the padding changes (custom-message.ts:48).

func (*CustomMessageComponent) SurfaceLive

func (c *CustomMessageComponent) SurfaceLive() bool

pig additive (D91): SurfaceLive reports a renderer component that changes on its own, which IsDirty reads, so a TuiSurface rebuilds the message every frame.

type DefaultModelReference

type DefaultModelReference struct {
	Provider string
	ID       string
}

DefaultModelReference names the default model (model-selector.ts DefaultModelReference).

type DefaultTextStyle

type DefaultTextStyle struct {
	Color, BgColor                         func(string) string
	Bold, Italic, Strikethrough, Underline bool
}

DefaultTextStyle decorates ordinary Markdown text; background is applied after layout and padding.

type DiffComponent

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

DiffComponent renders a diff string as colored output. It wraps RenderDiff from diff_render.go into the Component interface.

func NewDiffComponent

func NewDiffComponent(diffText, filePath string) *DiffComponent

NewDiffComponent creates a diff display component.

func (*DiffComponent) Invalidate

func (i *DiffComponent) Invalidate()

func (*DiffComponent) IsDirty

func (i *DiffComponent) IsDirty() bool

func (*DiffComponent) NeedsRedraw

func (i *DiffComponent) NeedsRedraw() bool

func (*DiffComponent) Render

func (d *DiffComponent) Render(width int) []string

Render produces colored diff lines.

func (*DiffComponent) SetDiff

func (d *DiffComponent) SetDiff(text string)

SetDiff updates the diff text.

type Disposable

type Disposable interface {
	Dispose()
}

Disposable is implemented by components that need cleanup.

type DynamicBorder

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

DynamicBorder renders a full-width horizontal rule using "─".

func NewDynamicBorder

func NewDynamicBorder(color ...func(string) string) *DynamicBorder

NewDynamicBorder creates a border drawn through color, which styles the whole rule. Without a color function the rule uses the active theme's border color, read at render time.

func NewDynamicBorderToken

func NewDynamicBorderToken(token string) *DynamicBorder

NewDynamicBorderToken creates a border colored with a theme token at render time (dynamic-border.ts takes a `(str) => theme.fg(token, str)` callback), so it follows theme changes.

func (*DynamicBorder) Invalidate

func (i *DynamicBorder) Invalidate()

func (*DynamicBorder) IsDirty

func (i *DynamicBorder) IsDirty() bool

func (*DynamicBorder) NeedsRedraw

func (i *DynamicBorder) NeedsRedraw() bool

func (*DynamicBorder) Render

func (d *DynamicBorder) Render(width int) []string

Render produces a full-width rule styled by the border's color function.

type Editor

type Editor struct {

	// EmbedWorkingStatus opts into the coding-agent status border.
	EmbedWorkingStatus bool

	// BorderColor colors a complete border after layout and truncation. Nil selects the application-derived default.
	BorderColor func(string) string
	// Focused emits widthx.CursorMarker so the TUI can position the hardware cursor for IME candidate windows.
	Focused bool

	// Thinking-level border color.
	// Mirrors upstream `editor.ts::updateEditorBorderColor` which maps
	// the thinking level to a per-level theme color. "off" uses borderMuted.
	// Bash mode overrides this (bashHeaderColor takes precedence).
	ThinkingLevel string // "off" | "low" | "medium" | "high"

	// Mirrors upstream editor.ts public hooks / flags.
	OnSubmit      func(string)
	OnChange      func(string)
	DisableSubmit bool
	// contains filtered or unexported fields
}

Editor is a multi-line text input with undo/kill-ring support.

func NewEditor

func NewEditor(options ...EditorOption) *Editor

func NewEditorWithTUI

func NewEditorWithTUI(ui TUI, theme EditorTheme, options EditorOptions) *Editor

NewEditorWithTUI is editor.ts constructor(tui, theme, options): the editor owns ui, asks it to render after a padding, autocomplete-limit or autocomplete-result change, and derives its visible line count and page size from the terminal rows (max(5, floor(rows * 0.3)); editor.ts:536, :1962). A zero theme follows the active theme live. NewEditor is the host-driven form: the host sets SetMaxVisibleLines and renders itself.

func (*Editor) AcceptAutocomplete

func (e *Editor) AcceptAutocomplete(done func(bool))

AcceptAutocomplete reports whether an accepted slash-name completion submits. Remote completion waits off-loop and calls done only after applying on the owner loop.

func (*Editor) AddToHistory

func (e *Editor) AddToHistory(text string)

AddToHistory trims JavaScript whitespace and adds a submitted prompt for Up/Down navigation. It skips empty strings and consecutive duplicates and retains at most 100 entries.

func (*Editor) ApplyBorderColor

func (e *Editor) ApplyBorderColor(text string) string

ApplyBorderColor is Pi's `this.borderColor(text)`: the editor's border color function applied to text, which without one is the color of its thinking level, of bash mode, or the default border. A custom component calls it to color its own border rows.

func (*Editor) ApplyEdit

func (e *Editor) ApplyEdit(from, to int, text string, cursor int)

ApplyEdit replaces the UTF-16 code units [from, to) of Text with text as one undo step, then puts the cursor at the UTF-16 offset cursor of the result. Offsets are clamped to the text. An edit that leaves the text as it was only moves the cursor. Inserted text is normalized as typed text is, and a cursor after the insertion moves with any change in its length.

func (*Editor) ApplyRemoteChange

func (e *Editor) ApplyRemoteChange(text, expanded string)

ApplyRemoteChange mirrors the remote's text (its onChange) and the same text with paste markers expanded.

func (*Editor) AsBase

func (e *Editor) AsBase(fn func())

AsBase runs fn with the editor's own editing, rendering and completion state in place of the remote's, which is Pi's `super` call from a CustomEditor subclass. It runs on the owner loop and does not nest.

func (*Editor) AutocompleteAccept

func (e *Editor) AutocompleteAccept() (submit bool)

AutocompleteAccept applies the currently-selected suggestion. Returns submit=true iff the host should now submit the editor (mirrors upstream editor.ts:644: Enter on a slash-name prefix inserts and falls through to submit).

func (*Editor) AutocompleteCancel

func (e *Editor) AutocompleteCancel()

AutocompleteCancel dismisses the popup without applying.

func (*Editor) AutocompleteMaxVisible

func (e *Editor) AutocompleteMaxVisible() int

func (*Editor) AutocompleteMove

func (e *Editor) AutocompleteMove(delta int)

AutocompleteMove moves the selection with keyboard-style wraparound. Mouse callers clamp their target before invoking it.

func (*Editor) AutocompleteOpen

func (e *Editor) AutocompleteOpen() bool

AutocompleteOpen reports whether the popup is currently visible. Used by the host (interactive.go) to gate Esc/Enter handling.

func (*Editor) AutocompleteProvider

func (e *Editor) AutocompleteProvider() AutocompleteProvider

AutocompleteProvider returns the local base captured by extension wrapper factories.

func (*Editor) CapturesSelectPageInput

func (e *Editor) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the editor handles tui.select.pageUp and tui.select.pageDown while its autocomplete list is open.

func (*Editor) Clear

func (e *Editor) Clear()

Clear resets the editor.

func (*Editor) ClearPastes

func (e *Editor) ClearPastes()

ClearPastes drops the compact-paste store. Callers that consume the editor's text via GetExpandedText (e.g. submit) should call this after expanding so subsequent edits don't re-expand stale markers. Mirrors upstream submitValue() resetting pastes + pasteCounter.

func (*Editor) GetCursor

func (e *Editor) GetCursor() EditorCursor

GetCursor returns the logical cursor position in JavaScript string units.

func (*Editor) GetExpandedText

func (e *Editor) GetExpandedText() string

GetExpandedText returns the editor content with any compact paste markers (`[paste #N +K lines]` / `[paste #N M chars]`) expanded back to their stored content. Mirrors upstream editor.ts::getExpandedText (.upstream/v0.69.0/packages/tui/src/components/editor.ts:929).

func (*Editor) GetLines

func (e *Editor) GetLines() []string

GetLines returns a defensive copy of the editor's logical lines.

func (*Editor) HandleInput

func (e *Editor) HandleInput(data string)

func (*Editor) HandleMouse

func (e *Editor) HandleMouse(event TuiMouseEvent) *TuiMouseEventResult

HandleMouse activates autocomplete rows and positions the editor cursor on a synthesized left click. Press, drag, and release remain unhandled so the alternate-screen renderer can own text selection. Mirrors upstream Editor.handleMouse. Autocomplete clicks retain the pressed item across scrolling.

func (*Editor) InsertTextAtCursor

func (e *Editor) InsertTextAtCursor(text string)

InsertTextAtCursor inserts normalized single- or multi-line text as one undoable edit.

func (*Editor) Invalidate

func (i *Editor) Invalidate()

func (*Editor) IsBashMode

func (e *Editor) IsBashMode() bool

IsBashMode reports whether the buffer is in bash-prefix mode, Pi's `text.trimStart().startsWith("!")` over the whole text (interactive-mode.ts setupKeyHandlers onChange): the first character after JavaScript whitespace, line breaks included, is `!`. Used to switch the editor border color and to suppress slash-autocomplete in this state.

func (*Editor) IsDelegated

func (e *Editor) IsDelegated() bool

IsDelegated reports whether the installed remote reaches this editor's editing through Editor.AsBase.

func (*Editor) IsDirty

func (e *Editor) IsDirty() bool

IsDirty reports whether the editor's rendered lines changed since the last consume. The embedded status indicator is animated and relabelled by its owner (spinner ticks, working message, retry countdown) without touching the editor, so its own dirty flag counts too; otherwise the per-child render cache would keep the old border row until a keystroke dirtied the editor.

func (*Editor) IsRemote

func (e *Editor) IsRemote() bool

IsRemote reports whether an extension's editor component stands in for the editor.

func (*Editor) MaxVisibleLines

func (e *Editor) MaxVisibleLines() int

MaxVisibleLines returns the current visible-line cap (mostly for tests).

func (*Editor) NeedsRedraw

func (e *Editor) NeedsRedraw() bool

NeedsRedraw consumes the editor's and the embedded indicator's dirty flags.

func (*Editor) PaddingX

func (e *Editor) PaddingX() int

PaddingX returns the editor's horizontal content padding.

func (*Editor) RefreshAutocomplete

func (e *Editor) RefreshAutocomplete()

RefreshAutocomplete queries the provider again for the current buffer, for a provider whose answer arrived after the keystroke that asked for it.

func (*Editor) Remote

func (e *Editor) Remote() EditorRemote

Remote returns the installed remote, or nil.

func (*Editor) Render

func (e *Editor) Render(width int) []string

func (*Editor) SetAsyncApply

func (e *Editor) SetAsyncApply(schedule func(func()))

SetAsyncApply installs a scheduler that runs the given closure on the host's main loop (single-threaded with keystroke handling). The editor uses it to apply async suggestion results without mutating its lock-free state from a worker goroutine. When unset, results are applied inline on the worker (single-threaded callers / tests only).

func (*Editor) SetAsyncAutocomplete

func (e *Editor) SetAsyncAutocomplete(provider *AsyncAutocompleteProvider, lifetime context.Context, start func(func()), input func(AutocompleteWork), report func(error))

SetAsyncAutocomplete selects a complete provider, not an additive suggestion source. start owns query workers; input owns ordered completion workers.

func (*Editor) SetAutocomplete

func (e *Editor) SetAutocomplete(p AutocompleteProvider)

SetAutocomplete replaces the provider and cancels pending completion without querying. The host rebuilds extension wrappers through its change callback.

func (*Editor) SetAutocompleteChanged

func (e *Editor) SetAutocompleteChanged(changed func(AutocompleteProvider))

SetAutocompleteChanged binds the owner's provider rebuild operation.

func (*Editor) SetAutocompleteMaxVisible

func (e *Editor) SetAutocompleteMaxVisible(maxVisible int)

SetAutocompleteMaxVisible changes the autocomplete row limit.

func (*Editor) SetAutocompleteTaskOwner

func (e *Editor) SetAutocompleteTaskOwner(ctx context.Context, start func(func()), report func(error))

SetAutocompleteTaskOwner binds the lifetime, joined worker launcher and owner-loop error reporter for native queries.

func (*Editor) SetCursor

func (e *Editor) SetCursor(line, col int)

SetCursor places the cursor at a logical line and UTF-16 column, clamped to the document: the cursor of a component whose sender owns the state (Node's Editor).

func (*Editor) SetDelegatedRemote

func (e *Editor) SetDelegatedRemote(remote EditorRemote)

SetDelegatedRemote installs remote like Editor.SetRemote for a component that subclasses the editor: it receives every key and renders every frame, and reaches this editor's own editing, rendering and app-action handling through Editor.AsBase, as a CustomEditor subclass reaches its super.

Pi builds a new Editor for each factory and copies only the text into it, so the component's base starts as a fresh instance: an empty prompt history and kill ring, no pastes, and an undo stack holding the empty document its setText(currentText) replaced. The default editor's own instance state returns when the component is removed or replaced.

func (*Editor) SetFocused

func (e *Editor) SetFocused(focused bool)

SetFocused records whether the editor holds TUI focus; only a focused editor emits the hardware-cursor marker.

func (*Editor) SetMaxVisibleLines

func (e *Editor) SetMaxVisibleLines(n int)

SetMaxVisibleLines updates the editor's maximum visible visual-line count. Mirrors upstream editor.ts maxVisibleLines (set from `max(5, floor(terminalRows * 0.3))` on resize). Clamped to ≥ 1.

func (*Editor) SetOnChange

func (e *Editor) SetOnChange(callback func(text string))

SetOnChange installs the change callback.

func (*Editor) SetOnSubmit

func (e *Editor) SetOnSubmit(callback func(text string))

SetOnSubmit installs the submit callback.

func (*Editor) SetPaddingX

func (e *Editor) SetPaddingX(padding int)

SetPaddingX changes the editor's horizontal content padding.

func (*Editor) SetRemote

func (e *Editor) SetRemote(remote EditorRemote)

SetRemote installs remote in place of the editor's own editing, or with nil restores it. The mirrored text becomes the editor's text.

func (*Editor) SetRemoteFrame

func (e *Editor) SetRemoteFrame(lines []string, width int, wantsKeyRelease bool)

SetRemoteFrame records the remote's latest render output for the terminal width it was laid out for.

func (*Editor) SetText

func (e *Editor) SetText(text string)

SetText normalizes and replaces the document, resets paste/typing state, records a changed document for undo, and cancels completion without querying.

func (*Editor) SetTheme

func (e *Editor) SetTheme(theme EditorTheme)

SetTheme restyles the editor's border and autocomplete list, as the constructor's theme argument does.

func (*Editor) SetWorkingStatusIndicator

func (e *Editor) SetWorkingStatusIndicator(indicator *StatusIndicator)

SetWorkingStatusIndicator selects the status displayed by an opted-in editor.

func (*Editor) SurfaceLive

func (e *Editor) SurfaceLive() bool

pig additive (D91): SurfaceLive reports that the embedded indicator, which changes without invalidating the editor, draws in the editor.

func (*Editor) Text

func (e *Editor) Text() string

Text returns the editor content as a single string.

func (*Editor) Undo

func (e *Editor) Undo()

Undo reverts the last change through the editor's undo history, as the undo key does.

func (*Editor) WantsKeyRelease

func (e *Editor) WantsKeyRelease() bool

WantsKeyRelease reports the remote component's wantsKeyRelease; the editor's own editing takes no key releases.

type EditorComponent

type EditorComponent interface {
	Component
	// Text returns the current text content.
	Text() string
	// SetText replaces the text content.
	SetText(text string)
	// HandleInput handles raw terminal input (key presses, paste sequences).
	HandleInput(data string)
	// SetOnSubmit installs the callback run when the user submits (Enter).
	SetOnSubmit(callback func(text string))
	// SetOnChange installs the callback run when the text changes.
	SetOnChange(callback func(text string))
}

EditorComponent is what a custom editor (an extension's vim or emacs mode, custom keybindings) provides so the application can host it in place of the built-in Editor.

Pi's required `onSubmit` and `onChange` callback properties are the SetOnSubmit and SetOnChange methods; the optional members are the small interfaces below, which the application asks for with a type assertion before using them. Pi's `getText` is Text, as on Editor.

upstream: packages/tui/src/editor-component.ts:11

type EditorCursor

type EditorCursor struct {
	Line int
	Col  int
}

EditorCursor is a logical line and UTF-16 column, not a terminal-cell position.

type EditorOption

type EditorOption func(*Editor)

EditorOption configures NewEditor.

func WithEditorTheme

func WithEditorTheme(theme EditorTheme) EditorOption

WithEditorTheme renders the editor with theme instead of the active theme (the editor.ts constructor's theme argument): the border uses theme.BorderColor and the autocomplete popup uses theme.SelectList.

type EditorOptions

type EditorOptions struct {
	PaddingX               *int
	AutocompleteMaxVisible *int
}

EditorOptions is editor.ts EditorOptions: PaddingX is the horizontal content padding (default 0, floored at 0) and AutocompleteMaxVisible the autocomplete row limit (default 5, clamped to 3..20).

type EditorRemote

type EditorRemote interface {
	// Input delivers one keystroke to the component's handleInput.
	Input(data string)
	SetText(text string)
	InsertTextAtCursor(text string)
	AddToHistory(text string)
	// Mouse delivers a left click, its row relative to the component's
	// first row, to the component's handleMouse.
	Mouse(event TuiMouseEvent)
	// StateChanged reports that the editor's padding, autocomplete size,
	// focus or thinking level changed, which the component mirrors.
	StateChanged()
}

EditorRemote is an extension's editor component standing in for the editor (Pi's ctx.ui.setEditorComponent). Pi replaces its editor with the component and routes to it everything it routes to the editor; with a remote installed the editor does the same: it forwards keystrokes and the host's text operations to the remote, shows the remote's frames, and mirrors the remote's text so the host reads it as it would its own.

type EditorRemoteInvalidator

type EditorRemoteInvalidator interface {
	Invalidate()
}

EditorRemoteInvalidator is an EditorRemote that learns of a theme change, which Pi's TUI delivers as invalidate() to every component it holds (container.ts invalidate forwards to its children; a custom editor clears its caches there).

type EditorRemoteRenderer

type EditorRemoteRenderer interface {
	RenderRemote(width int) (lines []string, ok bool)
}

EditorRemoteRenderer is an EditorRemote that renders its component on demand, for a component that runs in the host's process: the editor shows what the component renders at the width it is asked for, so a component that changes on its own (an animation, a timer) shows the change on the next render without a key. ok is false when the remote has only the frames it was sent.

type EditorTheme

type EditorTheme struct {
	BorderColor func(text string) string
	SelectList  SelectListTheme
}

EditorTheme styles an Editor: the border and the autocomplete list.

upstream: packages/tui/src/components/editor.ts:237 (EditorTheme)

type EditorWithAppearance

type EditorWithAppearance interface {
	EditorComponent
	SetPaddingX(padding int)
	SetAutocompleteMaxVisible(maxVisible int)
}

EditorWithAppearance is an EditorComponent with adjustable padding and autocomplete height.

type EditorWithAutocomplete

type EditorWithAutocomplete interface {
	EditorComponent
	SetAutocomplete(provider AutocompleteProvider)
}

EditorWithAutocomplete is an EditorComponent that takes an autocomplete provider.

type EditorWithExpandedText

type EditorWithExpandedText interface {
	EditorComponent
	GetExpandedText() string
}

EditorWithExpandedText is an EditorComponent whose text can carry markers (such as paste markers) that expand to their full content. Without it the application falls back to Text.

type EditorWithHistory

type EditorWithHistory interface {
	EditorComponent
	AddToHistory(text string)
}

EditorWithHistory is an EditorComponent with up/down history navigation.

type EditorWithTextInsertion

type EditorWithTextInsertion interface {
	EditorComponent
	InsertTextAtCursor(text string)
}

EditorWithTextInsertion is an EditorComponent that inserts text at the cursor.

type ExtensionInputComponent

type ExtensionInputComponent struct {
	Container
	// contains filtered or unexported fields
}

ExtensionInputComponent wraps a bare TextInput with extension-style chrome.

func NewExtensionInputComponent

func NewExtensionInputComponent(title, placeholder string, onSubmit func(value string), onCancel func(), options ...ExtensionInputOptions) *ExtensionInputComponent

NewExtensionInputComponent creates the editor-slot extension input wrapper, as upstream's constructor does (extension-input.ts:33-78). Placeholder is accepted for API parity; upstream ignores it. onSubmit receives the value when the user confirms and onCancel runs when the user cancels or the countdown expires; either may be nil, because a host that polls Done and Cancelled needs neither. The host-driven Done, Cancelled and Text state is set before the callback runs.

func (*ExtensionInputComponent) Cancel

func (e *ExtensionInputComponent) Cancel()

Cancel completes the input as cancelled, as upstream's countdown expiry calls onCancel.

func (*ExtensionInputComponent) Cancelled

func (e *ExtensionInputComponent) Cancelled() bool

Cancelled reports whether the user cancelled the input.

func (*ExtensionInputComponent) Dispose

func (e *ExtensionInputComponent) Dispose()

Dispose stops the countdown. Mirrors upstream dispose (extension-input.ts:95-97).

func (*ExtensionInputComponent) Done

func (e *ExtensionInputComponent) Done() bool

Done reports whether the user submitted or cancelled the input.

func (*ExtensionInputComponent) Focused

func (e *ExtensionInputComponent) Focused() bool

Focused reports the Focusable flag (upstream get focused, extension-input.ts:30-32).

func (*ExtensionInputComponent) HandleInput

func (e *ExtensionInputComponent) HandleInput(data string)

HandleInput resolves selection actions before delegating text editing to Input. The inner input's submit action does not complete the dialog.

func (*ExtensionInputComponent) Invalidate

func (i *ExtensionInputComponent) Invalidate()

func (*ExtensionInputComponent) IsDirty

func (i *ExtensionInputComponent) IsDirty() bool

func (*ExtensionInputComponent) NeedsRedraw

func (i *ExtensionInputComponent) NeedsRedraw() bool

func (*ExtensionInputComponent) SetCountdown

func (e *ExtensionInputComponent) SetCountdown(seconds int)

SetCountdown shows the seconds left before the input times out, as upstream's countdown sets the title to `${baseTitle} (${s}s)`.

func (*ExtensionInputComponent) SetFocused

func (e *ExtensionInputComponent) SetFocused(focused bool)

SetFocused implements Focusable: the flag propagates to the input so the hardware cursor lands in it (upstream set focused, extension-input.ts:33-36).

func (*ExtensionInputComponent) SetText

func (e *ExtensionInputComponent) SetText(s string)

SetText pre-fills the input.

func (*ExtensionInputComponent) StartCountdown

func (e *ExtensionInputComponent) StartCountdown(timeout time.Duration, dispatch func(func()), onTick, onExpire func())

StartCountdown starts the timer that shows the seconds left in the title and, at zero, cancels the input (the constructor's opts.timeout branch, which owns a CountdownTimer). dispatch runs each second on the loop that owns the input; onTick runs after each title update and onExpire after the cancellation. A running countdown is replaced.

func (*ExtensionInputComponent) Text

func (e *ExtensionInputComponent) Text() string

Text returns the current value.

type ExtensionInputOptions

type ExtensionInputOptions struct {
	// TUI receives a render request on every countdown tick.
	TUI TUI
	// Timeout is how long the input waits before it cancels itself; zero or less disables the countdown, which also needs TUI.
	Timeout time.Duration
	// InitialValue pre-fills the input.
	InitialValue string
	// Description is shown under the title.
	Description string
	// Dispatch runs each countdown second on the loop that owns the component; upstream's interval runs on its event loop. A nil Dispatch runs it on the timer goroutine.
	Dispatch func(func())
}

ExtensionInputOptions mirrors upstream ExtensionInputOptions (extension-input.ts:12-17).

type ExtensionSelectorComponent

type ExtensionSelectorComponent struct {
	Container
	// contains filtered or unexported fields
}

ExtensionSelectorComponent is the editor-slot overlay component extensions and built-in flows use to ask the user to pick from a list of string options. Like upstream it is a Container: border, spacer, title, [spacer, description], spacer, option list, spacer, hint, spacer, border.

func NewExtensionSelectorComponent

func NewExtensionSelectorComponent(title string, options []string, onSelect func(option string), onCancel func(), optionsArg ...ExtensionSelectorOptions) *ExtensionSelectorComponent

NewExtensionSelectorComponent creates a generic selector overlay, as upstream's constructor does (extension-selector.ts:30-85). The first option is pre-selected. onSelect receives the confirmed option and onCancel runs when the user cancels or the countdown expires; either may be nil, because a host that polls Done and Cancelled needs neither. The host-driven Done, Cancelled and SelectedIndex state is set before the callback runs.

func (*ExtensionSelectorComponent) Cancel

func (e *ExtensionSelectorComponent) Cancel()

Cancel completes the selector as cancelled, as upstream's countdown expiry calls onCancel.

func (*ExtensionSelectorComponent) Cancelled

func (e *ExtensionSelectorComponent) Cancelled() bool

Cancelled reports whether the cancellation action completed the selector.

func (*ExtensionSelectorComponent) CapturesSelectPageInput

func (e *ExtensionSelectorComponent) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the selector handles tui.select.pageUp and tui.select.pageDown.

func (*ExtensionSelectorComponent) Dispose

func (e *ExtensionSelectorComponent) Dispose()

Dispose stops the countdown (dispose() calls countdown?.dispose()). It is safe to call twice.

func (*ExtensionSelectorComponent) Done

func (e *ExtensionSelectorComponent) Done() bool

Done reports whether the user picked an option (or cancelled).

func (*ExtensionSelectorComponent) HandleInput

func (e *ExtensionSelectorComponent) HandleInput(data string)

HandleInput resolves expansion, navigation, confirmation and cancellation in that order. Empty options do not complete the selector.

func (*ExtensionSelectorComponent) Invalidate

func (i *ExtensionSelectorComponent) Invalidate()

func (*ExtensionSelectorComponent) IsDirty

func (i *ExtensionSelectorComponent) IsDirty() bool

func (*ExtensionSelectorComponent) NativeNode

func (e *ExtensionSelectorComponent) NativeNode() (frontend.Node, bool)

NativeNode reports the dialog as a selector. A title's first line is the heading and the rest, such as a confirm dialog's message, comes before the description. Item ids are option indexes.

func (*ExtensionSelectorComponent) NeedsRedraw

func (i *ExtensionSelectorComponent) NeedsRedraw() bool

func (*ExtensionSelectorComponent) Render

func (e *ExtensionSelectorComponent) Render(width int) []string

Render is the Container's render, except that with a preview (SetPreview) the option rows take the width of the longest row (wrapping only to keep the preview inside the dialog), the preview follows previewGapCells later, top-aligned with the first row, and the title, hint and borders keep the full width.

func (*ExtensionSelectorComponent) SelectedIndex

func (e *ExtensionSelectorComponent) SelectedIndex() int

SelectedIndex returns the index of the selected option, or -1 if cancelled.

func (*ExtensionSelectorComponent) SelectedValue

func (e *ExtensionSelectorComponent) SelectedValue() string

SelectedValue returns the selected option string, or "" if cancelled.

func (*ExtensionSelectorComponent) SetCountdown

func (e *ExtensionSelectorComponent) SetCountdown(seconds int)

SetCountdown shows the seconds left before the selector times out, as upstream's countdown sets the title to `${baseTitle} (${s}s)`.

func (*ExtensionSelectorComponent) SetDescription

func (e *ExtensionSelectorComponent) SetDescription(description string)

SetDescription sets optional explanatory text shown between the title and the options. Mirrors upstream ExtensionSelectorOptions.description.

func (*ExtensionSelectorComponent) SetPreview

func (e *ExtensionSelectorComponent) SetPreview(preview func(selectedIndex int) []string)

SetPreview supplies the dialog's right column: the lines drawn beside the option rows for the highlighted option, which the selector asks for on every render so the column follows the cursor. Nil, the default, draws upstream's selector with no preview column. Pig's sprite picker uses it to show the pig of the sprite under the cursor. pig divergence (D2): the preview column is Pig's sprite picker's; upstream's selector renders without one.

func (*ExtensionSelectorComponent) StartCountdown

func (e *ExtensionSelectorComponent) StartCountdown(timeout time.Duration, dispatch func(func()), onTick, onExpire func())

StartCountdown starts the timer that shows the seconds left in the title and, at zero, cancels the selector (the constructor's opts.timeout branch, which owns a CountdownTimer). dispatch runs each second on the loop that owns the selector; onTick runs after each title update and onExpire after the cancellation. A running countdown is replaced.

type ExtensionSelectorOptions

type ExtensionSelectorOptions struct {
	// TUI receives a render request on every countdown tick.
	TUI TUI
	// Timeout is how long the selector waits before it cancels itself; zero or less disables the countdown, which also needs TUI.
	Timeout time.Duration
	// OnToggleToolsExpanded runs on the app.tools.expand binding.
	OnToggleToolsExpanded func()
	// Description is shown under the title.
	Description string
	// Dispatch runs each countdown second on the loop that owns the component; upstream's interval runs on its event loop. A nil Dispatch runs it on the timer goroutine.
	Dispatch func(func())
}

ExtensionSelectorOptions mirrors upstream ExtensionSelectorOptions (extension-selector.ts:12-17).

type FilterableList

type FilterableList struct {
	Title  string
	Labels []string // display label per item

	// EnableSearch controls whether the upstream-style search input row is
	// rendered and whether printable input edits the filter. Default: true.
	// Settings submenus use false to mirror upstream SelectList-based menus.
	EnableSearch bool

	// Descriptions, when non-nil and width allows, render in a second
	// column to the right of each label. Mirrors upstream
	// select-list.ts SelectItem.description handling. Length should
	// match Labels; missing entries render as empty.
	Descriptions []string

	// MinPrimaryColumnWidth / MaxPrimaryColumnWidth bound the
	// label column when descriptions render. Mirrors upstream
	// SelectListLayoutOptions. Defaults to upstream's 32 cells.
	MinPrimaryColumnWidth int
	MaxPrimaryColumnWidth int

	// TruncatePrimary overrides primary-column truncation. Its output is still
	// clipped to MaxWidth, matching upstream SelectListLayoutOptions.
	TruncatePrimary func(context SelectListTruncatePrimaryContext) string

	// ScrollInfo styles the "(n/total)" line, as the scrollInfo function of upstream's SelectListTheme does. Nil styles it muted, the default theme's choice.
	ScrollInfo func(text string) string

	// MaxVisible bounds the visible window. Mirrors upstream
	// SelectList.maxVisible. Defaults to 20.
	MaxVisible int
	// contains filtered or unexported fields
}

FilterableList is a modal selector. After Done()==true callers inspect SelectedIndex (-1 on cancel) or Cancelled().

func NewFilterableList

func NewFilterableList(title string, labels []string) *FilterableList

NewFilterableList creates a list with the given labels and an optional title shown in the overlay border.

func (*FilterableList) Cancelled

func (f *FilterableList) Cancelled() bool

Cancelled reports whether the user pressed Esc.

func (*FilterableList) CapturesSelectPageInput

func (f *FilterableList) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the list handles tui.select.pageUp and tui.select.pageDown.

func (*FilterableList) CursorIndex

func (f *FilterableList) CursorIndex() int

CursorIndex returns the current index within the filtered view.

func (*FilterableList) Done

func (f *FilterableList) Done() bool

Done reports whether the user has confirmed or cancelled.

func (*FilterableList) FilterText

func (f *FilterableList) FilterText() string

FilterText returns the current filter query typed by the user. Used by ShowExtensionEditor to retrieve free-text input.

func (*FilterableList) HandleInput

func (f *FilterableList) HandleInput(data string)

HandleInput updates the filter or moves the cursor.

func (*FilterableList) HandleMouse

func (f *FilterableList) HandleMouse(event TuiMouseEvent) *TuiMouseDispatchResult

HandleMouse selects visible rows on press, activates them on click, and moves selection one item per wheel report without changing selection on hover. Mirrors upstream SelectList.handleMouse.

func (*FilterableList) Invalidate

func (i *FilterableList) Invalidate()

func (*FilterableList) IsDirty

func (i *FilterableList) IsDirty() bool

func (*FilterableList) NativeNode

func (f *FilterableList) NativeNode() (frontend.Node, bool)

NativeNode reports the list as a selector; item ids are indexes into Labels.

func (*FilterableList) NeedsRedraw

func (i *FilterableList) NeedsRedraw() bool

func (*FilterableList) Render

func (f *FilterableList) Render(width int) []string

Render draws the optional filter input and SelectList rows, with unpadded muted status rows.

func (*FilterableList) Reset

func (f *FilterableList) Reset()

Reset clears the confirmed or cancelled state, so a host that reacts to each confirm or cancel as upstream's per-key onSelect and onCancel callbacks do sees only the key that caused it.

func (*FilterableList) SelectedIndex

func (f *FilterableList) SelectedIndex() int

SelectedIndex returns the chosen index into Labels, or -1 on cancel.

func (*FilterableList) SetCursor

func (f *FilterableList) SetCursor(idx int)

SetCursor positions the cursor on a specific filtered-view row.

type Focusable

type Focusable interface {
	SetFocused(focused bool)
}

Focusable is pi-tui's Focusable: a component that renders differently while it holds TUI focus, as a focused Editor or TextInput emits the hardware-cursor marker. Go interfaces carry no fields, so the TUI sets the flag through SetFocused instead of assigning `focused`.

type FuzzyMatch

type FuzzyMatch struct {
	Matches bool
	Score   float64
}

FuzzyMatch is the result of matching a single query against a text. Matches=false means the query does not appear in text in order.

func FuzzyMatchScore

func FuzzyMatchScore(query, text string) FuzzyMatch

FuzzyMatchScore matches an ordered, case-insensitive UTF-16 subsequence and returns Pi's lower-is-better score.

type FuzzyQuery

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

FuzzyQuery is a query prepared for matching many texts: its lowercase UTF-16 units and those of its letter/digit swap.

func NewFuzzyQuery

func NewFuzzyQuery(query string) FuzzyQuery

NewFuzzyQuery prepares query for Match.

type FuzzyText

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

FuzzyText is a text prepared for matching many queries: its lowercase UTF-16 units.

func NewFuzzyText

func NewFuzzyText(text string) FuzzyText

NewFuzzyText prepares text for Match.

func (FuzzyText) Match

func (t FuzzyText) Match(query FuzzyQuery) FuzzyMatch

Match is FuzzyMatchScore of the query and the text.

type HStack

type HStack struct {
	*Stack
}

HStack ports pi-tui's HStack: children laid out left to right with flexbox widths and vertical alignment.

func NewHStack

func NewHStack(children []StackChild, options StackOptions) *HStack

NewHStack constructs a horizontal stack.

func (HStack) Invalidate

func (i HStack) Invalidate()

func (HStack) IsDirty

func (i HStack) IsDirty() bool

func (HStack) NeedsRedraw

func (i HStack) NeedsRedraw() bool

func (*HStack) Render

func (h *HStack) Render(width int) []string

Render ports upstream HStack.render.

type HighlightEpoch

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

HighlightEpoch is what HighlightCode's lines depend on besides its arguments: the active theme and the highlight.js languages loaded. Within one epoch HighlightCode returns the same lines for the same code and language, so a caller may keep lines it highlighted instead of highlighting the same code again.

func CurrentHighlightEpoch

func CurrentHighlightEpoch() HighlightEpoch

CurrentHighlightEpoch is the epoch HighlightCode highlights in now.

type HighlightFormatter

type HighlightFormatter func(text string) string

HighlightFormatter styles the text of one highlight.js scope.

type HighlightOptions

type HighlightOptions struct {
	Language       string
	IgnoreIllegals bool
	LanguageSubset []string
	Theme          HighlightTheme
}

HighlightOptions are the options of syntax-highlight.ts highlight. An empty Language auto-detects among LanguageSubset, or every language.

type HighlightTheme

type HighlightTheme map[string]HighlightFormatter

HighlightTheme maps highlight.js scope names to formatters; "default" styles text outside every mapped scope.

type ITerm2Options

type ITerm2Options struct {
	Width               any
	Height              any
	Name                string
	PreserveAspectRatio *bool
	Inline              *bool
}

ITerm2Options mirrors the options object of upstream encodeITerm2. A nil Width or Height, an empty Name and a nil pointer are the absent fields. Width and Height are a number or a string, as in upstream.

type IdleStatus

type IdleStatus struct{}

IdleStatus reserves the standalone loader's two rows after clearing it.

func (*IdleStatus) Invalidate

func (*IdleStatus) Invalidate()

func (*IdleStatus) Render

func (*IdleStatus) Render(width int) []string

type Image

type Image struct {
	Base64Data string
	MIMEType   string
	Dimensions ImageDimensions
	Theme      ImageTheme
	Options    ImageOptions
	// contains filtered or unexported fields
}

func NewImage

func NewImage(base64Data, mimeType string, theme ImageTheme, options ImageOptions, dimensions *ImageDimensions) *Image

NewImage creates an image component with Pi's constructor shape (base64Data, mimeType, theme, options, dimensions). Dimensions default to the data's own size, or 800x600 when it cannot be read; an ImageTheme without FallbackColor styles nothing. upstream: packages/tui/src/components/image.ts constructor

func (*Image) GetImageID

func (i *Image) GetImageID() int

func (*Image) Invalidate

func (i *Image) Invalidate()

func (*Image) IsDirty

func (i *Image) IsDirty() bool

func (*Image) NeedsRedraw

func (i *Image) NeedsRedraw() bool

func (*Image) Render

func (i *Image) Render(width int) []string

Render returns image protocol rows or a width-bounded, styled fallback.

type ImageBlock

type ImageBlock struct {
	Data     string // base64-encoded image data
	MIMEType string
}

ImageBlock describes one image from a tool result for rendering.

type ImageCellSize

type ImageCellSize struct {
	Columns int
	Rows    int
}

func CalculateImageCellSize

func CalculateImageCellSize(imageDimensions ImageDimensions, maxWidthCells int, maxHeightCells int, dims CellDimensions, optimizeAspectRatio ...bool) ImageCellSize

CalculateImageCellSize mirrors calculateImageCellSize; upstream defaults optimizeAspectRatio to false, so omit the argument for that default.

type ImageDimensions

type ImageDimensions struct {
	WidthPx  int
	HeightPx int
}

func GetGIFDimensions

func GetGIFDimensions(base64Data string) *ImageDimensions

func GetImageDimensions

func GetImageDimensions(base64Data, mimeType string) *ImageDimensions

func GetJPEGDimensions

func GetJPEGDimensions(base64Data string) *ImageDimensions

func GetPNGDimensions

func GetPNGDimensions(base64Data string) *ImageDimensions

func GetWebPDimensions

func GetWebPDimensions(base64Data string) *ImageDimensions

type ImageOptions

type ImageOptions struct {
	MaxWidthCells  int
	MaxHeightCells int
	Filename       string
	ImageID        int
}

type ImageProtocol

type ImageProtocol string
const (
	ImageProtocolKitty  ImageProtocol = "kitty"
	ImageProtocolITerm2 ImageProtocol = "iterm2"
)

type ImageRenderOptions

type ImageRenderOptions struct {
	MaxWidthCells       int
	MaxHeightCells      int
	PreserveAspectRatio *bool // nil preserves the aspect ratio
	ImageID             int
	Name                string
	MoveCursor          *bool // nil permits Kitty cursor movement; false emits C=1
}

type ImageTheme

type ImageTheme struct {
	FallbackColor func(string) string
}

func DefaultImageTheme

func DefaultImageTheme() ImageTheme

DefaultImageTheme is the theme-aware ImageTheme: the fallback text is muted in the active theme.

type ImageTranscoder

type ImageTranscoder func(base64Data, mimeType string) (string, bool)

ImageTranscoder converts base64 image data to base64 PNG data, or reports false if it cannot. It is called synchronously during rendering. upstream: packages/tui/src/components/image.ts:ImageTranscoder

type IndexedColor

type IndexedColor struct{ Index int }

IndexedColor is an ANSI palette index, 0-255 (upstream `IndexedColor`, kind "indexed").

func NewIndexedColor

func NewIndexedColor(index int) (IndexedColor, error)

NewIndexedColor mirrors `indexedColor`; the name differs because Go shares one namespace for types and functions.

func (IndexedColor) Kind

func (IndexedColor) Kind() string

Kind returns "indexed".

type InputHandler

type InputHandler interface {
	HandleInput(data string)
}

InputHandler is implemented by components that want keyboard events.

type InputOptions

type InputOptions struct {
	Prompt           *string
	Placeholder      string
	PlaceholderStyle func(string) string
}

InputOptions mirrors InputOptions. Nil Prompt selects "> "; nil PlaceholderStyle leaves text unstyled.

type KeyEventType

type KeyEventType string

KeyEventType is the Kitty key event kind of an input sequence (keys.ts:505). Upstream's parser records it only in write-only module state (keys.ts:521 _lastEventType); IsKeyRepeat and IsKeyRelease answer the observable questions.

const (
	KeyEventPress   KeyEventType = "press"
	KeyEventRepeat  KeyEventType = "repeat"
	KeyEventRelease KeyEventType = "release"
)

The KeyEventType values.

type KeyHelper

type KeyHelper struct {
	// Special keys.
	Escape, Esc, Enter, Return, Tab, Space, Backspace, Delete, Insert, Clear, Home, End KeyID
	PageUp, PageDown, Up, Down, Left, Right                                             KeyID
	F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12                                   KeyID

	// Symbol keys.
	Backtick, Hyphen, Equals, Leftbracket, Rightbracket, Backslash, Semicolon, Quote, Comma, Period, Slash KeyID
	Exclamation, At, Hash, Dollar, Percent, Caret, Ampersand, Asterisk, Leftparen, Rightparen, Underscore  KeyID
	Plus, Pipe, Tilde, Leftbrace, Rightbrace, Colon, Lessthan, Greaterthan, Question                       KeyID
}

KeyHelper ports the shape of upstream's Key object (keys.ts:163): named key identifiers for special and symbol keys, and builders that prefix a base key with modifiers. Upstream's template-literal return types become plain KeyID strings.

func (KeyHelper) Alt

func (KeyHelper) Alt(key KeyID) KeyID

Alt returns "alt+<key>".

func (KeyHelper) AltCtrl

func (KeyHelper) AltCtrl(key KeyID) KeyID

AltCtrl returns "alt+ctrl+<key>".

func (KeyHelper) AltShift

func (KeyHelper) AltShift(key KeyID) KeyID

AltShift returns "alt+shift+<key>".

func (KeyHelper) AltSuper

func (KeyHelper) AltSuper(key KeyID) KeyID

AltSuper returns "alt+super+<key>".

func (KeyHelper) Ctrl

func (KeyHelper) Ctrl(key KeyID) KeyID

Ctrl returns "ctrl+<key>".

func (KeyHelper) CtrlAlt

func (KeyHelper) CtrlAlt(key KeyID) KeyID

CtrlAlt returns "ctrl+alt+<key>".

func (KeyHelper) CtrlShift

func (KeyHelper) CtrlShift(key KeyID) KeyID

CtrlShift returns "ctrl+shift+<key>".

func (KeyHelper) CtrlShiftAlt

func (KeyHelper) CtrlShiftAlt(key KeyID) KeyID

CtrlShiftAlt returns "ctrl+shift+alt+<key>".

func (KeyHelper) CtrlShiftSuper

func (KeyHelper) CtrlShiftSuper(key KeyID) KeyID

CtrlShiftSuper returns "ctrl+shift+super+<key>".

func (KeyHelper) CtrlSuper

func (KeyHelper) CtrlSuper(key KeyID) KeyID

CtrlSuper returns "ctrl+super+<key>".

func (KeyHelper) Shift

func (KeyHelper) Shift(key KeyID) KeyID

Shift returns "shift+<key>".

func (KeyHelper) ShiftAlt

func (KeyHelper) ShiftAlt(key KeyID) KeyID

ShiftAlt returns "shift+alt+<key>".

func (KeyHelper) ShiftCtrl

func (KeyHelper) ShiftCtrl(key KeyID) KeyID

ShiftCtrl returns "shift+ctrl+<key>".

func (KeyHelper) ShiftSuper

func (KeyHelper) ShiftSuper(key KeyID) KeyID

ShiftSuper returns "shift+super+<key>".

func (KeyHelper) Super

func (KeyHelper) Super(key KeyID) KeyID

Super returns "super+<key>".

func (KeyHelper) SuperAlt

func (KeyHelper) SuperAlt(key KeyID) KeyID

SuperAlt returns "super+alt+<key>".

func (KeyHelper) SuperCtrl

func (KeyHelper) SuperCtrl(key KeyID) KeyID

SuperCtrl returns "super+ctrl+<key>".

func (KeyHelper) SuperShift

func (KeyHelper) SuperShift(key KeyID) KeyID

SuperShift returns "super+shift+<key>".

type KeyID

type KeyID = string

KeyID is upstream's KeyId (keys.ts:152): a key name such as "enter", "ctrl+c" or "ctrl+shift+f5". Upstream's template-literal union is open here; use the Key helper to build identifiers.

type KeyReleaseReceiver

type KeyReleaseReceiver interface {
	WantsKeyRelease() bool
}

KeyReleaseReceiver is implemented by components that want Kitty key-release events delivered to HandleInput. Mirrors upstream's optional Component.wantsKeyRelease (tui.ts:40), which defaults to false. Upstream opts in only for games (the space-invaders and doom-overlay example extensions), which need key-up to stop movement.

type KeybindingDefinitions

type KeybindingDefinitions = map[string]TUIKeybindingDef

KeybindingDefinitions is upstream KeybindingDefinitions (keybindings.ts:68): each keybinding id's default keys and description.

func TUIKeybindingDefinitionsFor

func TUIKeybindingDefinitionsFor(platform KeybindingPlatform) KeybindingDefinitions

TUIKeybindingDefinitionsFor returns the tui.* definition table for a platform: upstream TUI_KEYBINDINGS (packages/tui/src/keybindings.ts) with the per-platform tui.* defaults that coding-agent's KEYBINDINGS applies on top (core/keybindings.ts). Every call returns a fresh map. The default keys of all rows are copied into one array, each row owning a capacity-limited slice of it, so a call allocates that array besides the map.

type KeybindingPlatform

type KeybindingPlatform string

KeybindingPlatform selects a column of per-platform default keys. Upstream branches its default table on process.platform and on useWindowsKeybindings() (coding-agent core/keybindings.ts); these four values name every combination the table distinguishes. The values match the columns of the behavior-input inventory.

const (
	KeybindingPlatformDarwin   KeybindingPlatform = "darwin"
	KeybindingPlatformLinux    KeybindingPlatform = "linux"
	KeybindingPlatformLinuxWSL KeybindingPlatform = "linuxWsl"
	KeybindingPlatformWin32    KeybindingPlatform = "win32"
)

func HostKeybindingPlatform

func HostKeybindingPlatform() KeybindingPlatform

HostKeybindingPlatform returns the platform column for this process.

func KeybindingPlatformFor

func KeybindingPlatformFor(goos string, getenv func(string) string) KeybindingPlatform

KeybindingPlatformFor maps a runtime.GOOS value and an environment to the default-key column. Platforms upstream does not name (freebsd, etc.) take the Linux column, as process.platform comparisons fall through there.

func (KeybindingPlatform) UsesWindowsKeybindings

func (p KeybindingPlatform) UsesWindowsKeybindings() bool

UsesWindowsKeybindings reports whether the platform takes Windows defaults.

type KeybindingsConfig

type KeybindingsConfig = map[string][]string

KeybindingsConfig is upstream KeybindingsConfig (keybindings.ts:69): the user's key overrides by keybinding id. A single key and a one-element list are the same override.

type KillRing

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

KillRing is an Emacs-style kill/yank ring buffer.

Tracks killed (deleted) text entries. Consecutive kills accumulate into a single entry via Push(accumulate=true). Supports yank (paste most recent) and yank-pop (cycle through older entries via Rotate).

Mirrors upstream kill-ring.ts.

func (*KillRing) Len

func (k *KillRing) Len() int

Len returns the number of entries in the ring.

func (*KillRing) Length

func (k *KillRing) Length() int

Length mirrors upstream's `get length()` surface.

func (*KillRing) Peek

func (k *KillRing) Peek() string

Peek returns the most recent entry without modifying the ring. Returns "" if the ring is empty.

func (*KillRing) Push

func (k *KillRing) Push(text string, prepend bool, accumulate bool)

Push adds text to the kill ring.

  • prepend: when accumulating, prepend text (backward deletion) vs append (forward).
  • accumulate: merge with the most recent entry instead of creating a new one.

Empty text is a no-op.

func (*KillRing) Rotate

func (k *KillRing) Rotate()

Rotate moves the last entry to the front (for yank-pop cycling). No-op if the ring has fewer than 2 entries.

type KittyImageMetadata

type KittyImageMetadata struct {
	ImageID  int
	Columns  int
	Rows     int
	WidthPx  int
	HeightPx int
}

KittyImageMetadata is the public metadata for a registered Kitty image.

func GetKittyImageMetadata

func GetKittyImageMetadata(line string) *KittyImageMetadata

GetKittyImageMetadata returns the public metadata for the Kitty image on a rendered line, or nil if the line carries no registered image. Mirrors upstream getKittyImageMetadata.

type KittyImagePlacement

type KittyImagePlacement struct {
	ImageID                int
	TransmissionGeneration int
	TransmissionBytes      int
	EstimatedDecodedBytes  int
	// Rows is the placement's explicit `r=` rows, else the image's registered rows.
	Rows            int
	Sequence        string
	ReplacementLine string
}

KittyImagePlacement is a placement-only command derived from a transmitted Kitty image line. Mirrors upstream KittyImagePlacement.

func GetKittyImagePlacement

func GetKittyImagePlacement(line string) (KittyImagePlacement, bool)

GetKittyImagePlacement builds a placement-only command for an image line emitted by RenderImage, so the alt-screen renderer can re-place an already transmitted image without re-uploading its data. Returns ok=false for a line with no Kitty command or no registered metadata. Mirrors upstream getKittyImagePlacement.

type LayoutBox

type LayoutBox struct {
	Component          Component
	Rect               LayoutRect
	Clip               LayoutRect
	Children           []*LayoutBox
	Parent             *LayoutBox
	Lines              []string
	LineOffset         int
	ScrollView         *ScrollView
	ScrollContentLines []string
	Layer              int
}

LayoutBox is one node in the laid-out tree. Lines (non-nil) marks a leaf whose rendered lines paint directly; ScrollView/ScrollContentLines mark a scroll viewport. Optional upstream fields are zero values here.

func GetLayoutBoxesAt

func GetLayoutBoxesAt(frame LayoutFrame, x, y int) []*LayoutBox

GetLayoutBoxesAt returns the visual hit path at a point, from the deepest component to the layout root, highest layer first. Mirrors upstream getLayoutBoxesAt.

func GetScrollViewBox

func GetScrollViewBox(frame LayoutFrame, scrollView *ScrollView) *LayoutBox

GetScrollViewBox finds the layout box wrapping a given ScrollView, or nil. Mirrors upstream getScrollViewBox.

type LayoutComponent

type LayoutComponent interface {
	Component
	LayoutNode() LayoutNode
}

LayoutComponent is a Component that exposes a layout node. It ports upstream's LayoutComponent interface; the LAYOUT_NODE symbol method becomes LayoutNode().

type LayoutFrame

type LayoutFrame struct {
	Root              *LayoutBox
	Width             int
	Height            int
	Lines             []string
	PrimaryScrollView *ScrollView
}

LayoutFrame is a fully laid-out and painted viewport.

func RenderLayoutFrame

func RenderLayoutFrame(root Component, width, height int, requestRender func()) LayoutFrame

RenderLayoutFrame lays out a component tree into a width×height viewport and paints it. Mirrors upstream renderLayoutFrame.

type LayoutNode

type LayoutNode interface {
	// contains filtered or unexported methods
}

LayoutNode is the sealed union of layout node kinds (upstream's StackLayoutNode | ScrollLayoutNode discriminated union). Only the two node types in this package implement it.

type LayoutRect

type LayoutRect struct {
	X      int
	Y      int
	Width  int
	Height int
}

LayoutRect is an axis-aligned rectangle in terminal cells.

type LayoutViewport

type LayoutViewport struct {
	Width  int
	Height int
}

LayoutViewport is the available render area a stack entry's visibility predicate is evaluated against.

type LeafMouseHandler

type LeafMouseHandler interface {
	HandleMouse(event TuiMouseEvent) *TuiMouseEventResult
}

LeafMouseHandler is implemented by components whose handleMouse returns a plain TuiMouseEventResult, as upstream's Editor does. Go has no covariant results, so a component returns either that or a TuiMouseDispatchResult (MouseHandler); DispatchMouseEvent takes both.

type Loader

type Loader struct {
	Text
	// IntervalMs is the Start animation interval; zero selects DefaultLoaderIntervalMs.
	IntervalMs int

	Message           string
	Frame             int
	Frames            []string
	IndicatorVerbatim bool // extension frames include their own formatting
	// contains filtered or unexported fields
}

Loader shows an animated spinner with a message. Matches upstream Loader which extends Text(paddingX=1, paddingY=0).

Loader embeds Text, as upstream Loader extends Text: SetText and SetCustomBgFn are Text's, and the text shown is rewritten from the indicator and message on every render, as upstream updateDisplay does.

func NewLoader

func NewLoader(ui TUI, spinnerColorFn, messageColorFn func(string) string, message string, indicator *LoaderIndicatorOptions) *Loader

NewLoader is `new Loader(ui, spinnerColorFn, messageColorFn, message, indicator)` (components/loader.ts:28-41). ui may be nil; it receives a RequestRender after every change to the shown text. A nil color function leaves its text unstyled. A nil indicator is upstream's undefined (the default spinner); the constructor applies a non-nil one through SetIndicator, as upstream's constructor calls setIndicator(indicator).

func (*Loader) Invalidate

func (l *Loader) Invalidate()

Invalidate marks the loader for repaint and drops the cached text lines.

func (*Loader) IsDirty

func (i *Loader) IsDirty() bool

func (*Loader) MessageColorPrefix

func (l *Loader) MessageColorPrefix() string

MessageColorPrefix is the escape sequence the message color function writes before its text, "" for none.

func (*Loader) NeedsRedraw

func (i *Loader) NeedsRedraw() bool

func (*Loader) Render

func (l *Loader) Render(width int) []string

Render produces ["", paddedLine] matching upstream Loader.render(width) which returns ["", ...super.render(width)] where super is Text(paddingX=1).

func (*Loader) SetIndicator

func (l *Loader) SetIndicator(indicator *LoaderIndicatorOptions)

SetIndicator mirrors upstream Loader.setIndicator: a nil indicator restores the default spinner, and a non-nil one renders its frames verbatim (without the spinner color), using Frames when set and IntervalMs when positive. It restarts at the first frame and marks the loader for repaint. The animation restarts only when it is running; the owner that ticks the loader starts it otherwise.

func (*Loader) SetMessage

func (l *Loader) SetMessage(message string)

SetMessage replaces the message and marks the loader for repaint. Mirrors upstream Loader.setMessage, which updates the text and requests a render.

func (*Loader) SetPaddingX

func (l *Loader) SetPaddingX(paddingX int)

SetPaddingX is Text.setPaddingX on the Loader, which extends Text: the padding applies to every later render in place of the default of 1.

func (*Loader) SpinnerColorPrefix

func (l *Loader) SpinnerColorPrefix() string

SpinnerColorPrefix is the escape sequence the spinner color function writes before its text, "" for none. The remote editor carries it instead of the function.

func (*Loader) Start

func (l *Loader) Start()

Start renders the current frame and restarts the animation timer: with more than one frame, a goroutine advances the frame every IntervalMs until Stop (upstream Loader.start).

func (*Loader) Stop

func (l *Loader) Stop()

Stop ends the animation timer (upstream Loader.stop). It is safe to call more than once.

func (*Loader) Tick

func (l *Loader) Tick()

Tick advances the spinner one frame.

type LoaderIndicatorOptions

type LoaderIndicatorOptions struct {
	Frames     []string
	IntervalMs float64
}

LoaderIndicatorOptions mirrors upstream LoaderIndicatorOptions. Frames nil is upstream's undefined (the default spinner) and an empty slice hides the indicator; IntervalMs zero, negative or unset selects DefaultLoaderIntervalMs.

type LoginDialogComponent

type LoginDialogComponent struct {
	Container
	// contains filtered or unexported fields
}

LoginDialogComponent renders provider authentication in the editor slot. The caller owns I/O and feeds prompt, progress and completion events.

func NewLoginDialogComponent

func NewLoginDialogComponent(ui TUI, providerID string, onComplete func(success bool, message string), providerNameOverride string, titleOverride ...string) *LoginDialogComponent

NewLoginDialogComponent creates a provider dialog, as Pi's constructor does (login-dialog.ts:32-48), with PiG's configurable input privacy default enabled. onComplete runs with (false, "Login cancelled") when the user cancels. The title is "Login to <providerNameOverride or providerID>" unless titleOverride (the first value) is given; an empty providerNameOverride stands for Pi's undefined. A non-nil ui receives the dialog's render requests; SetCopyToClipboard may replace that request.

func (*LoginDialogComponent) Cancelled

func (d *LoginDialogComponent) Cancelled() bool

func (*LoginDialogComponent) Done

func (d *LoginDialogComponent) Done() bool

func (*LoginDialogComponent) Focused

func (d *LoginDialogComponent) Focused() bool

Focused reports the Focusable flag (upstream's focused getter, login-dialog.ts:23-24).

func (*LoginDialogComponent) HandleInput

func (d *LoginDialogComponent) HandleInput(data string)

HandleInput routes editing to the active prompt and cancels with the configured selector binding.

func (*LoginDialogComponent) Invalidate

func (i *LoginDialogComponent) Invalidate()

func (*LoginDialogComponent) IsDirty

func (i *LoginDialogComponent) IsDirty() bool

func (*LoginDialogComponent) NeedsRedraw

func (i *LoginDialogComponent) NeedsRedraw() bool

func (*LoginDialogComponent) Redact

func (d *LoginDialogComponent) Redact(text string) string

Redact removes masked prompt values from authentication errors emitted after the dialog closes.

func (*LoginDialogComponent) Render

func (d *LoginDialogComponent) Render(width int) []string

Render returns Pi's dialog layout: border, title, the content container, border. The content children read the dialog's redaction state, so the dialog's lock covers the whole render.

func (*LoginDialogComponent) SetCopyToClipboard

func (d *LoginDialogComponent) SetCopyToClipboard(copyText func(text string) error, requestRender func())

SetCopyToClipboard supplies the clipboard writer `app.message.copy` uses for a sign-in URL and the repaint request that shows the outcome; a nil requestRender keeps the constructor tui's.

func (*LoginDialogComponent) SetFocused

func (d *LoginDialogComponent) SetFocused(focused bool)

SetFocused implements Focusable: the focus flag propagates to the active prompt input so the hardware cursor lands in it (upstream's focused setter assigns input.focused, login-dialog.ts:25-28).

func (*LoginDialogComponent) SetMaskSecretInput

func (d *LoginDialogComponent) SetMaskSecretInput(enabled bool)

SetMaskSecretInput selects masking for subsequent secret prompts. Already masked history stays masked.

func (*LoginDialogComponent) ShowAuth

func (d *LoginDialogComponent) ShowAuth(url, instructions string)

ShowAuth replaces the dialog content with a URL and optional instructions.

func (*LoginDialogComponent) ShowDetails

func (d *LoginDialogComponent) ShowDetails(lines []string)

ShowDetails replaces the content with informational lines before a provider prompt.

func (*LoginDialogComponent) ShowDeviceCode

func (d *LoginDialogComponent) ShowDeviceCode(info OAuthDeviceCodeInfo)

ShowDeviceCode replaces the dialog content with a verification URL and the user code, as Pi's showDeviceCode(info) does (login-dialog.ts:117).

func (*LoginDialogComponent) ShowInfo

func (d *LoginDialogComponent) ShowInfo(message string, links []AuthInfoLink, showCloseHint bool)

ShowInfo appends provider instructions and links before the next prompt.

func (*LoginDialogComponent) ShowManualInput

func (d *LoginDialogComponent) ShowManualInput(prompt string) <-chan string

ShowManualInput appends a dim callback-code prompt with a cancel-only hint. Its returned channel delivers the submitted value and closes on cancellation.

func (*LoginDialogComponent) ShowProgress

func (d *LoginDialogComponent) ShowProgress(msg string)

ShowProgress appends an authentication diagnostic, redacting masked prompt values.

func (*LoginDialogComponent) ShowPrompt

func (d *LoginDialogComponent) ShowPrompt(prompt, placeholder string) <-chan string

ShowPrompt appends a text prompt to the existing content (login-dialog.ts:150-176 showPrompt). Its returned channel delivers the original submitted value and closes on cancellation.

func (*LoginDialogComponent) ShowSecretInput

func (d *LoginDialogComponent) ShowSecretInput(prompt, placeholder string) <-chan string

ShowSecretInput honors the configured privacy setting; false uses Pi's ordinary prompt and submitted-text rendering.

func (*LoginDialogComponent) ShowWaiting

func (d *LoginDialogComponent) ShowWaiting(msg string)

ShowWaiting appends a waiting message and cancellation hint.

func (*LoginDialogComponent) Success

func (d *LoginDialogComponent) Success()

Success marks the provider operation complete; the caller restores the editor.

type Markdown

type Markdown struct {
	Content string

	// Transform is an optional display-only rewrite of Content applied at the
	// render width before parsing, mirroring upstream MarkdownOptions.transform
	// (markdown.ts). Used to replace Mermaid code blocks with rendered diagrams.
	// A Transform that reads state outside (Content, width) must report it through
	// TransformState, or the render cache will serve a stale result.
	Transform func(markdown string, width int) string
	// TransformState reports external transform inputs so a retained Markdown component invalidates cached lines when those inputs change without a Content or width change.
	TransformState func() string
	// AsyncTransform rewrites off-loop and withholds new content until the complete rewrite is ready. During replacement it retains only a previously completed frame at the current width.
	AsyncTransform *AsyncMarkdownTransform
	// contains filtered or unexported fields
}

Markdown renders themed text with terminal-cell wrapping, padding and cached display transforms. Ports packages/tui/src/components/markdown.ts.

func NewMarkdown

func NewMarkdown(content string) *Markdown

func NewMarkdownWithOptions

func NewMarkdownWithOptions(content string, paddingX, paddingY int, theme *MarkdownTheme, style *DefaultTextStyle, options *MarkdownOptions) *Markdown

NewMarkdownWithOptions maps the full upstream constructor. NewMarkdown supplies its normal unpadded, active-theme defaults without a Go overload.

func (*Markdown) Dispose

func (m *Markdown) Dispose()

Dispose revokes this component's pending publication and removes its queued transform.

func (*Markdown) FinishStreaming

func (m *Markdown) FinishStreaming()

FinishStreaming drops the memos a streamed render keeps for the next delta (the wraps, the inline renderings and the resume point) and keeps none from later renders. The rows are the same with or without them. A text not drawn since its last change keeps them for that one render, which resumes from them and then drops them: the frame after message_end draws the last delta as the frames before it drew theirs, instead of the whole answer again.

func (*Markdown) Invalidate

func (m *Markdown) Invalidate()

Invalidate reruns the display transform and parser on the next render, even when the source text is unchanged.

func (*Markdown) IsDirty

func (m *Markdown) IsDirty() bool

IsDirty reports true while TransformState reads external state or an async transform can publish between frames, so a parent Container re-renders the child and the Markdown cache key decides whether the lines changed.

func (*Markdown) NeedsRedraw

func (i *Markdown) NeedsRedraw() bool

func (*Markdown) Render

func (m *Markdown) Render(width int) []string

func (*Markdown) SetDefaultColor

func (m *Markdown) SetDefaultColor(open string)

SetDefaultColor sets the ANSI foreground applied to ordinary Markdown text tokens. Headings, code, list markers and blockquotes retain their own theme styles. Passing an empty string restores terminal-default foreground and invalidates the cache.

func (*Markdown) SetText

func (m *Markdown) SetText(text string)

SetText replaces source text and invalidates its rendered output.

func (*Markdown) SurfaceLive

func (m *Markdown) SurfaceLive() bool

pig additive (D91): SurfaceLive reports the transforms that change the lines without invalidating the Markdown, as IsDirty does.

type MarkdownOptions

type MarkdownOptions struct {
	PreserveOrderedListMarkers bool
	PreserveBackslashEscapes   bool
	Transform                  func(markdown string, availableWidth int) string
	RenderLatex                *bool
}

MarkdownOptions controls source preservation, display transforms and math rendering. Nil RenderLatex selects the upstream default, true.

type MarkdownTheme

type MarkdownTheme struct {
	Heading, Link, LinkUrl, Code, CodeBlock, CodeBlockBorder func(string) string
	Quote, QuoteBorder, Hr, ListBullet                       func(string) string
	Bold, Italic, Strikethrough, Underline                   func(string) string
	HighlightCode                                            func(code, lang string) []string
	CodeBlockIndent                                          *string
}

MarkdownTheme supplies the styling functions used by Markdown. It mirrors packages/tui/src/components/markdown.ts.

func GetMarkdownTheme

func GetMarkdownTheme() MarkdownTheme

GetMarkdownTheme returns the markdown theme that styles each span with the active theme's markdown tokens (upstream theme.ts getMarkdownTheme). Every function reads ActiveTheme when it runs, so a theme switch restyles components that hold the result.

func MarkdownThemeFor

func MarkdownThemeFor(th *Theme) MarkdownTheme

MarkdownThemeFor is theme.ts getMarkdownTheme bound to th rather than the active theme (GetMarkdownTheme).

type MarkdownTransformContext

type MarkdownTransformContext struct {
	MessageType    string
	IsStreaming    bool
	AvailableWidth int
}

MarkdownTransformContext is upstream's MarkdownTransformContext: the kind of message text being rewritten ("assistant" or "assistant-thinking" here), whether the block is streaming, and the width the text renders at.

type MarkdownTransformQueue

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

MarkdownTransformQueue serializes individual transform generations in render admission order. Each component retains at most one queued replacement in addition to the owner's active callback.

type MarkdownTransformer

type MarkdownTransformer func(markdown string, context MarkdownTransformContext) (transformed string, ok bool)

MarkdownTransformer is upstream's MarkdownTransformer: it returns the rewritten markdown, or ok=false for a result that is not a string (upstream's undefined), which keeps the markdown unchanged.

type MessageRenderOptions

type MessageRenderOptions struct {
	Expanded  bool
	OutputPad int
}

MessageRenderOptions is upstream MessageRenderOptions: the state a custom message renderer lays out for.

type MessageRenderer

type MessageRenderer func(message *CustomMessage, options MessageRenderOptions) Component

MessageRenderer is upstream MessageRenderer: it returns a styled component for a custom message, or nil to use the default box. A panic is treated as nil.

type ModelItem

type ModelItem struct {
	FullID   string // "provider/model-id"
	Name     string // display name
	Provider string
}

ModelItem describes one model in the scoped-models list.

type ModelScope

type ModelScope int

ModelScope discriminates the two views of the picker.

const (
	ModelScopeScoped ModelScope = iota
	ModelScopeAll
)

type ModelSearchItem

type ModelSearchItem struct {
	ID       string
	Provider string
	Name     string
}

ModelSearchItem is the provider, bare id, and optional display name a model search text is built from. Mirrors upstream ModelSearchItem; an empty Name is upstream's absent (or empty) name.

type ModelSelectorComponent

type ModelSelectorComponent struct {
	Container
	Title string
	// contains filtered or unexported fields
}

ModelSelectorComponent renders a fuzzy-filtered list of models with a scope-toggle header.

func NewModelSelectorComponent

func NewModelSelectorComponent(ui TUI, current *ai.Model, runtime ModelSelectorRuntime, scoped []ScopedModelItem, onSelect func(*ai.Model), onCancel func(), initialSearch string, onSelectAsDefault func(*ai.Model), defaultModel *DefaultModelReference) *ModelSelectorComponent

NewModelSelectorComponent is model-selector.ts's constructor: it builds the picker, loads the runtime's available models and the scoped models' current metadata, asks the TUI to render, and starts the catalog refresh in the background (15 seconds at most). The refresh's outcome reaches the picker on the TUI's owner loop (PostToOwner); Dispose stops it. onSelect, onCancel and onSelectAsDefault run on the owner loop when the user decides; without onSelectAsDefault the picker has no "set as default" action. initialSearch starts the search input filled.

func NewStaticModelSelectorComponent

func NewStaticModelSelectorComponent(title string, scoped, allReachable []ModelSelectorItem, current string) *ModelSelectorComponent

NewStaticModelSelectorComponent constructs the picker from item lists the caller owns; NewModelSelectorComponent builds on it. scoped contains the session's scoped models; allReachable contains all models with configured auth. current is the current provider-qualified model ID, or empty when none is selected. With no scoped models, the picker starts in all scope and shows the provider hint.

func (*ModelSelectorComponent) Cancelled

func (m *ModelSelectorComponent) Cancelled() bool

func (*ModelSelectorComponent) CapturesSelectPageInput

func (m *ModelSelectorComponent) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the selector handles tui.select.pageUp and tui.select.pageDown.

func (*ModelSelectorComponent) Dispose

func (m *ModelSelectorComponent) Dispose()

Dispose stops the catalog refresh. The first call cancels it; later calls do nothing (model-selector.ts:224-229).

func (*ModelSelectorComponent) Done

func (m *ModelSelectorComponent) Done() bool

Done / Cancelled / SelectedFQ: modal contract.

func (*ModelSelectorComponent) Focused

func (m *ModelSelectorComponent) Focused() bool

Focused reports whether the search input holds the TUI focus (upstream `get focused`).

func (*ModelSelectorComponent) GetSearchInput

func (m *ModelSelectorComponent) GetSearchInput() *TextInput

GetSearchInput returns the search input (model-selector.ts:getSearchInput).

func (*ModelSelectorComponent) HandleInput

func (m *ModelSelectorComponent) HandleInput(data string)

HandleInput mirrors upstream model-selector.ts handleInput: it checks tui.input.tab, tui.select.up, tui.select.down, tui.select.confirm, tui.select.cancel and app.models.save in that order, and passes every other key to the search input before it reapplies the query.

func (*ModelSelectorComponent) Invalidate

func (i *ModelSelectorComponent) Invalidate()

func (*ModelSelectorComponent) IsDirty

func (i *ModelSelectorComponent) IsDirty() bool

func (*ModelSelectorComponent) NativeNode

func (m *ModelSelectorComponent) NativeNode() (frontend.Node, bool)

NativeNode reports the picker as a selector whose item ids are the models' provider/id. pig additive (D91): the scope line becomes the all/scoped tabs and the no-auth warning the description.

func (*ModelSelectorComponent) NeedsRedraw

func (i *ModelSelectorComponent) NeedsRedraw() bool

func (*ModelSelectorComponent) Scope

Scope returns the current scope (exposed for tests).

func (*ModelSelectorComponent) SelectedAsDefault

func (m *ModelSelectorComponent) SelectedAsDefault() bool

SelectedAsDefault reports whether the selection requested persistence via app.models.save.

func (*ModelSelectorComponent) SelectedFQ

func (m *ModelSelectorComponent) SelectedFQ() string

func (*ModelSelectorComponent) SetDefaultModel

func (m *ModelSelectorComponent) SetDefaultModel(fq string)

SetDefaultModel marks the settings default model ("<provider>/<id>"), which upstream badges with "· default", sorts after the current model, and matches for a "default" search.

func (*ModelSelectorComponent) SetError

func (m *ModelSelectorComponent) SetError(text string)

func (*ModelSelectorComponent) SetFilter

func (m *ModelSelectorComponent) SetFilter(query string)

func (*ModelSelectorComponent) SetFocused

func (m *ModelSelectorComponent) SetFocused(focused bool)

SetFocused propagates TUI focus to the search input, which emits the hardware-cursor marker only while focused, so the IME candidate window follows the query (upstream `set focused`, model-selector.ts:44-51).

func (*ModelSelectorComponent) SetRefreshCancel

func (m *ModelSelectorComponent) SetRefreshCancel(cancel context.CancelFunc)

SetRefreshCancel registers the cancel function of the catalog refresh this selector started (model-selector.ts refreshAbortController and refreshTimeout).

func (*ModelSelectorComponent) SetRefreshSuccess

func (m *ModelSelectorComponent) SetRefreshSuccess(text string)

SetRefreshSuccess shows the upstream "Model catalogs refreshed." status in the success color.

func (*ModelSelectorComponent) SetStatus

func (m *ModelSelectorComponent) SetStatus(text string)

func (*ModelSelectorComponent) UpdateModels

func (m *ModelSelectorComponent) UpdateModels(models []ModelSelectorItem)

UpdateModels replaces the available snapshot and refreshes scoped model metadata without dropping unavailable scoped entries. It retains the scope and query, reanchors on the current model (or clamps the cursor), then selects the best match when a query is active, like upstream loadModelsFromSnapshot followed by filterModels.

func (*ModelSelectorComponent) VisibleCount

func (m *ModelSelectorComponent) VisibleCount() int

VisibleCount returns the number of items in the filtered view.

type ModelSelectorItem

type ModelSelectorItem struct {
	Provider string
	ID       string // bare model id (e.g. "gpt-4o")
	// Name is the raw model display name (upstream model.name), empty when
	// the source has none. Search text omits an empty name; the selected-model
	// footer falls back to ID.
	Name string
}

ModelSelectorItem is one row in the picker.

func (ModelSelectorItem) FQ

func (m ModelSelectorItem) FQ() string

FQ returns the "<provider>/<id>" form used for switch dispatch.

type ModelSelectorRuntime

type ModelSelectorRuntime interface {
	GetAvailableSnapshot() []*ai.Model
	GetModel(provider, id string) *ai.Model
	GetError() string
	Refresh(ctx context.Context, options ...ai.ModelsRefreshOptions) ai.ModelsRefreshResult
}

ModelSelectorRuntime is the consumer-owned view of Pi's ModelRuntime that the selector reads (model-selector.ts:162, 169, 202 and refreshModelCatalogs' `modelRuntime.refresh({ signal })`): the available snapshot, one model by identity (nil when unknown), the runtime's load error, and the catalog refresh. Package tui cannot import coding, which owns ModelRuntime, so the interface lists exactly those four members; coding.ModelRuntime implements it (compile-time assertion in coding/model_runtime_selector.go).

type ModifierKey

type ModifierKey string

ModifierKey mirrors upstream native-platform.ts ModifierKey.

const (
	ModifierShift   ModifierKey = "shift"
	ModifierCommand ModifierKey = "command"
	ModifierControl ModifierKey = "control"
	ModifierOption  ModifierKey = "option"
)

type MouseHandler

type MouseHandler interface {
	HandleMouse(event TuiMouseEvent) *TuiMouseDispatchResult
}

MouseHandler is implemented by components with a normalized mouse handler. Mirrors upstream Component.handleMouse.

type MouseRegion

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

MouseRegion adds mouse handling to an existing component without changing its rendering. Ports pi-tui components/mouse-region.ts.

func NewMouseRegion

func NewMouseRegion(child Component, onMouse MouseRegionHandler) *MouseRegion

NewMouseRegion wraps child with onMouse. Mirrors upstream new MouseRegion.

func (*MouseRegion) HandleMouse

func (r *MouseRegion) HandleMouse(event TuiMouseEvent) *TuiMouseDispatchResult

HandleMouse gives nested mouse-aware children the first chance, then the region's own handler. Mirrors upstream MouseRegion.handleMouse.

func (*MouseRegion) Invalidate

func (r *MouseRegion) Invalidate()

Invalidate invalidates the wrapped child.

func (*MouseRegion) Render

func (r *MouseRegion) Render(width int) []string

Render renders the wrapped child unchanged.

type MouseRegionHandler

type MouseRegionHandler func(event TuiMouseEvent) *TuiMouseEventResult

MouseRegionHandler handles a mouse event that no nested child handled. Mirrors upstream MouseRegionHandler; nil means unhandled.

type NativeAction

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

NativeAction is one frontend action in progress. TuiSurface.NativeKeys steps it on the owner loop.

func NewNativeAction

func NewNativeAction(action frontend.Action) *NativeAction

NewNativeAction starts action.

type NativeClipboard

type NativeClipboard = nativeplatform.NativeClipboard

NativeClipboard is the platform helper's clipboard and optional modifier capabilities. Read methods are blocking Go equivalents of the upstream promises; invoke them off the input/render loop. available=false represents undefined, while a nil value with available=true represents null. GetFilePaths exists only on macOS, where Finder file copies are file URLs; elsewhere it is nil, upstream's undefined.

func GetNativeClipboard

func GetNativeClipboard() *NativeClipboard

func GetNativePlatformHelper

func GetNativePlatformHelper() *NativeClipboard

type NativeComponent

type NativeComponent interface {
	Component
	// NativeNode returns the component's node, and false while it shows
	// something the node does not model, which then arrives as lines.
	NativeNode() (frontend.Node, bool)
}

NativeComponent is a component that a frontend session draws as a frontend.Selector or frontend.Settings node when it takes the input editor's place in the dock.

type OAuthDeviceCodeInfo

type OAuthDeviceCodeInfo struct {
	UserCode         string
	VerificationURI  string
	IntervalSeconds  float64
	ExpiresInSeconds float64
}

OAuthDeviceCodeInfo is the user code and verification URL a device-code login shows (Pi's OAuthDeviceCodeInfo, ai compat/extension-oauth-types.ts:17); the dialog reads UserCode and VerificationURI.

type OAuthProvider

type OAuthProvider struct {
	ID       string // e.g. "github-copilot"
	Name     string // display name
	AuthType string // "oauth" or "api_key"
	// Method is the provider's auth method (Pi's `method?: ApiKeyAuth | OAuthAuth`); the selector searches its name.
	Method AuthMethod
	// Subscription reports whether the provider's OAuth sign-in is backed by a subscription. False labels it as an account; nil keeps the "subscription" label (oauth-selector.ts:20-24).
	Subscription *bool

	// Status is the provider's configured auth, or nil when it has none (Pi's `status?: AuthCheck`).
	Status AuthCheck
}

OAuthProvider is one entry in the auth provider selector.

type OAuthSelectorComponent

type OAuthSelectorComponent struct {
	Container
	// contains filtered or unexported fields
}

OAuthSelectorComponent renders the bordered provider picker (port of OAuthSelectorComponent in oauth-selector.ts).

func NewOAuthSelectorComponent

func NewOAuthSelectorComponent(mode string, providers []OAuthProvider, onSelect func(providerID, authType string), onCancel func(), initialSearch ...string) *OAuthSelectorComponent

NewOAuthSelectorComponent constructs the picker. onSelect receives the chosen provider's id and auth type and onCancel runs on cancel (upstream onSelect/onCancel); nil callbacks are skipped.

func (*OAuthSelectorComponent) Cancelled

func (s *OAuthSelectorComponent) Cancelled() bool

Cancelled reports whether Esc was pressed.

func (*OAuthSelectorComponent) CapturesSelectPageInput

func (s *OAuthSelectorComponent) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the selector handles tui.select.pageUp and tui.select.pageDown.

func (*OAuthSelectorComponent) Done

func (s *OAuthSelectorComponent) Done() bool

Done reports whether the user selected or cancelled.

func (*OAuthSelectorComponent) Focused

func (s *OAuthSelectorComponent) Focused() bool

Focused reports whether the search input holds the TUI focus (upstream `get focused`).

func (*OAuthSelectorComponent) HandleInput

func (s *OAuthSelectorComponent) HandleInput(data string)

HandleInput processes navigation, select, and cancel keys.

func (*OAuthSelectorComponent) Invalidate

func (i *OAuthSelectorComponent) Invalidate()

func (*OAuthSelectorComponent) IsDirty

func (i *OAuthSelectorComponent) IsDirty() bool

func (*OAuthSelectorComponent) NativeNode

func (s *OAuthSelectorComponent) NativeNode() (frontend.Node, bool)

NativeNode reports the picker as a selector whose item ids are the providers' ids, followed by ":" and the auth type in a list that mixes auth types, where one provider can appear once per auth type. pig additive (D91): each row's auth type label, in a mixed list, and its status indicator are its detail, and an empty list reports the empty message as the status.

func (*OAuthSelectorComponent) NeedsRedraw

func (i *OAuthSelectorComponent) NeedsRedraw() bool

func (*OAuthSelectorComponent) SelectedID

func (s *OAuthSelectorComponent) SelectedID() string

SelectedID returns the selected provider ID, or "" on cancel.

func (*OAuthSelectorComponent) SetFocused

func (s *OAuthSelectorComponent) SetFocused(focused bool)

SetFocused records TUI focus and propagates it to the search input for IME cursor positioning (upstream `set focused`).

type OkhslChannels

type OkhslChannels struct{ H, S, L float64 }

OkhslChannels are OKHSL channels: hue in degrees, saturation and lightness 0-1. Saturation is relative to the most the sRGB gamut allows at that hue and lightness, so every value is in gamut.

func ColorToOkhsl

func ColorToOkhsl(color Color) OkhslChannels

ColorToOkhsl converts any color to OKHSL channels.

type OklchChannels

type OklchChannels struct{ L, C, H float64 }

OklchChannels are OKLCH channels: lightness 0-1, chroma, hue in degrees.

func ColorToOklch

func ColorToOklch(color Color) OklchChannels

ColorToOklch converts any color to OKLCH channels.

type OklchColorValue

type OklchColorValue struct{ L, C, H float64 }

OklchColorValue is an OKLCH color (upstream `OklchColorValue`, kind "oklch"): lightness 0-1, chroma >= 0, hue in degrees [0, 360).

func NewOklchColor

func NewOklchColor(l, c, h float64) (OklchColorValue, error)

NewOklchColor mirrors `oklchColor`.

func (OklchColorValue) Kind

func (OklchColorValue) Kind() string

Kind returns "oklch".

type OscColorReply

type OscColorReply struct {
	Target OscColorTarget
	RGB    *RgbColor
}

OscColorReply is a parsed OSC 10, 11, or 4 reply. RGB is nil when the reply's color is unparseable.

func ParseOscColorResponse

func ParseOscColorResponse(data string) (reply OscColorReply, ok bool)

ParseOscColorResponse parses an OSC 10, 11, or 4 color reply. ok is false when data is not such a reply; the reply's RGB is nil when its color is unparseable.

type OscColorTarget

type OscColorTarget int

OscColorTarget names what an OSC color reply reports (upstream `"foreground" | "background" | number`): OscColorTargetForeground, OscColorTargetBackground, or a palette index (OSC 4) when non-negative.

const (
	OscColorTargetForeground OscColorTarget = -1
	OscColorTargetBackground OscColorTarget = -2
)

type OverlayBounds

type OverlayBounds struct {
	Row    int
	Col    int
	Width  int
	Height int
}

OverlayBounds is an overlay's last rendered terminal-relative rectangle. Mirrors upstream OverlayBounds.

type OverlayGeometry

type OverlayGeometry struct {
	Width, Row, Col int
	MaxHeight       int
	HasMaxHeight    bool
}

OverlayGeometry is the resolved placement of an overlay.

func ResolveOverlayGeometry

func ResolveOverlayGeometry(opts OverlayOptions, overlayHeight, termWidth, termHeight int) OverlayGeometry

ResolveOverlayGeometry resolves opts for a component of overlayHeight lines on a termWidth x termHeight screen, using the same resolver the compositor uses. Width is the width the component is rendered at.

type OverlayHandle

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

OverlayHandle lets callers control an overlay.

func (*OverlayHandle) Close

func (h *OverlayHandle) Close()

Close permanently removes this overlay.

func (*OverlayHandle) Focus

func (h *OverlayHandle) Focus()

Focus gives an eligible visible overlay keyboard focus.

func (*OverlayHandle) GetBounds

func (h *OverlayHandle) GetBounds() (OverlayBounds, bool)

GetBounds returns the most recent rendered bounds of a visible overlay. Mirrors upstream OverlayHandle.getBounds.

func (*OverlayHandle) Hide

func (h *OverlayHandle) Hide()

Hide permanently removes this overlay, matching Pi's OverlayHandle.hide.

func (*OverlayHandle) IsFocused

func (h *OverlayHandle) IsFocused() bool

IsFocused reports whether this overlay currently has focus.

func (*OverlayHandle) IsHidden

func (h *OverlayHandle) IsHidden() bool

IsHidden reports the mounted overlay's explicit hidden state.

func (*OverlayHandle) SetHidden

func (h *OverlayHandle) SetHidden(hidden bool)

SetHidden changes visibility without removing the overlay.

func (*OverlayHandle) Unfocus

func (h *OverlayHandle) Unfocus()

Unfocus restores focus to the next eligible component. It keeps its zero-argument signature so that a value assigned to interface{ Unfocus() } keeps compiling; UnfocusWith is upstream OverlayHandle.unfocus(options).

func (*OverlayHandle) UnfocusWith

func (h *OverlayHandle) UnfocusWith(options OverlayUnfocusOptions)

UnfocusWith releases focus to options' explicit target, which may be nil, instead of the next visible capturing overlay or previous target. Mirrors upstream OverlayHandle.unfocus(options).

type OverlayMarginAll

type OverlayMarginAll int

OverlayMarginAll is the numeric form of margin: the same margin on all four edges.

type OverlayMarginOption

type OverlayMarginOption interface {
	// contains filtered or unexported methods
}

OverlayMarginOption is upstream's `margin?: number | OverlayMargin` (tui.ts:243): the variants are OverlayMarginAll and OverlayMarginSpec, and nil is an omitted margin.

type OverlayMarginSpec

type OverlayMarginSpec struct {
	Top, Right, Bottom, Left int
}

OverlayMarginSpec mirrors upstream OverlayMargin: a margin per edge.

type OverlayOptions

type OverlayOptions struct {

	// Fullscreen marks an overlay that covers the whole screen, such as an
	// animation of fullscreen mode. pig additive (D91): a TuiSurface reports
	// it as a fullscreen frontend.Overlay at the session's screen size; the
	// terminal renderers lay it out by its other options.
	Fullscreen bool

	// WidthFraction, HeightFraction, and Title configure the private built-in
	// modal wrapper.
	WidthFraction  float64
	HeightFraction float64
	Title          string
	// contains filtered or unexported fields
}

OverlayOptions controls the size/position of an overlay.

type OverlaySpec

type OverlaySpec struct {
	Width        *OverlayValue
	MinWidth     *int
	MaxHeight    *OverlayValue
	Anchor       string
	OffsetX      int
	OffsetY      int
	Row          *OverlayValue
	Col          *OverlayValue
	Margin       OverlayMarginOption
	NonCapturing bool
}

OverlaySpec is the serialisable subset of upstream pi-tui OverlayOptions (everything except the visible callback). It lets callers outside this package, such as the subprocess extension bridge, open a component-framed overlay whose geometry resolves exactly like upstream showOverlay.

func (OverlaySpec) Options

func (s OverlaySpec) Options() OverlayOptions

Options converts the spec into OverlayOptions. The result carries no modal title or fractions, so ShowOverlay mounts the component without a frame.

type OverlayUnfocusOptions

type OverlayUnfocusOptions struct {
	Target Component
}

OverlayUnfocusOptions mirrors upstream OverlayUnfocusOptions: an explicit focus target, which may be nil, used after this overlay releases focus.

type OverlayValue

type OverlayValue struct {
	Value   float64
	Percent bool
	// Invalid preserves a supplied but malformed size, distinct from omission.
	Invalid bool
}

OverlayValue is a serialisable upstream SizeValue: an absolute cell count or, when Percent is set, a percentage of the terminal dimension.

type ParsedSkillBlock

type ParsedSkillBlock struct {
	Name    string
	Content string
}

ParsedSkillBlock holds the parsed skill invocation data. Mirrors upstream's ParsedSkillBlock.

type PlatformKeys

type PlatformKeys struct {
	Other    []string
	Darwin   []string
	Windows  []string
	Win32    []string
	LinuxWSL []string
}

PlatformKeys holds default keys that differ by platform. Other applies unless a narrower field is non-nil. Windows covers every platform that uses Windows keybindings (win32 and WSL); Win32, LinuxWSL, and Darwin override it for one platform. A non-nil empty slice means "no default key" on that platform, as upstream's `[]`.

func (PlatformKeys) For

func (k PlatformKeys) For(platform KeybindingPlatform) []string

For returns the default keys for platform.

type ProcessTerminal

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

ProcessTerminal is the concrete terminal control implementation backed by process stdin/stdout (or test doubles).

func NewProcessTerminal

func NewProcessTerminal(stdin, stdout *os.File) *ProcessTerminal

NewProcessTerminal constructs a terminal helper around the provided stdin and stdout files.

func NewProcessTerminalWithOutput

func NewProcessTerminalWithOutput(stdin, stdout *os.File, out io.Writer) *ProcessTerminal

NewProcessTerminalWithOutput constructs a terminal helper whose control bytes are written to out. Used by tests that want stdout-like behavior without touching the real terminal.

func NewStdioProcessTerminal

func NewStdioProcessTerminal() *ProcessTerminal

NewStdioProcessTerminal is `new ProcessTerminal()` (terminal.ts): a terminal over the process's own standard input and output.

func (*ProcessTerminal) CacheSizeUntilResize

func (t *ProcessTerminal) CacheSizeUntilResize() (invalidate, stop func())

CacheSizeUntilResize makes Columns and Rows reuse the size they last read, as Node keeps process.stdout.columns and rows and refreshes them only when SIGWINCH arrives (lib/tty.js WriteStream._refreshSize), instead of reading the size from the terminal for every frame. The caller must own SIGWINCH delivery and run invalidate on every SIGWINCH before it renders for it; stop ends the caching once every holder has stopped.

func (*ProcessTerminal) ClearFromCursor

func (t *ProcessTerminal) ClearFromCursor()

ClearFromCursor clears from the cursor to the end of the screen.

func (*ProcessTerminal) ClearLine

func (t *ProcessTerminal) ClearLine()

ClearLine clears from the cursor to the end of the current line.

func (*ProcessTerminal) ClearScreen

func (t *ProcessTerminal) ClearScreen()

ClearScreen clears the screen and homes the cursor.

func (*ProcessTerminal) Columns

func (t *ProcessTerminal) Columns() int

Columns returns the terminal width, falling back to COLUMNS or 80 when unavailable.

func (*ProcessTerminal) DrainInput

func (t *ProcessTerminal) DrainInput(maxWait, idleWait time.Duration) error

DrainInput drains pending stdin bytes for up to maxWait, exiting early once no new bytes arrive within idleWait. This mirrors upstream's slow-SSH guard against key release sequences leaking into the parent shell on exit. A read that fails (EOF from a hung-up terminal, EIO) ends the drain with that error, as Pi's stdin reports it to its error handler.

Disables the extended-key protocols first, as upstream's drainInput does: a drain that runs while the terminal is still reporting key events has no stable end, because releasing the keys pressed during the drain produces more input. Idempotent, so a caller that already disabled loses nothing.

func (*ProcessTerminal) EnterRawMode

func (t *ProcessTerminal) EnterRawMode() (restore func(), err error)

EnterRawMode puts this terminal into raw mode and returns a restore closure that drains late extended-key releases before restoring cooked mode.

func (*ProcessTerminal) HideCursor

func (t *ProcessTerminal) HideCursor()

HideCursor hides the terminal cursor.

func (*ProcessTerminal) KittyProtocolActive

func (*ProcessTerminal) KittyProtocolActive() bool

KittyProtocolActive reports whether this raw-mode session received non-zero Kitty keyboard protocol flags.

func (*ProcessTerminal) ModifyOtherKeysActive

func (*ProcessTerminal) ModifyOtherKeysActive() bool

ModifyOtherKeysActive reports whether modifyOtherKeys is enabled for this raw-mode session (terminal.ts: modifyOtherKeysActive getter).

func (*ProcessTerminal) MoveBy

func (t *ProcessTerminal) MoveBy(lines int)

MoveBy moves the cursor relative to its current row.

func (*ProcessTerminal) NewTerminalInput

func (t *ProcessTerminal) NewTerminalInput(onInput func(string)) *TerminalInput

NewTerminalInput constructs an input decoder bound to this terminal's protocol control output.

func (*ProcessTerminal) RestoreOnExit

func (t *ProcessTerminal) RestoreOnExit(before, after string)

RestoreOnExit is Terminal.restoreOnExit (ProcessTerminal.restoreOnExit upstream): it writes before, then this terminal's own mode resets, then after. The write is one synchronous write to the output. It skips the output lock when another goroutine holds it, because that goroutine may be the one stuck on a terminal that went away.

func (*ProcessTerminal) Rows

func (t *ProcessTerminal) Rows() int

Rows returns the terminal height, falling back to LINES or 24 when unavailable.

func (*ProcessTerminal) SetProgramStatus

func (t *ProcessTerminal) SetProgramStatus(status ProgramStatus)

SetProgramStatus implements Terminal: it records status and, once the terminal supports OSC 7501, writes it.

func (*ProcessTerminal) SetProgress

func (t *ProcessTerminal) SetProgress(active bool)

SetProgress writes the OSC 9;4 progress indicator and keeps it alive during agent work. Clearing stops the keepalive and writes OSC 9;4;0 followed directly by BEL.

func (*ProcessTerminal) SetTitle

func (t *ProcessTerminal) SetTitle(title string)

SetTitle writes an OSC 0 title update sequence.

func (*ProcessTerminal) ShowCursor

func (t *ProcessTerminal) ShowCursor()

ShowCursor shows the terminal cursor.

func (*ProcessTerminal) Start

func (t *ProcessTerminal) Start(onInput func(string), onResize func()) error

Start enters raw mode and owns input and resize delivery. Each onInput callback receives one framed, normalized event after keyboard negotiation filtering. Callbacks run synchronously in input order.

Use ProcessTerminal.StartWithReadError to distinguish terminal closure from user input. Caller-owned loops use EnterRawMode, ReadInputStream and TerminalInput instead.

Calling Start twice without an intervening Stop is a no-op.

func (*ProcessTerminal) StartWithReadError

func (t *ProcessTerminal) StartWithReadError(onInput func([]byte), onResize func(), onReadError func(error)) error

StartWithReadError starts terminal input and reports the error that ends the input loop. Cancellation through ProcessTerminal.Stop does not report an error.

func (*ProcessTerminal) Stop

func (t *ProcessTerminal) Stop()

Stop mirrors upstream `ProcessTerminal.stop()`. It cancels and joins the input goroutine, removes the resize handler, and restores cooked mode without draining unread input. This lets a subsequent terminal owner receive bytes typed during focus handoff. Safe to call multiple times; a standalone protocol query is unwound even when no reader was started.

func (*ProcessTerminal) Write

func (t *ProcessTerminal) Write(data string)

Write emits data to the terminal output.

type ProgramState

type ProgramState string

ProgramState is the state a ProgramStatus reports. `clear` removes the status instead of reporting one.

const (
	ProgramStateIdle    ProgramState = "idle"
	ProgramStateWorking ProgramState = "working"
	ProgramStateBlocked ProgramState = "blocked"
	ProgramStateDone    ProgramState = "done"
	ProgramStateError   ProgramState = "error"
	ProgramStateClear   ProgramState = "clear"
)

type ProgramStatus

type ProgramStatus struct {
	State ProgramState
	// App is a stable program name, `[A-Za-z0-9_.+-]{1,32}`. Other values are omitted.
	App string
	// Kind is what a blocked program waits for. Omitted for other states.
	Kind ProgramStatusKind
	// Message is one human-readable line. Control characters become spaces; longer text is cut to the spec limit.
	Message string
}

ProgramStatus is one status report. A field that is the empty string is upstream's absent (`undefined`) field.

type ProgramStatusKind

type ProgramStatusKind string

ProgramStatusKind is what a blocked program waits for.

const (
	ProgramStatusKindPermission ProgramStatusKind = "permission"
	ProgramStatusKindQuestion   ProgramStatusKind = "question"
	ProgramStatusKindAuth       ProgramStatusKind = "auth"
)

type RefreshStatusKind

type RefreshStatusKind string

RefreshStatusKind controls the refresh message emphasis.

const (
	RefreshStatusMuted   RefreshStatusKind = "muted"
	RefreshStatusSuccess RefreshStatusKind = "success"
	RefreshStatusWarning RefreshStatusKind = "warning"
)

type RemoteSuggestionQuery

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

RemoteSuggestionQuery captures a local provider's synchronous answer and its awaited work without reading the editor again.

func NewAutocompleteQuery

func NewAutocompleteQuery(provider AutocompleteProvider, lines []string, cursorLine, cursorCol int, force bool) *RemoteSuggestionQuery

NewAutocompleteQuery captures the local provider's answer and deferred filesystem search on the owner loop. Run awaits filesystem work off-loop.

func (*RemoteSuggestionQuery) RunResult

RunResult awaits the query and preserves callback errors for its caller.

type RenderDiffOptions

type RenderDiffOptions struct {
	FilePath string
}

RenderDiffOptions mirrors upstream RenderDiffOptions (diff.ts:68). The file path is unused and kept for API compatibility.

type RenderOverflowError

type RenderOverflowError struct {
	Line          int
	LineWidth     int
	TerminalWidth int
	LogPath       string
}

RenderOverflowError is the value doRender panics with when an over-wide non-image row reaches the differential-render loop. Its message is the Error thrown by upstream TuiMainScreen.doRender (tui-main-screen.ts:536-544).

func (*RenderOverflowError) Error

func (e *RenderOverflowError) Error() string

type RendererFallback

type RendererFallback interface {
	SetRendererFallback(func(width int) []string)
}

RendererFallback is implemented by a renderer component whose rendering can fail after it was returned, because an extension process renders it. The card supplies the fallback upstream shows for a renderer that throws.

type ResourceGroup

type ResourceGroup struct {
	Key       string
	Label     string
	Scope     string
	Origin    string
	Source    string
	Subgroups []*ResourceSubgroup
}

ResourceGroup is a top-level grouping (by origin + scope + source).

func BuildResourceGroups

func BuildResourceGroups(resources []ResourceItem) []*ResourceGroup

BuildResourceGroups constructs groups from resolved resource data. This is a helper for callers that have raw path lists.

type ResourceItem

type ResourceItem struct {
	Path         string
	Enabled      bool
	ResourceType ResourceType
	DisplayName  string
	GroupKey     string
	SubgroupKey  string
	Scope        string // "user" or "project"
	Origin       string // "package" or "top-level"
	Source       string
	BaseDir      string // for package-relative pattern generation
	// PackageRoot is the root of the package a resource belongs to (package-manager.ts PathMetadata.packageRoot): set for a local
	// directory or an installed npm or git package, empty for a local file source, whose BaseDir is only the file's directory.
	PackageRoot      string
	Pattern          string // authored Package-relative member path
	Health           string // empty or "missing"
	Override         string // "inherit", "load", or "unload" in project mode
	Inherited        bool
	InheritedEnabled bool
}

ResourceItem is a single toggleable resource.

type ResourceSubgroup

type ResourceSubgroup struct {
	Type  ResourceType
	Label string
	Items []*ResourceItem
}

ResourceSubgroup groups items by resource type within a group.

type ResourceType

type ResourceType string

ResourceType identifies the kind of package resource.

const (
	ResourceExtensions ResourceType = "extensions"
	ResourceSkills     ResourceType = "skills"
	ResourcePrompts    ResourceType = "prompts"
	ResourceThemes     ResourceType = "themes"
)

type RgbColor

type RgbColor struct {
	R float64
	G float64
	B float64
}

RgbColor preserves JavaScript numeric channels, including NaN when an overflowing channel is scaled by an infinite maximum.

func ColorToRgb

func ColorToRgb(color Color) RgbColor

ColorToRgb converts any color to sRGB.

func ParseOsc11BackgroundColor deprecated

func ParseOsc11BackgroundColor(data string) *RgbColor

ParseOsc11BackgroundColor parses a strict OSC 11 reply, or returns nil.

Deprecated: use ParseOscColorResponse.

type RgbColorValue

type RgbColorValue struct{ R, G, B float64 }

RgbColorValue is an sRGB color with channels 0-255 (upstream `RgbColorValue`, kind "rgb"). Channels may be fractional.

func NewOkhslColor

func NewOkhslColor(h, s, l float64) (RgbColorValue, error)

NewOkhslColor mirrors `okhslColor`: an OKHSL color converted to sRGB. Saturation is relative to the sRGB gamut at the hue and lightness, so equal saturation looks equally colorful across hues and lightness. h is in degrees; s and l are 0-1.

func NewRgbColor

func NewRgbColor(r, g, b float64) (RgbColorValue, error)

NewRgbColor mirrors `rgbColor`.

func (RgbColorValue) Kind

func (RgbColorValue) Kind() string

Kind returns "rgb".

type ScopedModelItem

type ScopedModelItem struct {
	Model         *ai.Model
	ThinkingLevel string
}

ScopedModelItem is one scoped model of a session (model-selector.ts ScopedModelItem).

type ScopedModelsConfig

type ScopedModelsConfig struct {
	AllModels       []ModelItem
	EnabledModelIDs []string // nil = all enabled
	RefreshStatus   string
}

ScopedModelsConfig configures the scoped-models list.

type ScopedModelsList

type ScopedModelsList struct {
	Container
	// contains filtered or unexported fields
}

ScopedModelsList is the /scoped-models selector component.

func NewScopedModelsList

func NewScopedModelsList(cfg ScopedModelsConfig) *ScopedModelsList

NewScopedModelsList creates a new scoped-models selector.

func (*ScopedModelsList) CapturesSelectPageInput

func (s *ScopedModelsList) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the list handles tui.select.pageUp and tui.select.pageDown.

func (*ScopedModelsList) ConsumeSave

func (s *ScopedModelsList) ConsumeSave() ([]string, bool)

ConsumeSave returns the most recent Ctrl+S save request and clears it.

func (*ScopedModelsList) Done

func (s *ScopedModelsList) Done() bool

Done reports whether the user has confirmed, persisted, or cancelled.

func (*ScopedModelsList) EnabledIDs

func (s *ScopedModelsList) EnabledIDs() []string

EnabledIDs returns the current enabled model IDs (nil = all).

func (*ScopedModelsList) HandleInput

func (s *ScopedModelsList) HandleInput(data string)

HandleInput processes a keystroke.

func (*ScopedModelsList) Invalidate

func (i *ScopedModelsList) Invalidate()

func (*ScopedModelsList) IsDirty

func (i *ScopedModelsList) IsDirty() bool

func (*ScopedModelsList) NativeNode

func (s *ScopedModelsList) NativeNode() (frontend.Node, bool)

NativeNode reports the list as a selector whose item ids are the models' full ids and whose checks are the enabled models. pig additive (D91): the status carries the refresh message, then the footer's enabled count and unsaved marker without its key hints.

func (*ScopedModelsList) NeedsRedraw

func (i *ScopedModelsList) NeedsRedraw() bool

func (*ScopedModelsList) Result

Result returns the outcome after Done()==true.

func (*ScopedModelsList) SetRefreshStatus

func (s *ScopedModelsList) SetRefreshStatus(message string, kind RefreshStatusKind)

SetRefreshStatus replaces the catalog refresh message rendered above the footer.

func (*ScopedModelsList) UpdateModels

func (s *ScopedModelsList) UpdateModels(models []ModelItem, enabledIDs ...[]string)

UpdateModels publishes a refreshed catalog while preserving the selected model. Supplying enabledIDs also replaces the selection; an explicit nil means all.

type ScopedModelsResult

type ScopedModelsResult struct {
	EnabledIDs []string // nil = all enabled
	Persisted  bool     // retained for compatibility; Ctrl+S no longer closes the selector
	Cancelled  bool
}

ScopedModelsResult describes the outcome after Done()==true.

type ScrollLayoutNode

type ScrollLayoutNode struct {
	Component Component
	State     ScrollLayoutState
}

ScrollLayoutNode is a scroll layout node. State holds the narrow interface, not the concrete ScrollView, preserving upstream's intentional narrowing.

type ScrollLayoutState

type ScrollLayoutState interface {
	ScrollTop() int
	Primary() bool
	Overscroll() string
	ViewportHeight() int
	GetContentWidth(width int) int
	UpdateLayout(contentHeight, viewportHeight int, requestRender func())
}

ScrollLayoutState is the narrow contract the layout engine sees for a scroll node; *ScrollView implements it and is passed as the node's State. Upstream's readonly fields (scrollTop, primary, overscroll, viewportHeight) are getter methods here because a Go interface cannot carry fields.

type ScrollView

type ScrollView struct {
	*Container
	// contains filtered or unexported fields
}

ScrollView ports pi-tui's ScrollView. It embeds pig's Container (holding the single child) and owns the transient-scrollbar timer.

func GetScrollViewsAt

func GetScrollViewsAt(frame LayoutFrame, x, y int) []*ScrollView

GetScrollViewsAt returns the scroll views under a point, deepest first. Mirrors upstream getScrollViewsAt.

func NewScrollView

func NewScrollView(component Component, options ScrollViewOptions) *ScrollView

NewScrollView constructs a ScrollView. It panics on an unsupported axis, mirroring upstream's constructor throw.

func (*ScrollView) Add

func (s *ScrollView) Add(Component)

Add panics: a ScrollView has exactly one child (upstream throw).

func (*ScrollView) Clear

func (s *ScrollView) Clear()

Clear panics: a ScrollView's child cannot be cleared (upstream throw).

func (*ScrollView) Dispose

func (s *ScrollView) Dispose()

Dispose stops the hide timer so no goroutine outlives the view.

func (*ScrollView) FollowEnd

func (s *ScrollView) FollowEnd() bool

FollowEnd reports whether the view was configured to follow its end.

func (*ScrollView) GetContentWidth

func (s *ScrollView) GetContentWidth(width int) int

GetContentWidth returns the child render width, reserving a column for an always-on scrollbar.

func (ScrollView) Invalidate

func (i ScrollView) Invalidate()

func (ScrollView) IsDirty

func (i ScrollView) IsDirty() bool

func (*ScrollView) IsFollowingEnd

func (s *ScrollView) IsFollowingEnd() bool

IsFollowingEnd reports whether the view is pinned to the end.

func (*ScrollView) IsScrollbarActive

func (s *ScrollView) IsScrollbarActive() bool

IsScrollbarActive reports whether the pointer is hovering or dragging the scrollbar.

func (*ScrollView) IsScrollbarVisible

func (s *ScrollView) IsScrollbarVisible() bool

IsScrollbarVisible reports whether the scrollbar should paint this frame.

func (*ScrollView) LayoutNode

func (s *ScrollView) LayoutNode() LayoutNode

LayoutNode ports upstream ScrollView[LAYOUT_NODE](): a scroll node whose state is this ScrollView narrowed to ScrollLayoutState.

func (ScrollView) NeedsRedraw

func (i ScrollView) NeedsRedraw() bool

func (*ScrollView) Overscroll

func (s *ScrollView) Overscroll() string

Overscroll reports the overscroll mode.

func (*ScrollView) Primary

func (s *ScrollView) Primary() bool

Primary reports whether this is the primary scroll view.

func (*ScrollView) Remove

func (s *ScrollView) Remove(Component)

Remove panics: a ScrollView's child cannot be removed (upstream throw).

func (*ScrollView) Render

func (s *ScrollView) Render(width int) []string

Render ports upstream ScrollView.render: render the child at the content width, padding each line by a column when a scrollbar column is reserved.

func (*ScrollView) ScrollBy

func (s *ScrollView) ScrollBy(lines int) int

ScrollBy scrolls by a relative number of lines and returns the leftover lines that could not be applied (for overscroll chaining).

func (*ScrollView) ScrollTo

func (s *ScrollView) ScrollTo(scrollTop int, opts ...ScrollViewScrollToOptions)

ScrollTo scrolls to an absolute offset, clamped to the scrollable range. Mirrors upstream scrollTo(scrollTop, options = {}); the optional options are the second parameter.

func (*ScrollView) ScrollToEnd

func (s *ScrollView) ScrollToEnd()

ScrollToEnd scrolls to the bottom.

func (*ScrollView) ScrollToStart

func (s *ScrollView) ScrollToStart()

ScrollToStart scrolls to the top.

func (*ScrollView) ScrollTop

func (s *ScrollView) ScrollTop() int

ScrollTop reports the current scroll offset.

func (*ScrollView) Scrollbar

func (s *ScrollView) Scrollbar() ScrollViewScrollbar

Scrollbar reports the current scrollbar mode.

func (*ScrollView) ScrollbarThumbStyle

func (s *ScrollView) ScrollbarThumbStyle(text string) string

ScrollbarThumbStyle styles scrollbar thumb cells (upstream scroll-view.ts:28).

func (*ScrollView) ScrollbarTrackStyle

func (s *ScrollView) ScrollbarTrackStyle(text string) string

ScrollbarTrackStyle styles scrollbar track cells: upstream's readonly `scrollbarTrackStyle` is a function property, so it is called with the text. upstream: packages/tui/src/components/scroll-view.ts:27

func (*ScrollView) SetScrollbar

func (s *ScrollView) SetScrollbar(scrollbar ScrollViewScrollbar)

SetScrollbar changes the scrollbar mode.

func (*ScrollView) SetScrollbarActive

func (s *ScrollView) SetScrollbarActive(active bool)

SetScrollbarActive marks the scrollbar as actively dragged (keeping it shown).

func (*ScrollView) UpdateLayout

func (s *ScrollView) UpdateLayout(contentHeight, viewportHeight int, requestRender func())

UpdateLayout is called by the layout engine each pass with the measured content and viewport heights; it clamps the scroll offset and stores the render callback the hide timer will invoke.

func (*ScrollView) ViewportHeight

func (s *ScrollView) ViewportHeight() int

ViewportHeight reports the current viewport height.

type ScrollViewOptions

type ScrollViewOptions struct {
	Axis                 string // "" (unset) or "vertical"
	Follow               string // "none" | "end"
	Primary              bool
	Overscroll           string // "chain" | "contain"
	Scrollbar            ScrollViewScrollbar
	ScrollbarTrackStyle  func(text string) string
	ScrollbarThumbStyle  func(text string) string
	ScrollbarHideDelayMs *int
}

ScrollViewOptions configure a ScrollView. Empty string fields take upstream's default; ScrollbarHideDelayMs nil defaults to 1000ms.

type ScrollViewScrollToOptions

type ScrollViewScrollToOptions struct {
	// DisableFollow keeps follow-end disabled even when the target is the
	// current content end.
	DisableFollow bool
}

ScrollViewScrollToOptions mirrors upstream ScrollViewScrollToOptions.

type ScrollViewScrollbar

type ScrollViewScrollbar string

ScrollViewScrollbar is the scrollbar mode: "hidden", "auto" or "always" (components/scroll-view.ts ScrollViewScrollbar).

const (
	ScrollbarHidden ScrollViewScrollbar = "hidden"
	ScrollbarAuto   ScrollViewScrollbar = "auto"
	ScrollbarAlways ScrollViewScrollbar = "always"
)

type ScrollbarGeometry

type ScrollbarGeometry struct {
	Column       int
	TrackTop     int
	TrackHeight  int
	ThumbTop     int
	ThumbHeight  int
	MaxScrollTop int
}

ScrollbarGeometry describes where a scroll viewport's scrollbar paints.

func GetScrollbarGeometry

func GetScrollbarGeometry(box *LayoutBox) *ScrollbarGeometry

GetScrollbarGeometry computes where a scroll box's scrollbar paints, or nil if it should not paint. Mirrors upstream getScrollbarGeometry(box).

type SegmentData

type SegmentData = wordsegmenter.SegmentData

type SelectItem

type SelectItem struct {
	Value       string
	Label       string
	Description string
}

SelectItem mirrors upstream pi-tui's SelectItem shape for submenu-style selectors (value + label + optional description).

type SelectList

type SelectList struct {

	// OnSelect runs when the selected item is confirmed (Enter or a click).
	OnSelect func(item SelectItem)
	// OnCancel runs on the cancel key.
	OnCancel func()
	// OnSelectionChange runs when the selection moves.
	OnSelectionChange func(item SelectItem)
	// contains filtered or unexported fields
}

SelectList is a scrolling list of [SelectItem]s with a primary column and optional descriptions. The visible window is centered on the selection.

upstream: select-list.ts:42 (SelectList)

func NewSelectList

func NewSelectList(items []SelectItem, maxVisible int, theme SelectListTheme, layout ...SelectListLayoutOptions) *SelectList

NewSelectList creates a list of items showing up to maxVisible rows.

func (*SelectList) CapturesSelectPageInput

func (l *SelectList) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the list handles tui.select.pageUp and tui.select.pageDown.

func (*SelectList) FilteredItems

func (l *SelectList) FilteredItems() []SelectItem

FilteredItems returns the items passing the current filter, in order.

func (*SelectList) HandleInput

func (l *SelectList) HandleInput(data string)

HandleInput moves the selection (wrapping at both ends), confirms or cancels through the tui.select.* keybindings.

func (*SelectList) HandleMouse

func (l *SelectList) HandleMouse(event TuiMouseEvent) *TuiMouseDispatchResult

HandleMouse scrolls on the wheel, selects on press and confirms on click; hover never changes the selection.

func (*SelectList) Invalidate

func (i *SelectList) Invalidate()

func (*SelectList) IsDirty

func (i *SelectList) IsDirty() bool

func (*SelectList) MaxVisible

func (l *SelectList) MaxVisible() int

MaxVisible returns the number of rows rendered at once.

func (*SelectList) NativeNode

func (l *SelectList) NativeNode() (frontend.Node, bool)

NativeNode reports the list as a selector whose item ids are the items' values.

func (*SelectList) NeedsRedraw

func (i *SelectList) NeedsRedraw() bool

func (*SelectList) Render

func (l *SelectList) Render(width int) []string

Render draws the visible rows, then a (selected/total) line when the list scrolls.

func (*SelectList) SelectedIndex

func (l *SelectList) SelectedIndex() int

SelectedIndex returns the selection's index into FilteredItems.

func (*SelectList) SelectedItem

func (l *SelectList) SelectedItem() (SelectItem, bool)

SelectedItem returns the selected item of the filtered list.

func (*SelectList) SetFilter

func (l *SelectList) SetFilter(filter string)

SetFilter keeps the items whose value starts with filter, ignoring case, and resets the selection to the first.

func (*SelectList) SetSelectedIndex

func (l *SelectList) SetSelectedIndex(index int)

SetSelectedIndex selects an item of the filtered list, clamping the index into range.

func (*SelectList) SetTheme

func (l *SelectList) SetTheme(theme SelectListTheme)

SetTheme restyles the list.

type SelectListLayoutOptions

type SelectListLayoutOptions struct {
	MinPrimaryColumnWidth int
	MaxPrimaryColumnWidth int
	// TruncatePrimary shortens the primary text; the result is clipped to the available width.
	TruncatePrimary func(context SelectListTruncatePrimaryContext) string
}

SelectListLayoutOptions sizes the primary column of a SelectList. A zero width is unset.

upstream: select-list.ts:36 (SelectListLayoutOptions)

type SelectListTheme

type SelectListTheme struct {
	SelectedPrefix func(text string) string
	SelectedText   func(text string) string
	Description    func(text string) string
	ScrollInfo     func(text string) string
	NoMatch        func(text string) string
}

SelectListTheme styles a SelectList. A nil function leaves the text unstyled.

upstream: packages/tui/src/components/select-list.ts:20 (SelectListTheme)

func GetSelectListTheme

func GetSelectListTheme() SelectListTheme

GetSelectListTheme is the list styling taken from the active theme (theme.ts getSelectListTheme): the selection and prefix are accent, everything else muted. The colors are read when each part is drawn.

func SelectListThemeFor

func SelectListThemeFor(th *Theme) SelectListTheme

SelectListThemeFor is theme.ts getSelectListTheme bound to th rather than the active theme (GetSelectListTheme).

type SelectListTruncatePrimaryContext

type SelectListTruncatePrimaryContext struct {
	Text        string
	MaxWidth    int
	ColumnWidth int
	Item        SelectItem
	IsSelected  bool
}

SelectListTruncatePrimaryContext describes one primary-column truncation. Mirrors upstream SelectListTruncatePrimaryContext.

type SelectPageInputCapturer

type SelectPageInputCapturer interface {
	CapturesSelectPageInput() bool
}

SelectPageInputCapturer is implemented by components whose selection handles tui.select.pageUp and tui.select.pageDown. Fullscreen mode gives those keys to the focused capturer before it scrolls the viewport. Mirrors Pi PR #7680's Component.capturesSelectPageInput.

type SelectSubmenuComponent

type SelectSubmenuComponent struct {
	Container

	// OnSelectionChange runs with the highlighted value after every up or down key that reaches a non-empty list, even when the
	// highlight lands on the same item, as upstream's SelectList onSelectionChange does.
	OnSelectionChange func(value string)
	// contains filtered or unexported fields
}

SelectSubmenuComponent shows a titled select list with optional fuzzy search.

func NewSelectSubmenu

func NewSelectSubmenu(title, description string, items []SelectItem, currentValue string, options ...SelectSubmenuOptions) *SelectSubmenuComponent

func (*SelectSubmenuComponent) Cancelled

func (s *SelectSubmenuComponent) Cancelled() bool

func (*SelectSubmenuComponent) CurrentValue

func (s *SelectSubmenuComponent) CurrentValue() string

func (*SelectSubmenuComponent) Done

func (s *SelectSubmenuComponent) Done() bool

func (*SelectSubmenuComponent) HandleInput

func (s *SelectSubmenuComponent) HandleInput(data string)

func (*SelectSubmenuComponent) Invalidate

func (i *SelectSubmenuComponent) Invalidate()

func (*SelectSubmenuComponent) IsDirty

func (i *SelectSubmenuComponent) IsDirty() bool

func (*SelectSubmenuComponent) NativeNode

func (s *SelectSubmenuComponent) NativeNode() (frontend.Node, bool)

NativeNode reports the submenu as a selector whose item ids are the items' values.

func (*SelectSubmenuComponent) NeedsRedraw

func (i *SelectSubmenuComponent) NeedsRedraw() bool

func (*SelectSubmenuComponent) SelectedValue

func (s *SelectSubmenuComponent) SelectedValue() string

func (*SelectSubmenuComponent) String

func (s *SelectSubmenuComponent) String() string

type SelectSubmenuOptions

type SelectSubmenuOptions struct {
	Searchable            bool
	MinPrimaryColumnWidth int
	MaxPrimaryColumnWidth int
}

SelectSubmenuOptions enables fuzzy search and overrides the primary-column layout.

type SettingItem

type SettingItem struct {
	ID           string   // unique identifier
	Label        string   // display label (left column)
	Description  string   // shown below list when selected
	CurrentValue string   // right column
	Values       []string // Enter/Space cycles through these
	// Submenu opens when Enter activates the item. done closes it: a non-nil selectedValue becomes the item's value, and options.NavigateTo moves the cursor to that item and activates it (settings-list.ts SettingItem.submenu).
	Submenu func(currentValue string, done func(selectedValue *string, options *SubmenuDoneOptions)) Component
}

SettingItem describes one toggle-able setting.

type SettingsList

type SettingsList struct {

	// Last change made (for the caller loop pattern).
	ChangedID    string
	ChangedValue string
	// contains filtered or unexported fields
}

SettingsList is a two-column selector that cycles setting values. After Done()==true, callers read ChangedID/ChangedValue for the last change, or Cancelled() if the user pressed Esc. A host that keeps the list open, as upstream's onChange does, applies the change and calls Reset.

func NewSettingsList

func NewSettingsList(items []SettingItem, maxVisible int, theme SettingsListTheme, onChange func(id, newValue string), onCancel func(), options ...SettingsListOptions) *SettingsList

NewSettingsList ports upstream's SettingsList constructor, `new SettingsList(items, maxVisible, theme, onChange, onCancel, options = {})` (settings-list.ts:55-73): the list is drawn with theme, onChange and onCancel are its callbacks, and search is off unless options.EnableSearch is true. Only the first options value is read, as upstream takes one. A nil callback keeps the caller-loop behaviour for that event: the list records the change in ChangedID/ChangedValue, or the cancel in Cancelled, for the host to read. onChange runs after the row shows the new value, including a value a submenu returns, and onCancel runs when Esc is pressed on the main list. maxVisible is clamped to at least 1.

func (*SettingsList) Cancelled

func (s *SettingsList) Cancelled() bool

Cancelled reports whether the user pressed Esc.

func (*SettingsList) CapturesSelectPageInput

func (s *SettingsList) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the list handles tui.select.pageUp and tui.select.pageDown.

func (*SettingsList) DisplayedItems

func (s *SettingsList) DisplayedItems() []SettingItem

DisplayedItems returns the items passing the current search, in order.

func (*SettingsList) Done

func (s *SettingsList) Done() bool

Done reports whether the user confirmed a change or cancelled.

func (*SettingsList) HandleInput

func (s *SettingsList) HandleInput(data string)

HandleInput processes keystrokes.

func (*SettingsList) HandleMouse

func (s *SettingsList) HandleMouse(event TuiMouseEvent) *TuiMouseDispatchResult

HandleMouse moves selection by wheel, selects a visible row on press, and activates the pressed row on click. Pointer motion does not change selection. Mirrors upstream SettingsList.handleMouse.

func (*SettingsList) Invalidate

func (i *SettingsList) Invalidate()

func (*SettingsList) IsDirty

func (i *SettingsList) IsDirty() bool

func (*SettingsList) Items

func (s *SettingsList) Items() []SettingItem

Items returns a copy of the rows with their current values.

func (*SettingsList) MaxVisible

func (s *SettingsList) MaxVisible() int

MaxVisible returns the number of item rows rendered at once.

func (*SettingsList) NativeNode

func (s *SettingsList) NativeNode() (frontend.Node, bool)

NativeNode reports the list as settings, or, while a submenu is open, the submenu's node.

func (*SettingsList) NeedsRedraw

func (i *SettingsList) NeedsRedraw() bool

func (*SettingsList) Query

func (s *SettingsList) Query() string

Query returns the search input value.

func (*SettingsList) Render

func (s *SettingsList) Render(width int) []string

Render draws the settings list. Matches upstream SettingsList.renderMainList.

func (*SettingsList) Reset

func (s *SettingsList) Reset()

Reset clears done/cancelled so the list can be reused in a loop.

func (*SettingsList) SearchEnabled

func (s *SettingsList) SearchEnabled() bool

SearchEnabled reports whether the list has a search input.

func (*SettingsList) SelectItem

func (s *SettingsList) SelectItem(id string)

SelectItem moves the selection to the item with the given id, as upstream's selectItem does; an id that is not displayed leaves the selection alone.

func (*SettingsList) SelectedIndex

func (s *SettingsList) SelectedIndex() int

SelectedIndex returns the selection's index into DisplayedItems, -1 when nothing is selected.

func (*SettingsList) SetQuery

func (s *SettingsList) SetQuery(query string)

SetQuery sets the search input value, its cursor at the end, and filters as typing it would; it does nothing when search is disabled.

func (*SettingsList) SetSelectedIndex

func (s *SettingsList) SetSelectedIndex(index int)

SetSelectedIndex selects DisplayedItems[index], clamped like SelectList.setSelectedIndex.

func (*SettingsList) SetTheme

func (s *SettingsList) SetTheme(theme SettingsListTheme)

SetTheme renders the list with theme from now on.

func (*SettingsList) SubmenuComponent

func (s *SettingsList) SubmenuComponent() Component

SubmenuComponent returns the open submenu, nil when none is open.

func (*SettingsList) UpdateValue

func (s *SettingsList) UpdateValue(id, newValue string)

UpdateValue sets a new current value for the item with the given ID.

type SettingsListOptions

type SettingsListOptions struct {
	EnableSearch bool
}

SettingsListOptions is upstream's SettingsListOptions (settings-list.ts:34-36). Upstream's absent enableSearch is false, as is Go's zero.

type SettingsListTheme

type SettingsListTheme struct {
	Label       func(text string, selected bool) string
	Value       func(text string, selected bool) string
	Description func(text string) string
	Cursor      string
	Hint        func(text string) string
}

SettingsListTheme styles a SettingsList (settings-list.ts SettingsListTheme). Cursor is the selected-row prefix.

func GetSettingsListTheme

func GetSettingsListTheme() SettingsListTheme

GetSettingsListTheme is the list styling taken from the active theme (theme.ts getSettingsListTheme): the colors are read when each part is drawn, the cursor prefix when the theme is requested.

func SettingsListThemeFor

func SettingsListThemeFor(th *Theme) SettingsListTheme

SettingsListThemeFor is theme.ts getSettingsListTheme bound to th rather than the active theme (GetSettingsListTheme).

type ShowImagesSelectorComponent

type ShowImagesSelectorComponent struct {
	Container
	// contains filtered or unexported fields
}

ShowImagesSelectorComponent renders a yes/no selector for image display: a Container of border, SelectList, border (show-images-selector.ts:14-52).

func NewShowImagesSelectorComponent

func NewShowImagesSelectorComponent(currentValue bool, onSelect func(show bool), onCancel func()) *ShowImagesSelectorComponent

NewShowImagesSelectorComponent creates the selector. currentValue pre-selects the matching entry. Confirming an item invokes onSelect with whether it is "yes"; the cancel key invokes onCancel. Each callback may be nil.

func (*ShowImagesSelectorComponent) GetSelectList

func (s *ShowImagesSelectorComponent) GetSelectList() *SelectList

GetSelectList returns the underlying SelectList (show-images-selector.ts getSelectList).

func (*ShowImagesSelectorComponent) HandleInput

func (s *ShowImagesSelectorComponent) HandleInput(data string)

HandleInput delegates to the list. A parent Container reuses this component's lines until it is invalidated, so a list change must invalidate it.

func (*ShowImagesSelectorComponent) Invalidate

func (i *ShowImagesSelectorComponent) Invalidate()

func (*ShowImagesSelectorComponent) IsDirty

func (i *ShowImagesSelectorComponent) IsDirty() bool

func (*ShowImagesSelectorComponent) NeedsRedraw

func (i *ShowImagesSelectorComponent) NeedsRedraw() bool

func (*ShowImagesSelectorComponent) Render

func (s *ShowImagesSelectorComponent) Render(width int) []string

Render draws the container and clips a row wider than width, as ThemeSelectorComponent.Render does for its SelectList.

type SkillInvocationMessageComponent

type SkillInvocationMessageComponent struct {
	*Box
	// contains filtered or unexported fields
}

SkillInvocationMessageComponent renders a skill invocation message. Like upstream's `extends Box`, it embeds the Box (padding 1, 1 and the customMessageBg background), so the Box members are inherited; each display update clears the Box and adds one mouse region.

func NewSkillInvocationMessageComponent

func NewSkillInvocationMessageComponent(block ParsedSkillBlock, markdownTheme *MarkdownTheme, outputPad int) *SkillInvocationMessageComponent

NewSkillInvocationMessageComponent creates a skill invocation component (constructor(skillBlock, markdownTheme = getMarkdownTheme(), outputPad = 1), skill-invocation-message.ts:16). A nil markdownTheme is the default markdown theme; outputPad is the horizontal padding of the Box.

func (*SkillInvocationMessageComponent) Expanded

func (s *SkillInvocationMessageComponent) Expanded() bool

Expanded reports the component's expanded state, which a click toggles.

func (*SkillInvocationMessageComponent) Invalidate

func (s *SkillInvocationMessageComponent) Invalidate()

Invalidate invalidates the Box and rebuilds the display, which bakes theme colors into its text.

func (SkillInvocationMessageComponent) IsDirty

func (i SkillInvocationMessageComponent) IsDirty() bool

func (SkillInvocationMessageComponent) NeedsRedraw

func (i SkillInvocationMessageComponent) NeedsRedraw() bool

func (*SkillInvocationMessageComponent) SetExpanded

func (s *SkillInvocationMessageComponent) SetExpanded(expanded bool)

SetExpanded toggles expanded/collapsed rendering.

func (*SkillInvocationMessageComponent) SetOutputPad

func (c *SkillInvocationMessageComponent) SetOutputPad(outputPad int)

SetOutputPad is Pi's setOutputPad(outputPad): the horizontal padding of the Box is the outputPad setting.

type SlashCommand

type SlashCommand struct {
	Name string
	// Value and Label are the AutocompleteItem form of an entry: Value names the command when Name is empty.
	Value                  string
	Label                  string
	Description            string
	ArgumentHint           string
	GetArgumentCompletions func(argPrefix string) []AutocompleteItem
	// AwaitArgumentCompletions is the Promise-returning form. The editor invokes it on its owned query worker, not while reading/rendering input.
	AwaitArgumentCompletions func(argPrefix string) ([]AutocompleteItem, error)
}

SlashCommand is the autocomplete-side view of a registered slash command. Matches upstream's `SlashCommand` interface in autocomplete.ts. GetArgumentCompletions is optional; nil means the command takes no completable arguments.

A SlashCommand also stands for the other member of upstream's `SlashCommand | AutocompleteItem` list: an entry with no Name and a Value is an AutocompleteItem (autocomplete.ts:304,308, `"name" in cmd ? cmd.name : cmd.value`); its Label is not read, and it takes no arguments.

type SlashOnlyProvider

type SlashOnlyProvider struct {
	Commands []SlashCommand
}

SlashOnlyProvider serves command names and their immediate or awaited argument completions. It does not perform path or attachment completion.

func NewSlashOnlyProvider

func NewSlashOnlyProvider(cmds []SlashCommand) *SlashOnlyProvider

NewSlashOnlyProvider constructs a provider over the given command list.

func (*SlashOnlyProvider) ApplyCompletion

func (p *SlashOnlyProvider) ApplyCompletion(lines []string, cursorLine, cursorCol int, item AutocompleteItem, prefix string) ([]string, int, int)

ApplyCompletion replaces the trailing `prefix` chars of the current line with the completion text. Three behaviors:

  • Slash-name completion (prefix starts with `/`, no space, at line start): inserts `/<value> ` (note trailing space). Cursor lands after the space. Mirrors autocomplete.ts:368-385.
  • Argument completion (prefix is the arg text, line contains `/cmd `): inserts `value` at cursor. No trailing space.
  • Other (defensive fallthrough): same as argument completion.

func (*SlashOnlyProvider) GetSuggestions

func (p *SlashOnlyProvider) GetSuggestions(ctx context.Context, lines []string, cursorLine, cursorCol int, options AutocompleteSuggestionOptions) *AutocompleteSuggestions

GetSuggestions implements AutocompleteProvider. Three cases:

  1. Buffer doesn't start with `/` (after trim of leading line slice up to cursor) → return nil (popup off).
  2. `/<partial>` (no space) → fuzzy-filter command names.
  3. `/<cmd> <argPrefix>` (space present) → delegate to the matched command's GetArgumentCompletions.

Mirrors `CombinedAutocompleteProvider.getSuggestions` slash branch (autocomplete.ts:262-342): minus the `@`/path branches.

func (*SlashOnlyProvider) SuggestionTask

func (p *SlashOnlyProvider) SuggestionTask(lines []string, line, col int, _ bool) (string, func(context.Context) ([]AutocompleteItem, error), bool)

SuggestionTask captures a Promise-returning command callback without invoking it on the input loop.

type Spacer

type Spacer struct {
	Lines int
	// contains filtered or unexported fields
}

Spacer component that renders empty lines.

func NewSpacer

func NewSpacer(n int) *Spacer

func (*Spacer) Invalidate

func (i *Spacer) Invalidate()

func (*Spacer) IsDirty

func (i *Spacer) IsDirty() bool

func (*Spacer) NeedsRedraw

func (i *Spacer) NeedsRedraw() bool

func (*Spacer) Render

func (s *Spacer) Render(_ int) []string

func (*Spacer) SetLines

func (s *Spacer) SetLines(n int)

SetLines updates the number of blank lines.

type Stack

type Stack struct {
	*Container
	// contains filtered or unexported fields
}

Stack is the abstract base shared by HStack and VStack. It embeds pig's Container and maintains the parallel entries slice with flexbox metadata.

func (*Stack) Add

func (s *Stack) Add(component Component)

Add shadows the promoted Container.Add so an options-free add still records an entry (equivalent to addChild with no options), keeping entries consistent.

func (*Stack) AddChild

func (s *Stack) AddChild(component Component, options StackEntryOptions)

AddChild mirrors upstream Stack.addChild: it adds the component to the container and records its normalized flexbox entry. A provided option is normalized and stored; an omitted (nil) option is left unset so the allocator applies its default.

func (*Stack) Clear

func (s *Stack) Clear()

Clear mirrors upstream Stack.clear: clear the container and the entries.

func (Stack) Invalidate

func (i Stack) Invalidate()

func (Stack) IsDirty

func (i Stack) IsDirty() bool

func (*Stack) LayoutNode

func (s *Stack) LayoutNode() LayoutNode

LayoutNode mirrors upstream Stack[LAYOUT_NODE](): the stack's layout node.

func (Stack) NeedsRedraw

func (i Stack) NeedsRedraw() bool

func (*Stack) Remove

func (s *Stack) Remove(component Component)

Remove shadows the promoted Container.Remove to keep entries consistent.

func (*Stack) RemoveChild

func (s *Stack) RemoveChild(component Component)

RemoveChild mirrors upstream Stack.removeChild: remove the component and its first matching entry.

type StackChild

type StackChild = StackEntry

StackChild is one child passed to a stack constructor (stack.ts:17 Component | StackEntry). Go has no union of a component and a struct, so the Component arm is a StackEntry without options.

type StackEntry

type StackEntry struct {
	Component Component
	StackEntryOptions
}

StackEntry is a component with its flexbox options (stack.ts:13). A bare component is StackEntry{Component: c} with zero-value options.

type StackEntryOptions

type StackEntryOptions struct {
	Basis   *int // nil == "auto"/undefined -> intrinsic size
	Grow    *int
	Shrink  *int
	MinSize *int
	MaxSize *int
	Visible func(viewport LayoutViewport) bool
}

StackEntryOptions are the per-child flexbox options. A nil pointer field is upstream's "undefined": the allocator applies the default at read time (Basis nil == "auto" -> intrinsic, Grow 0, Shrink 1, MinSize 0, MaxSize maxSafeInteger).

type StackLayoutEntry

type StackLayoutEntry struct {
	Component Component
	Basis     *int
	Grow      *int
	Shrink    *int
	MinSize   *int
	MaxSize   *int
	Visible   func(viewport LayoutViewport) bool
}

StackLayoutEntry is one child in a stack with flexbox sizing. The pointer fields are upstream's optional properties: nil means "unset", and the allocator applies the upstream default (Basis nil == "auto" -> intrinsic size, Grow 0, Shrink 1, MinSize 0, MaxSize maxSafeInteger).

type StackLayoutNode

type StackLayoutNode struct {
	Type    string
	Entries []StackLayoutEntry
	Gap     int
	Align   string
}

StackLayoutNode is a vstack or hstack layout node. Type holds upstream's literal discriminant ("vstack" | "hstack"); Align holds "stretch" | "start" | "center" | "end".

type StackOptions

type StackOptions struct {
	Gap   *int
	Align string // "stretch" | "start" | "center" | "end"
}

StackOptions configure a stack. Gap nil defaults to 0; Align "" defaults to "stretch".

type StaticText

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

StaticText is a Component that renders fixed pre-rendered lines. Used for content that never changes (e.g. login art/banner) but must survive full redraws because it's part of the TUI render buffer.

func NewStaticText

func NewStaticText(lines []string) *StaticText

NewStaticText creates a StaticText component from pre-rendered lines.

func (*StaticText) Invalidate

func (s *StaticText) Invalidate()

func (*StaticText) IsDirty

func (s *StaticText) IsDirty() bool

func (*StaticText) NeedsRedraw

func (s *StaticText) NeedsRedraw() bool

func (*StaticText) Render

func (s *StaticText) Render(_ int) []string

type StatusIndicator

type StatusIndicator struct {
	*Loader
	Kind string
}

StatusIndicator renders a loader either standalone or inside an editor border. Its owner advances animation and disposes operation timers on replacement.

func (StatusIndicator) IsDirty

func (i StatusIndicator) IsDirty() bool

func (StatusIndicator) NeedsRedraw

func (i StatusIndicator) NeedsRedraw() bool

func (*StatusIndicator) RenderInBorder

func (s *StatusIndicator) RenderInBorder(width int) string

func (*StatusIndicator) RenderSpinnerInBorder

func (s *StatusIndicator) RenderSpinnerInBorder(width int) string

type StdinBuffer

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

StdinBuffer accumulates partial escape sequences across reads and emits JavaScript UTF-16 units for ordinary text. Lone surrogate events use WTF-8. Bracketed pastes remain one framed payload. The zero value uses upstream's default timeouts.

pig divergence (D114): its listener surface (stdin_buffer_events.go) has no per-event listener limit, so it has no GetMaxListeners, SetMaxListeners or MaxListenersExceededWarning.

func NewStdinBuffer

func NewStdinBuffer(options StdinBufferOptions) *StdinBuffer

NewStdinBuffer mirrors the upstream StdinBuffer constructor.

func (*StdinBuffer) AddListener

func (b *StdinBuffer) AddListener(event StdinBufferEvent, listener *StdinBufferListener) *StdinBuffer

AddListener appends listener to the listeners of event and returns the buffer (EventEmitter.addListener). A nil listener is ignored.

func (*StdinBuffer) Clear

func (b *StdinBuffer) Clear()

func (*StdinBuffer) Destroy

func (b *StdinBuffer) Destroy()

Destroy releases the buffer the way terminal.ts stop() does: it clears pending input (stdin-buffer.ts:441-443 destroy calls clear).

func (*StdinBuffer) Emit

func (b *StdinBuffer) Emit(event StdinBufferEvent, data string) bool

Emit calls the listeners of event in order with data and reports whether there were any (EventEmitter.emit). It calls a snapshot of the list: a listener added during the emit waits for the next one, and one removed during it is still called.

func (*StdinBuffer) EventNames

func (b *StdinBuffer) EventNames() []StdinBufferEvent

EventNames lists the events that have listeners, in the order their first listener was added (EventEmitter.eventNames).

func (*StdinBuffer) Flush

func (b *StdinBuffer) Flush() []string

Flush returns an incomplete remainder as one chunk. An empty flush preserves pending Kitty printable deduplication; the input loop owns timeout cancellation.

func (*StdinBuffer) FlushExpired

func (b *StdinBuffer) FlushExpired() []string

FlushExpired is the flush timeout firing (stdin-buffer.ts process timeout callback). A flushed control string longer than its introducer is the Alt key followed by batched input: the introducer is emitted and the tail is parsed again, so text, Enter, and control keys are not swallowed as one event. The tail can leave a new remainder; HasPendingFlush arms its timeout.

func (*StdinBuffer) FlushTimeout

func (b *StdinBuffer) FlushTimeout() time.Duration

FlushTimeout is how long the buffered remainder waits for more input before Flush emits it: the escape timeout for a lone ESC, the sequence timeout for anything else. Mirrors the timeout StdinBuffer.process schedules upstream.

func (*StdinBuffer) GetBuffer

func (b *StdinBuffer) GetBuffer() string

GetBuffer returns the pending incomplete input, excluding paste content.

func (*StdinBuffer) HasPendingFlush

func (b *StdinBuffer) HasPendingFlush() bool

HasPendingFlush reports whether the remainder waits on the flush timeout. A remainder with a recognized reply header waits for its terminator instead: flushing it would turn a delayed tail into text and an OSC's BEL terminator into Ctrl+G. Other input, including Alt+] followed by text, keeps bounded recovery (stdin-buffer.ts process).

func (*StdinBuffer) ListenerCount

func (b *StdinBuffer) ListenerCount(event StdinBufferEvent, listener ...*StdinBufferListener) int

ListenerCount counts the registrations of event, or only those of listener when one is given (EventEmitter.listenerCount).

func (*StdinBuffer) Listeners

func (b *StdinBuffer) Listeners(event StdinBufferEvent) []*StdinBufferListener

Listeners returns the listeners of event as the caller added them: a once registration appears as its original (EventEmitter.listeners).

func (*StdinBuffer) Off

func (b *StdinBuffer) Off(event StdinBufferEvent, listener *StdinBufferListener) *StdinBuffer

Off is RemoveListener (EventEmitter.off).

func (*StdinBuffer) On

On is AddListener (EventEmitter.on).

func (*StdinBuffer) Once

func (b *StdinBuffer) Once(event StdinBufferEvent, listener *StdinBufferListener) *StdinBuffer

Once appends a listener that the first emit of event removes before calling it (EventEmitter.once).

func (*StdinBuffer) PrependListener

func (b *StdinBuffer) PrependListener(event StdinBufferEvent, listener *StdinBufferListener) *StdinBuffer

PrependListener adds listener ahead of the other listeners of event (EventEmitter.prependListener).

func (*StdinBuffer) PrependOnceListener

func (b *StdinBuffer) PrependOnceListener(event StdinBufferEvent, listener *StdinBufferListener) *StdinBuffer

PrependOnceListener adds a once listener ahead of the other listeners of event (EventEmitter.prependOnceListener).

func (*StdinBuffer) Process

func (b *StdinBuffer) Process(data string)

Process is upstream process(data): it feeds the string to the buffer and publishes each complete sequence to the listeners, returning nothing. ProcessString does the same and also returns the sequences it published.

upstream: packages/tui/src/stdin-buffer.ts:296 process

func (*StdinBuffer) ProcessBytes

func (b *StdinBuffer) ProcessBytes(data []byte) []string

ProcessBytes mirrors upstream process(Buffer): it feeds raw bytes and returns any complete keystroke chunks ready for dispatch. Terminal loops use ProcessTerminalBytes, which matches upstream's utf8-decoded stdin instead.

func (*StdinBuffer) ProcessString

func (b *StdinBuffer) ProcessString(s string) []string

ProcessString mirrors upstream process(string).

func (*StdinBuffer) ProcessTerminalBytes

func (b *StdinBuffer) ProcessTerminalBytes(data []byte) []string

ProcessTerminalBytes feeds one terminal read. It decodes UTF-8 across reads the way upstream ProcessTerminal's stdin.setEncoding("utf8") does, so a character split between reads is held until it is complete and a lone high byte is never rewritten as a Meta key; the decoded text then goes through ProcessString.

func (*StdinBuffer) RawListeners

func (b *StdinBuffer) RawListeners(event StdinBufferEvent) []*StdinBufferListener

RawListeners returns the registrations of event, a once registration as its wrapper; Original on the wrapper is the listener it stands for (EventEmitter.rawListeners).

func (*StdinBuffer) RemoveAllListeners

func (b *StdinBuffer) RemoveAllListeners(events ...StdinBufferEvent) *StdinBuffer

RemoveAllListeners removes every listener of the given events, or of every event when none is given (EventEmitter.removeAllListeners).

func (*StdinBuffer) RemoveListener

func (b *StdinBuffer) RemoveListener(event StdinBufferEvent, listener *StdinBufferListener) *StdinBuffer

RemoveListener removes the most recently added registration of listener from event, a once registration included (EventEmitter.removeListener). A listener that is not registered leaves the buffer unchanged.

type StdinBufferEvent

type StdinBufferEvent string

StdinBufferEvent names an event of a StdinBuffer (stdin-buffer.ts StdinBufferEventMap).

const (
	// StdinBufferEventData carries one complete input sequence.
	StdinBufferEventData StdinBufferEvent = "data"
	// StdinBufferEventPaste carries the content of one bracketed paste, without the paste markers.
	StdinBufferEventPaste StdinBufferEvent = "paste"
)

The events a StdinBuffer emits.

type StdinBufferEventMap

type StdinBufferEventMap struct {
	Data  [1]string
	Paste [1]string
}

StdinBufferEventMap is the arguments each event's listeners receive: one string, the sequence of a data event and the content of a paste event (stdin-buffer.ts StdinBufferEventMap = { data: [string]; paste: [string] }). It is the typed counterpart of the StdinBufferEvent names, and Emit sends each listener the one argument.

type StdinBufferListener

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

StdinBufferListener gives a Go callback the stable identity a JavaScript function has: Off and ListenerCount find a listener by it.

func NewStdinBufferListener

func NewStdinBufferListener(call func(data string)) *StdinBufferListener

NewStdinBufferListener wraps call as a listener.

func (*StdinBufferListener) Original

Original is the listener a once registration wraps, or nil for a plain registration (the `listener` property of the wrapper EventEmitter.rawListeners returns).

type StdinBufferOptions

type StdinBufferOptions struct {
	// Timeout is how long an incomplete escape sequence waits for more input.
	Timeout time.Duration
	// EscapeTimeout is how long a lone ESC waits before it is the Escape key.
	EscapeTimeout time.Duration
}

StdinBufferOptions mirrors upstream StdinBufferOptions. A zero field keeps the upstream default.

type StopOptions

type StopOptions struct {
	// PreserveScreen leaves the alternate screen contents visible on exit
	// instead of re-emitting the final frame into the main screen scrollback.
	PreserveScreen bool
}

StopOptions controls alt-screen teardown. Mirrors upstream TuiStopOptions.

type StreamedToolArgs

type StreamedToolArgs interface {
	// Object is the decoded argument object as the parser holds it, or nil when the arguments are not an object. The card
	// and the renderers read it in place and never modify it; the card calls it once per update.
	Object() map[string]any
	// JSON is their JSON text, or nil when they cannot be encoded. The card calls it only for a reader that needs text,
	// at most once per update.
	JSON() json.RawMessage
}

StreamedToolArgs is the arguments of a tool call whose text is still streaming, as the provider's streaming JSON parser has read them so far (upstream parseStreamingJson).

type SubmenuDoneOptions struct {
	// NavigateTo is the id of the item to select and activate after the submenu closes. Empty means no navigation.
	NavigateTo string
}

SubmenuDoneOptions is the optional second argument of a submenu's done callback.

type SurfaceHooks

type SurfaceHooks struct {
	// Streaming returns the assistant message still being generated, or
	// nil.
	Streaming func() *AssistantMessageComponent
	// ToolDiff returns the unified diff that a finished call's result value
	// (the value SetResultValue recorded) carries, or nil.
	ToolDiff func(name string, arguments map[string]any, result any) *frontend.Diff
	// Editor returns the input editor that the dock reports as a
	// [frontend.Editor] node, or nil.
	Editor func() *Editor
	// EditorSendable reports whether the input editor takes a send now.
	EditorSendable func() bool
	// Working returns the working indicator the dock reports above the
	// editor node, and false while none shows.
	Working func() (frontend.Working, bool)
	// Footer returns the footer node of the dock component c, and false
	// when c is not the footer or the footer does not show.
	Footer func(c Component) (frontend.Footer, bool)
	// SessionFile returns the file the current session persists to, or ""
	// for a session that is not persisted.
	SessionFile func() string
	// Mark returns the application's mark. It runs on every frame, and the
	// surface reports the mark when it differs from the last one reported,
	// so it should not rebuild an unchanged mark.
	Mark func() frontend.Mark
	// Mouse reports whether the run's terminal layout hands the mouse to
	// components, as Pi's fullscreen mode does; a click on an extension's
	// view reaches its component only then (D91).
	Mouse func() bool
}

SurfaceHooks supply state that the component tree does not hold. They run where the surface renders, on the interactive owner loop. A nil hook reports nothing.

type SystemThemeColors

type SystemThemeColors struct {
	Colors map[string]ThemeColorValue
	// Dim lists the foreground tokens rendered faint (SGR 2), for terminals that did not report colors.
	Dim []string
	// Appearance is empty when unknown.
	Appearance TerminalTheme
}

SystemThemeColors is the generated theme: hex colors, ANSI palette indices, or "" for the terminal default per token.

func GenerateSystemThemeColors

func GenerateSystemThemeColors(input SystemThemeInput) SystemThemeColors

GenerateSystemThemeColors generates the system theme's colors from the terminal's reported colors.

type SystemThemeInput

type SystemThemeInput struct {
	Foreground *RgbColor
	Background *RgbColor
	// Palette is ANSI colors 0-15.
	Palette []RgbColor
	// Saturation is a multiplier from 0 (grayscale) to 1. The first frame renders in grayscale until colors arrive.
	Saturation *float64
	// AppearanceHint applies when the terminal did not report its background, e.g. from its light/dark report or COLORFGBG.
	AppearanceHint TerminalTheme
}

SystemThemeInput is what the terminal reported plus generation options. A nil Saturation is 1.

type TUI

type TUI interface {
	// The Container and state members tui.ts:454-476 declares on TUI.
	AddChild(component Component)
	RemoveChild(component Component)
	Children() []Component
	Clear()
	HideOverlay()
	GetShowHardwareCursor() bool
	GetClearOnShrink() bool
	HandleMouse(event TuiMouseEvent) *TuiMouseDispatchResult
	Mode() TuiMode
	// OnDebug is the callback SetOnDebug stored, nil when none is set (tui.ts:457 onDebug).
	OnDebug() func()
	// FullRedraws counts full repaints (tui.ts:553 fullRedraws).
	FullRedraws() int
	// RenderNow renders at once and cancels a pending render; force makes the frame a full repaint (tui.ts:982 renderNow).
	RenderNow(force ...bool)
	Terminal() Terminal
	// Render performs a differential render pass now.
	Render()
	// RequestRender coalesces a render on the shared 16ms frame throttle; force (upstream requestRender(force = false)) makes the frame a full
	// repaint that renders on the next owner-loop turn.
	RequestRender(force ...bool)
	// RequestImmediateRender coalesces input updates onto the next owner-loop turn without throttle delay.
	RequestImmediateRender()
	// CancelPendingRender invalidates a throttled frame already queued for owner-loop delivery.
	CancelPendingRender()
	// ForceFullRender marks the next frame as a full (non-differential) redraw.
	ForceFullRender()
	// RepaintAll forces an immediate full repaint.
	RepaintAll()
	// RenderSnapshot returns the rendered document lines at the given width.
	RenderSnapshot(width int) []string
	// Add mounts a component in the render tree.
	Add(component Component)
	// Invalidate marks the render tree dirty.
	Invalidate()
	// ShowOverlay pushes an overlay and returns its handle.
	ShowOverlay(component Component, opts OverlayOptions) *OverlayHandle
	// SetFocus records the non-overlay target restored after overlay teardown.
	SetFocus(component Component)
	// ActiveOverlay prepares visibility and eligible focus restoration at the input boundary.
	ActiveOverlay() Component
	// FocusedComponent returns the current keyboard focus target.
	GetFocusedComponent() Component
	// SetOverlayCommandDispatcher binds remote overlay commands to the owner loop.
	SetOverlayCommandDispatcher(dispatch func(func()))
	// HasOverlay reports whether any overlay is currently open.
	HasOverlay() bool
	// Width and Height report the current terminal geometry.
	Width() int
	Height() int
	// QueryTerminalColors asks for the default colors and ANSI palette and returns its one-shot completion.
	QueryTerminalColors(options TerminalColorQueryOptions) <-chan TerminalColorsResult
	// ConsumeTerminalColorResponse intercepts color and DA1 replies before input listeners, including late replies after timeout.
	ConsumeTerminalColorResponse(data string) bool
	// AddInputListener registers a raw-input listener that runs before the focused component and returns its remover; RemoveInputListener removes it by pointer.
	AddInputListener(listener *TuiInputListener) func()
	RemoveInputListener(listener *TuiInputListener)
	// RunInputListeners passes input through the listeners and reports whether they consumed it.
	RunInputListeners(data string) (string, bool)
	// OnTerminalColorSchemeChange registers a light/dark report listener and returns its remover.
	OnTerminalColorSchemeChange(listener func(scheme TerminalColorScheme)) func()
	// SetTerminalColorSchemeNotifications turns light/dark reports on or off across Start and Stop.
	SetTerminalColorSchemeNotifications(enabled bool)
	// ConsumeTerminalColorSchemeReport notifies the listeners of a light/dark report and reports whether data was one.
	ConsumeTerminalColorSchemeReport(data string) bool
	// QueryCellSize asks an image-capable terminal for its cell size.
	QueryCellSize()
	// ConsumeCellSizeResponse applies and consumes a cell-size response.
	ConsumeCellSizeResponse(data string) bool
	// ShowCursor and HideCursor toggle the terminal cursor directly.
	ShowCursor()
	HideCursor()
	// SetShowHardwareCursor toggles hardware-cursor positioning.
	SetShowHardwareCursor(enabled bool)
	// SetClearOnShrink records the clear-on-shrink preference.
	SetClearOnShrink(enabled bool)
	// SetOnWidthChange registers a terminal-width-change callback.
	SetOnWidthChange(fn func(width int))

	// SetOnHeightChange registers a terminal-height-change callback.
	SetOnHeightChange(fn func(height int))
	// SetRenderDispatcher marshals timer-scheduled renders onto the driver loop.
	SetRenderDispatcher(dispatch func(render func()))
	// SetRenderDeadline makes the driver loop keep the throttled-frame deadline; RunDueRender runs the frame once it passed.
	SetRenderDeadline(wake func(due time.Time))
	RunDueRender()
	// HandleTerminalInput dispatches one chunk of terminal input as tui.ts:1044 handleTerminalInput does; DispatchFocusedInput is its last stage, for a driver that ran the earlier ones.
	HandleTerminalInput(data string)
	DispatchFocusedInput(data string)
	// SetOwnerDispatcher installs the seam PostToOwner uses; PostToOwner queues fn on the loop that owns component-tree mutation and returns once the loop accepted it or ctx ended.
	SetOwnerDispatcher(dispatch func(ctx context.Context, fn func()) error)
	PostToOwner(ctx context.Context, fn func()) error
	// SetOnDebug sets the global debug-key callback; ConsumeDebugKey runs it for Shift+Ctrl+D and reports whether data was consumed.
	SetOnDebug(onDebug func())
	ConsumeDebugKey(data string) bool
	// Start resumes rendering after Stop. The driver owns terminal input and raw mode.
	Start()
	// Stop tears down the renderer.
	Stop()
	// StopWithOptions tears down the renderer; PreserveScreen leaves the current
	// screen intact for a live renderer swap (no end-of-session output).
	StopWithOptions(options StopOptions)
}

TUI is the interactive-driver-facing rendering contract implemented by both the main-screen (TuiMainScreen) and alternate-screen (TuiAltScreen) renderers (packages/tui/src/tui.ts TUI); the driver holds one of these and does not care which renderer backs it.

type TUIKeybinding

type TUIKeybinding = string

TUIKeybinding is a named action for TUI components.

const (
	KBAltScreenHalfPageUp     TUIKeybinding = "tui.altScreen.halfPageUp"
	KBAltScreenHalfPageDown   TUIKeybinding = "tui.altScreen.halfPageDown"
	KBAltScreenLineUp         TUIKeybinding = "tui.altScreen.lineUp"
	KBAltScreenLineDown       TUIKeybinding = "tui.altScreen.lineDown"
	KBAltScreenSearch         TUIKeybinding = "tui.altScreen.search"
	KBAltScreenSearchNext     TUIKeybinding = "tui.altScreen.searchNext"
	KBAltScreenSearchPrevious TUIKeybinding = "tui.altScreen.searchPrevious"
	KBAltScreenSearchClose    TUIKeybinding = "tui.altScreen.searchClose"
)

Alt-screen viewport actions added in pi-tui v0.87.1 keybindings.ts. The action names are defined here; their default keys are in TUIKeybindingDefinitionsFor.

const (
	// Editor navigation and editing
	KBEditorCursorUp          TUIKeybinding = "tui.editor.cursorUp"
	KBEditorCursorDown        TUIKeybinding = "tui.editor.cursorDown"
	KBEditorHistoryPrevious   TUIKeybinding = "tui.editor.historyPrevious"
	KBEditorHistoryNext       TUIKeybinding = "tui.editor.historyNext"
	KBEditorCursorLeft        TUIKeybinding = "tui.editor.cursorLeft"
	KBEditorCursorRight       TUIKeybinding = "tui.editor.cursorRight"
	KBEditorCursorWordLeft    TUIKeybinding = "tui.editor.cursorWordLeft"
	KBEditorCursorWordRight   TUIKeybinding = "tui.editor.cursorWordRight"
	KBEditorCursorLineStart   TUIKeybinding = "tui.editor.cursorLineStart"
	KBEditorCursorLineEnd     TUIKeybinding = "tui.editor.cursorLineEnd"
	KBEditorJumpForward       TUIKeybinding = "tui.editor.jumpForward"
	KBEditorJumpBackward      TUIKeybinding = "tui.editor.jumpBackward"
	KBEditorPageUp            TUIKeybinding = "tui.editor.pageUp"
	KBEditorPageDown          TUIKeybinding = "tui.editor.pageDown"
	KBEditorDeleteCharBack    TUIKeybinding = "tui.editor.deleteCharBackward"
	KBEditorDeleteCharForward TUIKeybinding = "tui.editor.deleteCharForward"
	KBEditorDeleteWordBack    TUIKeybinding = "tui.editor.deleteWordBackward"
	KBEditorDeleteWordForward TUIKeybinding = "tui.editor.deleteWordForward"
	KBEditorDeleteToLineStart TUIKeybinding = "tui.editor.deleteToLineStart"
	KBEditorDeleteToLineEnd   TUIKeybinding = "tui.editor.deleteToLineEnd"
	KBEditorYank              TUIKeybinding = "tui.editor.yank"
	KBEditorYankPop           TUIKeybinding = "tui.editor.yankPop"
	KBEditorUndo              TUIKeybinding = "tui.editor.undo"

	// Generic input actions
	KBInputNewLine TUIKeybinding = "tui.input.newLine"
	KBInputSubmit  TUIKeybinding = "tui.input.submit"
	KBInputTab     TUIKeybinding = "tui.input.tab"
	KBInputCopy    TUIKeybinding = "tui.input.copy"

	// Generic selection actions
	KBSelectUp       TUIKeybinding = "tui.select.up"
	KBSelectDown     TUIKeybinding = "tui.select.down"
	KBSelectPageUp   TUIKeybinding = "tui.select.pageUp"
	KBSelectPageDown TUIKeybinding = "tui.select.pageDown"
	KBSelectConfirm  TUIKeybinding = "tui.select.confirm"
	KBSelectCancel   TUIKeybinding = "tui.select.cancel"

	// Alt-screen (fullscreen) viewport actions
	KBAltScreenPageUp         TUIKeybinding = "tui.altScreen.pageUp"
	KBAltScreenPageDown       TUIKeybinding = "tui.altScreen.pageDown"
	KBAltScreenPreviousPrompt TUIKeybinding = "tui.altScreen.previousPrompt"
	KBAltScreenNextPrompt     TUIKeybinding = "tui.altScreen.nextPrompt"
	KBAltScreenTop            TUIKeybinding = "tui.altScreen.top"
	KBAltScreenBottom         TUIKeybinding = "tui.altScreen.bottom"
)

TUI keybinding action constants: mirrors upstream Keybindings interface.

type TUIKeybindingConflict

type TUIKeybindingConflict struct {
	Key         string
	Keybindings []string
}

TUIKeybindingConflict is pi-tui's KeybindingConflict: a key claimed by more than one keybinding.

type TUIKeybindingDef

type TUIKeybindingDef struct {
	DefaultKeys []string
	Description string
}

TUIKeybindingDef defines a keybinding's default keys and description.

type TUIKeybindingsManager

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

TUIKeybindingsManager resolves keybindings for TUI components. Mirrors upstream KeybindingsManager in packages/tui/src/keybindings.ts.

func GetKeybindings

func GetKeybindings() *TUIKeybindingsManager

GetKeybindings mirrors upstream getKeybindings().

func GetTUIKeybindings

func GetTUIKeybindings() *TUIKeybindingsManager

GetTUIKeybindings returns the global TUI keybinding manager, creating a default one if none has been set.

func NewKeybindingsManager

func NewKeybindingsManager(definitions KeybindingDefinitions, userBindings KeybindingsConfig) *TUIKeybindingsManager

NewKeybindingsManager creates a manager over an explicit definition table. Mirrors upstream `new KeybindingsManager(definitions, userBindings)`; the coding agent passes its merged tui.* and app.* table here so components in this package resolve app actions (tree labels, thinking save) through the same manager, as upstream's single KEYBINDINGS table does.

func NewTUIKeybindingsManager

func NewTUIKeybindingsManager(userBindings KeybindingsConfig) *TUIKeybindingsManager

NewTUIKeybindingsManager creates a manager over upstream TUI_KEYBINDINGS, the same on every platform, with optional user overrides.

func (*TUIKeybindingsManager) GetConflicts

func (m *TUIKeybindingsManager) GetConflicts() []TUIKeybindingConflict

GetConflicts returns any user-binding conflicts detected.

func (*TUIKeybindingsManager) GetDefinition

func (m *TUIKeybindingsManager) GetDefinition(action TUIKeybinding) (TUIKeybindingDef, bool)

GetDefinition returns the definition for a keybinding action.

func (*TUIKeybindingsManager) GetKeys

func (m *TUIKeybindingsManager) GetKeys(action TUIKeybinding) []string

GetKeys returns the resolved keys for a keybinding action.

func (*TUIKeybindingsManager) GetResolvedBindings

func (m *TUIKeybindingsManager) GetResolvedBindings() KeybindingsConfig

GetResolvedBindings returns the fully resolved binding table after applying defaults and user overrides (keybindings.ts:299 getResolvedBindings). Pi gives a lone key as a string and several as an array; KeybindingsConfig holds each as a key list.

func (*TUIKeybindingsManager) GetUserBindings

func (m *TUIKeybindingsManager) GetUserBindings() KeybindingsConfig

GetUserBindings returns a defensive copy of the raw user overrides. Mirrors upstream KeybindingsManager.getUserBindings().

func (*TUIKeybindingsManager) HasBinding

func (m *TUIKeybindingsManager) HasBinding(action TUIKeybinding) bool

HasBinding reports whether the manager owns an action, including an explicit empty user override for an app.* action bridged from coding-agent.

func (*TUIKeybindingsManager) Matches

func (m *TUIKeybindingsManager) Matches(data string, action TUIKeybinding) bool

Matches checks whether raw terminal input data matches a keybinding action. Uses the same keyIDInputs lookup table as the app-level keybindings for legacy terminal sequence matching.

func (*TUIKeybindingsManager) SetUserBindings

func (m *TUIKeybindingsManager) SetUserBindings(bindings KeybindingsConfig)

SetUserBindings replaces user overrides and rebuilds.

type Terminal

type Terminal interface {
	// Start owns input framing, negotiation filtering and native normalization before invoking onInput for each event. The resize callback follows terminal dimension changes.
	Start(onInput func(string), onResize func()) error

	// Stop reverses Start: cancels and joins the input goroutine, removes the
	// resize handler, and restores cooked mode without draining unread input.
	// Call DrainInput explicitly before Stop only at process shutdown.
	Stop()

	DrainInput(maxWait, idleWait time.Duration) error
	Write(data string)
	Columns() int
	Rows() int
	KittyProtocolActive() bool
	MoveBy(lines int)
	HideCursor()
	ShowCursor()
	ClearLine()
	ClearFromCursor()
	ClearScreen()
	SetTitle(title string)
	SetProgress(active bool)

	// SetProgramStatus reports what the program is doing (OSC 7501). It is sent only to terminals that support it; the
	// latest status is sent again when support is confirmed or the terminal restarts.
	// upstream: terminal.ts Terminal.setProgramStatus
	SetProgramStatus(status ProgramStatus)

	// RestoreOnExit synchronously writes before, then this terminal's own mode resets, then after, when the process
	// exits without Stop having run. [RestoreTerminalOnExit] calls it for the started process terminal; a terminal that
	// owns no process modes writes nothing.
	// upstream: terminal.ts Terminal.restoreOnExit (Pi 9df819de)
	RestoreOnExit(before, after string)
}

Terminal mirrors the control surface of upstream `terminal.ts` in Go form.

Faithful port note: upstream's `start(onInput, onResize)` / `stop()` pair is provided here as `Start` / `Stop`. They are thin wrappers over `EnterRawMode` + a goroutine input loop + SIGWINCH notify, so legacy caller-owns-loop code paths (interactive mode, session selectors, the extension UI) keep working through `EnterRawMode` directly. New callers can use `Start`/`Stop` for a behavior-equivalent surface to upstream.

type TerminalCapabilities

type TerminalCapabilities struct {
	Images     ImageProtocol
	TrueColor  bool
	Hyperlinks bool
}

func ApplyCapabilityOverrides

func ApplyCapabilityOverrides(caps TerminalCapabilities, overrides CapabilityOverrides) TerminalCapabilities

ApplyCapabilityOverrides lays the settings overrides over detected capabilities, as `{...detectCapabilities(), ...overrides}` does.

func DetectCapabilities

func DetectCapabilities(tmuxForwardsHyperlink func() bool) TerminalCapabilities

DetectCapabilities mirrors upstream detectCapabilities: PI_HYPERLINKS, PI_IMAGE_PROTOCOL, and PI_TRUE_COLOR override auto-detection, and an explicit PI_HYPERLINKS replaces the tmux probe. A nil tmuxForwardsHyperlink uses the default tmux probe.

func GetCapabilities

func GetCapabilities() TerminalCapabilities

GetCapabilities mirrors upstream getCapabilities: detection with the PI_* environment, then the settings overrides on top.

type TerminalColorMode

type TerminalColorMode string

TerminalColorMode is the color depth a terminal accepts.

const (
	TerminalColorMode256       TerminalColorMode = "256color"
	TerminalColorModeTrueColor TerminalColorMode = "truecolor"
)

func GetTerminalColorMode

func GetTerminalColorMode(capabilities ...TerminalCapabilities) TerminalColorMode

GetTerminalColorMode is the color depth the terminal supports: truecolor when capabilities report it, else 256 colors. Upstream defaults the argument to getCapabilities(); omit it for that default. As upstream's default parameter, detection runs only when the argument is omitted, so passed capabilities never run the tmux probe.

type TerminalColorQueryOptions

type TerminalColorQueryOptions struct {
	TimeoutMs float64
	// OnLateReply receives the replies of a QueryTerminalColors query that completes after its timeout. It runs on the goroutine that consumed the completing reply.
	OnLateReply func(TerminalColors)
}

TerminalColorQueryOptions specifies the terminal query deadline in milliseconds.

type TerminalColorScheme

type TerminalColorScheme = TerminalTheme

TerminalColorScheme is the terminal's dark or light palette preference.

const (
	TerminalColorSchemeDark  TerminalColorScheme = "dark"
	TerminalColorSchemeLight TerminalColorScheme = "light"
)

The two TerminalColorScheme values (terminal-colors.ts:7 `"dark" | "light"`).

func ParseTerminalColorSchemeReport

func ParseTerminalColorSchemeReport(data string) TerminalColorScheme

ParseTerminalColorSchemeReport returns the last scheme in a complete sequence of palette reports, or an empty value for nonmatching input.

type TerminalColors

type TerminalColors struct {
	// Foreground is the default foreground (OSC 10).
	Foreground *RgbColor
	// Background is the default background (OSC 11).
	Background *RgbColor
	// Palette holds ANSI colors 0-15 (OSC 4). It is set only when the terminal reported all 16.
	Palette []RgbColor
}

TerminalColors are the colors the terminal reports for its current theme. A nil Foreground or Background, or a nil Palette, was not reported.

type TerminalColorsResult

type TerminalColorsResult struct {
	Colors TerminalColors
	Err    error
}

TerminalColorsResult is the completion of a terminal color query. Err reports a failed terminal write.

type TerminalInput

type TerminalInput struct {
	C <-chan time.Time
	// contains filtered or unexported fields
}

TerminalInput owns framing and protocol-response deadlines for one input loop. The caller serializes Process, Flush, FlushPending, and Close, and selects C alongside raw input or waits until NextDeadline. Callbacks run synchronously in sequence order; the dispatch owner applies native modifier normalization once before focus routing.

func NewTerminalInput

func NewTerminalInput(onInput func(string)) *TerminalInput

NewTerminalInput constructs the process terminal's decoder for a caller-owned input loop.

func (*TerminalInput) Close

func (p *TerminalInput) Close()

Close stops owned timers and discards pending input without dispatching it. It can be called from the input callback to stop the rest of a batch.

func (*TerminalInput) Flush

func (p *TerminalInput) Flush()

Flush dispatches expired framing and negotiation deadlines in chronological order.

func (*TerminalInput) FlushPending

func (p *TerminalInput) FlushPending()

FlushPending delivers any remaining input when the source reaches EOF.

func (*TerminalInput) NextDeadline

func (p *TerminalInput) NextDeadline() time.Time

NextDeadline reports when Flush next has a framing or negotiation deadline to dispatch, the zero time when none is pending. A caller that waits for raw input itself waits only until then, instead of selecting C.

func (*TerminalInput) Process

func (p *TerminalInput) Process(data []byte)

Process decodes a UTF-8 terminal read and dispatches complete sequences. Input ready alongside a timeout is processed first, so continuations can finish their pending sequence.

func (*TerminalInput) SetSequenceBarrier

func (p *TerminalInput) SetSequenceBarrier(barrier func())

SetSequenceBarrier installs barrier, which runs before the decoder interprets a sequence after forwarding input: before each framed sequence and after a forwarded negotiation fragment. Pi's data listeners run synchronously before the next sequence changes terminal state (terminal.ts setupStdinBuffer); a caller whose onInput returns before the input's listeners settle waits for them in barrier.

type TerminalTheme

type TerminalTheme string

func DetectColorFgBgTheme

func DetectColorFgBgTheme(env map[string]string) TerminalTheme

DetectColorFgBgTheme is dark or light from the COLORFGBG variable some terminals set, or empty without a usable background index. The value is `fg;bg` or `fg;xpm;bg` (rxvt), where a field is an ANSI color index or `default` when the color is not in the palette. The index refers to the terminal's own palette, whose colors are unknown here, so it is classified by index like Vim does: 0-6 and 8 (bright black, e.g. Solarized Dark's background) are dark, 7 and 9-15 are light. A nil env is the process environment. upstream: packages/coding-agent/src/modes/interactive/theme/theme.ts:detectColorFgBgTheme

func DetectTerminalTheme

func DetectTerminalTheme(colors TerminalColors, reportedScheme TerminalTheme, env map[string]string) TerminalTheme

DetectTerminalTheme is whether the terminal is dark or light. The background it renders decides, classified the same way the system theme does. Without a reported background: the terminal's light/dark report, then COLORFGBG, then dark. A nil env is the process environment. upstream: packages/coding-agent/src/modes/interactive/theme/theme.ts:detectTerminalTheme

func GetTerminalTheme

func GetTerminalTheme() TerminalTheme

GetTerminalTheme is whether the terminal is dark or light, from everything it reported so far.

func GetThemeForRgbColor deprecated

func GetThemeForRgbColor(rgb RgbColor) TerminalTheme

GetThemeForRgbColor is the appearance of a terminal with this background, classified like the system theme.

Deprecated: use DetectTerminalTheme.

type TerminalThemeDetection deprecated

type TerminalThemeDetection struct {
	Theme      TerminalTheme
	Source     string
	Detail     string
	Confidence string
}

TerminalThemeDetection is the appearance DetectTerminalBackground derives from the environment.

Deprecated: use DetectTerminalTheme or GetTerminalTheme.

func DetectTerminalBackground deprecated

func DetectTerminalBackground(options TerminalThemeDetectionOptions) TerminalThemeDetection

DetectTerminalBackground classifies COLORFGBG like DetectColorFgBgTheme and falls back to a low-confidence dark theme without a usable index.

Deprecated: use DetectColorFgBgTheme, DetectTerminalTheme or GetTerminalTheme.

type TerminalThemeDetectionOptions deprecated

type TerminalThemeDetectionOptions struct {
	Env map[string]string
}

TerminalThemeDetectionOptions supplies the environment DetectTerminalBackground reads; a nil Env is the process environment.

Deprecated: use DetectTerminalTheme or DetectColorFgBgTheme.

type Text

type Text struct {
	Content    string
	PaddingX   int
	PaddingY   int
	CustomBgFn func(string) string
	Style      string // pig compatibility: extra ANSI prefix applied per line
	// contains filtered or unexported fields
}

Text component - displays multi-line text with word wrapping.

func NewPaddedText

func NewPaddedText(content string, paddingX, paddingY int, bgFn func(string) string) *Text

NewPaddedText creates a text component with explicit padding.

func NewText

func NewText(content string) *Text

NewText creates a text component. pig keeps zero padding as the default for existing call sites; upstream-style padding is available via fields.

func (*Text) Invalidate

func (t *Text) Invalidate()

func (*Text) IsDirty

func (i *Text) IsDirty() bool

func (*Text) NeedsRedraw

func (i *Text) NeedsRedraw() bool

func (*Text) Render

func (t *Text) Render(width int) []string

func (*Text) SetCustomBgFn

func (t *Text) SetCustomBgFn(bgFn func(string) string)

func (*Text) SetPaddingX

func (t *Text) SetPaddingX(paddingX int)

SetPaddingX sets the horizontal padding and invalidates the cached lines (text.ts setPaddingX).

func (*Text) SetText

func (t *Text) SetText(content string)

type TextAttributes

type TextAttributes struct {
	Bold, Dim, Italic, Underline, Inverse, Strikethrough bool
}

TextAttributes are the non-color attributes StyleText applies.

type TextInput

type TextInput struct {
	Focused bool

	OnSubmit func(string)
	OnEscape func()
	// contains filtered or unexported fields
}

TextInput is a single-line input with UTF-16 cursor offsets and grapheme-aware editing. Unpaired UTF-16 units use the internal WTF-8 string representation.

func NewInput

func NewInput(options InputOptions) *TextInput

NewInput creates upstream Input's callback-driven component, initially unfocused.

func NewTextInput

func NewTextInput(_ string) *TextInput

NewTextInput creates a host-owned confirmation input. The title is supplied by its enclosing dialog; Done and Cancelled report completion.

func (*TextInput) Cancelled

func (t *TextInput) Cancelled() bool

func (*TextInput) Cursor

func (t *TextInput) Cursor() int

Cursor is the cursor's UTF-16 offset in the value.

func (*TextInput) Done

func (t *TextInput) Done() bool

func (*TextInput) GetValue

func (t *TextInput) GetValue() string

GetValue returns the current JavaScript string, retaining unpaired UTF-16 units.

func (*TextInput) HandleInput

func (t *TextInput) HandleInput(data string)

HandleInput applies one input event. Paste state spans chunks; submission and cancellation use the selected owner/callback contract.

func (*TextInput) HandleMouse

func (t *TextInput) HandleMouse(event TuiMouseEvent) *TuiMouseDispatchResult

HandleMouse places the UTF-16 cursor at the clicked grapheme and requests focus.

func (*TextInput) Invalidate

func (i *TextInput) Invalidate()

func (*TextInput) IsDirty

func (i *TextInput) IsDirty() bool

func (*TextInput) NeedsRedraw

func (i *TextInput) NeedsRedraw() bool

func (*TextInput) Render

func (t *TextInput) Render(width int) []string

Render returns the prompt, horizontally scrolled value and fake cursor. Cursor slicing follows UTF-16 even when setValue retained a surrogate-half offset.

func (*TextInput) SetCursor

func (t *TextInput) SetCursor(offset int)

SetCursor places the cursor at a UTF-16 offset of the value, clamped to it: the cursor of a component whose sender owns the state (Node's Input).

func (*TextInput) SetFocused

func (t *TextInput) SetFocused(focused bool)

SetFocused records whether the input holds TUI focus; only a focused input emits the hardware-cursor marker.

func (*TextInput) SetText

func (t *TextInput) SetText(value string)

SetText sets the component text. Callback-driven Input retains its cursor as setValue does; host confirmation inputs prefill at the end.

func (*TextInput) SetValue

func (t *TextInput) SetValue(value string)

SetValue replaces the value and clamps the existing UTF-16 cursor without rounding surrogate-half positions.

func (*TextInput) Text

func (t *TextInput) Text() string

type TextStyle

type TextStyle struct {
	TextAttributes
	Fg, Bg Color
}

TextStyle is a TextAttributes plus optional foreground and background colors; a nil Color is unset.

type Theme

type Theme struct {
	// Name of the theme (e.g. "dark", "light", or a custom name).
	Name string
	// SourceInfo is where the theme came from, set by the resource loader after it loads the theme (theme.ts Theme.sourceInfo).
	SourceInfo *source.SourceInfo
	// SourcePath is the file the theme was loaded from, empty for a built-in or in-memory theme (theme.ts Theme.sourcePath).
	SourcePath string

	// ─── Core colors ─────────────────────────────────────────
	Accent  string // accent text (teal/cyan)
	Success string // green
	Error   string // red
	Warning string // yellow
	Muted   string // gray
	Dim     string // dim gray
	Text    string // default text (empty = terminal default)

	// ─── Border colors ───────────────────────────────────────
	Border       string // blue
	BorderAccent string // cyan
	BorderMuted  string // dark gray

	// ─── Background colors ───────────────────────────────────
	UserMessageBg      string // ANSI bg escape
	UserMessageText    string // fg text on user message bg
	ToolPendingBg      string // tool running
	ToolSuccessBg      string // tool completed successfully
	ToolErrorBg        string // tool failed
	ToolTitle          string // tool header text
	ToolOutput         string // tool output text (gray)
	SelectedBg         string // selected item bg
	CustomMessageBg    string // custom message bg
	CustomMessageText  string // custom message text
	CustomMessageLabel string // custom message label

	// ─── Markdown colors ─────────────────────────────────────
	MDHeading         string
	MDLink            string
	MDLinkUrl         string
	MDCode            string
	MDCodeBlock       string
	MDCodeBlockBorder string
	MDQuote           string
	MDQuoteBorder     string
	MDHr              string
	MDListBullet      string

	// ─── Diff colors ─────────────────────────────────────────
	ToolDiffAdded   string
	ToolDiffRemoved string
	ToolDiffContext string

	// ─── Syntax highlighting ─────────────────────────────────
	SyntaxComment     string
	SyntaxKeyword     string
	SyntaxFunction    string
	SyntaxVariable    string
	SyntaxString      string
	SyntaxNumber      string
	SyntaxType        string
	SyntaxOperator    string
	SyntaxPunctuation string

	// ─── Thinking level indicators ───────────────────────────
	ThinkingText    string
	ThinkingOff     string
	ThinkingMinimal string
	ThinkingLow     string
	ThinkingMedium  string
	ThinkingHigh    string
	ThinkingXhigh   string

	// ─── Misc ────────────────────────────────────────────────
	BashMode string // bash mode indicator

	// ─── Export colors (for HTML export) ─────────────────────
	ExportPageBg string // hex string (not ANSI)
	ExportCardBg string // hex string
	ExportInfoBg string // hex string

	// Reset escapes.
	BgClose string
	Reset   string
	// contains filtered or unexported fields
}

Theme holds the resolved color palette for the current session. All fields are pre-computed ANSI escape sequences (fg or bg).

func ActiveTheme

func ActiveTheme() *Theme

ActiveTheme returns the current theme; before any selection it is the built-in dark theme.

func ExportTheme

func ExportTheme() *Theme

ExportTheme is the theme HTML export reads: the selected theme, or a generated system theme until one is selected (theme.ts getResolvedThemeColors).

func ExportThemeNamed

func ExportThemeNamed(name string) *Theme

ExportThemeNamed is the theme HTML export reads for an export theme name (theme.ts getResolvedThemeColors(themeName)): the named theme, or ExportTheme when the name is empty or names no theme.

func LoadBuiltinTheme

func LoadBuiltinTheme(name string) (*Theme, error)

LoadBuiltinTheme returns a built-in theme by name ("dark" or "light") in the terminal's color mode.

func LoadThemeFile

func LoadThemeFile(path string) (*Theme, error)

LoadThemeFile reads a theme JSON file and returns the resolved Theme in the terminal's color mode, reporting invalid JSON with ECMAScript SyntaxError text.

func LoadThemeFromPath

func LoadThemeFromPath(path string, mode TerminalColorMode) (*Theme, error)

LoadThemeFromPath reads a theme JSON file and returns the resolved Theme in mode (theme.ts loadThemeFromPath).

func NewTheme

func NewTheme(foregrounds, backgrounds []ThemeTokenValue, mode TerminalColorMode, options ThemeOptions) (*Theme, error)

NewTheme is the theme.ts Theme constructor: a token set to "" has no color of its own and follows the terminal's default colors.

func NewThemeFromANSIPalette

func NewThemeFromANSIPalette(name string, foregrounds, backgrounds map[string]string, mode TerminalColorMode) (theme *Theme, err error)

NewThemeFromANSIPalette is the inverse of Theme.ANSIPalette: the theme whose Fg and Bg draw with the given opening escape sequences. A subprocess extension holds the host's theme as such a palette, and a helper the host answers for it (highlightCode) must draw with the theme the extension holds, not with the one the host has active. The theme has no JSON source, so Theme.WithColorMode returns it unchanged. A palette that lacks a token the interface draws with is an error.

func ThemeByName

func ThemeByName(name string) *Theme

ThemeByName is theme.ts getThemeByName: the registered theme with the name, or nil when there is none.

func (*Theme) ANSIPalette

func (t *Theme) ANSIPalette() (map[string]string, map[string]string)

ANSIPalette returns every resolved token as foreground and background ANSI openings. It is used at process boundaries where theme helper functions cannot cross but their current immutable token table can.

func (*Theme) Appearance

func (t *Theme) Appearance() ThemeAppearance

Appearance is the background the theme is designed for: declared in the theme JSON, detected from its colors, or, for a theme without usable colors, the terminal's appearance.

func (*Theme) Bg

func (t *Theme) Bg(token, text string) string

Bg wraps text in the background color of a token and resets only the background (theme.bg). An unknown token panics with `Unknown theme color: <token>`, as upstream throws.

func (*Theme) Bold

func (t *Theme) Bold(text string) string

Bold wraps text in bold, closing with SGR 22. Mirrors upstream theme.bold(text); an empty text stays empty.

func (*Theme) ColorKeys

func (t *Theme) ColorKeys() []string

ColorKeys returns the color token names in upstream's Theme construction order. Used by HTML export to emit CSS variables in the same order as upstream.

func (*Theme) Colors

func (t *Theme) Colors() map[string]Color

Colors returns a concrete color for every token. Tokens set to "" (terminal default) use the terminal's reported default colors, or a guess based on the appearance when the terminal did not report them. Faint tokens are approximated by mixing their color toward the background. The map is shared and must not be modified.

func (*Theme) Fg

func (t *Theme) Fg(token, text string) string

Fg returns text in the foreground color of a token, closing the color (and the faint attribute of a faint token). Mirrors upstream theme.fg(tokenName, text); an unknown token panics with `Unknown theme color: <token>`, as upstream throws.

func (*Theme) GetBashModeBorderColor

func (t *Theme) GetBashModeBorderColor() func(string) string

GetBashModeBorderColor returns the function that colors a border in bash mode with the bashMode token. Mirrors upstream theme.getBashModeBorderColor().

func (*Theme) GetBgAnsi

func (t *Theme) GetBgAnsi(token string) string

GetBgAnsi returns the opening escape sequence of a background token. Mirrors upstream theme.getBgAnsi(tokenName). Like upstream it panics with `Unknown theme color: <token>` for a token the theme does not define.

func (*Theme) GetColorMode

func (t *Theme) GetColorMode() TerminalColorMode

TerminalColorMode mirrors theme.ts Theme.getColorMode.

func (*Theme) GetFgAnsi

func (t *Theme) GetFgAnsi(token string) string

GetFgAnsi returns the opening escape sequence of a foreground token; faint tokens include SGR 2, which "\x1b[22m" closes. Mirrors upstream theme.getFgAnsi(tokenName). Like upstream it panics with `Unknown theme color: <token>` for a token the theme does not define (theme.ts:tokenAnsi).

func (*Theme) GetResolvedThemeColors

func (t *Theme) GetResolvedThemeColors() map[string]string

GetResolvedThemeColors returns the resolved theme colors as CSS values keyed by token name: the concrete colors as hex, and tokens set to "" as the terminal's default colors (theme.ts getResolvedThemeColors). Used by HTML export to mirror upstream CSS variable generation.

func (*Theme) GetThinkingBorderColor

func (t *Theme) GetThinkingBorderColor(level string) func(string) string

GetThinkingBorderColor returns the function that colors a border for a thinking level with the level's theme token; a level without a token uses thinkingOff. Mirrors upstream theme.getThinkingBorderColor(level).

func (*Theme) Inverse

func (t *Theme) Inverse(text string) string

Inverse wraps text in reverse video. Mirrors upstream theme.inverse(text).

func (*Theme) Italic

func (t *Theme) Italic(text string) string

Italic wraps text in italic. Mirrors upstream theme.italic(text).

func (*Theme) Strikethrough

func (t *Theme) Strikethrough(text string) string

Strikethrough wraps text in strikethrough. Mirrors upstream theme.strikethrough(text).

func (*Theme) Style

func (t *Theme) Style(text string, style ThemeStyle) (string, error)

Style renders text in style. A token is only accepted in its own slot, because "" (terminal default) means the default foreground or background depending on the slot. Mirrors upstream theme.style(text, options).

func (*Theme) Underline

func (t *Theme) Underline(text string) string

Underline wraps text in underline. Mirrors upstream theme.underline(text).

func (*Theme) WithColorMode

func (t *Theme) WithColorMode(mode TerminalColorMode) *Theme

WithColorMode returns this theme resolved in mode, mirroring theme.ts createTheme(themeJson, mode). Rebuilt themes are not cached, so obsolete themes can be collected. A theme without JSON source is returned unchanged. The variant keeps the theme's name: it is the same theme in another mode, and a registry entry activated by name must stay that name even when its JSON names another theme.

func (*Theme) WithTokenColors

func (t *Theme) WithTokenColors(colors map[string]Color) (*Theme, error)

WithTokenColors returns a copy of t whose given tokens use the given colors, escaped in t's color mode as the theme constructor escapes a concrete color. Faint tokens stay faint. The copy has no JSON source, so WithColorMode returns it unchanged. A token that is neither a foreground nor a background token of t is an error.

type ThemeAppearance

type ThemeAppearance = TerminalTheme

ThemeAppearance is the background a theme is designed for (theme.ts:186 `type ThemeAppearance = TerminalTheme`).

type ThemeBg

type ThemeBg string

ThemeBg is a background theme token: upstream `ThemeBg` (theme.ts:108).

const (
	ThemeBgSelectedBg      ThemeBg = "selectedBg"
	ThemeBgSearchMatchBg   ThemeBg = "searchMatchBg"
	ThemeBgUserMessageBg   ThemeBg = "userMessageBg"
	ThemeBgCustomMessageBg ThemeBg = "customMessageBg"
	ThemeBgToolPendingBg   ThemeBg = "toolPendingBg"
	ThemeBgToolSuccessBg   ThemeBg = "toolSuccessBg"
	ThemeBgToolErrorBg     ThemeBg = "toolErrorBg"
)

The ThemeBg tokens, in upstream order.

type ThemeColor

type ThemeColor string

ThemeColor is a foreground theme token: upstream `ThemeColor` (modes/interactive/theme/theme.ts:57).

const (
	ThemeColorAccent             ThemeColor = "accent"
	ThemeColorBorder             ThemeColor = "border"
	ThemeColorBorderAccent       ThemeColor = "borderAccent"
	ThemeColorBorderMuted        ThemeColor = "borderMuted"
	ThemeColorSuccess            ThemeColor = "success"
	ThemeColorError              ThemeColor = "error"
	ThemeColorWarning            ThemeColor = "warning"
	ThemeColorMuted              ThemeColor = "muted"
	ThemeColorDim                ThemeColor = "dim"
	ThemeColorText               ThemeColor = "text"
	ThemeColorThinkingText       ThemeColor = "thinkingText"
	ThemeColorScrollbarTrack     ThemeColor = "scrollbarTrack"
	ThemeColorScrollbarThumb     ThemeColor = "scrollbarThumb"
	ThemeColorSearchMatchText    ThemeColor = "searchMatchText"
	ThemeColorUserMessageText    ThemeColor = "userMessageText"
	ThemeColorCustomMessageText  ThemeColor = "customMessageText"
	ThemeColorCustomMessageLabel ThemeColor = "customMessageLabel"
	ThemeColorToolTitle          ThemeColor = "toolTitle"
	ThemeColorToolOutput         ThemeColor = "toolOutput"
	ThemeColorMdHeading          ThemeColor = "mdHeading"
	ThemeColorMdLink             ThemeColor = "mdLink"
	ThemeColorMdLinkUrl          ThemeColor = "mdLinkUrl"
	ThemeColorMdCode             ThemeColor = "mdCode"
	ThemeColorMdCodeBlock        ThemeColor = "mdCodeBlock"
	ThemeColorMdCodeBlockBorder  ThemeColor = "mdCodeBlockBorder"
	ThemeColorMdQuote            ThemeColor = "mdQuote"
	ThemeColorMdQuoteBorder      ThemeColor = "mdQuoteBorder"
	ThemeColorMdHr               ThemeColor = "mdHr"
	ThemeColorMdListBullet       ThemeColor = "mdListBullet"
	ThemeColorToolDiffAdded      ThemeColor = "toolDiffAdded"
	ThemeColorToolDiffRemoved    ThemeColor = "toolDiffRemoved"
	ThemeColorToolDiffContext    ThemeColor = "toolDiffContext"
	ThemeColorSyntaxComment      ThemeColor = "syntaxComment"
	ThemeColorSyntaxKeyword      ThemeColor = "syntaxKeyword"
	ThemeColorSyntaxFunction     ThemeColor = "syntaxFunction"
	ThemeColorSyntaxVariable     ThemeColor = "syntaxVariable"
	ThemeColorSyntaxString       ThemeColor = "syntaxString"
	ThemeColorSyntaxNumber       ThemeColor = "syntaxNumber"
	ThemeColorSyntaxType         ThemeColor = "syntaxType"
	ThemeColorSyntaxOperator     ThemeColor = "syntaxOperator"
	ThemeColorSyntaxPunctuation  ThemeColor = "syntaxPunctuation"
	ThemeColorThinkingOff        ThemeColor = "thinkingOff"
	ThemeColorThinkingMinimal    ThemeColor = "thinkingMinimal"
	ThemeColorThinkingLow        ThemeColor = "thinkingLow"
	ThemeColorThinkingMedium     ThemeColor = "thinkingMedium"
	ThemeColorThinkingHigh       ThemeColor = "thinkingHigh"
	ThemeColorThinkingXhigh      ThemeColor = "thinkingXhigh"
	ThemeColorThinkingMax        ThemeColor = "thinkingMax"
	ThemeColorBashMode           ThemeColor = "bashMode"
)

The ThemeColor tokens, in upstream order.

type ThemeColorToken

type ThemeColorToken struct {
	Name, Description string
	Optional          bool
}

ThemeColorToken is one token of the theme "colors" object: its description and whether a theme may omit it.

func ThemeColorTokens

func ThemeColorTokens() []ThemeColorToken

ThemeColorTokens returns the tokens of ThemeJsonSchema.colors in schema order.

type ThemeColorValue

type ThemeColorValue struct {
	Text    string
	Index   int
	IsIndex bool
	// contains filtered or unexported fields
}

ThemeColorValue mirrors theme-schema.ts ColorValue: a hex color, variable reference or empty string (Text), or a 256-color palette index (Index, when IsIndex is set).

func (ThemeColorValue) MarshalJSON

func (v ThemeColorValue) MarshalJSON() ([]byte, error)

MarshalJSON writes the value as the JSON string or number it was read from (theme-schema.ts ColorValue is `string | number`); an unset value writes the empty string.

func (*ThemeColorValue) UnmarshalJSON

func (v *ThemeColorValue) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a JSON string or an integral JSON number. The 0..255 range is enforced by ValidateThemeJSON for user-authored themes.

type ThemeJSON

type ThemeJSON struct {
	Name string `json:"name"`
	// Appearance is the background the theme is designed for, "dark" or "light"; empty means it is detected from the theme's colors.
	Appearance TerminalTheme              `json:"appearance,omitempty"`
	Vars       map[string]ThemeColorValue `json:"vars"`
	Colors     map[string]ThemeColorValue `json:"colors"`
	Export     map[string]ThemeColorValue `json:"export,omitempty"`
	// contains filtered or unexported fields
}

ThemeJSON is the upstream-compatible theme file schema. Mirrors upstream theme-schema.json.

type ThemeOptions

type ThemeOptions struct {
	Name       string
	SourcePath string
	// SourceInfo is where the theme came from; the resource loader also sets it after loading (theme.ts Theme.sourceInfo).
	SourceInfo *source.SourceInfo
	Appearance ThemeAppearance
	// Dim lists the foreground tokens to render faint (SGR 2).
	Dim []string
}

ThemeOptions are the Theme constructor's options (theme.ts Theme constructor `options`).

type ThemeRegistry

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

ThemeRegistry holds all loaded themes and enables switching.

func ActiveThemeRegistry

func ActiveThemeRegistry() *ThemeRegistry

ActiveThemeRegistry returns the global theme registry. Initializes with built-in themes on first call.

func NewThemeRegistry

func NewThemeRegistry() *ThemeRegistry

NewThemeRegistry creates a registry with the system theme and the built-in dark and light themes.

func (*ThemeRegistry) Add

func (r *ThemeRegistry) Add(t *Theme)

Add registers a theme. If a theme with the same name already exists, it is replaced. The name is derived from the theme's Name field.

func (*ThemeRegistry) AddFile

func (r *ThemeRegistry) AddFile(t *Theme, path string)

AddFile registers a theme loaded from path and records path as its source, which the startup resource listing and getAllThemes report.

func (*ThemeRegistry) Get

func (r *ThemeRegistry) Get(name string) *Theme

Get returns a theme by name, or nil.

func (*ThemeRegistry) LoadDir

func (r *ThemeRegistry) LoadDir(dir string) error

LoadDir scans a directory for .json theme files and registers them, recording each theme's source file so extensions can report it.

func (*ThemeRegistry) Names

func (r *ThemeRegistry) Names() []string

Names returns a copy of the available theme names: the system theme first, then the others in localeCompare order (theme.ts getAvailableThemesWithPaths).

func (*ThemeRegistry) PathOf

func (r *ThemeRegistry) PathOf(name string) string

PathOf returns the file a theme was loaded from, or "" for built-ins.

type ThemeSelectorComponent

type ThemeSelectorComponent struct {
	Container
	// contains filtered or unexported fields
}

ThemeSelectorComponent renders a theme picker with live preview: a Container of border, SelectList, border (theme-selector.ts:14-67).

func NewThemeSelectorComponent

func NewThemeSelectorComponent(currentTheme string, onSelect func(themeName string), onCancel func(), onPreview func(themeName string)) *ThemeSelectorComponent

NewThemeSelectorComponent creates a theme selector over the available themes. currentTheme is pre-selected and marked "(current)"; onPreview runs when the selection moves. Each callback may be nil.

func (*ThemeSelectorComponent) GetSelectList

func (ts *ThemeSelectorComponent) GetSelectList() *SelectList

GetSelectList returns the underlying SelectList (theme-selector.ts getSelectList).

func (*ThemeSelectorComponent) HandleInput

func (ts *ThemeSelectorComponent) HandleInput(data string)

HandleInput delegates to the list. A parent Container reuses this component's lines until it is invalidated, so a list change must invalidate it.

func (*ThemeSelectorComponent) Invalidate

func (i *ThemeSelectorComponent) Invalidate()

func (*ThemeSelectorComponent) IsDirty

func (i *ThemeSelectorComponent) IsDirty() bool

func (*ThemeSelectorComponent) NeedsRedraw

func (i *ThemeSelectorComponent) NeedsRedraw() bool

func (*ThemeSelectorComponent) Render

func (ts *ThemeSelectorComponent) Render(width int) []string

Render draws the container and clips a row wider than width. SelectList draws its two-cell row prefix at any width, so at a width of one it would overflow, which upstream's TUI treats as fatal ("Rendered line N exceeds terminal width").

type ThemeStyle

type ThemeStyle struct {
	TextAttributes
	FgToken, BgToken string
	Fg, Bg           Color
}

ThemeStyle is the style theme.style applies: a foreground and a background, each a theme token or a concrete Color, and text attributes. Setting both the token and the color of a slot is an error.

type ThemeToken

type ThemeToken string

ThemeToken is a foreground or background theme token: upstream `ThemeToken = ThemeColor | ThemeBg` (theme.ts:117).

type ThemeTokenValue

type ThemeTokenValue struct {
	Token string
	Value ThemeColorValue
}

ThemeTokenValue is one theme token with its color, in the order the Theme constructor takes them (theme.ts fgColors and bgColors records).

type ThemeWatcher

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

ThemeWatcher owns native notifications and the reload worker for one interactive mode. Close cancels and joins the worker. Dispatch transfers publication to the UI owner; file reading and color resolution stay on the worker.

func StartThemeWatcher

func StartThemeWatcher(ctx context.Context, directory string, dispatch func(context.Context, func()) error) *ThemeWatcher

StartThemeWatcher enables custom-theme watching for the selected name. The caller owns Close. A nil dispatcher publishes directly for non-UI callers.

func (*ThemeWatcher) Close

func (w *ThemeWatcher) Close()

Close stops notifications and drains owned reload work. Already queued UI actions check cancellation and generation before publishing.

type ThemedText

type ThemedText struct {
	*Text
	// contains filtered or unexported fields
}

ThemedText is Text whose content applies theme colors: the string is rebuilt from build after every invalidation.

func NewThemedText

func NewThemedText(build func() string, paddingX, paddingY int) *ThemedText

NewThemedText builds lazily; build must return the same content each time, apart from colors.

func (*ThemedText) Invalidate

func (t *ThemedText) Invalidate()

Invalidate marks the text stale.

func (ThemedText) IsDirty

func (i ThemedText) IsDirty() bool

func (ThemedText) NeedsRedraw

func (i ThemedText) NeedsRedraw() bool

func (*ThemedText) Render

func (t *ThemedText) Render(width int) []string

Render rebuilds a stale text before rendering it.

type ThinkingBlock

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

ThinkingBlock is a TUI component that renders a thinking/reasoning block.

func NewThinkingBlock

func NewThinkingBlock(hidden bool) *ThinkingBlock

NewThinkingBlock creates a thinking block. Pass hidden=true when the user has toggled visibility off (Ctrl+T). Content starts empty (invisible).

func (*ThinkingBlock) Content

func (b *ThinkingBlock) Content() string

Content returns the current thinking text.

func (*ThinkingBlock) Invalidate

func (i *ThinkingBlock) Invalidate()

func (*ThinkingBlock) IsDirty

func (i *ThinkingBlock) IsDirty() bool

func (*ThinkingBlock) NeedsRedraw

func (i *ThinkingBlock) NeedsRedraw() bool

func (*ThinkingBlock) Render

func (b *ThinkingBlock) Render(width int) []string

Render implements Component. Returns nil/empty when content is empty (invisible, takes zero height).

func (*ThinkingBlock) SetContent

func (b *ThinkingBlock) SetContent(content string)

SetContent updates the thinking text (streaming or final).

func (*ThinkingBlock) SetHidden

func (b *ThinkingBlock) SetHidden(hidden bool)

SetHidden controls whether the full text or a "Thinking..." indicator is shown.

type ToolDefinitionRenderers

type ToolDefinitionRenderers struct {
	Self   bool
	Call   func(ToolRenderInput) (Component, bool)
	Result func(ToolRenderInput) (Component, bool)
	// CallReadsFields reports that Call reads a streaming call's arguments from ToolRenderInput.Fields: the card then
	// hands it the decoded arguments and no text, so a frame does not encode arguments that grow with every delta.
	CallReadsFields bool
}

ToolDefinitionRenderers is a registered tool definition as the card draws it. Call and Result run the definition's renderCall and renderResult for the card's current state and return the component. They report false when the definition has no such renderer or the renderer failed; the card then draws upstream's fallback. Self is renderShell "self".

func (*ToolDefinitionRenderers) ToolRenderers

ToolRenderers makes the renderers themselves a ToolDefinitionSource (upstream's bare ToolRenderers member). A nil receiver is the undefined source.

type ToolDefinitionSource

type ToolDefinitionSource interface {
	ToolRenderers() *ToolDefinitionRenderers
}

ToolDefinitionSource is upstream's `ToolRenderers | ToolDefinition` (tool-execution.ts:66): anything that carries the renderers a tool card draws with, the bare renderers or a full tool definition. A nil source is upstream's undefined.

type ToolExecutionComponent

type ToolExecutionComponent struct {
	Container

	Name string
	// ToolCallID identifies the tool call the card shows (tool-execution.ts toolCallId); renderers receive it in their context.
	ToolCallID string
	// Label is ignored: the fallback call header names the tool by Name, as upstream createCallFallback does.
	//
	// Deprecated: a registered tool's card draws its definition; Label has no effect.
	Label string
	// ArgsPreview is a short human-readable rendering of the tool args.
	// Build it with FormatToolArgs() before assigning, or use SetRunning().
	ArgsPreview string

	// Cwd is the session working directory, used to resolve relative tool
	// paths to absolute file:// URLs for OSC-8 hyperlinks in the header.
	Cwd string

	State  ToolExecutionState
	Output string

	// Collapsed controls the renderer's expanded state. New tool cards start
	// collapsed to match upstream; final results may apply tool-specific rules.
	Collapsed bool

	// Elapsed is shown on done/error states when > 0.
	Elapsed time.Duration

	// DurationMs is the recorded execution time of the final result in milliseconds, which survives a session reload; nil when the
	// result carries none. A final result's recorded duration wins over the card's own clock.
	// upstream: tool-execution.ts result.durationMs
	DurationMs *int64

	// StartedAt records when the tool began executing. Used to render a live
	// "Elapsed X.Xs" footer while a shell tool runs (mirrors upstream bash.ts
	// renderResult, which ticks the elapsed every second during execution).
	StartedAt time.Time

	// Configurable thresholds. Zero values fall back to defaults.
	AutoCollapseLines int // default 8
	BodyMaxLines      int // default 40

	// BodyRenderer, when non-nil, replaces the default plain-text body
	// rendering. Used for per-tool rich displays: unified diff for
	// edit, line-numbered output for read, etc. The function receives
	// the available width and the current expanded state so it can show
	// a truncated preview or full output depending on Ctrl+O toggle.
	//
	// When set, the line-count annotation in the header is computed
	// from the renderer's row count instead of the raw Output text so
	// `(N lines, 1.2s)` accurately reflects what the user can see.
	BodyRenderer func(width int, expanded bool) []string

	// ImageBlocks holds image content blocks from tool results.
	// When non-empty and ShowImages is true, they render after the body.
	// Mirrors upstream tool-execution.ts imageComponents/imageSpacers.
	ImageBlocks []ImageBlock

	// ShowImages controls whether ImageBlocks are rendered.
	// Mirrors upstream ToolExecutionOptions.showImages.
	ShowImages bool

	// ImageWidthCells caps the width of rendered images in columns.
	// Mirrors upstream ToolExecutionOptions.imageWidthCells (default 60).
	ImageWidthCells int

	// IsPartial mirrors upstream tool-execution.ts isPartial. true while
	// the tool is still being streamed/executed, false after final result.
	// Controls the pending bg tint before execution completes.
	IsPartial bool
	// contains filtered or unexported fields
}

ToolExecutionComponent renders one tool call in the chat transcript.

Visual model (mirrors upstream per-tool renderCall functions):

$ expr 20 + 22             ← bash: bold "$ <command>"
read README.md             ← read: bold "read <path>"
write out.txt              ← write: bold "write <path>"
edit main.go               ← edit: bold "edit <path>"
grep /pattern/ in .           ← grep: bold "grep /<pat>/ in <path>"
find *.go in .             ← find: bold "find <pat> in <path>"
ls src/                    ← ls: bold "ls <path>"

No lifecycle markers (✓/▶/✗): upstream conveys state only via background color (pending, success, error). No "(N lines, Xs)" annotation in the header: upstream shows duration in body footer.

State transitions:

  • SetRunning: state → Running, output cleared
  • SetResult: state → Done or Error, body filled

Output thresholds:

  • autoCollapseLines: outputs longer than this start collapsed (overridden to expanded for errors)
  • bodyMaxLines: lines shown in the expanded view; overflow shows a "\u2026 (N more lines)" footer line.

func NewToolExecutionComponent

func NewToolExecutionComponent(toolName, toolCallID string, args json.RawMessage, options ToolExecutionOptions, definition ToolDefinitionSource, ui TUI, cwd string) *ToolExecutionComponent

NewToolExecutionComponent returns a Running-state component for a tool call (tool-execution.ts constructor(toolName, toolCallId, args, options = {}, toolDefinition, ui, cwd)). args are the call's current arguments: the card draws its header and, with a definition, its renderers from them. definition is the tool's registered renderers, nil for the built-in or generic presentation: a ToolDefinitionSource, upstream's `ToolRenderers | ToolDefinition | undefined` (tool-execution.ts:66). ui is the TUI the card asks for a render when an asynchronous change, such as the image transcoder registering, needs one; nil asks for none. cwd resolves relative tool paths in the header.

func (*ToolExecutionComponent) Aborted

func (c *ToolExecutionComponent) Aborted() bool

Aborted reports whether MarkAborted or FinalizeAborted ended the call.

func (*ToolExecutionComponent) Collapse

func (c *ToolExecutionComponent) Collapse()

Collapse forces the body closed.

func (*ToolExecutionComponent) Expand

func (c *ToolExecutionComponent) Expand()

Expand forces the body open.

func (*ToolExecutionComponent) FinalizeAborted

func (c *ToolExecutionComponent) FinalizeAborted(elapsed time.Duration)

FinalizeAborted freezes a still-running tool when its turn is aborted mid-execution. It transitions out of Running so the live "Elapsed X.Xs" footer stops recomputing time.Since(StartedAt) on every subsequent render (which otherwise forced a repaint on every keystroke and agent chunk, breaking terminal scrollback) while keeping any partial streamed output. No-op if the tool already reached a terminal state.

func (*ToolExecutionComponent) HandleMouse

HandleMouse delegates to nested renderer components before toggling a completed or partial result. Images and the outer spacer never toggle the card.

func (*ToolExecutionComponent) HasDefinition

func (c *ToolExecutionComponent) HasDefinition() bool

HasDefinition reports whether the card draws a registered tool definition.

func (*ToolExecutionComponent) Invalidate

func (c *ToolExecutionComponent) Invalidate()

Invalidate marks the card for redraw. A card with a definition also reruns its renderers, as upstream ToolExecutionComponent.invalidate calls updateDisplay.

func (*ToolExecutionComponent) IsDirty

func (c *ToolExecutionComponent) IsDirty() bool

IsDirty reports whether the component needs re-rendering. While a shell tool runs, the live "Elapsed X.Xs" footer recomputes time.Since(StartedAt) on every frame driven by the 100ms tick loop, but the tick does not Invalidate this component. Reporting dirty while that footer is live keeps the per-child render cache from freezing the elapsed counter.

func (*ToolExecutionComponent) MarkAborted

func (c *ToolExecutionComponent) MarkAborted()

pig additive (D91): MarkAborted records that the call ended because the user aborted its turn, so a frontend session reports it as cancelled. It changes nothing the card draws. A later error result keeps the mark, since a tool reports the abort as its error; a successful result clears it.

func (*ToolExecutionComponent) MarkExecutionStarted

func (c *ToolExecutionComponent) MarkExecutionStarted()

MarkExecutionStarted records that the tool has begun executing. Mirrors upstream tool-execution.ts markExecutionStarted.

func (*ToolExecutionComponent) NeedsRedraw

func (i *ToolExecutionComponent) NeedsRedraw() bool

func (*ToolExecutionComponent) Render

func (c *ToolExecutionComponent) Render(width int) []string

Render mirrors upstream render (tool-execution.ts:262-292): a registered definition with renderShell "self" draws its components after one blank row, or nothing when they draw nothing; every other card is the Container of spacer, content box and images.

func (*ToolExecutionComponent) ResultValue

func (c *ToolExecutionComponent) ResultValue() any

ResultValue returns the structured result recorded by SetResultValue.

func (*ToolExecutionComponent) SetArgsComplete

func (c *ToolExecutionComponent) SetArgsComplete()

SetArgsComplete records that the args JSON is finalized. Mirrors upstream tool-execution.ts setArgsComplete.

func (*ToolExecutionComponent) SetDefinition

func (c *ToolExecutionComponent) SetDefinition(definition *ToolDefinitionRenderers, args json.RawMessage)

SetDefinition makes the card draw a registered tool definition as upstream does, instead of the built-in or generic presentation. args are the call's current arguments. A nil definition returns the card to that presentation.

func (*ToolExecutionComponent) SetDefinitionArgs

func (c *ToolExecutionComponent) SetDefinitionArgs(args json.RawMessage)

SetDefinitionArgs replaces the arguments the definition's renderers receive, as upstream updateArgs does.

func (*ToolExecutionComponent) SetExpanded

func (c *ToolExecutionComponent) SetExpanded(expanded bool)

SetExpanded forces the body open or closed and records the user's intent so subsequent SetResult calls don't snap it back. Used by global Ctrl+O (toggle-all-tools) so every component lands in the same state.

func (*ToolExecutionComponent) SetHeaderArgs

func (c *ToolExecutionComponent) SetHeaderArgs(args json.RawMessage)

SetHeaderArgs records the call arguments the collapsed read card's compact label and a frontend session's tool node are drawn from. They replace streamed arguments.

func (*ToolExecutionComponent) SetImageWidthCells

func (c *ToolExecutionComponent) SetImageWidthCells(width int)

SetImageWidthCells updates the max image width. Mirrors upstream setImageWidthCells.

func (*ToolExecutionComponent) SetOutputPad

func (c *ToolExecutionComponent) SetOutputPad(outputPad int)

SetShowImages toggles image rendering. Mirrors upstream setShowImages. SetOutputPad is Pi's setOutputPad(outputPad) (tool-execution.ts:207): the card's horizontal padding, applied at once to the content box (updateDisplay's renderContainer.setPaddingX) and to the default card.

func (*ToolExecutionComponent) SetResult

func (c *ToolExecutionComponent) SetResult(output string, isError bool, elapsed time.Duration)

SetResult finalises the component with output text and an error flag, applying the auto-collapse rule unless the user has already toggled.

func (*ToolExecutionComponent) SetResultValue

func (c *ToolExecutionComponent) SetResultValue(result any)

SetResultValue records the structured tool result, partial while the tool runs, that the definition's result renderer receives.

func (*ToolExecutionComponent) SetRunning

func (c *ToolExecutionComponent) SetRunning(argsPreview string)

SetRunning marks the component as in-flight with the given pre-formatted args preview. Idempotent.

func (*ToolExecutionComponent) SetShowImages

func (c *ToolExecutionComponent) SetShowImages(show bool)

func (*ToolExecutionComponent) SetStreamedArgs

func (c *ToolExecutionComponent) SetStreamedArgs(args StreamedToolArgs)

SetStreamedArgs is upstream updateArgs(content.arguments) on message_update (interactive-mode.ts:3548-3552): the card draws the partial arguments of a streaming call, so a write card shows the lines received so far. The card reads the decoded arguments as they are and encodes them only for a reader that needs their text, so neither a delta nor a frame drawn by a renderer that reads them decoded costs more as the arguments grow.

func (*ToolExecutionComponent) SetStreaming

func (c *ToolExecutionComponent) SetStreaming(snapshot string)

SetStreaming updates the live output body during execution without changing expansion state. Only SetExpanded or Toggle changes that state while running.

func (*ToolExecutionComponent) SetStructuredArgs deprecated

func (c *ToolExecutionComponent) SetStructuredArgs(args json.RawMessage)

SetStructuredArgs draws the card as a registered tool definition without renderers, whose fallback call header shows args.

Deprecated: use SetDefinition(&ToolDefinitionRenderers{}, args).

func (*ToolExecutionComponent) Toggle

func (c *ToolExecutionComponent) Toggle()

Toggle flips the collapsed state and records that the user touched it so subsequent SetResult calls don't snap it back.

func (*ToolExecutionComponent) UpdateArgs

func (c *ToolExecutionComponent) UpdateArgs(args json.RawMessage)

UpdateArgs updates the displayed header from partial/complete args. Called progressively during streaming as ToolCallDelta events arrive. Mirrors upstream tool-execution.ts updateArgs(args): the tool name is fixed when the card is constructed.

func (*ToolExecutionComponent) UpdateResult

func (c *ToolExecutionComponent) UpdateResult(result ToolResultUpdate, isPartial ...bool)

UpdateResult is tool-execution.ts updateResult(result, isPartial = false): it records the result, converts its image blocks, and redraws. A partial result streams its text into the running card; a final one settles the card with its error state and duration.

type ToolExecutionOptions

type ToolExecutionOptions struct {
	ShowImages      *bool
	ImageWidthCells *int
	// OutputPad is options.outputPad, the horizontal padding of the card; nil keeps Pi's default of 1.
	OutputPad *int
}

ToolExecutionOptions are the optional constructor settings of a tool card (tool-execution.ts:25). A nil field is upstream's undefined: images show (`showImages ?? true`) and render 60 cells wide (`imageWidthCells ?? 60`).

type ToolExecutionState

type ToolExecutionState int

ToolExecutionState is the lifecycle stage of a tool call display.

const (
	ToolStateRunning ToolExecutionState = iota
	ToolStateDone
	ToolStateError
)

type ToolRenderInput

type ToolRenderInput struct {
	// ToolCallID is the card's tool call id (tool-execution.ts toolCallId).
	ToolCallID string
	// Args is the call's arguments as JSON text. It is nil while Fields is set.
	Args json.RawMessage
	// Fields is the decoded argument object of a call whose arguments are still streaming, as the streaming parser holds
	// it, for a Call that reads it (ToolDefinitionRenderers.CallReadsFields); nil otherwise. A renderer must not modify it.
	Fields           map[string]any
	ExecutionStarted bool
	ArgsComplete     bool
	IsPartial        bool
	Expanded         bool
	ShowImages       bool
	IsError          bool
	OutputPad        int
	// DurationMs is the recorded execution time of a final result in milliseconds; nil while the result is partial.
	// upstream: tool-execution.ts:137 durationMs: this.isPartial ? undefined : this.result?.durationMs
	DurationMs *int64
}

ToolRenderInput is the card state upstream ToolExecutionComponent passes to a registered tool definition's renderers.

type ToolResultContent

type ToolResultContent struct {
	Type     string // "text" or "image"
	Text     string
	Data     string
	MimeType string
}

ToolResultContent is one block of a tool result's content: tool-execution.ts updateResult's `{ type, text?, data?, mimeType? }`.

type ToolResultUpdate

type ToolResultUpdate struct {
	Content []ToolResultContent
	// Details is the tool's structured details. A card with a registered definition reads them through Result.
	Details any
	IsError bool
	// DurationMs is the recorded execution time of a final result; nil for a partial result and for one stored without a duration.
	DurationMs *int64
	// Result is the structured result handed to the registered definition's result renderer (agent.AgentToolResult in production).
	// Nil leaves the renderer's result unchanged. Pi passes `{ content, details }` itself; the card has no agent types.
	Result any
	// Elapsed is the final result's wall time for the done/error footer; zero shows none (Pi's card keeps no such footer).
	Elapsed time.Duration
}

ToolResultUpdate is the result argument of UpdateResult: tool-execution.ts updateResult's `{ content, details?, isError, durationMs? }`, plus the two Go-side carriers the card needs.

type TreeList

type TreeList struct {

	// OnSelect runs with the selected entry's ID on the confirm key (TreeList.onSelect).
	OnSelect func(entryID string)
	// OnCancel runs on the cancel key when no search is active (TreeList.onCancel).
	OnCancel func()
	// MaxVisibleLines is the number of tree rows shown at once. Upstream
	// TreeSelectorComponent uses max(5, floor(terminalHeight / 2)); see
	// TreeVisibleLines. Zero uses treeWindow.
	MaxVisibleLines int

	// OnLabelEdit is called when the user commits a label (Enter).
	// entryID is the target entry; label is the new name (empty string
	// clears any existing label, matching upstream undefined→delete).
	// The caller is responsible for persisting via Session.AppendLabelChange.
	OnLabelEdit func(entryID, label string)
	// OnCopy receives the full selected entry text, or nil when the entry has no copyable text.
	OnCopy func(*string)
	// contains filtered or unexported fields
}

TreeList is upstream's TreeList (tree-selector.ts:106-1335): the flattened session tree with its folding, filter, search, selection, scrolling and label-edit state, and the key handling that drives them.

func (*TreeList) Cancelled

func (t *TreeList) Cancelled() bool

func (*TreeList) CapturesSelectPageInput

func (t *TreeList) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the list handles tui.select.pageUp and tui.select.pageDown.

func (*TreeList) Done

func (t *TreeList) Done() bool

func (*TreeList) GetSelectedNode

func (t *TreeList) GetSelectedNode() TreeNode

GetSelectedNode returns the node under the cursor, or nil when no row is visible (TreeList.getSelectedNode).

func (*TreeList) HandleInput

func (t *TreeList) HandleInput(data string)

HandleInput moves the cursor, commits the selection, or delegates label editing to the shared Input.

Ctrl+Left/Alt+Left folds the highlighted branch or moves to the current branch segment start. Ctrl+Right/Alt+Right unfolds it or moves to the next branch segment. Shift+T toggles label timestamps. Colliding bindings use upstream's action priority.

func (*TreeList) Invalidate

func (t *TreeList) Invalidate()

Invalidate tells the hosting Container that the list changed.

func (*TreeList) Render

func (t *TreeList) Render(width int) []string

Render draws the visible tree rows and the position line (tree-selector.ts TreeList.render).

func (*TreeList) SelectedID

func (t *TreeList) SelectedID() string

func (*TreeList) SetInitialCursor

func (t *TreeList) SetInitialCursor(currentLeafID, initialSelectedID string)

SetInitialCursor orders and marks the active root-to-leaf path, then selects initialSelectedID or the current leaf. A hidden target resolves to its nearest visible ancestor. Call it after construction and before rendering.

func (*TreeList) WarmSearchTexts

func (t *TreeList) WarmSearchTexts()

WarmSearchTexts memoizes every row's lowercase searchable text, so the first search keystroke is a plain scan instead of building the texts. The host calls it once after the selector's first paint, before it reads input.

type TreeNode

type TreeNode interface {
	NodeID() string
	NodeLabel() string // single-line display, no \n
	NodeChildren() []TreeNode
}

TreeNode is the shape TreeSelectorComponent operates on. SessionTreeNode in codingagent satisfies this via a thin adapter.

type TreeNodeSearchableText

type TreeNodeSearchableText interface {
	// NodeSearchableText returns the lowercase-matchable text for the
	// node, excluding any ANSI formatting.
	NodeSearchableText() string
}

TreeNodeSearchableText is implemented by adapters that expose the plain-text a type-to-search query is matched against. Mirrors upstream `getSearchableText` (tree-selector.ts:559-600): the label plus role, message content, and entry-type fields. Adapters that don't implement it are matched on their NodeLabel only.

type TreeNodeWithBranchLabel

type TreeNodeWithBranchLabel interface {
	// NodeBranchLabel returns the user-set branch label, or "" when none is set.
	NodeBranchLabel() string
}

TreeNodeWithBranchLabel is implemented by adapters that carry a user-set branch label. Upstream renders this label outside the entry text as theme.fg("warning", "[label] ") (tree-selector.ts:673); it must not be folded into NodeLabel(), otherwise it loses its warning colour and selected rows bold the label instead of only bolding entry content.

type TreeNodeWithCopyText

type TreeNodeWithCopyText interface {
	NodeCopyText() *string
}

TreeNodeWithCopyText exposes complete copyable entry content separately from its abbreviated display label.

type TreeNodeWithFilterTags

type TreeNodeWithFilterTags interface {
	// NodeFilterTags returns zero or more semantic tags. Stable per
	// node: the picker caches them at flatten time.
	NodeFilterTags() []string
}

TreeNodeWithFilterTags is implemented by adapters that classify nodes for filter-mode skip-sets. Settings, tool, user, and labeled tags drive the default, no-tools, user-only, labeled-only, and all modes; the usage tag hides a node in every mode. Adapters without tags remain visible in every mode.

type TreeNodeWithLabelTimestamp

type TreeNodeWithLabelTimestamp interface {
	// NodeLabelTimestamp returns the upstream wire-format timestamp
	// of the LabelEntry that set the label, or "" when no label is
	// set or no timestamp is available.
	NodeLabelTimestamp() string
}

TreeNodeWithLabelTimestamp is implemented by adapters that carry a user-set branch label with its set-time. When `T` toggles label timestamps on, the picker prepends `hh:mm` (or a longer form for cross-day stamps) to the row content. Adapters that don't implement this interface render with no timestamp - equivalent to upstream's silent-empty branch when `flatNode.node.labelTimestamp` is undefined (tree-selector.ts:678-682).

type TreeSelectorComponent

type TreeSelectorComponent struct {
	Container
	// TreeList is the list the component hosts; GetTreeList returns it (tree-selector.ts:1432).
	*TreeList

	Title string
	// contains filtered or unexported fields
}

TreeSelectorComponent overlay: a Container of spacer, borders, title, key hints, search line, the TreeList and the label input (tree-selector.ts:1336-1436). Done()/Cancelled()/SelectedID() mirror the FilterableList contract.

func NewTreeSelectWithInitialFilter

func NewTreeSelectWithInitialFilter(title string, root TreeNode, initialFilterMode string) *TreeSelectorComponent

NewTreeSelectWithInitialFilter builds a selector whose first visibility pass uses initialFilterMode, mirroring the TreeSelectorComponent initialFilterMode argument (tree-selector.ts constructor). An unknown mode falls back to "default".

func NewTreeSelectorComponent

func NewTreeSelectorComponent(title string, root TreeNode) *TreeSelectorComponent

NewTreeSelectorComponent builds a selector in the default filter mode.

func NewTreeSelectorComponentFrom

func NewTreeSelectorComponentFrom(tree []TreeNode, currentLeafID *string, terminalHeight int, onSelect func(entryID string), onCancel func(), onLabelChange func(entryID string, label *string), initialSelectedID *string, initialFilterMode string) *TreeSelectorComponent

NewTreeSelectorComponentFrom builds the selector as tree-selector.ts's constructor does: tree holds the session's root nodes, currentLeafID the active leaf (nil when the session has none), terminalHeight sizes the window to max(5, floor(height/2)), and initialSelectedID (nil for none) and initialFilterMode (an unknown mode is "default") choose the opening state. onSelect and onCancel are the TreeList callbacks, run when the confirm or cancel key is handled; onLabelChange receives the committed label of a node, nil when it was cleared. An empty tree cancels itself after 100ms, so onCancel runs on a timer goroutine then. Any callback may be nil.

func (*TreeSelectorComponent) Focused

func (t *TreeSelectorComponent) Focused() bool

Focused reports the TUI focus flag (upstream `get focused`).

func (*TreeSelectorComponent) GetTreeList

func (t *TreeSelectorComponent) GetTreeList() *TreeList

Done / Cancelled / SelectedID implement the modal contract. GetTreeList returns the list the component hosts (tree-selector.ts:1432-1434).

func (*TreeSelectorComponent) Invalidate

func (t *TreeSelectorComponent) Invalidate()

Invalidate drops the Container's cached lines.

func (*TreeSelectorComponent) IsDirty

func (i *TreeSelectorComponent) IsDirty() bool

func (*TreeSelectorComponent) NativeNode

func (t *TreeSelectorComponent) NativeNode() (frontend.Node, bool)

NativeNode reports the visible rows as a selector whose item ids are the node ids, checked on the active path, with the filter modes as tabs in the order app.tree.filter.cycleForward steps through them. pig additive (D91): a row's label is its plain text after the tree connectors (fold marker, branch label, label time, entry), the status the filter and label time labels, and the label editor is not modelled, so the dock shows it as lines.

func (*TreeSelectorComponent) NeedsRedraw

func (i *TreeSelectorComponent) NeedsRedraw() bool

func (*TreeSelectorComponent) Render

func (t *TreeSelectorComponent) Render(width int) []string

Render draws the component's children. TreeList also has a Render, so the component names its own.

func (*TreeSelectorComponent) SetFocused

func (t *TreeSelectorComponent) SetFocused(focused bool)

SetFocused records TUI focus and propagates it to an active label input for IME cursor positioning (upstream `set focused`).

type TruncatedText

type TruncatedText struct {
	Content  string
	PaddingX int
	PaddingY int
	// contains filtered or unexported fields
}

TruncatedText renders text truncated to fit viewport width.

func NewTruncatedText

func NewTruncatedText(content string, paddingX, paddingY int) *TruncatedText

NewTruncatedText ports the constructor (text, paddingX = 0, paddingY = 0) of truncated-text.ts:12; Go has no default parameters, so a caller passes 0.

func (*TruncatedText) Invalidate

func (i *TruncatedText) Invalidate()

func (*TruncatedText) IsDirty

func (i *TruncatedText) IsDirty() bool

func (*TruncatedText) NeedsRedraw

func (i *TruncatedText) NeedsRedraw() bool

func (*TruncatedText) Render

func (t *TruncatedText) Render(width int) []string

type TruncationResult

type TruncationResult struct {
	Content     string `json:"content"`
	Truncated   bool   `json:"truncated"`
	TruncatedBy string `json:"truncatedBy"` // "lines" | "bytes" | ""
	TotalLines  int    `json:"totalLines"`
	TotalBytes  int    `json:"totalBytes"`
	OutputLines int    `json:"outputLines"`
	OutputBytes int    `json:"outputBytes"`
	// LastLinePartial: the last line of the original output is the
	// only one that fit (and was truncated from its end). Bash-only
	// edge case.
	LastLinePartial bool `json:"lastLinePartial"`
	// FirstLineExceedsLimit: head-truncation case where the first line
	// alone exceeds maxBytes. We return empty content and let the
	// caller decide.
	FirstLineExceedsLimit bool `json:"firstLineExceedsLimit"`
	MaxLines              int  `json:"maxLines"`
	MaxBytes              int  `json:"maxBytes"`
}

TruncationResult captures every fact a renderer needs to format the "[Showing lines X-Y of Z. Full output: <path>]" warning row.

Layout matches upstream TruncationResult:

{ content, truncated, truncatedBy, totalLines, totalBytes,
  outputLines, outputBytes, lastLinePartial, firstLineExceedsLimit,
  maxLines, maxBytes }

type TuiAltScreen

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

TuiAltScreen is the alternate-screen renderer. It embeds tuiBase for the shared render machinery (requestRender coalescing, overlays, terminal I/O).

func NewTuiAltScreen

func NewTuiAltScreen(terminal Terminal, showHardwareCursor *bool, logDirectory string, options ...TuiAltScreenOptions) *TuiAltScreen

NewTuiAltScreen is `new TuiAltScreen(terminal, showHardwareCursor, logDirectory, options = {})` (tui-alt-screen.ts:255-282): the fullscreen renderer that draws on terminal and reads its size from it. A nil terminal is the process's own terminal, which the interactive driver uses. A nil showHardwareCursor keeps TuiBase's default, false (tui.ts:508,536-538; only the settings getter reads PI_HARDWARE_CURSOR); logDirectory is where the differential-render overflow crash log goes, the OS temp directory when empty. Only the first options value is read.

func NewTuiAltScreenWithOutput

func NewTuiAltScreenWithOutput(out io.Writer, cols, rows int, options TuiAltScreenOptions) *TuiAltScreen

NewTuiAltScreenWithOutput creates a fixed-size alt-screen renderer for tests.

func (*TuiAltScreen) ActiveOverlay

func (t *TuiAltScreen) ActiveOverlay() Component

ActiveOverlay refreshes overlay visibility and restores eligible focus before input dispatch. An active replacement keeps input until it changes focus, even if it is not mounted in the render tree.

func (*TuiAltScreen) AddInputListener

func (t *TuiAltScreen) AddInputListener(listener *TuiInputListener) func()

AddInputListener registers listener after the existing ones and returns the function that removes it.

func (*TuiAltScreen) CancelPendingRender

func (t *TuiAltScreen) CancelPendingRender()

CancelPendingRender invalidates a throttled frame, including one whose timer callback has already handed it to the owner loop. It maps the single-threaded JavaScript event-loop rule that a later state transition can consume a queued request before its callback runs.

func (*TuiAltScreen) ConsumeCellSizeResponse

func (t *TuiAltScreen) ConsumeCellSizeResponse(data string) bool

ConsumeCellSizeResponse reports whether data is a complete cell-size response. A response with positive dimensions updates the cell dimensions, invalidates every mounted component so images re-render at the new size, and requests a render; a response with a zero dimension is still consumed. Any other input returns false so it reaches the focused component. Mirrors upstream tui.ts consumeCellSizeResponse.

func (*TuiAltScreen) ConsumeDebugKey

func (t *TuiAltScreen) ConsumeDebugKey(data string) bool

ConsumeDebugKey runs the debug callback and consumes data when it is the global debug key (Shift+Ctrl+D) and a callback is set (tui.ts TuiBase.handleInput).

func (*TuiAltScreen) ConsumeTerminalColorResponse

func (t *TuiAltScreen) ConsumeTerminalColorResponse(data string) bool

ConsumeTerminalColorResponse consumes a color or DA1 reply that belongs to the oldest pending color query and reports whether it did. Terminals answer in order, so color replies belong to the oldest query. Call it before terminal-input listeners or focused-component dispatch, including after a query timeout, when a query still waits for its DA1 reply.

func (*TuiAltScreen) ConsumeTerminalColorSchemeReport

func (t *TuiAltScreen) ConsumeTerminalColorSchemeReport(data string) bool

ConsumeTerminalColorSchemeReport notifies the listeners of a light/dark report and reports whether data was one.

func (*TuiAltScreen) CopyActiveSelectionToClipboard

func (t *TuiAltScreen) CopyActiveSelectionToClipboard() bool

CopyActiveSelectionToClipboard copies the current selection and reports success.

func (*TuiAltScreen) DispatchFocusedInput

func (t *TuiAltScreen) DispatchFocusedInput(data string)

DispatchFocusedInput is the end of tui.ts:1044 handleTerminalInput, for a driver that has run the earlier stages itself: the global debug key (Shift+Ctrl+D) runs onDebug whatever has focus, then the overlay visibility and focus restoration are refreshed ([tuiBase.ActiveOverlay]), and the focused component's HandleInput receives the input, except a key release it does not ask for. Input is latency-sensitive, so a delivery requests an immediate render.

func (*TuiAltScreen) Flash

func (t *TuiAltScreen) Flash(message string, durationMs int)

Flash shows a transient message in the alternate-screen flash stack.

func (*TuiAltScreen) ForceFullRender

func (t *TuiAltScreen) ForceFullRender()

ForceFullRender marks the next frame as a full redraw. The alt-screen detects a full redraw when previousScreen is empty, so this resets the render state. Mirrors TUI.ForceFullRender (the main-screen sets forceRedraw, consumed by its differential renderer).

func (*TuiAltScreen) FullRedraws

func (t *TuiAltScreen) FullRedraws() int

FullRedraws counts the full repaints of the screen. Mirrors upstream `fullRedraws`.

func (*TuiAltScreen) GetClearOnShrink

func (t *TuiAltScreen) GetClearOnShrink() bool

GetClearOnShrink reports whether shrinking content triggers a full redraw to clear empty rows. Mirrors upstream TUI.getClearOnShrink().

func (*TuiAltScreen) GetCopyOnSelect

func (t *TuiAltScreen) GetCopyOnSelect() bool

GetCopyOnSelect reports whether a completed selection is copied automatically.

func (*TuiAltScreen) GetFocusedComponent

func (t *TuiAltScreen) GetFocusedComponent() Component

FocusedComponent returns the current overlay or non-overlay focus target.

func (*TuiAltScreen) GetScreenLines

func (t *TuiAltScreen) GetScreenLines() []string

GetScreenLines returns the lines of the last rendered frame, one per terminal row, as written to the terminal. The slice is a copy (tui-alt-screen.ts:315-318).

func (*TuiAltScreen) GetShowHardwareCursor

func (t *TuiAltScreen) GetShowHardwareCursor() bool

GetShowHardwareCursor reports whether the real terminal cursor is shown. Mirrors upstream TUI.getShowHardwareCursor().

func (*TuiAltScreen) HandleFocusedSearchInput

func (t *TuiAltScreen) HandleFocusedSearchInput(data string) bool

HandleFocusedSearchInput delivers a key to the transcript search box when it has focus and reports whether it did. Upstream's TUI hands focused-component input to the search box itself; PiG's driver owns input routing, so the driver calls this where upstream would reach the focused component.

func (*TuiAltScreen) HandleTerminalInput

func (t *TuiAltScreen) HandleTerminalInput(data string)

HandleTerminalInput is the renderer's dispatcher for one chunk of terminal input, in the order of tui.ts:1044 handleTerminalInput: color replies and light/dark reports, the input listeners, the cell-size reply, then [tuiBase.DispatchFocusedInput].

func (*TuiAltScreen) HandleViewportInput

func (t *TuiAltScreen) HandleViewportInput(data string) bool

HandleViewportInput routes a raw input chunk that targets the viewport: focus reports, mouse reports, and viewport keybindings. It returns true when it consumed the input so the driver does not dispatch it as a keystroke. Mirrors upstream handleViewportInput.

func (*TuiAltScreen) HasActiveSelection

func (t *TuiAltScreen) HasActiveSelection() bool

HasActiveSelection reports whether the fullscreen viewport has selected text.

func (*TuiAltScreen) HasOverlay

func (t *TuiAltScreen) HasOverlay() bool

HasOverlay reports whether any overlay entry is mounted. The interactive driver uses this for the upstream hasOverlayEntries renderer-switch guard.

func (*TuiAltScreen) Height

func (t *TuiAltScreen) Height() int

Height returns the terminal height of the last size the renderer took. It never takes t.mu and is safe from any goroutine.

func (*TuiAltScreen) HideCursor

func (t *TuiAltScreen) HideCursor()

HideCursor hides the terminal cursor.

func (*TuiAltScreen) HideOverlay

func (t *TuiAltScreen) HideOverlay()

HideOverlay permanently removes the most recently appended mounted entry. Focus and visual order do not affect this target. Mirrors upstream hideOverlay.

func (*TuiAltScreen) IsFollowingOutput

func (t *TuiAltScreen) IsFollowingOutput() bool

IsFollowingOutput reports whether the primary scroll view is pinned to the end.

func (*TuiAltScreen) IsSearchFocused

func (t *TuiAltScreen) IsSearchFocused() bool

IsSearchFocused reports whether the transcript search box has focus.

func (*TuiAltScreen) Mode

func (t *TuiAltScreen) Mode() TuiMode

Mode reports the renderer mode. Mirrors upstream `mode = "fullscreen"`.

func (*TuiAltScreen) OnDebug

func (t *TuiAltScreen) OnDebug() func()

OnDebug returns the global debug-key callback, nil when none is set (tui.ts TuiBase.onDebug).

func (*TuiAltScreen) OnTerminalColorSchemeChange

func (t *TuiAltScreen) OnTerminalColorSchemeChange(listener func(scheme TerminalColorScheme)) func()

OnTerminalColorSchemeChange registers a light/dark report listener and returns the function that removes it.

func (*TuiAltScreen) PostToOwner

func (t *TuiAltScreen) PostToOwner(ctx context.Context, fn func()) error

PostToOwner queues fn on the owner loop (see SetOwnerDispatcher). It never drops fn: it returns once the loop has accepted it, or ctx's error when ctx ends first. Without a dispatcher fn runs inline, as the other dispatch seams do. Thread-safe.

func (*TuiAltScreen) QueryCellSize

func (t *TuiAltScreen) QueryCellSize()

Ports packages/tui/src/tui.ts (queryCellSize, cell-size response handling). QueryCellSize writes the cell-size query when the terminal supports images, since only image rendering uses the cell size. Mirrors upstream tui.ts queryCellSize, which start() sends after the terminal starts.

func (*TuiAltScreen) QueryTerminalColors

func (t *TuiAltScreen) QueryTerminalColors(options TerminalColorQueryOptions) <-chan TerminalColorsResult

QueryTerminalColors queries the terminal's theme colors: the default foreground (OSC 10), the default background (OSC 11), and ANSI colors 0-15 (OSC 4), followed by a DA1 request that marks the end of the replies. The completion arrives when the DA1 reply or all color replies arrive, or when the timeout expires. Colors the terminal did not report are nil; the palette is set only when all 16 arrived. A query that completes after the timeout reports its replies to OnLateReply. Stop does not cancel the deadline, matching the terminal query's independent Promise lifetime. Mirrors tui.ts queryTerminalColors.

func (*TuiAltScreen) RemoveInputListener

func (t *TuiAltScreen) RemoveInputListener(listener *TuiInputListener)

RemoveInputListener removes a registered listener. Removing one that is not registered does nothing.

func (*TuiAltScreen) Render

func (t *TuiAltScreen) Render()

Render performs a differential render pass using inline-flow output.

Mirrors upstream pi-tui's `render()`. New content is appended with `\r\n`, which scrolls the viewport up and pushes older lines into the terminal's native scrollback. The terminal's normal scrolling makes our chat history reachable via the user's mouse wheel / Cmd-↑ after pig exits, just like a regular shell.

Algorithm sketch:

  1. Detect width/height change → fullRender(clear).
  2. First render → fullRender(no clear). Lines emitted with `\r\n` between them flow naturally.
  3. Diff prevLines vs newLines to find [firstChanged, lastChanged].
  4. If visible tail content shrinks and exposes rows above the old viewport, repaint only the new visible viewport.
  5. If only deletions remain, clear those rows in place.
  6. If firstChanged is above the current viewport → fullRender(clear).
  7. Otherwise: move cursor to firstChanged (scrolling if it's below the viewport bottom), rewrite affected lines, clear any extras.

func (*TuiAltScreen) RenderNow

func (t *TuiAltScreen) RenderNow(force ...bool)

RenderNow renders immediately, cancelling any pending render; force=true makes the frame a full repaint. Mirrors upstream renderNow(force) (tui.ts:982).

func (*TuiAltScreen) RenderSnapshot

func (t *TuiAltScreen) RenderSnapshot(width int) []string

RenderSnapshot returns the rendered document lines at the given width. Mirrors TUI.RenderSnapshot; the alt-screen renders the layout root (or base children) at natural height, matching upstream render(width).

func (*TuiAltScreen) RepaintAll

func (t *TuiAltScreen) RepaintAll()

RepaintAll forces an immediate full repaint. Mirrors TUI.RepaintAll (which clears hasRendered then renders); the alt-screen clears its differential state.

func (*TuiAltScreen) RequestImmediateRender

func (t *TuiAltScreen) RequestImmediateRender()

RequestImmediateRender preempts a throttled frame and coalesces keyboard updates onto the next owner-loop turn. It exposes TuiBase.requestImmediateRender to the Go driver's separately owned input path.

func (*TuiAltScreen) RequestRender

func (t *TuiAltScreen) RequestRender(force ...bool)

RequestRender asks the TUI to render soon, coalescing repeated calls and enforcing the upstream 16ms frame throttle. Use this for hot streaming paths (thinking/text deltas); direct Render() is reserved for low-frequency state changes and final flushes.

force is upstream's requestRender(force = false): true resets the render state so the next frame is a full repaint and renders on the next owner-loop turn instead of waiting for the frame throttle.

func (*TuiAltScreen) ResetTextSelection

func (t *TuiAltScreen) ResetTextSelection()

ResetTextSelection drops the text selection and multi-click history, for example before the host replaces the transcript (pi 1.1.0 tui-alt-screen.ts resetTextSelection).

func (*TuiAltScreen) RunDueRender

func (t *TuiAltScreen) RunDueRender()

RunDueRender runs the frame whose SetRenderDeadline deadline has passed, on the calling owner loop. A frame not yet due stays pending.

func (*TuiAltScreen) RunInputListeners

func (t *TuiAltScreen) RunInputListeners(data string) (string, bool)

RunInputListeners passes data through the registered listeners in registration order. It returns the data after any replacements and whether a listener consumed it or left it empty, in which case nothing else should receive it. pig divergence (D105): the driver owns the terminal reader; extension input listeners run asynchronously around the renderer's listener chain.

func (*TuiAltScreen) ScrollBy

func (t *TuiAltScreen) ScrollBy(lines int)

ScrollBy scrolls the primary scroll view by the given number of lines.

func (*TuiAltScreen) ScrollToBottom

func (t *TuiAltScreen) ScrollToBottom()

ScrollToBottom scrolls the primary scroll view to its end.

func (*TuiAltScreen) ScrollToTop

func (t *TuiAltScreen) ScrollToTop()

ScrollToTop scrolls the primary scroll view to its start.

func (*TuiAltScreen) SetClearOnShrink

func (t *TuiAltScreen) SetClearOnShrink(enabled bool)

SetClearOnShrink configures whether shrinking content triggers a full redraw when no overlays are active. Mirrors upstream TUI.setClearOnShrink().

func (*TuiAltScreen) SetCopyOnSelect

func (t *TuiAltScreen) SetCopyOnSelect(enabled bool)

SetCopyOnSelect changes automatic selection copy without rebuilding the renderer.

func (*TuiAltScreen) SetFixedSize

func (t *TuiAltScreen) SetFixedSize(cols, rows int)

SetFixedSize changes the size of a renderer built with a fixed size (NewWithOutput), as a terminal resize would; the next render sees it. Renderers that read the real terminal size ignore it.

func (*TuiAltScreen) SetFocus

func (t *TuiAltScreen) SetFocus(component Component)

SetFocus records a non-overlay target for focus restoration.

func (*TuiAltScreen) SetLayoutRoot

func (t *TuiAltScreen) SetLayoutRoot(component Component)

SetLayoutRoot installs the fullscreen layout tree (transcript scroll view + pinned footer). nil falls back to the implicit scroll view wrapping the base document. Mirrors upstream setLayoutRoot.

func (*TuiAltScreen) SetOnDebug

func (t *TuiAltScreen) SetOnDebug(onDebug func())

SetOnDebug sets the global debug-key callback (tui.ts TuiBase.onDebug); nil clears it.

func (*TuiAltScreen) SetOnHeightChange

func (t *TuiAltScreen) SetOnHeightChange(fn func(height int))

SetOnHeightChange registers a terminal-height callback. Fullscreen coalesces pending changes while a callback runs. Thread-safe.

func (*TuiAltScreen) SetOnWidthChange

func (t *TuiAltScreen) SetOnWidthChange(fn func(width int))

SetOnWidthChange registers a terminal-width callback. Fullscreen coalesces pending changes while a callback runs. Thread-safe.

func (*TuiAltScreen) SetOverlayCommandDispatcher

func (t *TuiAltScreen) SetOverlayCommandDispatcher(dispatch func(func()))

SetOverlayCommandDispatcher installs the ordered ingress used by remote producers. The dispatcher owns command ordering on the application loop.

func (*TuiAltScreen) SetOwnerDispatcher

func (t *TuiAltScreen) SetOwnerDispatcher(dispatch func(ctx context.Context, fn func()) error)

SetOwnerDispatcher installs the seam PostToOwner uses to queue work on the loop that owns component-tree mutation. The dispatcher blocks until the loop accepts fn or ctx ends, and returns an error only in the second case. Thread-safe.

func (*TuiAltScreen) SetRenderDeadline

func (t *TuiAltScreen) SetRenderDeadline(wake func(due time.Time))

SetRenderDeadline makes the loop that owns component-tree mutation keep the throttled-frame deadline, as Pi's requestRender arms one setTimeout on its event loop: a frame request records when its frame is due and calls wake with that time, or with the zero time once no frame is pending, instead of arming a timer whose callback runs on a goroutine of its own. The owner calls RunDueRender when the time passes. wake runs under the renderer's lock, so it must not call back into the renderer or block. It replaces a SetRenderDispatcher hook; nil restores the timer goroutine. Thread-safe.

func (*TuiAltScreen) SetRenderDispatcher

func (t *TuiAltScreen) SetRenderDispatcher(dispatch func(render func()))

SetRenderDispatcher installs a hook that runs throttled scheduled renders on the caller's main loop. The dispatcher receives a render closure and is responsible for eventually invoking it on the goroutine that owns component-tree mutation (it may enqueue it on an event loop). When nil (default), scheduled renders run inline on the throttle-timer goroutine, which is correct for standalone / single-goroutine use. It replaces a SetRenderDeadline owner. Thread-safe.

func (*TuiAltScreen) SetShowHardwareCursor

func (t *TuiAltScreen) SetShowHardwareCursor(enabled bool)

SetShowHardwareCursor toggles the hardware cursor and requests a frame, as upstream setShowHardwareCursor does (the frame runs on the next render tick, so changes made together share one). Mirrors TUI.SetShowHardwareCursor.

func (*TuiAltScreen) SetTerminalColorSchemeNotifications

func (t *TuiAltScreen) SetTerminalColorSchemeNotifications(enabled bool)

SetTerminalColorSchemeNotifications turns the terminal's light/dark reports (mode 2031) on or off. While the renderer is stopped only the preference changes; Start applies it.

func (*TuiAltScreen) SetTickDispatcher

func (t *TuiAltScreen) SetTickDispatcher(dispatch func(func()))

SetTickDispatcher installs the blocking owner-loop seam for owned state-machine ticks (alt-screen selection auto-scroll). It must marshal fn onto the loop that owns rendering, backpressuring rather than dropping while that loop is alive; see the tickOnMain doc. When unset the tick runs inline. Thread-safe.

func (*TuiAltScreen) SetWheelScrollLines

func (t *TuiAltScreen) SetWheelScrollLines(lines WheelScrollLines)

SetWheelScrollLines changes the wheel line setting at runtime and resets any acceleration gesture.

func (*TuiAltScreen) ShowCursor

func (t *TuiAltScreen) ShowCursor()

ShowCursor shows the terminal cursor.

func (*TuiAltScreen) ShowOverlay

func (t *TuiAltScreen) ShowOverlay(c Component, opts OverlayOptions) *OverlayHandle

ShowOverlay pushes a component onto the overlay append stack and returns a targeted handle. Callers must Close when the overlay is dismissed.

func (*TuiAltScreen) Start

func (t *TuiAltScreen) Start()

Start enters the alternate screen and paints at once, as a live switch into fullscreen needs. Mirrors upstream beforeTerminalStart + the enter write.

func (*TuiAltScreen) StartRequestingRender

func (t *TuiAltScreen) StartRequestingRender()

StartRequestingRender enters the alternate screen as Start does but requests the first frame instead of painting it, as Pi's TUI.start does (tui.ts start(): requestRender()). The first frame has no earlier frame to throttle against, so the request goes to the render dispatcher's loop at once, which runs it on its next turn.

func (*TuiAltScreen) Stop

func (t *TuiAltScreen) Stop()

Stop tears down the alternate screen and reflows the transcript into the main-screen scrollback. Satisfies the TUI interface (matching the driver's no-arg Stop call sites); use StopWithOptions for preserve-screen teardown.

func (*TuiAltScreen) StopWithOptions

func (t *TuiAltScreen) StopWithOptions(options StopOptions)

func (*TuiAltScreen) Terminal

func (t *TuiAltScreen) Terminal() Terminal

Terminal returns the terminal this renderer draws on (tui.ts TuiBase.terminal, a public property). A renderer built for the process terminal returns that terminal; one built with a fixed output and size returns a terminal that writes to the output and reports the size. The same value comes back every time.

Terminal and the returned terminal's size never take t.mu: components such as the Editor (editor.ts render reads tui.terminal.rows) call them from Render while the renderer holds t.mu for the frame.

func (*TuiAltScreen) ViewportTop

func (t *TuiAltScreen) ViewportTop() int

ViewportTop returns the primary scroll view's current scroll offset.

func (*TuiAltScreen) Width

func (t *TuiAltScreen) Width() int

Width returns the terminal width of the last size the renderer took. It never takes t.mu and is safe from any goroutine: the extension host reads it off the owner loop while a frame updates it.

func (*TuiAltScreen) WriteRaw

func (t *TuiAltScreen) WriteRaw(data string)

WriteRaw writes data to the terminal as is, as upstream's terminal.write does for a component that drives the terminal itself.

type TuiAltScreenOptions

type TuiAltScreenOptions struct {
	// WheelScrollLines is the logical lines moved per wheel event (default 1);
	// Auto accelerates fast wheel spins on terminals that send one event per notch.
	// Alt+wheel moves five times as far.
	WheelScrollLines WheelScrollLines
	// Mouse captures mouse events for viewport scrolling and selection.
	Mouse *bool
	// CopyOnSelect copies a completed text selection. The default is true.
	CopyOnSelect *bool
	// CopySelection writes selected text to the host clipboard; OSC 52 is used when it is nil. Pi's callback result `boolean | string`
	// is the Go error: a nil error is true, a non-empty error message is that string (shown as the error flash), and an empty error
	// message is false (a generic "Copy failed"). TestAltScreenCopySelectionResultOutcomes pins all three.
	CopySelection func(text string) error
	// OpenURL activates an OSC 8 hyperlink on primary-button click.
	OpenURL func(url string)
	// SearchMatchStyle styles a non-current transcript search match.
	SearchMatchStyle func(text string) string
	// SearchCurrentMatchStyle styles the current transcript search match.
	SearchCurrentMatchStyle func(text string) string
	// SearchNavigationButtonStyle styles a transcript search navigation button.
	SearchNavigationButtonStyle func(text string, hovered bool) string
	// ScrollToEndIndicator renders a clickable jump-to-end label, centered on
	// the last row of a follow-end primary scroll view while that view is
	// scrolled away from its end.
	ScrollToEndIndicator func() string
	// OnRightClickPaste handles an unmodified secondary-button press for
	// clipboard paste. Currently enabled on Windows only.
	OnRightClickPaste func()
}

TuiAltScreenOptions configures the alt-screen renderer. Mirrors upstream TuiAltScreenOptions.

type TuiInputListener

type TuiInputListener func(data string) *TuiInputResult

TuiInputListener sees raw terminal input before the focused component. A nil result passes the input on unchanged. Go function values are not comparable, so listeners are registered by pointer; the pointer is the identity RemoveInputListener matches.

type TuiInputResult

type TuiInputResult struct {
	Consume bool
	Data    *string
}

TuiInputResult is what an input listener returns. Consume stops the input from reaching later listeners and the focused component. A non-nil Data replaces the input for later listeners and the focused component.

type TuiMainScreen

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

TuiMainScreen is the main-screen renderer: differential rendering into the terminal's main screen + scrollback, overlays, cursor, raw input. It ports pi-tui's TuiMainScreen.

func New

func New() *TuiMainScreen

New creates the main-screen renderer for the process's terminal.

func NewTuiMainScreen

func NewTuiMainScreen(terminal Terminal, showHardwareCursor *bool, logDirectory string) *TuiMainScreen

NewTuiMainScreen is `new TuiMainScreen(terminal, showHardwareCursor, logDirectory)` (tui-main-screen.ts, TuiBase's constructor): the inline-flow renderer that draws on terminal and reads its size from it. A nil showHardwareCursor keeps TuiBase's default, false (tui.ts:508,536-538; only the settings getter reads PI_HARDWARE_CURSOR); logDirectory is where the differential-render overflow crash log goes, the OS temp directory when empty.

func NewWithOutput

func NewWithOutput(out io.Writer, cols, rows int) *TuiMainScreen

NewWithOutput creates a TUI that writes to a fixed io.Writer with fixed dimensions. Used only by tests; production code uses New().

func (*TuiMainScreen) ActiveOverlay

func (t *TuiMainScreen) ActiveOverlay() Component

ActiveOverlay refreshes overlay visibility and restores eligible focus before input dispatch. An active replacement keeps input until it changes focus, even if it is not mounted in the render tree.

func (*TuiMainScreen) AddInputListener

func (t *TuiMainScreen) AddInputListener(listener *TuiInputListener) func()

AddInputListener registers listener after the existing ones and returns the function that removes it.

func (*TuiMainScreen) CancelPendingRender

func (t *TuiMainScreen) CancelPendingRender()

CancelPendingRender invalidates a throttled frame, including one whose timer callback has already handed it to the owner loop. It maps the single-threaded JavaScript event-loop rule that a later state transition can consume a queued request before its callback runs.

func (*TuiMainScreen) CaptureRenderState

func (t *TuiMainScreen) CaptureRenderState() TuiMainScreenRenderState

CaptureRenderState snapshots the current inline-flow render state so a renderer swap can restore it. Mirrors upstream TuiMainScreen.captureRenderState.

func (*TuiMainScreen) ConsumeCellSizeResponse

func (t *TuiMainScreen) ConsumeCellSizeResponse(data string) bool

ConsumeCellSizeResponse reports whether data is a complete cell-size response. A response with positive dimensions updates the cell dimensions, invalidates every mounted component so images re-render at the new size, and requests a render; a response with a zero dimension is still consumed. Any other input returns false so it reaches the focused component. Mirrors upstream tui.ts consumeCellSizeResponse.

func (*TuiMainScreen) ConsumeDebugKey

func (t *TuiMainScreen) ConsumeDebugKey(data string) bool

ConsumeDebugKey runs the debug callback and consumes data when it is the global debug key (Shift+Ctrl+D) and a callback is set (tui.ts TuiBase.handleInput).

func (*TuiMainScreen) ConsumeTerminalColorResponse

func (t *TuiMainScreen) ConsumeTerminalColorResponse(data string) bool

ConsumeTerminalColorResponse consumes a color or DA1 reply that belongs to the oldest pending color query and reports whether it did. Terminals answer in order, so color replies belong to the oldest query. Call it before terminal-input listeners or focused-component dispatch, including after a query timeout, when a query still waits for its DA1 reply.

func (*TuiMainScreen) ConsumeTerminalColorSchemeReport

func (t *TuiMainScreen) ConsumeTerminalColorSchemeReport(data string) bool

ConsumeTerminalColorSchemeReport notifies the listeners of a light/dark report and reports whether data was one.

func (*TuiMainScreen) DispatchFocusedInput

func (t *TuiMainScreen) DispatchFocusedInput(data string)

DispatchFocusedInput is the end of tui.ts:1044 handleTerminalInput, for a driver that has run the earlier stages itself: the global debug key (Shift+Ctrl+D) runs onDebug whatever has focus, then the overlay visibility and focus restoration are refreshed ([tuiBase.ActiveOverlay]), and the focused component's HandleInput receives the input, except a key release it does not ask for. Input is latency-sensitive, so a delivery requests an immediate render.

func (*TuiMainScreen) ForceFullRender

func (t *TuiMainScreen) ForceFullRender()

ForceFullRender marks the next Render() as a destructive full repaint. Use it when the physical buffer is invalid, including semantic transcript replacement, not for ordinary dynamic shrink or streaming updates.

func (*TuiMainScreen) FullRedraws

func (t *TuiMainScreen) FullRedraws() int

FullRedraws counts the full repaints of the screen. Mirrors upstream `fullRedraws` (tui.ts:553).

func (*TuiMainScreen) GetClearOnShrink

func (t *TuiMainScreen) GetClearOnShrink() bool

GetClearOnShrink reports whether shrinking content triggers a full redraw to clear empty rows. Mirrors upstream TUI.getClearOnShrink().

func (*TuiMainScreen) GetFocusedComponent

func (t *TuiMainScreen) GetFocusedComponent() Component

FocusedComponent returns the current overlay or non-overlay focus target.

func (*TuiMainScreen) GetShowHardwareCursor

func (t *TuiMainScreen) GetShowHardwareCursor() bool

GetShowHardwareCursor reports whether the real terminal cursor is shown. Mirrors upstream TUI.getShowHardwareCursor().

func (*TuiMainScreen) HandleTerminalInput

func (t *TuiMainScreen) HandleTerminalInput(data string)

HandleTerminalInput is the renderer's dispatcher for one chunk of terminal input, in the order of tui.ts:1044 handleTerminalInput: color replies and light/dark reports, the input listeners, the cell-size reply, then [tuiBase.DispatchFocusedInput].

func (*TuiMainScreen) HasOverlay

func (t *TuiMainScreen) HasOverlay() bool

HasOverlay reports whether any overlay entry is mounted. The interactive driver uses this for the upstream hasOverlayEntries renderer-switch guard.

func (*TuiMainScreen) Height

func (t *TuiMainScreen) Height() int

Height returns the terminal height of the last size the renderer took. It never takes t.mu and is safe from any goroutine.

func (*TuiMainScreen) HideCursor

func (t *TuiMainScreen) HideCursor()

HideCursor hides the terminal cursor.

func (*TuiMainScreen) HideOverlay

func (t *TuiMainScreen) HideOverlay()

HideOverlay permanently removes the most recently appended mounted entry. Focus and visual order do not affect this target. Mirrors upstream hideOverlay.

func (*TuiMainScreen) Mode

func (t *TuiMainScreen) Mode() TuiMode

Mode reports the renderer mode. Mirrors upstream `mode = "regular"` of TuiMainScreen.

func (*TuiMainScreen) OnDebug

func (t *TuiMainScreen) OnDebug() func()

OnDebug returns the global debug-key callback, nil when none is set (tui.ts TuiBase.onDebug).

func (*TuiMainScreen) OnTerminalColorSchemeChange

func (t *TuiMainScreen) OnTerminalColorSchemeChange(listener func(scheme TerminalColorScheme)) func()

OnTerminalColorSchemeChange registers a light/dark report listener and returns the function that removes it.

func (*TuiMainScreen) PostToOwner

func (t *TuiMainScreen) PostToOwner(ctx context.Context, fn func()) error

PostToOwner queues fn on the owner loop (see SetOwnerDispatcher). It never drops fn: it returns once the loop has accepted it, or ctx's error when ctx ends first. Without a dispatcher fn runs inline, as the other dispatch seams do. Thread-safe.

func (*TuiMainScreen) QueryCellSize

func (t *TuiMainScreen) QueryCellSize()

Ports packages/tui/src/tui.ts (queryCellSize, cell-size response handling). QueryCellSize writes the cell-size query when the terminal supports images, since only image rendering uses the cell size. Mirrors upstream tui.ts queryCellSize, which start() sends after the terminal starts.

func (*TuiMainScreen) QueryTerminalColors

func (t *TuiMainScreen) QueryTerminalColors(options TerminalColorQueryOptions) <-chan TerminalColorsResult

QueryTerminalColors queries the terminal's theme colors: the default foreground (OSC 10), the default background (OSC 11), and ANSI colors 0-15 (OSC 4), followed by a DA1 request that marks the end of the replies. The completion arrives when the DA1 reply or all color replies arrive, or when the timeout expires. Colors the terminal did not report are nil; the palette is set only when all 16 arrived. A query that completes after the timeout reports its replies to OnLateReply. Stop does not cancel the deadline, matching the terminal query's independent Promise lifetime. Mirrors tui.ts queryTerminalColors.

func (*TuiMainScreen) RemoveInputListener

func (t *TuiMainScreen) RemoveInputListener(listener *TuiInputListener)

RemoveInputListener removes a registered listener. Removing one that is not registered does nothing.

func (*TuiMainScreen) Render

func (t *TuiMainScreen) Render()

Render performs a differential render pass using inline-flow output.

Mirrors upstream pi-tui's `render()`. New content is appended with `\r\n`, which scrolls the viewport up and pushes older lines into the terminal's native scrollback. The terminal's normal scrolling makes our chat history reachable via the user's mouse wheel / Cmd-↑ after pig exits, just like a regular shell.

Algorithm sketch:

  1. Detect width/height change → fullRender(clear).
  2. First render → fullRender(no clear). Lines emitted with `\r\n` between them flow naturally.
  3. Diff prevLines vs newLines to find [firstChanged, lastChanged].
  4. If visible tail content shrinks and exposes rows above the old viewport, repaint only the new visible viewport.
  5. If only deletions remain, clear those rows in place.
  6. If firstChanged is above the current viewport → fullRender(clear).
  7. Otherwise: move cursor to firstChanged (scrolling if it's below the viewport bottom), rewrite affected lines, clear any extras.

func (*TuiMainScreen) RenderNow

func (t *TuiMainScreen) RenderNow(force ...bool)

RenderNow renders immediately, cancelling any pending render; force=true makes the frame a full repaint. Mirrors upstream renderNow(force) (tui.ts:982).

func (*TuiMainScreen) RenderSnapshot

func (t *TuiMainScreen) RenderSnapshot(width int) []string

RenderSnapshot returns the current frame's fully rendered lines at the given width without writing to the terminal. Used by the /debug command to dump the frame. Mirrors upstream TUI.render(width) (tui.ts).

func (*TuiMainScreen) RepaintAll

func (t *TuiMainScreen) RepaintAll()

RepaintAll forces an immediate screen-clearing repaint after an external program has changed the terminal. Ordinary editor updates use differential rendering instead.

func (*TuiMainScreen) RequestImmediateRender

func (t *TuiMainScreen) RequestImmediateRender()

RequestImmediateRender preempts a throttled frame and coalesces keyboard updates onto the next owner-loop turn. It exposes TuiBase.requestImmediateRender to the Go driver's separately owned input path.

func (*TuiMainScreen) RequestRender

func (t *TuiMainScreen) RequestRender(force ...bool)

RequestRender asks the TUI to render soon, coalescing repeated calls and enforcing the upstream 16ms frame throttle. Use this for hot streaming paths (thinking/text deltas); direct Render() is reserved for low-frequency state changes and final flushes.

force is upstream's requestRender(force = false): true resets the render state so the next frame is a full repaint and renders on the next owner-loop turn instead of waiting for the frame throttle.

func (*TuiMainScreen) RestoreRenderState

func (t *TuiMainScreen) RestoreRenderState(state TuiMainScreenRenderState)

RestoreRenderState restores a previously captured render state so the next differential render is computed against the pre-switch screen. Image lines are blanked and the Kitty image-id set is cleared, since those images are no longer on the terminal after the switch. Mirrors upstream TuiMainScreen.restoreRenderState.

func (*TuiMainScreen) RunDueRender

func (t *TuiMainScreen) RunDueRender()

RunDueRender runs the frame whose SetRenderDeadline deadline has passed, on the calling owner loop. A frame not yet due stays pending.

func (*TuiMainScreen) RunInputListeners

func (t *TuiMainScreen) RunInputListeners(data string) (string, bool)

RunInputListeners passes data through the registered listeners in registration order. It returns the data after any replacements and whether a listener consumed it or left it empty, in which case nothing else should receive it. pig divergence (D105): the driver owns the terminal reader; extension input listeners run asynchronously around the renderer's listener chain.

func (*TuiMainScreen) SetClearOnShrink

func (t *TuiMainScreen) SetClearOnShrink(enabled bool)

SetClearOnShrink configures whether shrinking content triggers a full redraw when no overlays are active. Mirrors upstream TUI.setClearOnShrink().

func (*TuiMainScreen) SetFixedSize

func (t *TuiMainScreen) SetFixedSize(cols, rows int)

SetFixedSize changes the size of a renderer built with a fixed size (NewWithOutput), as a terminal resize would; the next render sees it. Renderers that read the real terminal size ignore it.

func (*TuiMainScreen) SetFocus

func (t *TuiMainScreen) SetFocus(component Component)

SetFocus records a non-overlay target for focus restoration.

func (*TuiMainScreen) SetLogDirectory

func (t *TuiMainScreen) SetLogDirectory(dir string)

SetLogDirectory sets the redraw and overflow log directory. Empty disables redraw logging and selects the OS temp directory for crash dumps, matching TuiBase's logDirectory constructor argument.

func (*TuiMainScreen) SetOnDebug

func (t *TuiMainScreen) SetOnDebug(onDebug func())

SetOnDebug sets the global debug-key callback (tui.ts TuiBase.onDebug); nil clears it.

func (*TuiMainScreen) SetOnHeightChange

func (t *TuiMainScreen) SetOnHeightChange(fn func(height int))

SetOnHeightChange registers a terminal-height callback. Fullscreen coalesces pending changes while a callback runs. Thread-safe.

func (*TuiMainScreen) SetOnWidthChange

func (t *TuiMainScreen) SetOnWidthChange(fn func(width int))

SetOnWidthChange registers a terminal-width callback. Fullscreen coalesces pending changes while a callback runs. Thread-safe.

func (*TuiMainScreen) SetOverlayCommandDispatcher

func (t *TuiMainScreen) SetOverlayCommandDispatcher(dispatch func(func()))

SetOverlayCommandDispatcher installs the ordered ingress used by remote producers. The dispatcher owns command ordering on the application loop.

func (*TuiMainScreen) SetOwnerDispatcher

func (t *TuiMainScreen) SetOwnerDispatcher(dispatch func(ctx context.Context, fn func()) error)

SetOwnerDispatcher installs the seam PostToOwner uses to queue work on the loop that owns component-tree mutation. The dispatcher blocks until the loop accepts fn or ctx ends, and returns an error only in the second case. Thread-safe.

func (*TuiMainScreen) SetRenderDeadline

func (t *TuiMainScreen) SetRenderDeadline(wake func(due time.Time))

SetRenderDeadline makes the loop that owns component-tree mutation keep the throttled-frame deadline, as Pi's requestRender arms one setTimeout on its event loop: a frame request records when its frame is due and calls wake with that time, or with the zero time once no frame is pending, instead of arming a timer whose callback runs on a goroutine of its own. The owner calls RunDueRender when the time passes. wake runs under the renderer's lock, so it must not call back into the renderer or block. It replaces a SetRenderDispatcher hook; nil restores the timer goroutine. Thread-safe.

func (*TuiMainScreen) SetRenderDispatcher

func (t *TuiMainScreen) SetRenderDispatcher(dispatch func(render func()))

SetRenderDispatcher installs a hook that runs throttled scheduled renders on the caller's main loop. The dispatcher receives a render closure and is responsible for eventually invoking it on the goroutine that owns component-tree mutation (it may enqueue it on an event loop). When nil (default), scheduled renders run inline on the throttle-timer goroutine, which is correct for standalone / single-goroutine use. It replaces a SetRenderDeadline owner. Thread-safe.

func (*TuiMainScreen) SetShowHardwareCursor

func (t *TuiMainScreen) SetShowHardwareCursor(enabled bool)

SetShowHardwareCursor controls whether the real terminal cursor is shown while still positioning it for IME/caret parity, and requests a frame, so changes made together share one. Mirrors upstream TUI.setShowHardwareCursor().

func (*TuiMainScreen) SetTerminalColorSchemeNotifications

func (t *TuiMainScreen) SetTerminalColorSchemeNotifications(enabled bool)

SetTerminalColorSchemeNotifications turns the terminal's light/dark reports (mode 2031) on or off. While the renderer is stopped only the preference changes; Start applies it.

func (*TuiMainScreen) SetTickDispatcher

func (t *TuiMainScreen) SetTickDispatcher(dispatch func(func()))

SetTickDispatcher installs the blocking owner-loop seam for owned state-machine ticks (alt-screen selection auto-scroll). It must marshal fn onto the loop that owns rendering, backpressuring rather than dropping while that loop is alive; see the tickOnMain doc. When unset the tick runs inline. Thread-safe.

func (*TuiMainScreen) ShowCursor

func (t *TuiMainScreen) ShowCursor()

ShowCursor shows the terminal cursor.

func (*TuiMainScreen) ShowOverlay

func (t *TuiMainScreen) ShowOverlay(c Component, opts OverlayOptions) *OverlayHandle

ShowOverlay pushes a component onto the overlay append stack and returns a targeted handle. Callers must Close when the overlay is dismissed.

func (*TuiMainScreen) Start

func (t *TuiMainScreen) Start()

Start resumes the main-screen renderer after a terminal handoff. The driver restores input and requests the full repaint, as Pi's TUI.start does.

func (*TuiMainScreen) Stop

func (t *TuiMainScreen) Stop()

func (*TuiMainScreen) StopWithOptions

func (t *TuiMainScreen) StopWithOptions(options StopOptions)

func (*TuiMainScreen) Terminal

func (t *TuiMainScreen) Terminal() Terminal

Terminal returns the terminal this renderer draws on (tui.ts TuiBase.terminal, a public property). A renderer built for the process terminal returns that terminal; one built with a fixed output and size returns a terminal that writes to the output and reports the size. The same value comes back every time.

Terminal and the returned terminal's size never take t.mu: components such as the Editor (editor.ts render reads tui.terminal.rows) call them from Render while the renderer holds t.mu for the frame.

func (*TuiMainScreen) Width

func (t *TuiMainScreen) Width() int

Width returns the terminal width of the last size the renderer took. It never takes t.mu and is safe from any goroutine: the extension host reads it off the owner loop while a frame updates it.

func (*TuiMainScreen) WriteRaw

func (t *TuiMainScreen) WriteRaw(data string)

WriteRaw writes data to the terminal as is, as upstream's terminal.write does for a component that drives the terminal itself.

type TuiMainScreenRenderState

type TuiMainScreenRenderState struct {
	PreviousLines       []string
	PreviousWidth       int
	PreviousHeight      int
	CursorRow           int
	HardwareCursorRow   int
	MaxLinesRendered    int
	PreviousViewportTop int
}

Stop cleanly shuts down the TUI. Moves the cursor to the end of rendered content, writes a newline, and shows the cursor. This preserves the screen content so the user sees the final state after exit. Mirrors upstream tui.ts stop() (lines 473-494). TuiMainScreenRenderState is a snapshot of the main-screen renderer's inline-flow render state. It lets InteractiveMode preserve regular-mode scrollback position across a live tui-mode switch (a fullscreen round-trip discards and rebuilds the renderer). Mirrors upstream TuiMainScreenRenderState (tui-main-screen.ts:113).

type TuiMode

type TuiMode string

TuiMode is the renderer mode. Mirrors upstream TuiMode (tui.ts:448).

const (
	TuiModeRegular    TuiMode = "regular"
	TuiModeFullscreen TuiMode = "fullscreen"
)

type TuiMouseButton

type TuiMouseButton string

TuiMouseButton mirrors upstream TuiMouseButton.

const (
	MouseButtonLeft   TuiMouseButton = "left"
	MouseButtonMiddle TuiMouseButton = "middle"
	MouseButtonRight  TuiMouseButton = "right"
	MouseButtonNone   TuiMouseButton = "none"
)

type TuiMouseDispatchResult

type TuiMouseDispatchResult struct {
	TuiMouseEventResult
	Target TuiMouseDispatchTarget
	// FocusTarget is the keyboard focus target, which may be a delegating
	// parent container. nil means Target.Component.
	FocusTarget Component
}

TuiMouseDispatchResult is a handled result bound to its target. Mirrors upstream TuiMouseDispatchResult. A handler returning a result whose Target.Component is nil has not been dispatched yet.

func DispatchMouseEvent

func DispatchMouseEvent(component Component, event TuiMouseEvent) *TuiMouseDispatchResult

DispatchMouseEvent dispatches an event to a component and retains the exact target and coordinate transform. Containers use it to forward events to nested children. Mirrors upstream dispatchMouseEvent.

type TuiMouseDispatchTarget

type TuiMouseDispatchTarget struct {
	Component Component
	OriginX   int
	OriginY   int
	Width     int
	Height    int
}

TuiMouseDispatchTarget records the exact component a mouse event reached and the coordinate transform used to reach it. Mirrors upstream TuiMouseDispatchTarget.

type TuiMouseEvent

type TuiMouseEvent struct {
	Type    TuiMouseEventType
	Button  TuiMouseButton
	X       int
	Y       int
	ScreenX int
	ScreenY int
	Width   int
	Height  int
	Shift   bool
	Alt     bool
	Ctrl    bool
	// WheelDelta is the logical line delta of a wheel event (negative scrolls
	// up); zero on every other event.
	WheelDelta int
	// ClickCount is the consecutive click count of a click event; zero on every
	// other event.
	ClickCount int
}

TuiMouseEvent is a normalized cell-based mouse event. Coordinates are zero-based. X/Y are local to the receiving component, ScreenX/ScreenY are absolute terminal coordinates, and Width/Height are the receiving component's current bounds. Mirrors upstream TuiMouseEvent.

func RetargetMouseEvent

func RetargetMouseEvent(event TuiMouseEvent, target TuiMouseDispatchTarget) TuiMouseEvent

RetargetMouseEvent recreates local coordinates for a previously dispatched mouse target. Mirrors upstream retargetMouseEvent.

type TuiMouseEventResult

type TuiMouseEventResult struct {
	// Handled stops propagation and suppresses renderer-level fallback behavior.
	Handled bool
	// Capture routes subsequent drag/release events to this component. Implies
	// Handled.
	Capture bool
	// Focus gives keyboard focus to this component. Implies Handled.
	Focus bool
	// Render explicitly requests (true) or suppresses (false) a render. nil
	// takes the default: move and release do not render; press, click, drag,
	// and wheel do.
	Render *bool
}

TuiMouseEventResult mirrors upstream TuiMouseEventResult.

type TuiMouseEventType

type TuiMouseEventType string

TuiMouseEventType mirrors upstream TuiMouseEventType.

const (
	MousePress   TuiMouseEventType = "press"
	MouseRelease TuiMouseEventType = "release"
	MouseMove    TuiMouseEventType = "move"
	MouseDrag    TuiMouseEventType = "drag"
	MouseClick   TuiMouseEventType = "click"
	MouseWheel   TuiMouseEventType = "wheel"
)

type TuiSurface

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

TuiSurface draws the interactive layout through a frontend.Session. The document's leaf components become the session's main nodes. Tool cards are reported as frontend.ToolCard and messages as frontend.MarkdownText; an assistant message is a run of nodes, one per part, whose ids extend the message's id. The dock renders as one dock node, or around the input editor as frontend.Editor, or around a NativeComponent in its place, with the working indicator and the footer as their own nodes, while no overlay that takes the keys shows. Overlays are reported as frontend.Overlay nodes. A frame costs what changed, not the transcript's length: a component that invalidates itself reports each change to the surface, which rebuilds only the components it was told about and those it must poll.

func NewTuiSurface

func NewTuiSurface(session frontend.Session, onApplyError func(error)) *TuiSurface

NewTuiSurface creates a surface renderer for session at the process terminal's size. onApplyError, if set, receives every failed frame.

func NewTuiSurfaceWithSize

func NewTuiSurfaceWithSize(session frontend.Session, cols, rows int, onApplyError func(error)) *TuiSurface

NewTuiSurfaceWithSize creates a fixed-size surface renderer for tests.

func (*TuiSurface) ActiveOverlay

func (t *TuiSurface) ActiveOverlay() Component

ActiveOverlay refreshes overlay visibility and restores eligible focus before input dispatch. An active replacement keeps input until it changes focus, even if it is not mounted in the render tree.

func (*TuiSurface) AddInputListener

func (t *TuiSurface) AddInputListener(listener *TuiInputListener) func()

AddInputListener registers listener after the existing ones and returns the function that removes it.

func (*TuiSurface) CancelPendingRender

func (t *TuiSurface) CancelPendingRender()

CancelPendingRender invalidates a throttled frame, including one whose timer callback has already handed it to the owner loop. It maps the single-threaded JavaScript event-loop rule that a later state transition can consume a queued request before its callback runs.

func (*TuiSurface) Click

func (t *TuiSurface) Click(click frontend.Click)

Click hands a session's click to the component that drew the node: an extension's overlay or dock component as the terminal's click at that cell (D91), a main node's component inside its Click area, with the screen cell it shows at when the session covers its view, or a fullscreen overlay's component. While the component handles it, ScreenLines draws the screen with the component in view. Call it on the owner loop.

func (*TuiSurface) ConsumeCellSizeResponse

func (t *TuiSurface) ConsumeCellSizeResponse(data string) bool

ConsumeCellSizeResponse reports whether data is a complete cell-size response. A response with positive dimensions updates the cell dimensions, invalidates every mounted component so images re-render at the new size, and requests a render; a response with a zero dimension is still consumed. Any other input returns false so it reaches the focused component. Mirrors upstream tui.ts consumeCellSizeResponse.

func (*TuiSurface) ConsumeDebugKey

func (t *TuiSurface) ConsumeDebugKey(data string) bool

ConsumeDebugKey runs the debug callback and consumes data when it is the global debug key (Shift+Ctrl+D) and a callback is set (tui.ts TuiBase.handleInput).

func (*TuiSurface) ConsumeTerminalColorResponse

func (t *TuiSurface) ConsumeTerminalColorResponse(data string) bool

ConsumeTerminalColorResponse consumes a color or DA1 reply that belongs to the oldest pending color query and reports whether it did. Terminals answer in order, so color replies belong to the oldest query. Call it before terminal-input listeners or focused-component dispatch, including after a query timeout, when a query still waits for its DA1 reply.

func (*TuiSurface) ConsumeTerminalColorSchemeReport

func (t *TuiSurface) ConsumeTerminalColorSchemeReport(data string) bool

ConsumeTerminalColorSchemeReport notifies the listeners of a light/dark report and reports whether data was one.

func (*TuiSurface) DispatchFocusedInput

func (t *TuiSurface) DispatchFocusedInput(data string)

DispatchFocusedInput is the end of tui.ts:1044 handleTerminalInput, for a driver that has run the earlier stages itself: the global debug key (Shift+Ctrl+D) runs onDebug whatever has focus, then the overlay visibility and focus restoration are refreshed ([tuiBase.ActiveOverlay]), and the focused component's HandleInput receives the input, except a key release it does not ask for. Input is latency-sensitive, so a delivery requests an immediate render.

func (*TuiSurface) ForceFullRender

func (t *TuiSurface) ForceFullRender()

ForceFullRender replaces every node on the next frame.

func (*TuiSurface) FullRedraws

func (t *TuiSurface) FullRedraws() int

FullRedraws counts the frames that replaced every node, the surface's full redraws (tui.ts fullRedraws).

func (*TuiSurface) GetClearOnShrink

func (t *TuiSurface) GetClearOnShrink() bool

GetClearOnShrink reports whether shrinking content triggers a full redraw to clear empty rows. Mirrors upstream TUI.getClearOnShrink().

func (*TuiSurface) GetFocusedComponent

func (t *TuiSurface) GetFocusedComponent() Component

FocusedComponent returns the current overlay or non-overlay focus target.

func (*TuiSurface) GetShowHardwareCursor

func (t *TuiSurface) GetShowHardwareCursor() bool

GetShowHardwareCursor reports whether the real terminal cursor is shown. Mirrors upstream TUI.getShowHardwareCursor().

func (*TuiSurface) HandleFrontendInput

func (t *TuiSurface) HandleFrontendInput(data string) bool

HandleFrontendInput offers terminal input to the session. A sequence that changes the session's region widths repaints.

func (*TuiSurface) HandleTerminalInput

func (t *TuiSurface) HandleTerminalInput(data string)

HandleTerminalInput is the renderer's dispatcher for one chunk of terminal input, in the order of tui.ts:1044 handleTerminalInput: color replies and light/dark reports, the input listeners, the cell-size reply, then [tuiBase.DispatchFocusedInput].

func (*TuiSurface) HasOverlay

func (t *TuiSurface) HasOverlay() bool

HasOverlay reports whether any overlay entry is mounted. The interactive driver uses this for the upstream hasOverlayEntries renderer-switch guard.

func (*TuiSurface) Height

func (t *TuiSurface) Height() int

Height returns the terminal height of the last size the renderer took. It never takes t.mu and is safe from any goroutine.

func (*TuiSurface) HideCursor

func (t *TuiSurface) HideCursor()

HideCursor hides the terminal cursor.

func (*TuiSurface) HideOverlay

func (t *TuiSurface) HideOverlay()

HideOverlay permanently removes the most recently appended mounted entry. Focus and visual order do not affect this target. Mirrors upstream hideOverlay.

func (*TuiSurface) Mode

func (t *TuiSurface) Mode() TuiMode

Mode reports the regular mode: the surface stands in for Pi's main-screen renderer (tui.ts TuiMode).

func (*TuiSurface) NativeKeys

func (t *TuiSurface) NativeKeys(a *NativeAction) []string

NativeKeys returns the keys that take a its next step against the node it names as that node is now, or nil once the action is complete or the node is no longer shown. Each key is one input sequence.

func (*TuiSurface) OnDebug

func (t *TuiSurface) OnDebug() func()

OnDebug returns the global debug-key callback, nil when none is set (tui.ts TuiBase.onDebug).

func (*TuiSurface) OnTerminalColorSchemeChange

func (t *TuiSurface) OnTerminalColorSchemeChange(listener func(scheme TerminalColorScheme)) func()

OnTerminalColorSchemeChange registers a light/dark report listener and returns the function that removes it.

func (*TuiSurface) PostToOwner

func (t *TuiSurface) PostToOwner(ctx context.Context, fn func()) error

PostToOwner queues fn on the owner loop (see SetOwnerDispatcher). It never drops fn: it returns once the loop has accepted it, or ctx's error when ctx ends first. Without a dispatcher fn runs inline, as the other dispatch seams do. Thread-safe.

func (*TuiSurface) QueryCellSize

func (t *TuiSurface) QueryCellSize()

Ports packages/tui/src/tui.ts (queryCellSize, cell-size response handling). QueryCellSize writes the cell-size query when the terminal supports images, since only image rendering uses the cell size. Mirrors upstream tui.ts queryCellSize, which start() sends after the terminal starts.

func (*TuiSurface) QueryTerminalColors

func (t *TuiSurface) QueryTerminalColors(options TerminalColorQueryOptions) <-chan TerminalColorsResult

QueryTerminalColors queries the terminal the session draws on for its colors, as the ANSI renderer queries its own; the replies are consumed by ConsumeTerminalColorResponse.

func (*TuiSurface) RemoveInputListener

func (t *TuiSurface) RemoveInputListener(listener *TuiInputListener)

RemoveInputListener removes a registered listener. Removing one that is not registered does nothing.

func (*TuiSurface) Render

func (t *TuiSurface) Render()

Render performs a differential render pass using inline-flow output.

Mirrors upstream pi-tui's `render()`. New content is appended with `\r\n`, which scrolls the viewport up and pushes older lines into the terminal's native scrollback. The terminal's normal scrolling makes our chat history reachable via the user's mouse wheel / Cmd-↑ after pig exits, just like a regular shell.

Algorithm sketch:

  1. Detect width/height change → fullRender(clear).
  2. First render → fullRender(no clear). Lines emitted with `\r\n` between them flow naturally.
  3. Diff prevLines vs newLines to find [firstChanged, lastChanged].
  4. If visible tail content shrinks and exposes rows above the old viewport, repaint only the new visible viewport.
  5. If only deletions remain, clear those rows in place.
  6. If firstChanged is above the current viewport → fullRender(clear).
  7. Otherwise: move cursor to firstChanged (scrolling if it's below the viewport bottom), rewrite affected lines, clear any extras.

func (*TuiSurface) RenderNow

func (t *TuiSurface) RenderNow(force ...bool)

RenderNow renders immediately, cancelling any pending render; force=true makes the frame a full repaint. Mirrors upstream renderNow(force) (tui.ts:982).

func (*TuiSurface) RenderSnapshot

func (t *TuiSurface) RenderSnapshot(width int) []string

RenderSnapshot returns the document and dock lines at width.

func (*TuiSurface) RepaintAll

func (t *TuiSurface) RepaintAll()

RepaintAll replaces every node now.

func (*TuiSurface) RequestImmediateRender

func (t *TuiSurface) RequestImmediateRender()

RequestImmediateRender preempts a throttled frame and coalesces keyboard updates onto the next owner-loop turn. It exposes TuiBase.requestImmediateRender to the Go driver's separately owned input path.

func (*TuiSurface) RequestRender

func (t *TuiSurface) RequestRender(force ...bool)

RequestRender asks the TUI to render soon, coalescing repeated calls and enforcing the upstream 16ms frame throttle. Use this for hot streaming paths (thinking/text deltas); direct Render() is reserved for low-frequency state changes and final flushes.

force is upstream's requestRender(force = false): true resets the render state so the next frame is a full repaint and renders on the next owner-loop turn instead of waiting for the frame throttle.

func (*TuiSurface) Resume

func (t *TuiSurface) Resume()

Resume tells the session that PiG owns the terminal again and draws what changed since Suspend, which is no frame when nothing changed. It does nothing unless suspended; after a Stop it only resumes the session.

func (*TuiSurface) RunDueRender

func (t *TuiSurface) RunDueRender()

RunDueRender runs the frame whose SetRenderDeadline deadline has passed, on the calling owner loop. A frame not yet due stays pending.

func (*TuiSurface) RunInputListeners

func (t *TuiSurface) RunInputListeners(data string) (string, bool)

RunInputListeners passes data through the registered listeners in registration order. It returns the data after any replacements and whether a listener consumed it or left it empty, in which case nothing else should receive it. pig divergence (D105): the driver owns the terminal reader; extension input listeners run asynchronously around the renderer's listener chain.

func (*TuiSurface) Screen

func (t *TuiSurface) Screen() (frontend.Screen, bool)

Screen reports the screen a fullscreen overlay covers, its size counted from the terminal's where the session gives zero or less, and false when the session is not a frontend.ScreenSession or cannot show one now. Call it on the owner loop.

func (*TuiSurface) ScreenLines

func (t *TuiSurface) ScreenLines() []string

ScreenLines draws the screen a fullscreen overlay covers as the session shows it: the dock's lines at the bottom, unless the session shows the dock itself, and above them the document's end, or, while a click is dispatched, the document from the clicked component when the end would leave it out of view. It reports nil when the session shows no screen. Call it on the owner loop.

func (*TuiSurface) Session

func (t *TuiSurface) Session() frontend.Session

Session returns the frontend session the renderer draws through.

func (*TuiSurface) SetClearOnShrink

func (t *TuiSurface) SetClearOnShrink(bool)

SetClearOnShrink has no effect: the session lays out its own document.

func (*TuiSurface) SetFixedSize

func (t *TuiSurface) SetFixedSize(cols, rows int)

SetFixedSize changes the size of a renderer built with a fixed size (NewWithOutput), as a terminal resize would; the next render sees it. Renderers that read the real terminal size ignore it.

func (*TuiSurface) SetFocus

func (t *TuiSurface) SetFocus(component Component)

SetFocus records a non-overlay target for focus restoration.

func (*TuiSurface) SetHooks

func (t *TuiSurface) SetHooks(hooks SurfaceHooks)

SetHooks installs the hooks the next frame reads. The next frame rebuilds every node from them.

func (*TuiSurface) SetLayout

func (t *TuiSurface) SetLayout(document, dock Component)

SetLayout sets the transcript document and the input dock.

func (*TuiSurface) SetOnDebug

func (t *TuiSurface) SetOnDebug(onDebug func())

SetOnDebug sets the global debug-key callback (tui.ts TuiBase.onDebug); nil clears it.

func (*TuiSurface) SetOnHeightChange

func (t *TuiSurface) SetOnHeightChange(fn func(height int))

SetOnHeightChange registers a terminal-height callback. Fullscreen coalesces pending changes while a callback runs. Thread-safe.

func (*TuiSurface) SetOnWidthChange

func (t *TuiSurface) SetOnWidthChange(fn func(width int))

SetOnWidthChange registers a terminal-width callback. Fullscreen coalesces pending changes while a callback runs. Thread-safe.

func (*TuiSurface) SetOverlayCommandDispatcher

func (t *TuiSurface) SetOverlayCommandDispatcher(dispatch func(func()))

SetOverlayCommandDispatcher installs the ordered ingress used by remote producers. The dispatcher owns command ordering on the application loop.

func (*TuiSurface) SetOwnerDispatcher

func (t *TuiSurface) SetOwnerDispatcher(dispatch func(ctx context.Context, fn func()) error)

SetOwnerDispatcher installs the seam PostToOwner uses to queue work on the loop that owns component-tree mutation. The dispatcher blocks until the loop accepts fn or ctx ends, and returns an error only in the second case. Thread-safe.

func (*TuiSurface) SetRenderDeadline

func (t *TuiSurface) SetRenderDeadline(wake func(due time.Time))

SetRenderDeadline makes the loop that owns component-tree mutation keep the throttled-frame deadline, as Pi's requestRender arms one setTimeout on its event loop: a frame request records when its frame is due and calls wake with that time, or with the zero time once no frame is pending, instead of arming a timer whose callback runs on a goroutine of its own. The owner calls RunDueRender when the time passes. wake runs under the renderer's lock, so it must not call back into the renderer or block. It replaces a SetRenderDispatcher hook; nil restores the timer goroutine. Thread-safe.

func (*TuiSurface) SetRenderDispatcher

func (t *TuiSurface) SetRenderDispatcher(dispatch func(render func()))

SetRenderDispatcher installs a hook that runs throttled scheduled renders on the caller's main loop. The dispatcher receives a render closure and is responsible for eventually invoking it on the goroutine that owns component-tree mutation (it may enqueue it on an event loop). When nil (default), scheduled renders run inline on the throttle-timer goroutine, which is correct for standalone / single-goroutine use. It replaces a SetRenderDeadline owner. Thread-safe.

func (*TuiSurface) SetShowHardwareCursor

func (t *TuiSurface) SetShowHardwareCursor(enabled bool)

SetShowHardwareCursor records the setting; the session draws no hardware cursor.

func (*TuiSurface) SetTerminalColorSchemeNotifications

func (t *TuiSurface) SetTerminalColorSchemeNotifications(enabled bool)

SetTerminalColorSchemeNotifications turns the light/dark reports (mode 2031) of the terminal the session draws on on or off. While the surface is stopped only the preference changes; Start and Resume apply it, as the main-screen renderer's Start does.

func (*TuiSurface) SetTerminalOut

func (t *TuiSurface) SetTerminalOut(out io.Writer)

SetTerminalOut sets the terminal the session draws on, which the surface writes the terminal color query to. Until it is set, the query goes nowhere and times out.

func (*TuiSurface) SetTickDispatcher

func (t *TuiSurface) SetTickDispatcher(dispatch func(func()))

SetTickDispatcher installs the blocking owner-loop seam for owned state-machine ticks (alt-screen selection auto-scroll). It must marshal fn onto the loop that owns rendering, backpressuring rather than dropping while that loop is alive; see the tickOnMain doc. When unset the tick runs inline. Thread-safe.

func (*TuiSurface) ShowCursor

func (t *TuiSurface) ShowCursor()

ShowCursor shows the terminal cursor.

func (*TuiSurface) ShowOverlay

func (t *TuiSurface) ShowOverlay(c Component, opts OverlayOptions) *OverlayHandle

ShowOverlay pushes a component onto the overlay append stack and returns a targeted handle. Callers must Close when the overlay is dismissed.

func (*TuiSurface) Start

func (t *TuiSurface) Start()

Start begins rendering and draws the whole tree. A session still suspended is resumed first.

func (*TuiSurface) Stop

func (t *TuiSurface) Stop()

Stop stops rendering.

func (*TuiSurface) StopWithOptions

func (t *TuiSurface) StopWithOptions(StopOptions)

StopWithOptions stops rendering. The session owns the terminal surface, so PreserveScreen changes nothing. The components stop reporting their invalidations, and a later start rebuilds every node.

func (*TuiSurface) Suspend

func (t *TuiSurface) Suspend()

Suspend stops rendering while another program owns the terminal and tells the session so. Unlike Stop, the components keep reporting their invalidations, so the frame after Resume carries only what changed. It does nothing before Start, after Stop, or while suspended.

func (*TuiSurface) Terminal

func (t *TuiSurface) Terminal() Terminal

Terminal returns the terminal the session draws on (tui.ts TuiBase.terminal): the renderer's terminal, whose SetProgramStatus reports to the session. It takes no lock, as a component such as the editor asks for it while it renders.

func (*TuiSurface) TerminalOut

func (t *TuiSurface) TerminalOut() io.Writer

TerminalOut returns the terminal SetTerminalOut set, for PiG's other writes while the session draws.

func (*TuiSurface) Width

func (t *TuiSurface) Width() int

Width returns the terminal width of the last size the renderer took. It never takes t.mu and is safe from any goroutine: the extension host reads it off the owner loop while a frame updates it.

func (*TuiSurface) WriteRaw

func (t *TuiSurface) WriteRaw(data string)

WriteRaw writes data to the terminal as is, as upstream's terminal.write does for a component that drives the terminal itself.

type UndoStack

type UndoStack[S any] struct {
	// contains filtered or unexported fields
}

UndoStack stores detached state snapshots for undo/redo style flows.

func (*UndoStack[S]) Clear

func (u *UndoStack[S]) Clear()

Clear removes all snapshots.

func (*UndoStack[S]) Len

func (u *UndoStack[S]) Len() int

Len reports the number of snapshots.

func (*UndoStack[S]) Pop

func (u *UndoStack[S]) Pop() (S, bool)

Pop returns the most recent snapshot.

func (*UndoStack[S]) Push

func (u *UndoStack[S]) Push(state S)

Push stores a snapshot.

type UserMessageComponent

type UserMessageComponent struct {
	Container
	// contains filtered or unexported fields
}

UserMessageComponent renders user Markdown in a padded background with OSC 133 zone markers. Closing markers prefix the existing bottom padding row and do not add height.

func NewUserMessageComponent

func NewUserMessageComponent(text string, markdownTheme *MarkdownTheme, outputPad int, markdownTransformers []markdowntransform.MarkdownTransformer) *UserMessageComponent

NewUserMessageComponent preserves source list markers and backslash escapes in user text. It is Pi's constructor(text, markdownTheme = getMarkdownTheme(), outputPad = 1, markdownTransformers = []) (user-message.ts:18-31): a nil markdownTheme is the active theme's, outputPad is the horizontal padding (Pi keeps any value; a negative one cannot be repeated, so it is 0), and markdownTransformers run in order on each render as the display-only transform createMarkdownTransform("user", false, markdownTransformers).

func (*UserMessageComponent) Dispose

func (u *UserMessageComponent) Dispose()

Dispose releases this message's pending Markdown generation.

func (*UserMessageComponent) Invalidate

func (u *UserMessageComponent) Invalidate()

Invalidate also invalidates the child Markdown transform state so display transformers run again.

func (*UserMessageComponent) IsDirty

func (i *UserMessageComponent) IsDirty() bool

func (*UserMessageComponent) NeedsRedraw

func (i *UserMessageComponent) NeedsRedraw() bool

func (*UserMessageComponent) Render

func (u *UserMessageComponent) Render(width int) []string

func (*UserMessageComponent) SetAsyncMarkdownTransform

func (u *UserMessageComponent) SetAsyncMarkdownTransform(transform *AsyncMarkdownTransform)

SetAsyncMarkdownTransform installs an off-loop rewrite that completes before the message content is painted.

func (*UserMessageComponent) SetImages

func (u *UserMessageComponent) SetImages(images []ImageBlock)

SetImages records the image blocks the message carries. The terminal renderer draws none, as Pi's UserMessageComponent; a frontend session receives them on the message's MarkdownText (pig additive, D91).

func (*UserMessageComponent) SetMarkdownTransform

func (u *UserMessageComponent) SetMarkdownTransform(transform func(string, int) string)

SetMarkdownTransform installs the display-only constructor transform at the message's available content width.

func (*UserMessageComponent) SetMarkdownTransformState

func (u *UserMessageComponent) SetMarkdownTransformState(fn func() string)

SetMarkdownTransformState declares the external state the installed transform reads, for the Markdown render cache key.

func (*UserMessageComponent) SetOutputPad

func (u *UserMessageComponent) SetOutputPad(padding int)

SetOutputPad changes horizontal content padding while retaining the Markdown child and its transform lifetime.

type UserMessageItem

type UserMessageItem struct {
	// ID is the entry ID in the session.
	ID string
	// Text is the message text.
	Text string
	// Timestamp is the message's optional timestamp.
	Timestamp string
}

UserMessageItem is one selectable user message (user-message-selector.ts UserMessageItem).

type UserMessageList

type UserMessageList struct {

	// OnSelect runs with the entry ID of the selected message on confirm.
	OnSelect func(entryID string)
	// OnCancel runs on the cancel key.
	OnCancel func()
	// contains filtered or unexported fields
}

UserMessageList is upstream's UserMessageList: the chronological user-message rows.

func (*UserMessageList) CapturesSelectPageInput

func (s *UserMessageList) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the list handles tui.select.pageUp and tui.select.pageDown.

func (*UserMessageList) HandleInput

func (s *UserMessageList) HandleInput(data string)

HandleInput checks up, down, confirm and cancel in user-message-selector.ts order, so a key bound to two of them keeps the earlier action.

func (*UserMessageList) Invalidate

func (i *UserMessageList) Invalidate()

func (*UserMessageList) IsDirty

func (i *UserMessageList) IsDirty() bool

func (*UserMessageList) NeedsRedraw

func (i *UserMessageList) NeedsRedraw() bool

func (*UserMessageList) Render

func (s *UserMessageList) Render(width int) []string

type UserMessageSelectorComponent

type UserMessageSelectorComponent struct {
	Container
	// contains filtered or unexported fields
}

UserMessageSelectorComponent renders the upstream /fork user-message picker in the editor slot. It mirrors user-message-selector.ts: it is a Container of a spacer, the title and descriptive copy, a border, the user-message list and a closing border, with the newest message selected by default.

func NewUserMessageSelectorComponent

func NewUserMessageSelectorComponent(messages []UserMessageItem, onSelect func(entryID string), onCancel func(), initialSelectedID string) *UserMessageSelectorComponent

NewUserMessageSelectorComponent creates a selector for chronological user messages (oldest to newest). The message with initialSelectedID is selected initially, else the newest; an empty initialSelectedID stands for an omitted argument. With no messages, onCancel runs once after 100ms on a timer goroutine (user-message-selector.ts:146-148), so it must be safe to call from there.

func (*UserMessageSelectorComponent) CapturesSelectPageInput

func (s *UserMessageSelectorComponent) CapturesSelectPageInput() bool

CapturesSelectPageInput reports that the list inside handles tui.select.pageUp and tui.select.pageDown.

func (*UserMessageSelectorComponent) GetMessageList

func (s *UserMessageSelectorComponent) GetMessageList() *UserMessageList

GetMessageList returns the message list (user-message-selector.ts getMessageList).

func (*UserMessageSelectorComponent) HandleInput

func (s *UserMessageSelectorComponent) HandleInput(data string)

HandleInput forwards to the message list, as the host drives upstream's getMessageList(). A parent Container reuses this component's lines until it is invalidated, so a list change must invalidate it.

func (*UserMessageSelectorComponent) Invalidate

func (i *UserMessageSelectorComponent) Invalidate()

func (*UserMessageSelectorComponent) IsDirty

func (i *UserMessageSelectorComponent) IsDirty() bool

func (*UserMessageSelectorComponent) NativeNode

func (s *UserMessageSelectorComponent) NativeNode() (frontend.Node, bool)

NativeNode reports the picker as a selector whose item ids are the messages' chronological indexes. pig additive (D91): each row's "Message i of n" line is its detail, and an empty list reports the empty message as the status.

func (*UserMessageSelectorComponent) NeedsRedraw

func (i *UserMessageSelectorComponent) NeedsRedraw() bool

type VStack

type VStack struct {
	*Stack
}

VStack ports pi-tui's VStack: children laid out top to bottom with flexbox heights.

func NewVStack

func NewVStack(children []StackChild, options StackOptions) *VStack

NewVStack constructs a vertical stack.

func (VStack) Invalidate

func (i VStack) Invalidate()

func (VStack) IsDirty

func (i VStack) IsDirty() bool

func (VStack) NeedsRedraw

func (i VStack) NeedsRedraw() bool

func (*VStack) Render

func (v *VStack) Render(width int) []string

Render ports upstream VStack.render.

type ViewSource

type ViewSource interface {
	FrontendView(width int) *frontend.View
}

ViewSource is a component whose lines an extension's view of Pi's tui components describes (D107): a ui.custom overlay, a widget, the header or footer, or a renderer's output. FrontendView returns the structure of Render(width), or nil when it has none.

type ViewportTUI

type ViewportTUI interface {
	TUI
	ViewportTop() int
	IsFollowingOutput() bool
	SetLayoutRoot(component Component)
}

ViewportTUI is implemented by renderers with an application-owned scrollable viewport (the alt-screen renderer). Mirrors upstream ViewportTUI; the driver uses it to set the fullscreen layout root. Upstream's VIEWPORT_TUI Symbol brand is expressed here as a distinct Go interface.

type VisualKeep

type VisualKeep string

VisualKeep selects which visual lines a preview keeps.

const (
	VisualKeepStart VisualKeep = "start"
	VisualKeepEnd   VisualKeep = "end"
)

The two ends of the text a preview can keep.

type VisualLinePreview

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

VisualLinePreview is collapsed tool output limited to a number of visual lines, like bash output. Limiting logical lines instead lets a single long line (such as minified JSON) wrap across the whole screen. It caches its lines per width, since it renders on every frame for every result in the transcript.

Ports packages/coding-agent/src/modes/interactive/components/visual-truncate.ts (VisualLinePreview).

func NewVisualLinePreview

func NewVisualLinePreview(options VisualLinePreviewOptions) *VisualLinePreview

NewVisualLinePreview returns a preview of options.Text.

func (*VisualLinePreview) Invalidate

func (p *VisualLinePreview) Invalidate()

Invalidate drops the cached lines.

func (*VisualLinePreview) Render

func (p *VisualLinePreview) Render(width int) []string

Render returns the preview's lines for width.

type VisualLinePreviewOptions

type VisualLinePreviewOptions struct {
	// Text is styled text; it may contain newlines.
	Text           string
	MaxVisualLines int
	// Keep selects the visual lines to keep. The hint goes before kept end lines and after kept start lines.
	Keep VisualKeep
	// FormatHint returns the styled hint line for the number of hidden visual lines.
	FormatHint func(hidden int) string
}

VisualLinePreviewOptions configure a VisualLinePreview.

type VisualTruncateResult

type VisualTruncateResult struct {
	VisualLines  []string
	SkippedCount int
}

VisualTruncateResult holds truncated lines and a skip count.

func TruncateToVisualLines

func TruncateToVisualLines(text string, maxVisualLines, width int, paddingX ...int) VisualTruncateResult

TruncateToVisualLines truncates text to maxVisualLines from the end, wrapping lines at the given width. The optional padding matches Text's horizontal padding.

func TruncateToVisualLinesKeeping

func TruncateToVisualLinesKeeping(text string, maxVisualLines, width, paddingX int, keep VisualKeep) VisualTruncateResult

TruncateToVisualLinesKeeping is TruncateToVisualLines with the choice of the lines to keep: the last ones or the first ones.

type WheelScrollAccelerator

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

WheelScrollAccelerator converts wheel events into line counts.

In Auto mode on terminals that do not accelerate wheel input, the count follows event velocity: an isolated notch moves one line, while a fast spin moves up to six lines per event. For example, notches 100 ms apart move 1 line each, 50 ms apart move 2, and 20 ms apart move 5. Settings changes may come from a different goroutine than wheel input, so its state is locked.

func NewWheelScrollAccelerator

func NewWheelScrollAccelerator(lines WheelScrollLines, accelerate ...bool) *WheelScrollAccelerator

NewWheelScrollAccelerator mirrors the constructor. Upstream defaults `accelerate` to `!terminalAcceleratesWheel()`; omit the argument for that default.

func (*WheelScrollAccelerator) Next

func (a *WheelScrollAccelerator) Next(direction int, now float64) int

Next returns the positive line count for a wheel event in direction (-1 or 1) at time now, in milliseconds.

func (*WheelScrollAccelerator) SetLines

func (a *WheelScrollAccelerator) SetLines(lines WheelScrollLines)

SetLines replaces the line setting and resets the gesture state.

type WheelScrollLines

type WheelScrollLines struct {
	Auto  bool
	Lines float64
}

WheelScrollLines is the lines moved per mouse-wheel event, or Auto to accelerate fast wheel spins (upstream `number | "auto"`). The zero value moves one line.

type WordNavigationOptions

type WordNavigationOptions struct {
	Segment         func(text string) iter.Seq[SegmentData]
	IsAtomicSegment func(segment string) bool
}

WordNavigationOptions replaces word segmentation or marks indivisible segments such as collapsed paste markers.

Source Files

Directories

Path Synopsis
internal
Package widthx implements Pi's terminal width, grapheme and ANSI operations with JavaScript UTF-16 semantics.
Package widthx implements Pi's terminal width, grapheme and ANSI operations with JavaScript UTF-16 semantics.

Jump to

Keyboard shortcuts

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