Documentation
¶
Overview ¶
Package tty provides an embeddable interactive tmux component for sending keystrokes, mouse events, and clipboard paste to a tmux pane while capturing and rendering its output.
Package tty provides an embeddable tmux terminal model for TUI plugins. It handles tmux session management, key mapping, cursor rendering, and adaptive polling.
Index ¶
- Constants
- Variables
- func CalculatePollingInterval(lastActivityTime time.Time) time.Duration
- func CapturePaneOutput(target string, scrollback int) (string, error)
- func ClaimGeometryLease(target string)
- func ContainsMouseSequence(s string) bool
- func CursorStyle() lipgloss.Style
- func DetectBracketedPasteMode(output string) bool
- func DetectMouseReportingMode(output string) bool
- func EditorAvailable() bool
- func ExtractUnknownCSIBytes(msg interface{}) []byte
- func HoldGeometryLease(target string)
- func IsPasteInput(msg tea.KeyPressMsg) bool
- func IsSessionDeadError(err error) bool
- func LooksLikeMouseFragment(s string) bool
- func MapKeyToTmux(msg tea.KeyPressMsg) (key string, useLiteral bool)
- func NewSession(args ...string) error
- func NormalizeEditorName(editor string) string
- func NormalizeToCSIu(raw []byte) string
- func NoteUserInput()
- func PaneSizeIndicator(paneWidth, paneHeight, shownWidth, shownHeight int) string
- func PasteClipboardToTmuxCmd(scope MessageScope, sessionName string, bracketed bool) tea.Cmd
- func PrepareServer() error
- func QueryCursorPositionSync(target string) (row, col, paneHeight, paneWidth int, visible, ok bool)
- func QueryPaneSize(target string) (width, height int, ok bool)
- func ReleaseGeometryHold(target string)
- func ReleaseGeometryLeases()
- func RenderCursorLine(line string, cursorCol int, visible bool) string
- func RenderWithCursor(content string, cursorRow, cursorCol int, visible bool) string
- func ResizeTmuxPane(paneID string, width, height int)
- func ResolveEditor() string
- func SendBracketedPasteToTmux(sessionName, text string) error
- func SendKeyToTmux(sessionName, key string) error
- func SendKeys(sessionName string, keys ...KeySpec) error
- func SendKeysCmd(scope MessageScope, sessionName string, keys ...KeySpec) tea.Cmd
- func SendKeysOrdered(target string, keys ...KeySpec) <-chan error
- func SendLiteralToTmux(sessionName, text string) error
- func SendOrdered(target string, run func() error) <-chan error
- func SendPasteInput(sessionName, text string, bracketed bool) error
- func SendPasteInputCmd(scope MessageScope, sessionName, text string, bracketed bool) tea.Cmd
- func SendPasteToTmux(sessionName, text string) error
- func SendSGRMouse(sessionName string, button, col, row int, release bool) error
- func SendSGRWheel(sessionName string, up bool, col, row, notches int) error
- func SetAppFocused(focused bool)
- func SetWindowSizeManual(sessionName string)
- func TouchGeometryLease(target string)
- func WaitForPendingSends()
- type CaptureRange
- type CaptureResultMsg
- type Config
- type ControlManager
- type ControlRequest
- type ControlSnapshot
- type ControlSubscription
- type EditorSession
- type EditorSessionOptions
- type EscapeTimerMsg
- type KeySpec
- type KeyedScheduler
- func (s *KeyedScheduler) Current(key string) int
- func (s *KeyedScheduler) Invalidate(key string) int
- func (s *KeyedScheduler) IsCurrent(key string, generation int) bool
- func (s *KeyedScheduler) Reset()
- func (s *KeyedScheduler) Schedule(key string, delay time.Duration, message func(generation int) tea.Msg) tea.Cmd
- type LeaseDecision
- type LeaseObservation
- type LeasePolicy
- type MessageScope
- type Model
- func (m *Model) Cursor() *tea.Cursor
- func (m *Model) Enter(sessionName, paneID string) tea.Cmd
- func (m *Model) Exit()
- func (m *Model) GetTarget() string
- func (m *Model) IsActive() bool
- func (m *Model) PaneCoords(col, row int) (int, int, bool)
- func (m *Model) PreferredMouseMode() tea.MouseMode
- func (m *Model) ResizeAndPollImmediate(width, height int) tea.Cmd
- func (m *Model) Scope() MessageScope
- func (m *Model) SetDimensions(width, height int) tea.Cmd
- func (m *Model) SizeIndicator() string
- func (m *Model) Update(msg tea.Msg) tea.Cmd
- func (m *Model) View() string
- type OutputBuffer
- func (b *OutputBuffer) AbsoluteRange() (start, end int, ok bool)
- func (b *OutputBuffer) Clear()
- func (b *OutputBuffer) LastNonEmptyLine() int
- func (b *OutputBuffer) Len() int
- func (b *OutputBuffer) LineCount() int
- func (b *OutputBuffer) Lines() []string
- func (b *OutputBuffer) LinesAbsoluteRange(start, end int) []string
- func (b *OutputBuffer) LinesRange(start, end int) []string
- func (b *OutputBuffer) PrependSnapshot(content string, baseLine int) bool
- func (b *OutputBuffer) String() string
- func (b *OutputBuffer) Update(content string) bool
- func (b *OutputBuffer) UpdateSnapshot(content string, baseLine int) bool
- func (b *OutputBuffer) WouldChange(content string) bool
- func (b *OutputBuffer) WouldChangeSnapshot(content string, baseLine int) bool
- func (b *OutputBuffer) Write(content string)
- type PaneFit
- type PaneFitInput
- type PaneResizedMsg
- type PasteResultMsg
- type PollTickMsg
- type SessionDeadMsg
- type State
Constants ¶
const ( // PollingDecayFast is the polling interval during active typing. PollingDecayFast = 50 * time.Millisecond // PollingDecayMedium is the polling interval after brief inactivity. PollingDecayMedium = 200 * time.Millisecond // PollingDecaySlow is the polling interval after extended inactivity. PollingDecaySlow = 250 * time.Millisecond // KeystrokeDebounce delays polling after keystrokes to batch rapid typing. // Allows typing bursts to coalesce into fewer polls, reducing CPU usage. KeystrokeDebounce = 20 * time.Millisecond // InactivityMediumThreshold triggers medium polling. InactivityMediumThreshold = 2 * time.Second // InactivitySlowThreshold triggers slow polling. InactivitySlowThreshold = 10 * time.Second )
Polling interval constants for adaptive polling
const ( SGRWheelUp = 64 SGRWheelDown = 65 )
SGR wheel button codes. Wheel notches are reported as button presses in the 64+ range and have no matching release event.
const ( BracketedPasteEnable = "\x1b[?2004h" // ESC[?2004h - app enables bracketed paste BracketedPasteDisable = "\x1b[?2004l" // ESC[?2004l - app disables bracketed paste BracketedPasteStart = "\x1b[200~" // ESC[200~ - start of pasted content BracketedPasteEnd = "\x1b[201~" // ESC[201~ - end of pasted content MouseModeEnable1000 = "\x1b[?1000h" MouseModeEnable1002 = "\x1b[?1002h" MouseModeEnable1003 = "\x1b[?1003h" MouseModeEnable1006 = "\x1b[?1006h" MouseModeEnable1015 = "\x1b[?1015h" MouseModeDisable1000 = "\x1b[?1000l" MouseModeDisable1002 = "\x1b[?1002l" MouseModeDisable1003 = "\x1b[?1003l" MouseModeDisable1006 = "\x1b[?1006l" MouseModeDisable1015 = "\x1b[?1015l" )
Terminal mode escape sequences
const DefaultScrollbackLines = 600
DefaultScrollbackLines is the number of scrollback lines captured from a pane when no explicit scrollback is requested. The live capture stays small; older ranges are fetched lazily as the user scrolls past the loaded boundary.
const ( // DoubleEscapeDelay is the max time between Escape presses for double-escape exit. // Single Escape is delayed by this amount to detect double-press. DoubleEscapeDelay = 150 * time.Millisecond )
Interactive mode timing constants
const HistoryLimit = 10000
HistoryLimit is the minimum scrollback retained for sidecar-managed panes.
Variables ¶
var DefaultLeasePolicy = LeasePolicy{ StaleTicks: 5, StaleAfter: 60 * time.Second, RefreshTicks: 2, RefreshAfter: 5 * time.Second, PreemptIdle: 5 * time.Second, }
DefaultLeasePolicy leaves an owner at least three refreshes of slack at the slowest poll interval in the app (20s) before anyone else treats its lease as abandoned, and hands geometry to whichever machine the user is actually typing on within a few seconds.
var ( // partialMouseSeqRegex matches SGR mouse sequences that lost their ESC prefix // due to split-read timing in terminal input. PartialMouseSeqRegex = regexp.MustCompile(`^(\[<\d+;\d+;\d+[Mm])+$`) )
Regexes for cleaning terminal output
Functions ¶
func CalculatePollingInterval ¶
CalculatePollingInterval determines the appropriate polling interval based on the time since the last user activity.
func CapturePaneOutput ¶
CapturePaneOutput captures the current output of a tmux pane. Uses capture-pane with -p flag to print to stdout and -e to preserve ANSI escape sequences (colors, styles). The scrollback parameter controls how many lines of history to capture.
func ClaimGeometryLease ¶ added in v0.92.0
func ClaimGeometryLease(target string)
ClaimGeometryLease takes ownership of target's session for this instance, overriding whatever lease it finds. Reserved for unambiguous local actions — attaching to a session, entering interactive mode — where the user has just proved which machine they are sitting at.
func ContainsMouseSequence ¶
ContainsMouseSequence checks if input looks like it contains SGR mouse data (td-e2ce50). More lenient than PartialMouseSeqRegex - catches truncated/split sequences. Used to filter spurious key events during fast scrolling.
func CursorStyle ¶
CursorStyle returns the cursor style using current theme colors. Uses bold reverse video with a bright background for maximum visibility. The bright cyan/white combination stands out against most terminal backgrounds including Claude Code's diff highlighting and colored output.
func DetectBracketedPasteMode ¶
DetectBracketedPasteMode checks captured output to determine if the app has enabled bracketed paste mode. Looks for the most recent occurrence of either the enable (ESC[?2004h) or disable (ESC[?2004l) sequence.
func DetectMouseReportingMode ¶
DetectMouseReportingMode checks captured output to determine if the app has enabled mouse reporting. Looks for the most recent occurrence of enable vs disable sequences across all mouse mode types.
func EditorAvailable ¶ added in v0.88.0
func EditorAvailable() bool
EditorAvailable reports whether tmux can host an embedded editor.
func ExtractUnknownCSIBytes ¶
func ExtractUnknownCSIBytes(msg interface{}) []byte
ExtractUnknownCSIBytes extracts an unparsed CSI sequence from Bubble Tea's current ultraviolet event types. The reflection fallback preserves compatibility with Bubble Tea v1's unexported []byte message.
func HoldGeometryLease ¶ added in v0.92.0
func HoldGeometryLease(target string)
HoldGeometryLease claims target and keeps its lease refreshed from outside the event loop, for actions that suspend the TUI for their whole duration — attaching to a session. Pair every call with ReleaseGeometryHold on the way back; a crash in between is safe, since the refresher dies with the process and the lease then goes stale like any other.
func IsPasteInput ¶
func IsPasteInput(msg tea.KeyPressMsg) bool
IsPasteInput detects if a key message is actually a paste operation.
In bubbletea v2, true bracketed pastes arrive as a separate tea.PasteMsg (handled in Update), so this heuristic only catches terminals that deliver multi-rune text as a single KeyPressMsg without bracketed paste. It returns true if the typed text contains newlines or is suspiciously long for typing.
func IsSessionDeadError ¶
IsSessionDeadError checks if an error indicates the tmux session/pane is gone.
func LooksLikeMouseFragment ¶
LooksLikeMouseFragment checks if input could be a fragment of an SGR mouse sequence (td-e2ce50). This is even more lenient than ContainsMouseSequence - catches very short fragments like "[<" or "M[<" that occur when terminal splits mouse events across reads. Used to suppress snap-back and key forwarding during fast scrolling.
func MapKeyToTmux ¶
func MapKeyToTmux(msg tea.KeyPressMsg) (key string, useLiteral bool)
MapKeyToTmux translates a Bubble Tea key message to a tmux send-keys argument. Returns the tmux key name and whether to use literal mode (-l). For modified keys and special keys, returns the tmux key name. For literal characters, returns the character with useLiteral=true.
func NewSession ¶ added in v0.88.0
NewSession creates a tmux session only after the server-wide history default is known to be configured. The mutex keeps every sidecar new-session path ordered behind preparation and makes a failed preparation retryable.
func NormalizeEditorName ¶ added in v0.88.0
NormalizeEditorName maps common aliases to their editor family.
func NormalizeToCSIu ¶
NormalizeToCSIu converts an unknown CSI sequence to CSI u format for forwarding to tmux. It handles:
CSI u: ESC [ keycode ; modifier u → passed through modifyOtherKeys: ESC [ 27 ; modifier ; keycode ~ → converted to CSI u
Returns the CSI u formatted string, or empty string if unrecognized.
func NoteUserInput ¶ added in v0.92.0
func NoteUserInput()
NoteUserInput records keyboard or mouse input on this instance. Focus reports only what one machine's window server believes, and the machine the user walked away from never hears about it — so recent input, compared as a duration between machines, is what actually decides who owns geometry.
func PaneSizeIndicator ¶ added in v0.92.0
PaneSizeIndicator describes a clipped pane as "200x50, showing 120x40". It returns "" when nothing is hidden, so callers can append it unconditionally.
func PasteClipboardToTmuxCmd ¶
func PasteClipboardToTmuxCmd(scope MessageScope, sessionName string, bracketed bool) tea.Cmd
PasteClipboardToTmuxCmd returns a tea.Cmd that pastes clipboard content to a tmux session. The bracketed parameter determines whether to use bracketed paste mode. Returns a PasteResultMsg with the result.
func PrepareServer ¶ added in v0.88.0
func PrepareServer() error
PrepareServer configures tmux before any sidecar session is created. Raising the global default before new-session is the only behavior that works on older tmux releases where history-limit changes do not affect existing panes. Existing user settings above the sidecar minimum are preserved.
func QueryCursorPositionSync ¶
QueryCursorPositionSync synchronously queries cursor position for the given target. Used to capture cursor position atomically with output in poll goroutines. Returns row, col (0-indexed), paneHeight, paneWidth, visible, and ok (false if query failed). paneHeight is needed to calculate cursor offset when display height differs from pane height.
func QueryPaneSize ¶
QueryPaneSize queries the current size of a tmux pane.
func ReleaseGeometryHold ¶ added in v0.92.0
func ReleaseGeometryHold(target string)
ReleaseGeometryHold ends the background refresh started by HoldGeometryLease. The lease stays with this instance; it just goes back to being refreshed by the geometry loop.
func ReleaseGeometryLeases ¶ added in v0.92.0
func ReleaseGeometryLeases()
ReleaseGeometryLeases gives up every lease this instance holds. Call it on the way out of the process.
func RenderCursorLine ¶ added in v0.88.0
RenderCursorLine overlays the cursor on one terminal line. Keeping the line-level primitive separate lets viewport renderers avoid splitting and joining the complete rendered buffer a second time.
func RenderWithCursor ¶
RenderWithCursor overlays the cursor on content at the specified position. cursorRow is relative to the visible content (0 = first visible line). cursorCol is the column within the line (0-indexed). Preserves ANSI escape codes in surrounding content while rendering cursor.
func ResizeTmuxPane ¶
ResizeTmuxPane resizes a tmux window/pane to the specified dimensions. resize-window works for detached sessions; resize-pane is a fallback.
The geometry ownership lease is enforced here rather than at the dozen call sites (td-ee222a): callers stay dumb, and an instance that does not own the session simply renders the geometry it finds. See geometry_lease.go.
func ResolveEditor ¶ added in v0.88.0
func ResolveEditor() string
ResolveEditor returns the configured editor, preserving the established EDITOR > VISUAL > vim precedence.
func SendBracketedPasteToTmux ¶
SendBracketedPasteToTmux sends text wrapped in bracketed paste sequences. Used when the target app has enabled bracketed paste mode.
func SendKeyToTmux ¶
SendKeyToTmux sends a key to a tmux pane using send-keys. Uses the tmux key name syntax (e.g., "Enter", "C-c", "Up").
func SendKeys ¶ added in v0.88.0
SendKeys sends keys to tmux synchronously and preserves their order.
func SendKeysCmd ¶
func SendKeysCmd(scope MessageScope, sessionName string, keys ...KeySpec) tea.Cmd
SendKeysCmd sends keys to tmux asynchronously.
The batch is queued at call time (see send_queue.go) so keystrokes reach tmux in the order Update handled them, not the order Bubble Tea happens to schedule their goroutines in. Call this from Update, not from inside another tea.Cmd. Returns SessionDeadMsg if the session has ended.
func SendKeysOrdered ¶ added in v0.88.0
SendKeysOrdered queues a keystroke batch for a tmux target. The batch is delivered atomically with respect to other queued work for the same target.
func SendLiteralToTmux ¶
SendLiteralToTmux sends literal text to a tmux pane using send-keys -l. This prevents tmux from interpreting special key names.
func SendOrdered ¶ added in v0.88.0
SendOrdered queues work for a tmux target and returns a channel that receives its result. Jobs for the same target run one at a time, in call order.
Call this from the Update loop, not from inside a tea.Cmd — the ordering guarantee is only as good as the ordering of the calls.
func SendPasteInput ¶ added in v0.88.0
SendPasteInput forwards paste text using the target applications current bracketed-paste mode.
func SendPasteInputCmd ¶
func SendPasteInputCmd(scope MessageScope, sessionName, text string, bracketed bool) tea.Cmd
SendPasteInputCmd sends paste text to tmux asynchronously. Used for multi-character terminal input (not clipboard paste which is already async).
func SendPasteToTmux ¶
SendPasteToTmux pastes multi-line text via tmux buffer. Uses load-buffer + paste-buffer which works regardless of app paste mode state.
func SendSGRMouse ¶
SendSGRMouse sends an SGR mouse event to a tmux pane. button is the mouse button (0=left, 1=middle, 2=right). col and row are 1-indexed coordinates. release indicates if this is a button release event.
func SendSGRWheel ¶ added in v0.88.2
SendSGRWheel sends `notches` wheel reports to a tmux pane. col and row are 1-indexed. A wheel notch has no release event, so only the press form is emitted — sending a release would look like a stray button-4/5 release to the application.
The reports go out as one send-keys: the pane sees the same byte stream either way, and a flick would otherwise spawn one tmux process per notch.
func SetAppFocused ¶ added in v0.92.0
func SetAppFocused(focused bool)
SetAppFocused tells geometry arbitration whether the user is looking at this sidecar instance. ControlManager.SetAppFocused forwards here, so every resize path — including the filebrowser and notes inline editors, which have no focus plumbing of their own — observes the same bit.
func SetWindowSizeManual ¶
func SetWindowSizeManual(sessionName string)
SetWindowSizeManual sets the tmux window-size option to "manual" for a session. This prevents tmux from auto-constraining window size based on attached clients, allowing resize-window commands to stick reliably.
func TouchGeometryLease ¶ added in v0.92.0
func TouchGeometryLease(target string)
TouchGeometryLease advances the lease for target without asserting geometry.
The lease is refreshed by the work it guards, and callers skip ResizeTmuxPane once a pane already matches — so an owner that has settled on the right size stops refreshing and eventually looks abandoned to everyone else. Every geometry loop therefore ticks the lease on the passes where it decides not to resize; polling the pane at all is what makes this instance the one driving its geometry, not the resize call that occasionally follows.
func WaitForPendingSends ¶ added in v0.88.0
func WaitForPendingSends()
WaitForPendingSends blocks until every queued send has run.
Enqueueing happens where the key is handled, so the tmux call escapes the caller's goroutine and can land arbitrarily later — after a test has restored PATH, for instance, or while a different test owns the fake tmux. Tests that assert on what was spawned use this to draw a hard line around themselves.
Types ¶
type CaptureRange ¶ added in v0.88.0
CaptureRange is a bounded tmux history capture with absolute pane coordinates. StartLine and EndLine describe Output as a half-open range.
func CapturePaneRange ¶ added in v0.88.0
func CapturePaneRange(target string, start, end int) (CaptureRange, error)
CapturePaneRange captures the inclusive tmux range [start, end]. Negative coordinates address history above the visible pane, as in capture-pane.
type CaptureResultMsg ¶
type CaptureResultMsg struct {
Scope MessageScope
PollGeneration int
Target string // Pane or session this capture is for
Output string // Captured output (empty on error)
Err error // Non-nil if capture failed
// Cursor state captured atomically with output
CursorRow int
CursorCol int
CursorVisible bool
PaneHeight int
PaneWidth int
}
CaptureResultMsg delivers async tmux capture results. Used to avoid blocking the UI thread on tmux subprocess calls.
type Config ¶
type Config struct {
// ExitKey is the keybinding to exit interactive mode (default: "ctrl+\\").
ExitKey string
// AttachKey is the keybinding to attach to the full tmux session (default: "ctrl+]").
AttachKey string
// CopyKey is the keybinding to copy selection (default: "alt+c").
CopyKey string
// PasteKey is the keybinding to paste clipboard (default: "alt+v").
PasteKey string
// ScrollbackLines is the number of scrollback lines to capture
// (default: DefaultScrollbackLines).
ScrollbackLines int
}
Config holds configuration options for a tty Model.
type ControlManager ¶ added in v0.88.0
type ControlManager struct {
// contains filtered or unexported fields
}
ControlManager owns a small pool of control clients keyed by tmux session. tmux control clients are attached to exactly one session, so pooling by pane alone would silently miss notifications from Sidecar's other sessions.
func NewControlManager ¶ added in v0.88.0
func NewControlManager() *ControlManager
func (*ControlManager) SetAppFocused ¶ added in v0.88.0
func (m *ControlManager) SetAppFocused(focused bool)
func (*ControlManager) Stop ¶ added in v0.88.0
func (m *ControlManager) Stop()
func (*ControlManager) Subscribe ¶ added in v0.88.0
func (m *ControlManager) Subscribe(request ControlRequest) (*ControlSubscription, error)
type ControlRequest ¶ added in v0.88.0
type ControlRequest struct {
Session string
Pane string
Width int
Height int
Scrollback int
Visible bool
Focused bool
OnSnapshot func(ControlSnapshot)
OnFallback func(error)
}
ControlRequest describes one active/visible terminal consumer. Consumers retain their existing polling path and resume it from OnFallback whenever control mode cannot start or its client dies.
type ControlSnapshot ¶ added in v0.88.0
type ControlSnapshot struct {
Session string
Pane string
Output string
HistorySize int
CaptureBase int
HasHistory bool
CursorRow int
CursorCol int
CursorVisible bool
PaneHeight int
PaneWidth int
Generation uint64
// MouseReporting mirrors tmux's #{mouse_any_flag}: the app running in the
// pane has enabled at least one mouse tracking mode. It is asked of tmux
// rather than scanned out of the capture because `capture-pane -e` emits
// rendering escapes only — DECSET mode sequences never survive it.
MouseReporting bool
// PaneTitle and CurrentCommand are captured in the same control-mode
// metadata response as the screen. Semantic agent probes must never reuse
// identity from an older ordinary poll while that polling path is suspended.
PaneTitle string
CurrentCommand string
}
ControlSnapshot is an authoritative rendered screen captured in-band over a tmux control connection after an output or layout notification.
type ControlSubscription ¶ added in v0.88.0
type ControlSubscription struct {
// contains filtered or unexported fields
}
ControlSubscription is a handle to one manager subscription.
func (*ControlSubscription) Close ¶ added in v0.88.0
func (s *ControlSubscription) Close()
func (*ControlSubscription) Resize ¶ added in v0.88.0
func (s *ControlSubscription) Resize(width, height int)
func (*ControlSubscription) SetFocused ¶ added in v0.88.0
func (s *ControlSubscription) SetFocused(focused bool)
func (*ControlSubscription) SetVisible ¶ added in v0.88.0
func (s *ControlSubscription) SetVisible(visible bool)
func (*ControlSubscription) UsingControl ¶ added in v0.88.0
func (s *ControlSubscription) UsingControl() bool
type EditorSession ¶ added in v0.88.0
EditorSession owns the tmux-specific lifecycle and editor conventions shared by inline editor consumers. Domain state (files, tabs, notes, persistence) remains with the calling plugin.
func StartEditorSession ¶ added in v0.88.0
func StartEditorSession(opts EditorSessionOptions) (EditorSession, error)
StartEditorSession creates a detached tmux editor with consistent TERM, dimensions, and history setup.
func (EditorSession) CursorToEnd ¶ added in v0.88.0
func (s EditorSession) CursorToEnd() bool
CursorToEnd positions supported editors at the end of their buffer.
func (EditorSession) IsAlive ¶ added in v0.88.0
func (s EditorSession) IsAlive() bool
IsAlive reports whether the session still exists.
func (EditorSession) Kill ¶ added in v0.88.0
func (s EditorSession) Kill()
Kill terminates the session. A missing/already-dead session is harmless.
func (EditorSession) KillCmd ¶ added in v0.88.0
func (s EditorSession) KillCmd() tea.Cmd
KillCmd defers session cleanup to Bubble Tea's command runner.
func (EditorSession) MouseCmd ¶ added in v0.88.0
func (s EditorSession) MouseCmd(scope MessageScope, button, col, row int, release bool) tea.Cmd
MouseCmd forwards one SGR mouse event and reports a dead session through the owning tty model's scope.
func (EditorSession) SaveAndQuit ¶ added in v0.88.0
func (s EditorSession) SaveAndQuit() bool
SaveAndQuit sends the editor-specific save-and-exit sequence. It reports whether the editor is known, independently of command delivery success.
type EditorSessionOptions ¶ added in v0.88.0
type EditorSessionOptions struct {
NamePrefix string
Editor string
Path string
Line int // zero-indexed; values <= 0 omit the editor line argument
Width int
Height int
CursorAtEnd bool
}
EditorSessionOptions describes a detached editor session.
type EscapeTimerMsg ¶
type EscapeTimerMsg struct {
Scope MessageScope
}
EscapeTimerMsg is sent when the escape delay timer fires. If pendingEscape is still true, we forward the single Escape to tmux.
type KeyedScheduler ¶ added in v0.88.0
type KeyedScheduler struct {
// contains filtered or unexported fields
}
KeyedScheduler provides one generation/invalidation mechanism for any number of independently polled panes. It is intended for Bubble Tea's single update goroutine; callers namespace keys by pane source.
func (*KeyedScheduler) Current ¶ added in v0.88.0
func (s *KeyedScheduler) Current(key string) int
Current returns the current generation token for key.
func (*KeyedScheduler) Invalidate ¶ added in v0.88.0
func (s *KeyedScheduler) Invalidate(key string) int
Invalidate advances key's generation and returns the new token.
func (*KeyedScheduler) IsCurrent ¶ added in v0.88.0
func (s *KeyedScheduler) IsCurrent(key string, generation int) bool
IsCurrent reports whether generation still owns key's poll chain.
func (*KeyedScheduler) Reset ¶ added in v0.88.0
func (s *KeyedScheduler) Reset()
Reset invalidates all outstanding keys without retaining old pane names.
type LeaseDecision ¶ added in v0.92.0
type LeaseDecision struct {
// Resize reports whether this instance may assert pane geometry.
Resize bool
// Write reports whether it should stamp a fresh token — a claim when the
// lease was free or stale, a refresh when it already held it.
Write bool
// Reason names the rule that fired, for tests and logs.
Reason string
}
LeaseDecision is the verdict for one tick.
func DecideGeometryLease ¶ added in v0.92.0
func DecideGeometryLease(obs LeaseObservation, policy LeasePolicy) LeaseDecision
DecideGeometryLease is the whole arbitration rule, state-free so a headless caller can adopt it unchanged.
type LeaseObservation ¶ added in v0.92.0
type LeaseObservation struct {
// SelfID identifies this sidecar instance. A token belongs to us when it
// carries this ID.
SelfID string
// Token is the raw @sidecar-owner value, empty when the option is unset.
Token string
// Focused reports whether the user is looking at this instance.
Focused bool
// UnchangedTicks is how many of the reader's ticks Token has been identical
// for. Zero on the tick it changed.
UnchangedTicks int
// UnchangedFor is how long Token has been identical in the reader's own
// elapsed time.
UnchangedFor time.Duration
// TicksSinceWrite is how many ticks since this instance last wrote a token.
TicksSinceWrite int
// SinceWrite is how long since this instance last wrote a token, measured on
// its own clock. Zero when it never has.
SinceWrite time.Duration
// SelfIdle is how long since the user last gave this instance input.
SelfIdle time.Duration
// OwnerIdle is what the current token says its writer's idle time was when
// it was written, valid only when OwnerIdleKnown.
OwnerIdle time.Duration
OwnerIdleKnown bool
// OwnerDefunct reports that Token was written by an instance the reader can
// prove is gone — in practice a previous sidecar on this same machine whose
// PID no longer exists. Only ever provable locally; a token from another
// machine is never defunct as far as this reader is concerned.
OwnerDefunct bool
}
LeaseObservation is everything arbitration needs: what this instance is, what the shared option currently says, and how long the reader has watched it.
type LeasePolicy ¶ added in v0.92.0
type LeasePolicy struct {
// StaleTicks is how many consecutive ticks a foreign token may stay
// unchanged before the lease is considered abandoned and claimable.
StaleTicks int
// StaleAfter is the wall-clock floor on the same judgement, for sessions
// whose ticks are sporadic. Zero disables it. It must stay comfortably above
// RefreshAfter *and* above the slowest poll interval any caller ticks on,
// since an owner can only refresh on a tick of its own.
StaleAfter time.Duration
// RefreshTicks is how many ticks the owner lets pass before writing a new
// token, so readers elsewhere keep seeing it change.
RefreshTicks int
// RefreshAfter bounds the same cadence in elapsed time. A tick is a poll,
// and polls run as slowly as 20s, so a tick count alone lets the owner's
// refresh period stretch to a multiple of an arbitrary poll interval — past
// the point where peers polling just as slowly call it abandoned. Zero
// disables the elapsed-time arm.
RefreshAfter time.Duration
// PreemptIdle is how much longer than us the current owner must have gone
// without user input before we take the lease off it. It doubles as the
// window in which our own last input counts as "the user is here". Zero
// disables idle preemption.
PreemptIdle time.Duration
}
LeasePolicy is the budget arbitration runs on. Ticks are the reader's own local ticks; they carry no cross-machine meaning. Durations are elapsed measurements, never timestamps, so they do carry across machines.
type MessageScope ¶ added in v0.88.0
MessageScope identifies one activation of one Model. Bubble Tea broadcasts messages to every plugin, so terminal messages must be scoped to prevent a capture or session failure from one consumer affecting another.
type Model ¶
type Model struct {
Config Config
State *State
// Width and Height are set by the containing plugin
Width int
Height int
// Callbacks for plugin integration
OnExit func() tea.Cmd // Called when user exits interactive mode
OnAttach func() tea.Cmd // Called when user requests full tmux attach
// contains filtered or unexported fields
}
Model is an embeddable component that provides interactive tmux functionality. Plugins embed this Model and delegate Update/View when interactive mode is active.
func New ¶
New creates a new tty Model with the given configuration. If config is nil, DefaultConfig() is used.
func (*Model) Cursor ¶ added in v0.88.0
Cursor returns the native cursor position relative to View().
func (*Model) Enter ¶
Enter enters interactive mode for the specified tmux session/pane. Returns a tea.Cmd to start polling for output.
func (*Model) PaneCoords ¶ added in v0.92.0
PaneCoords maps 1-indexed coordinates within the rendered content area to the 1-indexed pane coordinates tmux's mouse protocol expects. A clipped pane is drawn scrolled, so a click lands ColOffset columns and RowOffset rows in (td-73fa86).
func (*Model) PreferredMouseMode ¶ added in v0.88.0
PreferredMouseMode reports the mode suitable for an active embedded terminal. Containers still own coordinate translation and mouse forwarding.
func (*Model) ResizeAndPollImmediate ¶
ResizeAndPollImmediate updates dimensions and triggers an immediate resize and poll. Unlike SetDimensions, this bypasses debouncing for use with WindowSizeMsg. The resize and poll are batched so the view updates immediately after resize.
func (*Model) Scope ¶ added in v0.88.0
func (m *Model) Scope() MessageScope
Scope returns the identity of the current Model activation. Commands created for this model should include this scope in their result messages.
func (*Model) SetDimensions ¶
SetDimensions updates the view dimensions for resize handling.
func (*Model) SizeIndicator ¶ added in v0.92.0
SizeIndicator describes a pane that is larger than the viewport it is drawn into, e.g. "200x50, showing 120x40". It returns "" when the whole pane is visible, so callers can render it unconditionally.
func (*Model) Update ¶
Update handles messages in interactive mode. Returns the updated model and any commands to execute. Plugins should call this when they receive messages and interactive mode is active.
type OutputBuffer ¶
type OutputBuffer struct {
// contains filtered or unexported fields
}
OutputBuffer is a thread-safe bounded buffer for terminal output. Uses maphash for efficient content change detection to avoid duplicate processing.
func NewOutputBuffer ¶
func NewOutputBuffer(capacity int) *OutputBuffer
NewOutputBuffer creates a new output buffer with the given capacity.
func (*OutputBuffer) AbsoluteRange ¶ added in v0.88.0
func (b *OutputBuffer) AbsoluteRange() (start, end int, ok bool)
AbsoluteRange reports the half-open absolute line range represented by the buffer. ok is false until the buffer has received an absolute snapshot.
func (*OutputBuffer) Clear ¶
func (b *OutputBuffer) Clear()
Clear removes all lines from the buffer.
func (*OutputBuffer) LastNonEmptyLine ¶ added in v0.88.0
func (b *OutputBuffer) LastNonEmptyLine() int
LastNonEmptyLine returns the index of the last line containing printable content, or -1 when every line is empty. It scans under the buffer lock and avoids copying the full scrollback into the render path.
func (*OutputBuffer) Len ¶
func (b *OutputBuffer) Len() int
Len returns the number of lines in the buffer.
func (*OutputBuffer) LineCount ¶
func (b *OutputBuffer) LineCount() int
LineCount returns the number of lines without copying.
func (*OutputBuffer) Lines ¶
func (b *OutputBuffer) Lines() []string
Lines returns a copy of all lines in the buffer.
func (*OutputBuffer) LinesAbsoluteRange ¶ added in v0.88.0
func (b *OutputBuffer) LinesAbsoluteRange(start, end int) []string
LinesAbsoluteRange returns a copy of absolute lines in [start, end).
func (*OutputBuffer) LinesRange ¶
func (b *OutputBuffer) LinesRange(start, end int) []string
LinesRange returns a copy of lines in the specified range [start, end). This is more efficient than Lines() when only a portion is needed.
func (*OutputBuffer) PrependSnapshot ¶ added in v0.88.0
func (b *OutputBuffer) PrependSnapshot(content string, baseLine int) bool
PrependSnapshot merges an older bounded capture into an absolute buffer. The ranges must overlap or touch; a gap is rejected because inventing blank terminal rows would make selection and search coordinates incorrect.
func (*OutputBuffer) String ¶
func (b *OutputBuffer) String() string
String returns the buffer contents as a single string.
func (*OutputBuffer) Update ¶
func (b *OutputBuffer) Update(content string) bool
Update replaces buffer content if it has changed (detected via hash). Returns true if content was updated, false if content was unchanged.
func (*OutputBuffer) UpdateSnapshot ¶ added in v0.88.0
func (b *OutputBuffer) UpdateSnapshot(content string, baseLine int) bool
UpdateSnapshot merges a live capture whose first line has the supplied absolute pane coordinate. Older lines loaded with PrependSnapshot are retained while the overlapping live tail is replaced.
func (*OutputBuffer) WouldChange ¶ added in v0.88.0
func (b *OutputBuffer) WouldChange(content string) bool
WouldChange reports whether content differs from the last raw update without mutating the buffer. Async capture commands use this to do status work off the UI goroutine while deferring the actual update until ownership is checked.
func (*OutputBuffer) WouldChangeSnapshot ¶ added in v0.88.0
func (b *OutputBuffer) WouldChangeSnapshot(content string, baseLine int) bool
WouldChangeSnapshot reports whether an absolute live capture differs from the last one without mutating the buffer.
func (*OutputBuffer) Write ¶
func (b *OutputBuffer) Write(content string)
Write replaces content in the buffer (for backward compatibility). Prefer Update() for change detection.
type PaneFit ¶ added in v0.92.0
type PaneFit struct {
// Width and Height are the display region, never larger than the viewport
// and never larger than the pane.
Width int
Height int
// ColOffset is the first pane column rendered. Non-zero only when the pane
// is wider than the viewport and the cursor sits past the right edge.
ColOffset int
// RowOffset is the first pane row rendered. Non-zero only when the pane is
// taller than the viewport; it anchors the window on the cursor so the row
// being typed into stays on screen, and falls back to the pane's tail when
// there is no cursor to anchor to.
RowOffset int
// ClippedWidth/ClippedHeight report that the pane is larger than the
// viewport on that axis, so part of it is not shown.
ClippedWidth bool
ClippedHeight bool
// LetterboxedWidth/LetterboxedHeight report that the pane is smaller than
// the viewport on that axis, so the pane is padded rather than stretched.
LetterboxedWidth bool
LetterboxedHeight bool
}
PaneFit is the projection of a pane onto a viewport: the region actually drawn, plus the horizontal scroll needed to keep the cursor in view.
func FitPane ¶ added in v0.92.0
func FitPane(in PaneFitInput) PaneFit
FitPane projects a pane of the observed size onto the viewport. It is a pure function so both the workspace viewport and tty.Model share one rule.
func (PaneFit) Letterboxed ¶ added in v0.92.0
Letterboxed reports whether the pane is smaller than the viewport on either axis.
func (PaneFit) PaneCoords ¶ added in v0.92.0
PaneCoords maps a 0-indexed cell of the rendered region to 1-indexed pane coordinates, which is what tmux's mouse protocol speaks. It reports false for a cell outside the rendered region, so hit testing moves with the pixels instead of assuming the viewport and the pane are aligned (td-73fa86).
type PaneFitInput ¶ added in v0.92.0
type PaneFitInput struct {
ViewWidth int
ViewHeight int
PaneWidth int
PaneHeight int
// CursorCol and CursorRow are the pane-relative cursor coordinates used to
// anchor clipping. Ignored unless HasCursor is set.
CursorCol int
CursorRow int
HasCursor bool
}
PaneFitInput describes a tmux pane's real geometry alongside the local viewport it has to be shown in.
Sidecar never owns a tmux session exclusively: the same session can be driven by another sidecar instance on a differently sized terminal, so the pane's actual size routinely disagrees with the size this instance last requested (td-73fa86). Rendering therefore has to derive from the observed size, not the requested one.
PaneWidth/PaneHeight of 0 mean "unknown" — the viewport is used as-is.
type PaneResizedMsg ¶
type PaneResizedMsg struct {
Scope MessageScope
}
PaneResizedMsg is sent when a pane resize operation completes. Triggers a fresh poll so captured content reflects the new width/wrapping.
type PasteResultMsg ¶
type PasteResultMsg struct {
Scope MessageScope
Err error // Non-nil if paste failed
Empty bool // True if clipboard was empty
SessionDead bool // True if session died during paste
}
PasteResultMsg is sent after a paste operation completes.
type PollTickMsg ¶
type PollTickMsg struct {
Scope MessageScope
Target string // Which pane/session to poll
Generation int // For invalidating stale polls
}
PollTickMsg is sent to trigger a poll for output updates.
type SessionDeadMsg ¶
type SessionDeadMsg struct {
Scope MessageScope
}
SessionDeadMsg indicates the tmux session has ended. Sent when send-keys or capture fails with a session/pane not found error.
type State ¶
type State struct {
// Active indicates whether interactive mode is currently active.
Active bool
// TargetPane is the tmux pane ID (e.g., "%12") receiving input.
TargetPane string
// TargetSession is the tmux session name for the active pane.
TargetSession string
// LastKeyTime tracks when the last key was sent for polling decay.
LastKeyTime time.Time
// Escape handling state
EscapePressed bool
EscapeTime time.Time
EscapeTimerPending bool
// LastMouseEventTime tracks when the last tea.MouseMsg was received,
// used to suppress split-CSI "[" that leaks from mouse sequences.
LastMouseEventTime time.Time
// Cursor state (updated asynchronously via CaptureResultMsg)
CursorRow int
CursorCol int
CursorVisible bool
PaneHeight int
PaneWidth int
// Terminal mode state (updated from captured output)
BracketedPasteEnabled bool
MouseReportingEnabled bool
// Visible buffer range for selection mapping
VisibleStart int
VisibleEnd int
ContentRowOffset int
// Resize debouncing
LastResizeAt time.Time
// Output buffer
OutputBuf *OutputBuffer
// Poll generation for invalidating stale polls
PollGeneration int
}
State tracks the interactive mode state for a tmux session.