Documentation
¶
Overview ¶
Package tmux manages the tmux sessions that drive each agent.
A TmuxSession wraps one tmux session: start, attach, detach, capture pane content for prompt detection, and cleanup. Loom's session names are prefixed with TmuxPrefix ("loom_"); LegacyTmuxPrefix ("claudesquad_") is still recognized so that sessions created before the rebrand are renamed on startup by RenameLegacySessions and swept by the orphan-cleanup path.
Platform-specific code is split across tmux_unix.go and tmux_windows.go. The PTY factory is pluggable via PtyFactory so tests can inject a fake PTY without touching real file descriptors; see NewTmuxSessionWithDeps for the injectable constructor.
Index ¶
- Constants
- func CleanupSessions(cmdExec internalexec.Executor) error
- func EmulatorEnabled() bool
- func RenameLegacySessions(titles []string, cmdExec internalexec.Executor)
- func SetNotifier(n Notifier)
- func TerminalSessionName(title string) string
- func ToLegacyTmuxName(str string) string
- func ToLoomTmuxName(str string) string
- type Notifier
- type Pty
- type PtyFactory
- type TmuxSession
- func (t *TmuxSession) CaptureAndProcess() (content string, updated bool, hasPrompt bool, trustHandled bool, err error)
- func (t *TmuxSession) CaptureHistory() (string, bool)
- func (t *TmuxSession) CapturePaneContent() (string, error)
- func (t *TmuxSession) CheckAndHandleTrustPrompt() bool
- func (t *TmuxSession) Close() error
- func (t *TmuxSession) CloseRelatedSession(rawName string) error
- func (t *TmuxSession) CursorState() (vt.Cursor, bool)
- func (t *TmuxSession) DoesSessionExist() bool
- func (t *TmuxSession) ForwardFocus(in bool) error
- func (t *TmuxSession) ForwardMouse(cb, col, row int, press bool) error
- func (t *TmuxSession) ForwardWheel(up bool, n int) error
- func (t *TmuxSession) FullScreenAttachCmd() *exec.Cmd
- func (t *TmuxSession) GetContentHash() []byte
- func (t *TmuxSession) HasEmulator() bool
- func (t *TmuxSession) HasUpdated() (updated bool, hasPrompt bool)
- func (t *TmuxSession) IsAlternateScreen() bool
- func (t *TmuxSession) PaneTitle() (string, bool)
- func (t *TmuxSession) Paste(text string) error
- func (t *TmuxSession) PausePreview() error
- func (t *TmuxSession) PtmxAlive() bool
- func (t *TmuxSession) RenderEmulator() (string, bool)
- func (t *TmuxSession) Restore() error
- func (t *TmuxSession) ResumePreview() error
- func (t *TmuxSession) SendKeys(keys string) error
- func (t *TmuxSession) SendKeysRaw(b []byte) error
- func (t *TmuxSession) SessionName() string
- func (t *TmuxSession) SetCmdExecForTest(cmdExec internalexec.Executor)
- func (t *TmuxSession) SetDetachedSize(width, height int) error
- func (t *TmuxSession) SetEmulatorForTest(emu vt.Emulator)
- func (t *TmuxSession) SimulateStuckPumpForTest()
- func (t *TmuxSession) Start(workDir string) (err error)
- func (t *TmuxSession) TapDAndEnter() error
- func (t *TmuxSession) TapEnter() error
Constants ¶
const ( ProgramClaude = "claude" ProgramAider = "aider" ProgramGemini = "gemini" )
ProgramClaude, ProgramAider, and ProgramGemini are the canonical program identifiers for the built-in agents. They match the literal command names (no path or flags). Per-program behavior — trust-prompt and pending-prompt detection — is resolved through the session/agent registry, which matches on the basename of the program's first token so paths and launch flags don't defeat the lookup.
const LegacyTmuxPrefix = "claudesquad_"
LegacyTmuxPrefix is the tmux session prefix used before the rename from claude-squad to loom. Still recognized by orphan-sweep logic and by the startup rename pass so in-flight sessions survive the upgrade transparently.
const TmuxPrefix = "loom_"
TmuxPrefix is the tmux session-name prefix applied to every Loom session. Orphan sweeps and session lookup rely on this prefix to distinguish Loom-owned sessions from sessions owned by other tools sharing the user's tmux server.
Variables ¶
This section is empty.
Functions ¶
func CleanupSessions ¶
func CleanupSessions(cmdExec internalexec.Executor) error
CleanupSessions kills all Loom-owned tmux sessions — both the current loom_ prefix and the legacy claudesquad_ prefix, so `loom reset` also clears sessions created before the rename.
func EmulatorEnabled ¶ added in v0.8.0
func EmulatorEnabled() bool
EmulatorEnabled reports whether panes render from the in-process emulator — i.e. whether the event-driven update path (pane dirty/quiet/dead events) is available. False selects the legacy tick-polled snapshot path.
func RenameLegacySessions ¶
func RenameLegacySessions(titles []string, cmdExec internalexec.Executor)
RenameLegacySessions renames any tmux sessions matching the legacy claudesquad_* prefix to their loom_* equivalent so that in-flight sessions from a pre-rename binary continue to be found by reconcile on the next startup.
Called from Storage.LoadAndReconcile immediately before that storage's per-record reconcile pass — once per storage, so in multi-tab restore it runs once per slot over that slot's titles. Idempotent: on later launches the legacy sessions are gone and the loop is a no-op.
Rename failures are logged at debug rather than swallowed. The common causes (no such legacy session, unreachable tmux server) are harmless, but a genuine collision — both claudesquad_<t> and loom_<t> exist, so tmux refuses the rename — would otherwise leave the legacy session alive and unrenamed, which the orphan sweep (CleanupOrphanedSessions) then kills. The log makes that diagnosable.
func SetNotifier ¶ added in v0.8.0
func SetNotifier(n Notifier)
SetNotifier installs the process-wide pane-event notifier. Called once at app startup (and with the zero value to tear down). A package-level hook — rather than per-session constructor plumbing — because ui/terminal.go creates its own TmuxSessions outside app's reach.
func TerminalSessionName ¶ added in v0.6.0
TerminalSessionName returns the raw (pre-ToLoomTmuxName) tmux session name for the terminal pane belonging to the instance with the given title. Centralized here so session.Instance can tear this session down by name — without depending on ui.TerminalPane — and ui/terminal.go can construct the identical name when creating it.
func ToLegacyTmuxName ¶
ToLegacyTmuxName returns the pre-rename tmux session name for a given instance title. Used only by RenameLegacySessions at startup; no production code path should depend on this name otherwise.
func ToLoomTmuxName ¶
ToLoomTmuxName returns the canonical tmux session name for a given instance title under the current prefix.
Types ¶
type Notifier ¶ added in v0.8.0
type Notifier struct {
// Output fires when a pane emitted output, coalesced to at most one
// event per dirtyCoalesceInterval per session (leading + trailing edge).
Output func(session string)
// Quiet fires once when a pane has emitted nothing for quietDelay after
// a burst — the app runs status/prompt detection on settled content.
Quiet func(session string)
// Bell fires when the pane's emulator receives BEL. Never coalesced.
Bell func(session string)
// Dead fires when the output pump exits on a genuine read error (PTY
// EOF/close) — NOT on deliberate stops (Close/Restore/PausePreview).
Dead func(session string)
}
Notifier carries the app's sinks for pump-driven pane events. All funcs are optional (nil = dropped). They are invoked from pump/timer goroutines, so implementations must be goroutine-safe — in practice each one wraps tea.Program.Send, which is designed for exactly this.
type Pty ¶
type Pty struct{}
Pty is the production PtyFactory implementation. It wraps github.com/creack/pty so every new tmux session gets a real PTY that tmux can drive with terminal control sequences.
func (Pty) Close ¶
func (pt Pty) Close()
Close is a no-op for the production factory — each PTY is owned by its caller, not by the factory.
func (Pty) Start ¶
Start allocates a PTY, launches cmd attached to it, and returns the master file descriptor. The caller closes the returned file when the session ends. The child is reaped in the background: no caller retains cmd, so without the Wait every tmux client subprocess would linger as a zombie for the life of the Loom process.
type PtyFactory ¶
type PtyFactory interface {
// Start launches cmd attached to a freshly-allocated PTY and returns
// the controlling file descriptor. Ownership transfers to the caller,
// who must Close the returned file when done.
Start(cmd *exec.Cmd) (*os.File, error)
// Close releases any factory-level resources. The default Pty has none,
// but a mock factory may use it to flush recorded state.
Close()
}
PtyFactory abstracts creation of a pseudo-terminal for the tmux subprocess so tests can inject a scripted fake instead of opening a real PTY device. The production implementation is Pty; tests supply a stub that records invocations and returns a synthetic *os.File.
func MakePtyFactory ¶
func MakePtyFactory() PtyFactory
MakePtyFactory returns the production PtyFactory. Call sites that need a fake for tests should construct one inline rather than shadowing this function.
type TmuxSession ¶
type TmuxSession struct {
// contains filtered or unexported fields
}
TmuxSession is a managed tmux session bound to a single instance. The zero value is not usable — construct via NewTmuxSession (or NewTmuxSessionWithDeps in tests) so the PTY factory and executor are wired up. One TmuxSession owns exactly one tmux session and one detached-mode PTY. The ptmx and monitor fields are touched from two goroutines — the metadata fan-out (CaptureAndProcess/HasUpdated/keystroke injection) and the Update loop's attach lifecycle (Restore/PausePreview/ Close) — so both are guarded by stateMu (see its doc).
func NewTmuxSession ¶
func NewTmuxSession(name string, program string, env ...string) *TmuxSession
NewTmuxSession constructs a TmuxSession wired to the production PTY factory and subprocess executor. The tmux session is NOT created at this point — call Start (for a fresh session) or Restore (to attach to one that already exists on disk). env, if given, is a set of "KEY=VALUE" pairs applied to the tmux session via `new-session -e`.
func NewTmuxSessionWithDeps ¶
func NewTmuxSessionWithDeps(name string, program string, ptyFactory PtyFactory, cmdExec internalexec.Executor, env ...string) *TmuxSession
NewTmuxSessionWithDeps is NewTmuxSession with injected dependencies for tests. Pass a fake PtyFactory and internalexec.Executor to avoid spawning real subprocesses or allocating real PTYs.
func (*TmuxSession) CaptureAndProcess ¶
func (t *TmuxSession) CaptureAndProcess() (content string, updated bool, hasPrompt bool, trustHandled bool, err error)
CaptureAndProcess captures pane content once and runs both trust prompt and update detection checks, avoiding duplicate CapturePaneContent calls. Returns a non-nil err when the pane capture itself failed — callers must surface this instead of treating zero values as "no change", which used to hide tmux failures as a frozen UI.
func (*TmuxSession) CaptureHistory ¶ added in v0.3.0
func (t *TmuxSession) CaptureHistory() (string, bool)
CaptureHistory returns the full pane buffer — scrollback history plus the visible screen — as physical rows with ANSI escapes, via capture-pane -S -. Returns ("", false) on error. This is tmux's AUTHORITATIVE scrollback: the in-process emulator only ever sees the visible screen from the tmux client stream (tmux paints clients with redraws, not scroll-through history), so the windowed scroll-back must be sourced here rather than from emu.Scrollback().
func (*TmuxSession) CapturePaneContent ¶
func (t *TmuxSession) CapturePaneContent() (string, error)
CapturePaneContent captures the content of the tmux pane
func (*TmuxSession) CheckAndHandleTrustPrompt ¶
func (t *TmuxSession) CheckAndHandleTrustPrompt() bool
CheckAndHandleTrustPrompt checks the pane content once for a trust prompt and dismisses it if found. Returns true if the prompt was found and handled.
func (*TmuxSession) Close ¶
func (t *TmuxSession) Close() error
Close terminates the tmux session and cleans up resources
func (*TmuxSession) CloseRelatedSession ¶ added in v0.6.0
func (t *TmuxSession) CloseRelatedSession(rawName string) error
CloseRelatedSession best-effort kills another tmux session identified by its raw (pre-ToLoomTmuxName) name, reusing this session's cmdExec. It does not touch t's own PTY/emulator state.
This exists so a resource whose lifecycle is tied to this session (e.g. the terminal pane's shell, which shares this instance's title but is otherwise untracked by *TmuxSession) can be torn down at the same point this session is — without the caller needing its own injected executor. The common case is "no such session", which is expected and harmless.
func (*TmuxSession) CursorState ¶ added in v0.8.0
func (t *TmuxSession) CursorState() (vt.Cursor, bool)
CursorState returns the pane's live cursor (position, visibility, shape, blink) from the in-process emulator, or ok=false when no emulator is wired (snapshot/Windows path — those panes show no cursor).
func (*TmuxSession) DoesSessionExist ¶
func (t *TmuxSession) DoesSessionExist() bool
DoesSessionExist reports whether the backing tmux session is still alive on the tmux server. Used as a sanity check before attach and for orphan detection during reconcile.
func (*TmuxSession) ForwardFocus ¶ added in v0.8.0
func (t *TmuxSession) ForwardFocus(in bool) error
ForwardFocus writes a focus-in (CSI I) or focus-out (CSI O) event into the pane's PTY — but only when the inner app enabled focus reporting (mode 1004). No-op (nil) otherwise: apps that never asked must not receive it.
func (*TmuxSession) ForwardMouse ¶ added in v0.3.0
func (t *TmuxSession) ForwardMouse(cb, col, row int, press bool) error
ForwardMouse writes one SGR mouse event into the attach PTY so a focused TUI agent receives a click/drag/release at (col,row), 1-indexed. cb is the SGR button code (0=left, +32 = motion/drag, 64/65 = wheel up/down); press=true emits the 'M' (press) final byte, false emits 'm' (release).
func (*TmuxSession) ForwardWheel ¶ added in v0.3.0
func (t *TmuxSession) ForwardWheel(up bool, n int) error
ForwardWheel writes n mouse-wheel events (up or down) into the attach PTY, so a full-screen TUI agent scrolls its OWN view — the alternate screen has no tmux scrollback to window. This is the same path full-screen attach uses to deliver real mouse input to the app: tmux forwards the client's mouse bytes to the mouse-aware foreground app. Writing in-process (no `tmux send-keys` subprocess per notch) keeps rapid wheel scrolling smooth. All n notches go in one write, using SGR mouse encoding at the pane's top-left.
func (*TmuxSession) FullScreenAttachCmd ¶
func (t *TmuxSession) FullScreenAttachCmd() *exec.Cmd
FullScreenAttachCmd returns a command that attaches to this tmux session in the foreground. It's intended to be handed to tea.ExecProcess, which releases and restores the terminal around the call so the child tmux owns the real tty for the duration of the attach. Detach is driven by the C-q key binding installed during Start (see bind-key call).
func (*TmuxSession) GetContentHash ¶
func (t *TmuxSession) GetContentHash() []byte
GetContentHash returns the last computed content hash from HasUpdated or CaptureAndProcess. Returns nil if no hash has been computed yet.
func (*TmuxSession) HasEmulator ¶ added in v0.8.0
func (t *TmuxSession) HasEmulator() bool
HasEmulator reports whether this session renders through the in-process emulator (event-driven path) or the legacy capture-pane snapshot path.
func (*TmuxSession) HasUpdated ¶
func (t *TmuxSession) HasUpdated() (updated bool, hasPrompt bool)
HasUpdated checks if the tmux pane content has changed since the last tick. It also returns true if the tmux pane has a prompt for aider or claude code.
func (*TmuxSession) IsAlternateScreen ¶ added in v0.3.0
func (t *TmuxSession) IsAlternateScreen() bool
IsAlternateScreen reports whether the pane's foreground app is on the alternate screen (a full-screen TUI like Claude), which keeps NO tmux scrollback. Callers use this to decide whether scroll-back can be windowed from CaptureHistory or must instead be forwarded into the app itself.
func (*TmuxSession) PaneTitle ¶ added in v0.8.0
func (t *TmuxSession) PaneTitle() (string, bool)
PaneTitle returns the inner app's OSC-set window title, or ok=false when no emulator is wired, no title was ever set, or the title is invalid UTF-8. The last case guards a known vendored charmbracelet/x/vt parser bug that can truncate a title mid multi-byte rune (e.g. Claude Code's "✳ ..." status) — better to fall back to the instance title than forward a mangled byte sequence into the host terminal's own title escape sequence.
func (*TmuxSession) Paste ¶ added in v0.3.0
func (t *TmuxSession) Paste(text string) error
Paste writes text to the attach PTY wrapped in bracketed-paste markers (ESC[200~ … ESC[201~), so the focused agent treats it as a paste rather than typed input. No-op for empty text.
func (*TmuxSession) PausePreview ¶
func (t *TmuxSession) PausePreview() error
PausePreview closes the detached preview PTY and waits for its pump to exit. Call this immediately before tea.ExecProcess hands the tty to a foreground `tmux attach-session`, so there are no stray readers on the session during the attach. ResumePreview re-opens the PTY afterwards.
func (*TmuxSession) PtmxAlive ¶ added in v0.7.0
func (t *TmuxSession) PtmxAlive() bool
PtmxAlive reports whether a PTY is currently attached. This is distinct from DoesSessionExist: the tmux session can be alive on the server while this is false — e.g. Restore's reattach failed (attach-session errored after the prior ptmx was already cleared) or a full-screen attach has PausePreview'd this session and not yet resumed. Callers that want to self-heal a dead-ptmx-but-alive-session instance should re-run Restore; callers checking during a legitimate PausePreview window must not.
func (*TmuxSession) RenderEmulator ¶ added in v0.3.0
func (t *TmuxSession) RenderEmulator() (string, bool)
RenderEmulator returns the current visible screen from the in-process emulator as an ANSI-styled string, or ("", false) if no emulator is wired (callers then fall back to CapturePaneContent).
func (*TmuxSession) Restore ¶
func (t *TmuxSession) Restore() error
Restore attaches to an existing session and restores the window size. It starts a background pump goroutine that drains PTY output to prevent buffer deadlock (the tmux client blocks on stdout when the buffer fills, which also blocks stdin processing).
func (*TmuxSession) ResumePreview ¶
func (t *TmuxSession) ResumePreview() error
ResumePreview reopens the detached preview PTY after a full-screen attach returns control. It is a thin wrapper around Restore kept as a named method for clarity at the call sites in app.Update.
func (*TmuxSession) SendKeys ¶
func (t *TmuxSession) SendKeys(keys string) error
SendKeys writes the given string to the tmux PTY as raw bytes. Unlike SendKeysRaw, callers pass a Go string rather than a byte slice; no escaping or translation is performed.
func (*TmuxSession) SendKeysRaw ¶
func (t *TmuxSession) SendKeysRaw(b []byte) error
SendKeysRaw writes raw bytes directly to the tmux PTY.
func (*TmuxSession) SessionName ¶ added in v0.8.0
func (t *TmuxSession) SessionName() string
SessionName returns the sanitized tmux session name — the identity carried by pane events (Notifier callbacks) and used by the app to route them.
func (*TmuxSession) SetCmdExecForTest ¶ added in v0.6.0
func (t *TmuxSession) SetCmdExecForTest(cmdExec internalexec.Executor)
SetCmdExecForTest swaps this session's executor after construction, so a test can assert on the commands issued by methods (like Close or CloseRelatedSession) that a fixture built via NewTmuxSessionWithDeps already exercises for other purposes. Test-only: the name and doc comment are guardrails, nothing about the method enforces test-only use.
func (*TmuxSession) SetDetachedSize ¶
func (t *TmuxSession) SetDetachedSize(width, height int) error
SetDetachedSize set the width and height of the session while detached. This makes the tmux output conform to the specified shape.
func (*TmuxSession) SetEmulatorForTest ¶ added in v0.8.0
func (t *TmuxSession) SetEmulatorForTest(emu vt.Emulator)
SetEmulatorForTest wires an emulator directly, bypassing Restore's attach lifecycle. Test-only: the name and doc comment are guardrails, nothing about the method enforces test-only use.
func (*TmuxSession) SimulateStuckPumpForTest ¶
func (t *TmuxSession) SimulateStuckPumpForTest()
SimulateStuckPumpForTest replaces any live pump state with a live channel nobody closes, modeling a pathological case where the pump goroutine has wedged (stuck ptmx.Read, platform-specific Close that doesn't interrupt a blocked Read, etc.). Lifecycle methods that previously bare-waited on pumpDone would have hung indefinitely; with waitPumpExit in place they now return within pumpWaitTimeout. Test-only: the name and doc comment are guardrails, nothing about the method enforces test-only use.
func (*TmuxSession) Start ¶
func (t *TmuxSession) Start(workDir string) (err error)
Start creates and starts a new tmux session, then attaches to it. Program is the command to run in the session (ex. claude). workdir is the git worktree directory.
func (*TmuxSession) TapDAndEnter ¶
func (t *TmuxSession) TapDAndEnter() error
TapDAndEnter sends 'D' followed by an enter keystroke to the tmux pane.
func (*TmuxSession) TapEnter ¶
func (t *TmuxSession) TapEnter() error
TapEnter sends an enter keystroke to the tmux pane.