tty

package
v0.95.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 28 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package 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

View Source
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

View Source
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.

View Source
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

View Source
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.

View Source
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

View Source
const HistoryLimit = 10000

HistoryLimit is the minimum scrollback retained for sidecar-managed panes.

Variables

View Source
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.

View Source
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

func CalculatePollingInterval(lastActivityTime time.Time) time.Duration

CalculatePollingInterval determines the appropriate polling interval based on the time since the last user activity.

func CapturePaneOutput

func CapturePaneOutput(target string, scrollback int) (string, error)

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

func ContainsMouseSequence(s string) bool

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

func CursorStyle() lipgloss.Style

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

func DetectBracketedPasteMode(output string) bool

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

func DetectMouseReportingMode(output string) bool

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

func IsSessionDeadError(err error) bool

IsSessionDeadError checks if an error indicates the tmux session/pane is gone.

func LooksLikeMouseFragment

func LooksLikeMouseFragment(s string) bool

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

func NewSession(args ...string) error

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

func NormalizeEditorName(editor string) string

NormalizeEditorName maps common aliases to their editor family.

func NormalizeToCSIu

func NormalizeToCSIu(raw []byte) string

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

func PaneSizeIndicator(paneWidth, paneHeight, shownWidth, shownHeight int) string

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) tea.Cmd

PasteClipboardToTmuxCmd returns a tea.Cmd that pastes clipboard content to a tmux session. Whether the paste is bracketed is tmux's call, not the caller's. 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

func QueryCursorPositionSync(target string) (row, col, paneHeight, paneWidth int, visible, ok bool)

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

func QueryPaneSize(target string) (width, height int, ok bool)

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

func RenderCursorLine(line string, cursorCol int, visible bool) string

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

func RenderWithCursor(content string, cursorRow, cursorCol int, visible bool) string

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 ResetScreenCompare added in v0.94.0

func ResetScreenCompare()

ResetScreenCompare clears the counters. Tests use it; production never does.

func ResizeTmuxPane

func ResizeTmuxPane(paneID string, width, height int)

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 ScreenCompareEnabled added in v0.94.0

func ScreenCompareEnabled() bool

ScreenCompareEnabled reports whether shadow comparison is on for this process.

func SendKeyToTmux

func SendKeyToTmux(sessionName, key string) error

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

func SendKeys(sessionName string, keys ...KeySpec) error

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

func SendKeysOrdered(target string, keys ...KeySpec) <-chan error

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

func SendLiteralToTmux(sessionName, text string) error

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

func SendOrdered(target string, run func() error) <-chan error

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

func SendPasteInput(sessionName, text string) error

SendPasteInput forwards paste text to the pane, letting tmux apply the target application's current bracketed-paste mode.

func SendPasteInputCmd

func SendPasteInputCmd(scope MessageScope, sessionName, text string) tea.Cmd

SendPasteInputCmd sends paste text to tmux asynchronously. Used for multi-character terminal input (not clipboard paste which is already async).

func SendPasteToTmux

func SendPasteToTmux(sessionName, text string) error

SendPasteToTmux pastes text into a pane through a uniquely named tmux buffer.

tmux, not Sidecar, decides whether the paste is bracketed: `paste-buffer -p` emits the bracketed-paste control codes only when the pane's application has actually requested that mode. That state is not exposed as a tmux format and cannot be reconstructed from a capture, so any bracketing Sidecar did itself would be a guess. `-d` drops the buffer once it has been pasted, and `-t` names the pane explicitly.

`-r` is deliberately NOT passed, although the plan for this work specified it. It disables tmux's default LF→CR translation, and a raw-mode program that has not requested bracketed paste reads CR — not LF — as "submit this line". With `-r` a multi-line paste into such a program (measured: the pane received `41 0a 42` instead of `41 0d 42`) stops submitting its lines. Line-ending behavior therefore stays exactly as it has always been; `-p` is the part that actually matters. Pinned in both directions by TestSendPasteToTmuxBracketedAndPlain.

func SendSGRMouse

func SendSGRMouse(sessionName string, button, col, row int, release bool) error

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

func SendSGRWheel(sessionName string, up bool, col, row, notches int) error

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 CaptureInput added in v0.94.0

type CaptureInput struct {
	// Output is the capture text and BaseLine its first row's absolute line
	// number, meaningful only when Absolute is set.
	Output   string
	BaseLine int
	Absolute bool

	// PaneHeight is the pane's grid height at the instant of the capture. Zero
	// means no geometry was observed, and no split is published.
	PaneHeight int

	// RowsJoined says the capture was taken with tmux's -J, which collapses each
	// wrapped line into a single row. Such a capture has no row-for-row
	// correspondence with the grid, so no split can be stated for it.
	RowsJoined bool
}

CaptureInput is one capture-pane rendering plus the geometry observed with it, as handed to CaptureSnapshot.

type CaptureRange added in v0.88.0

type CaptureRange struct {
	Output      string
	HistorySize int
	StartLine   int
	EndLine     int
}

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.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration.

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)
	// ModelPresentation permits a live byte-fed model to suppress capture for
	// ordinary output bursts. It is separate from OnModelFrame because the
	// diagnostic comparison oracle deliberately retains independent captures.
	ModelPresentation bool

	// OnModelFrame receives permanent model-backed presentation frames. Command
	// response callbacks, including capture recovery callbacks, run on the
	// client's single
	// ordered actor, which is what makes the seed cut exact. A consequence: an
	// OnSnapshot callback that blocks now backpressures the reader, so a slow
	// consumer can make tmux pause the pane or discard bytes for this client,
	// which was not possible before. No Sidecar consumer blocks in OnSnapshot,
	// but a future one must not.
	//
	// A frame is published only after a seed transaction and its post-seed
	// replay have both completed. Until then — and forever, in this slice —
	// capture/polling ownership is unchanged.
	OnModelFrame func(ModelFrame)
	// OnModelInvalid reports that the pane model needs a fresh seed or has
	// stopped. It never implies anything about the capture path.
	OnModelInvalid func(ModelInvalidation)
}

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
	// HistoryRows and PaneRows split Output into the scrolled-off rows above the
	// pane and the pane's own grid. They are counted while the capture is still
	// a line slice: once Output is joined, a blank final pane row is
	// indistinguishable from a trailing terminator, and a consumer that
	// re-derives the split loses that row and places the cursor one row too high
	// (td-d29821).
	HistoryRows   int
	PaneRows      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 a rendered screen captured in-band over a tmux control connection. It supplies bootstrap/recovery presentation and independent semantic or diagnostic evidence 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

type EditorSession struct {
	Name   string
	Editor string
}

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 HistoryInfo added in v0.94.0

type HistoryInfo struct {
	HistorySize int
	CaptureBase int
	LoadedStart int
	LoadedEnd   int
	HasHistory  bool
}

HistoryInfo is the transport-neutral absolute history state exposed to an embedding viewport. It contains coordinates only; control frames and the screen-model implementation remain private to Model.

type KeySpec

type KeySpec struct {
	Value   string
	Literal bool
}

KeySpec describes a key to send to tmux with ordering preserved.

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.

func (*KeyedScheduler) Schedule added in v0.88.0

func (s *KeyedScheduler) Schedule(key string, delay time.Duration, message func(generation int) tea.Msg) tea.Cmd

Schedule supersedes any outstanding work for key and returns a delayed command stamped with the new generation.

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

type MessageScope struct {
	Owner      uint64
	Target     string
	Generation uint64
}

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

func New(config *Config) *Model

New creates a new tty Model with the given configuration. If config is nil, DefaultConfig() is used.

func (*Model) Close added in v0.94.0

func (m *Model) Close()

Close releases the current target and rejects all queued deliveries.

func (*Model) Cursor added in v0.88.0

func (m *Model) Cursor() *tea.Cursor

Cursor returns the native cursor position relative to View().

func (*Model) Enter

func (m *Model) Enter(sessionName, paneID string) tea.Cmd

Enter enters interactive mode for the specified tmux session/pane. Returns a tea.Cmd to start polling for output.

func (*Model) Exit

func (m *Model) Exit()

Exit exits interactive mode.

func (*Model) GetTarget

func (m *Model) GetTarget() string

GetTarget returns the current tmux target (pane ID or session name).

func (*Model) History added in v0.94.0

func (m *Model) History() HistoryInfo

History returns a read-only snapshot of absolute history metadata and the currently loaded half-open range. HasHistory is false for legacy/provisional captures that do not carry trustworthy absolute coordinates.

func (*Model) IsActive

func (m *Model) IsActive() bool

IsActive returns whether interactive mode is currently active.

func (*Model) LinesAbsoluteRange added in v0.94.0

func (m *Model) LinesAbsoluteRange(start, end int) []string

LinesAbsoluteRange returns loaded terminal rows in [start, end).

func (*Model) Open added in v0.94.0

func (m *Model) Open(target Target) tea.Cmd

Open activates the terminal for target. Enter remains as the compatibility spelling for existing embedders.

func (*Model) PaneCoords added in v0.92.0

func (m *Model) PaneCoords(col, row int) (int, int, bool)

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

func (m *Model) PreferredMouseMode() tea.MouseMode

PreferredMouseMode reports the mode suitable for an active embedded terminal. Containers still own coordinate translation and mouse forwarding.

func (*Model) PrependHistory added in v0.94.0

func (m *Model) PrependHistory(content string, baseLine int) bool

PrependHistory merges an older overlapping capture into the loaded absolute buffer. Transport and scheduling remain owned by Model's embedding journey.

func (*Model) Resize added in v0.94.0

func (m *Model) Resize(width, height int) tea.Cmd

Resize is the terminal-surface spelling of SetDimensions.

func (*Model) ResizeAndPollImmediate

func (m *Model) ResizeAndPollImmediate(width, height int) tea.Cmd

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

func (m *Model) SetDimensions(width, height int) tea.Cmd

SetDimensions updates the view dimensions for resize handling.

func (*Model) SetFocused added in v0.94.0

func (m *Model) SetFocused(focused bool)

SetFocused updates focus policy for the current target.

func (*Model) SetVisible added in v0.94.0

func (m *Model) SetVisible(visible bool) tea.Cmd

SetVisible controls transport activity without destroying the target.

func (*Model) SizeIndicator added in v0.92.0

func (m *Model) SizeIndicator() string

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

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

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.

func (*Model) View

func (m *Model) View() string

View renders the interactive terminal content. Cursor ownership is exposed separately through Cursor so the containing plugin can place Bubble Tea's native cursor after applying its pane offset. Plugins should call this to render the terminal when interactive mode is active.

type ModelFrame added in v0.94.0

type ModelFrame struct {
	Session    string
	Pane       string
	Generation uint64
	// Seeds counts completed seed transactions for this subscription. A frame
	// whose Seeds differs from the previous frame's follows a resynchronization.
	Seeds int
	Frame screenmodel.Frame

	// Discarded is the last client_discarded value observed for this control
	// client, and DiscardCheckedAt is when it was observed. tmux offers no
	// notification for the counter, so it is only known at a seed and on the
	// discardProbeInterval cadence: between the last check and now, tmux may have
	// dropped bytes for this client and this frame would be built from an
	// incomplete stream with nothing in the frame to say so.
	//
	// These two fields are what makes that window discriminable rather than
	// invisible. Any consumer comparing this frame against another source (the
	// slice-2 shadow comparison) must treat a mismatch observed later than
	// DiscardCheckedAt as unattributable until the next check confirms the
	// counter did not move. See §6 of the slice-1 evidence.
	Discarded        int64
	DiscardCheckedAt time.Time
}

ModelFrame is one rendered byte-fed frame for a model-backed subscription. It is delivered only after a seed and its post-seed replay have completed.

type ModelInvalidation added in v0.94.0

type ModelInvalidation struct {
	Session    string
	Pane       string
	Generation uint64
	Reason     ResyncReason
	Terminal   bool
	Err        error
}

ModelInvalidation reports that a pane model lost presentation. Terminal invalidations end the model for that subscription; the consumer stays on the existing capture/polling path, which slice 1 never leaves in the first place.

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) ApplySnapshot added in v0.94.0

func (b *OutputBuffer) ApplySnapshot(s PaneSnapshot) bool

ApplySnapshot replaces the buffer's live tail with one observed snapshot, recording its pane split in the same critical section as its content.

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) PaneWindow added in v0.94.0

func (b *OutputBuffer) PaneWindow() (lineCount, paneTop int, ok bool)

PaneWindow reports the buffer's line count together with the index of the line holding pane row 0, both read under one lock. ok is false until a producer has stated the split, which is what a consumer needs in order to fall back to its own geometry rather than trust a stale or invented value.

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.

The content carries no pane split, so the buffer reports none. Producers that know where the live grid starts should call ApplySnapshot instead.

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) Clipped added in v0.92.0

func (f PaneFit) Clipped() bool

Clipped reports whether any part of the pane is hidden.

func (PaneFit) Letterboxed added in v0.92.0

func (f PaneFit) Letterboxed() bool

Letterboxed reports whether the pane is smaller than the viewport on either axis.

func (PaneFit) PaneCoords added in v0.92.0

func (f PaneFit) PaneCoords(relX, relY, paneWidth, paneHeight int) (col, row int, ok bool)

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).

func (PaneFit) WithWidth added in v0.92.0

func (f PaneFit) WithWidth(width int, paneWidth, cursorCol int, hasCursor bool) PaneFit

WithWidth returns the fit re-derived for a narrower display region, which is how a caller that steals a column (a scrollbar) keeps ColOffset honest.

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 PaneSnapshot added in v0.94.0

type PaneSnapshot struct {
	// Output is history rows followed by PaneRows live grid rows.
	Output string
	// BaseLine is the absolute line number of Output's first row. It is
	// meaningful only when Absolute is set.
	BaseLine int
	// Absolute says the snapshot carries trustworthy absolute coordinates, so
	// lazily loaded older history can be merged with it.
	Absolute bool
	// HistoryRows is how many of Output's leading rows sit above pane row 0, and
	// PaneRows how many trailing rows are the live grid. PaneRows of 0 means the
	// producer does not know the split; the buffer then reports no pane top and
	// consumers fall back to their own geometry.
	HistoryRows int
	PaneRows    int
}

PaneSnapshot is one atomically observed screen: history rows followed by the live pane grid, plus the split between them. The producer states the split rather than leaving it to be inferred from the content, because every way of re-deriving it downstream mixes observations taken at different instants and drifts (td-d29821).

PaneRows is also what disambiguates the serialization. Capture-shaped output is row *separated*, so a final blank row and a trailing terminator look identical once split — and the difference is exactly one grid row, the row a cursor sits on at the bottom of a screen.

func CaptureSnapshot added in v0.94.0

func CaptureSnapshot(in CaptureInput) PaneSnapshot

CaptureSnapshot describes a capture-pane rendering: PaneHeight grid rows preceded by whatever history the capture carried. It is a plain function over the capture and the geometry observed with it, so every capture-shaped producer — control snapshots, poll fallbacks, the workspace's own pollers — states the split the same way.

The invariant it rests on is that the capture's rows and the pane's rows correspond one for one, which is what makes "the last PaneHeight rows are the grid" true. A -J capture breaks it — wrapped lines arrive collapsed, so the capture has fewer rows than the grid and both halves of the split would be wrong — and RowsJoined is how a producer says so. It publishes no split rather than an authoritative wrong one; consumers then fall back to their own geometry, which is where they were before the split was carried at all.

A degenerate capture that carries fewer rows than the pane is tall has no usable split either; it is reported as all-pane, which puts pane row 0 at the top of the buffer, matching what such a capture actually shows.

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 ResyncReason added in v0.94.0

type ResyncReason uint8

ResyncReason says why a pane model needs a fresh seed, or why it stopped.

const (
	// ResyncFirstSeed is the initial bootstrap: first subscribe, Sidecar
	// restart, or a pane switch that created a new subscription.
	ResyncFirstSeed ResyncReason = iota + 1
	// ResyncReconnect is a replacement control client for the same session.
	ResyncReconnect
	// ResyncPause is %pause, or the %continue that follows it. tmux drops the
	// pane's buffered output while paused, so continuity is broken either way.
	ResyncPause
	// ResyncDiscarded is growth in the control client's client_discarded byte
	// counter: tmux dropped output because this client fell behind.
	ResyncDiscarded
	// ResyncLayout is a layout or window-pane change.
	ResyncLayout
	// ResyncResize is a Sidecar-initiated geometry change. tmux is resized
	// first and the seed reads back the authoritative resulting geometry.
	ResyncResize
	// ResyncSeedRace means pane bytes arrived between the seed transaction's
	// metadata response and its capture response, so the metadata describes an
	// older moment than the capture. Never observed against tmux 3.6b; it is
	// detected rather than assumed away.
	ResyncSeedRace
	// ResyncPaneIdentity means tmux reported a different pane id than the one
	// subscribed to. Terminal for the feed.
	ResyncPaneIdentity
	// ResyncModelFault is a malformed payload, parser error, impossible
	// geometry, or model panic. Terminal for the feed.
	ResyncModelFault
)

Resync reasons.

func (ResyncReason) String added in v0.94.0

func (r ResyncReason) String() string

type ScreenCompareSample added in v0.94.0

type ScreenCompareSample struct {
	Signature string `json:"signature"`
	Class     string `json:"class"`
	Row       int    `json:"row"`
	Col       int    `json:"col"`
}

ScreenCompareSample locates one mismatch without describing it. Coordinates and class only: a grapheme, a colour value, or a link URL would be terminal content and is never recorded.

type ScreenCompareSnapshot added in v0.94.0

type ScreenCompareSnapshot struct {
	// Model lifecycle.
	Seeds        int            `json:"seeds"`
	SeedRaces    int            `json:"seed_races"`
	Resyncs      map[string]int `json:"resyncs"`
	Faults       int            `json:"faults"`
	Fallbacks    int            `json:"fallbacks"`
	ModelsOpened int            `json:"models_opened"`
	ModelsClosed int            `json:"models_closed"`

	// Byte flow.
	RawEvents      int   `json:"raw_events"`
	RawBytes       int64 `json:"raw_bytes"`
	DiscardedBytes int64 `json:"discarded_bytes"`

	// Frames and captures.
	ModelFrames     int `json:"model_frames"`
	Captures        int `json:"captures"`
	MetadataQueries int `json:"metadata_queries"`
	// CapturesWhileModelLive is the number of capture transactions that ran at
	// a moment a live pane model already held the same screen. Under byte-fed
	// authority these are exactly the captures that would not be issued, which
	// is what the decision gate's "zero capture-pane per output burst" asks
	// about. SeedCaptures is the expected remainder.
	CapturesWhileModelLive int `json:"captures_while_model_live"`
	SeedCaptures           int `json:"seed_captures"`
	DiscardProbes          int `json:"discard_probes"`

	// Comparison outcome.
	Comparisons          int `json:"comparisons"`
	ComparisonsClean     int `json:"comparisons_clean"`
	ComparisonsAttrib    int `json:"comparisons_attributable"`
	ComparisonsOpenWin   int `json:"comparisons_in_open_discard_window"`
	ComparisonsMetaRaced int `json:"comparisons_with_capture_metadata_race"`
	// UncomparableCells counts cell differences dropped because capture-pane
	// cannot express the answer (trailing trimmed blanks). They are neither
	// agreements nor mismatches; recorded so "clean" is never overstated.
	UncomparableCells int `json:"uncomparable_cells"`
	// ComparedCells is the total visible surface offered to the comparator
	// (width × height per comparison). It is the denominator UncomparableCells
	// has to be read against; without it an absolute count of declined cells
	// says nothing about how much of the screen was actually covered.
	ComparedCells int64 `json:"compared_cells"`
	// ComparisonsSkipped counts comparisons abandoned because the capture side
	// described no surface. They are not clean and not mismatched.
	ComparisonsSkipped int `json:"comparisons_skipped"`

	// Mismatches, split the way the decision gate is judged.
	MismatchesBySignature map[string]int `json:"mismatches_by_signature"`
	MismatchesByClass     map[string]int `json:"mismatches_by_class"`
	// FramesWithMismatch counts comparisons (not cells) that had at least one
	// mismatch, so one corrupted row does not read as hundreds of failures.
	FramesWithMismatch            int                   `json:"frames_with_mismatch"`
	FramesWithUnexplainedMismatch int                   `json:"frames_with_unexplained_mismatch"`
	Samples                       []ScreenCompareSample `json:"samples"`

	// Timing, in microseconds, and memory, in bytes.
	OutputToFrameUS   latencyStat `json:"output_to_frame_us"`
	OutputToCaptureUS latencyStat `json:"output_to_capture_us"`
	ModelWriteUS      latencyStat `json:"model_write_us"`
	ModelRenderUS     latencyStat `json:"model_render_us"`
	CompareUS         latencyStat `json:"compare_us"`
	ModelBytesPeak    int64       `json:"model_bytes_peak"`
	ModelBytesLast    int64       `json:"model_bytes_last"`

	Started time.Time `json:"started"`
}

ScreenCompareSnapshot is the counter payload, separated from its mutex so a reader can copy and marshal it.

type ScreenCompareStats added in v0.94.0

type ScreenCompareStats struct {
	ScreenCompareSnapshot
	// contains filtered or unexported fields
}

ScreenCompareStats is the privacy-safe diagnostic counter set the plan's "Rollback and observability" section requires. A zero value is usable.

func ScreenCompare added in v0.94.0

func ScreenCompare() *ScreenCompareStats

ScreenCompare returns the process-wide shadow-comparison counters.

func (*ScreenCompareStats) JSON added in v0.94.0

func (s *ScreenCompareStats) JSON() []byte

JSON renders the counters. The output is safe to attach to a report: by construction it contains no terminal content.

func (*ScreenCompareStats) Report added in v0.94.0

func (s *ScreenCompareStats) Report() string

Report renders the decision-gate evidence as markdown.

func (*ScreenCompareStats) Snapshot added in v0.94.0

Snapshot returns a copy safe to read and marshal.

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

	// 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.

type Target added in v0.94.0

type Target struct {
	Session string
	Pane    string
}

Target identifies the tmux session and pane displayed by a Model.

Directories

Path Synopsis
Package screenmodel owns Sidecar's byte-fed pane screen model.
Package screenmodel owns Sidecar's byte-fed pane screen model.

Jump to

Keyboard shortcuts

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