tmux

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: AGPL-3.0 Imports: 16 Imported by: 0

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

View Source
const (
	ProgramClaude = "claude"
	ProgramAider  = "aider"
	ProgramGemini = "gemini"
)

ProgramClaude, ProgramAider, and ProgramGemini are the canonical program identifiers used by trust-prompt detection and adapter lookup. They match the literal command names (no path or flags); per-program behavior is keyed off these constants in CheckAndHandleTrustPrompt and the session/agent registry.

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

View Source
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 tmux sessions that start with "session-"

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 TerminalSessionName added in v0.6.0

func TerminalSessionName(title string) string

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

func ToLegacyTmuxName(str string) string

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

func ToLoomTmuxName(str string) string

ToLoomTmuxName returns the canonical tmux session name for a given instance title under the current prefix.

Types

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

func (pt Pty) Start(cmd *exec.Cmd) (*os.File, error)

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.

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

Jump to

Keyboard shortcuts

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