tmux

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: AGPL-3.0 Imports: 22 Imported by: 0

README

session/tmux

Tmux session management: launching, probing and killing sessions for lifecycle, the attach clients the TUI renders panes through, the output pump and its event coalescer, and the one place tmux is invoked. Session names carry the prefix loom_ (tmux.TmuxPrefix); claudesquad_ (tmux.LegacyTmuxPrefix, LegacyTmuxPrefix) is still recognized by the orphan sweep and the startup rename pass (RenameLegacySessions).

Files

File Holds
command.go (session/tmux/command.go) tmux.Command, tmux.CommandOnSocket, tmuxCommand, UseServer, ResolveServer, ServerRunning, SameServer, EnclosingSessionName
target.go (session/tmux/target.go) tmux.SessionTarget, tmux.PaneTarget, ToLoomTmuxName, ExactlyTargetable
session.go Session: launch, probes, capture-pane, TrustPromptShown/TrustPromptChoice/AnswerTrustPrompt, SelectedOption/IsOption, TypeText/SendPrompt/PressKeys, AnswersTrustPrompt, WithProgramEnv, NewSessionNamed, NewSessionNamedWithDeps, NewSessionWithDeps
tmux.go TmuxSession, the attach client: Restore, PausePreview, Close, the output pump, stateMu, ForwardMouse, Attached, PtmxAlive, statusContent, PaneTitle, NewTmuxSessionWithDeps, ToLegacyTmuxName, RenameLegacySessions
attach.go NewAttachClient, NewAttachClientWithDeps, DetectStatus
notify.go the per-session coalescer and tmux.SetNotifier
nesting.go CheckNestingFromEnv, the nesting guard's tmux half
emulator_unix.go, emulator_windows.go the embedded VT emulator per platform, gated by LOOM_PANE_RENDERER
pty.go PtyFactory

Sessions and attach clients

Session (session.go) is a session as lifecycle sees it: Start launches without attaching and Close kills. It also covers liveness probes, capture-pane, the trust-prompt primitives (AnswersTrustPrompt, TrustPromptShown, TrustPromptChoice, AnswerTrustPrompt, and SelectedOption/IsOption for a menu's cursor), and input with no client: TypeText/SendPrompt send text through load-buffer + paste-buffer -d -r (raw bytes in one paste, with no length limit), never send-keys -l, which tmux refuses past about 16 KiB ("command too long") and which treats a trailing ; as a command separator even after --; PressKeys sends key names through send-keys. TestTypeTextMatchesPTYWrite_RealTmux pins both against a write to an attach client's PTY, byte for byte, including the trailing-; and over-16-KiB cases.

Trust prompts are the daemon's. An agent may stop at a trust prompt right after it launches. Core's launch watch (core/launch_watch.go) builds a Session by name (NewSessionNamedWithDeps, on the model's executor), skips an agent with nothing to answer (AnswersTrustPrompt: the adapter has trust-prompt patterns and keys), captures the pane and answers each prompt it shows once: the adapter's keys (AnswerTrustPrompt), or, for a prompt with a choice (TrustPromptChoice), Down until SelectedOption reads the choice, then Enter. Nothing in a TmuxSession (an attach client) answers one: CaptureAndProcess and DetectStatus only read the pane (TestDetectStatus_LeavesTheTrustPromptToTheDaemon), since two answerers would send a second Enter into whatever the agent shows next.

TmuxSession (tmux.go) embeds a Session and is an attach client: Close detaches it and then kills the session, while PausePreview only detaches it, which is how the TUI releases a client. NewAttachClient (attach.go) builds an unattached client for a session it did not start, by name, which Restore then attaches. NewTmuxSession plus Start both launch and attach, and only the terminal pane's shells use that path.

A started program's environment is the session's own (-e), plus the variables tmux's update-environment option lists (SSH_AUTH_SOCK, DISPLAY, …) as the starting process has them, plus the tmux server's global environment, which is that of whatever started the server (Session.Start): an agent's update-environment variables are the daemon's, the terminal pane's shells' the TUI's, and everything else (the credential overrides, the default account's CLAUDE_CONFIG_DIR, PATH) the server's.

Every loom session sets detach-on-destroy on, through Session.Start and, for a session an older loom launched, through Restore. Under a global off, tmux switches a destroyed session's clients to another session instead of ending them, so a client keyed by the dead session's name would show, and take inline-attach keys for, another agent's pane, and never read EOF. With it on, an agent that exits during a full-screen attach drops the user back to loom, and a user's own terminal attached to a loom session detaches when that session dies (TestKilledSessionsClientExits_RealTmux).

A client is usable only while TmuxSession.Attached holds: its PTY is open and the pump draining it has not hit EOF on its own. Each pump owns its exit flag (pumpDone), set after its Dead notification returns, so a late old pump can't mark a newer attach dead (TestAttached_LateOldPumpExitLeavesTheNewAttach). PtmxAlive stays true after that EOF and only says there is a handle to close. On creack/pty the attach fd is blocking, so the read deadline signalPumpStop sets can't cut the pump's read short: closing a client of a still-live session waits the full pumpWaitTimeout (waitPumpExit), while a dead session's client closes at once.

Output pump, emulator and status

The pump writes ptmx output through vt.NewAltScreenFilter into an embedded VT emulator (emulator_unix.go/emulator_windows.go, gated by LOOM_PANE_RENDERER), so panes render from the emulator with a capture-pane fallback, and ForwardMouse and bracketed paste back interact mode. tmux clients enter the alternate screen at attach and never leave it, and x/vt only accumulates scrollback on the primary screen, so the filter strips the alt-screen mode switches. Restore seeds pre-attach history once per attach (capture-pane -S - -E -1, stored as SeedHistory); the TUI's ui.ScrollModel windows seed, emulator scrollback and screen through the emulator's RenderWindow/ScrollbackLen.

TmuxSession.stateMu guards the ptmx/monitor/emulator fields of a tmux.TmuxSession against the race between status scans off the TUI's Update goroutine (statusDetectCmd, snapshotScan) and the attach lifecycle. The pump also drives the event-based UI: a per-session coalescer (notify.go) emits dirty (rate-limited), quiet (after output settles), bell, and dead notifications through the package-level tmux.SetNotifier hook, which app.Run wires to tea.Program.Send. Status detection (statusContent) reads the emulator in-process; capture-pane remains only as the snapshot path's fallback. Prompt detection (TmuxSession.DetectStatus, attach.go) surfaces a Prompting status and sends nothing to the pane.

Commands, servers and targets

Every tmux invocation goes through tmux.Command or tmux.CommandOnSocket (command.go). Command targets the server tmux.UseServer pinned (-S <path>), else LOOM_TMUX_SOCKET's (-L); CommandOnSocket's explicit socket outranks the pin. The daemon pins the server it resolved at start (daemon.TmuxServer) and each TUI the one the daemon's hello names (peer.Tmux), so every process reaches the agents where the daemon runs them, whatever its own environment says. A raw tmux exec (exec.Command("tmux", …)) would follow $TMUX to whatever server encloses the process.

Both pass -u. tmux prints a non-UTF-8 command-line client's output through utf8_sanitize, which turns every byte outside printable ASCII into _ (tabs, escapes, non-ASCII paths), and a client is UTF-8 only when $TMUX is set (even empty) or LC_ALL/LC_CTYPE/LANG names UTF-8. Without -u, a loom started outside tmux under no UTF-8 locale (a service, a bare SSH login, the Nix build sandbox) read #{session_name}\t#{session_path} as one name, and the held-name guard, finding no session of its name, killed another workspace's (TestCommand_ListingSurvivesANonUTF8Client_RealTmux). So argv starts tmux -u [-S path | -L sock] <sub> (tmuxCommand).

Every target is exact, built by tmux.SessionTarget or tmux.PaneTarget (target.go). A bare -t name falls back to a prefix match when no session has exactly that name, and loom's sessions die on their own all the time, so a command aimed at a dead loom_api lands on a live loom_api-v2: closing it killed the sibling (TestKillIsExactMatch_RealTmux), and Restore/ResumePreview attached the dead session's preview PTY to it, sending every keystroke, paste and initial prompt to the other agent (TestDeadSessionNeverReachesPrefixSibling_RealTmux; likewise FullScreenAttachCmd, the captures, and RenameLegacySessions, which renamed claudesquad_api-v2). Session-typed commands (attach-session, has-session, kill-session, rename-session, switch-client) take "-t", SessionTarget(name) (=name); pane- and window-typed ones (capture-pane, display-message, send-keys, paste-buffer, set-option, resize-window, list-panes) take "-t", PaneTarget(name) (=name:). Plain =name fails there ("can't find pane: =loom_x"; set-option says "no such session"), while =name: works and fails cleanly on a missing session (display-message then prints empty formats and exits 0).

Session names never hold : or .: ToLoomTmuxName/ToLegacyTmuxName drop whitespace and map both to _, because tmux creates loom_fix:login literally but every target parses : and . as its session:window.pane separators (-t=loom_fix:login asks for window login of loom_fix). A title like "fix: login" used to probe Dead until Start timed out, Close could not kill it, and the failed-start cleanup removed the worktree under the running agent (TestColonTitle_StartsProbesAliveAndCloses_RealTmux). Titles differing only in those characters share a session name; the second Start fails with "already exists". A name that still holds one (made by an older loom, or another tool) cannot be targeted exactly at all (-t=loom_feat:0 kills loom_feat), so the orphan sweep skips it (tmux.ExactlyTargetable).

Tests

  • Dependency injection: cmd.Executor for subprocesses and tmux.PtyFactory for PTYs; NewSessionWithDeps(), NewAttachClientWithDeps() and NewTmuxSessionWithDeps() accept mock dependencies.
  • argv starts tmux -u [-S …|-L …], so mocks dispatch on cmd_test.TmuxSubcommand(argv) (cmd/cmd_test/testutils.go), never argv[1], or their assert.Empty checks pass vacuously.
  • TestNoRawTmuxExec fails the build on a raw tmux exec outside command.go, which it exempts whole (EnclosingSessionName there is the deliberate raw exec); it matches only the identifier exec and an interpreted "tmux" literal, so an aliased os/exec import or a raw-string literal escapes it; TestTmuxTargetsAreExact fails on a production "-t" not followed by one of the two target helpers, and on a target spelled inline ("-t="+name, fmt.Sprintf("-t=%s", …)), with an allow-list holding only EnclosingSessionName's $TMUX_PANE pane id. They live in command_enforce_test.go and target_enforce_test.go.
  • Real-tmux tests call privateTmux(t, tag) (realtmux_helpers_test.go): a fresh private server killed when the test ends, $TMUX cleared, and a short TMUX_TMPDIR so the socket path stays under the 104/108-byte sun_path cap. TestMain unsets LOOM_TMUX_SOCKET, since argv-exact mock assertions assume the default server.

Documentation

Overview

Package tmux manages the tmux sessions that drive each agent.

A tmux session is handled in two halves. A Session is the session as lifecycle sees it: it launches the session without attaching, probes its liveness, captures pane content, types into it through tmux commands (load-buffer + paste-buffer for text, send-keys for keys) and kills it. It owns no PTY. A TmuxSession embeds a Session and is an attach client: a PTY attached to the session, an output pump feeding an embedded terminal emulator, and the status scan that reads its screen. session.Instance holds only a Session; the TUI attaches its own clients by session name (NewAttachClient). The terminal pane's shells are the one place a TmuxSession both launches and attaches its session.

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 NewSessionWithDeps, NewAttachClientWithDeps and NewTmuxSessionWithDeps for the injectable constructors.

Index

Constants

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

View Source
const EnvAllowNested = "LOOM_ALLOW_NESTED"

EnvAllowNested bypasses CheckNesting when set to "1".

View Source
const EnvTmuxSocket = "LOOM_TMUX_SOCKET"

EnvTmuxSocket names the environment variable that points every loom tmux invocation at a private server via `tmux -L <name>`. Unset (or empty) keeps tmux's own server selection: $TMUX when running inside tmux, else the default socket.

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

View Source
var ErrSessionExists = errors.New("tmux session already exists")

ErrSessionExists is Start's refusal to create a session whose name is already taken. Nothing was launched: the caller's workdir was never handed to a program.

Functions

func CheckNesting added in v0.13.0

func CheckNesting(getenv func(string) string, enclosing func() (string, error), server string) error

CheckNesting returns a *NestedError when the process runs inside a loom-managed tmux session (loom_* or claudesquad_*) on server, the tmux server (its socket's path) the process is about to pin and manage. The enclosing server is the one $TMUX names (its first comma-separated field), compared with SameServer. What LOOM_TMUX_SOCKET names decides nothing: a daemon keeps the last daemon's server while that server runs, whatever its own environment selects (daemon.TmuxServer), so a dev loom run in a loom pane with a private socket set would otherwise start the user's daemon on the user's server. A loomdev sandbox passes on its own: its global dir is its own, and so is its server. A lookup that fails on that server (a timeout under load) fails closed, as replaceGuard does: the session may be one of loom's.

func CheckNestingFromEnv added in v0.13.0

func CheckNestingFromEnv(server string) error

CheckNestingFromEnv is CheckNesting wired to the process environment and the real enclosing-session lookup, for the tmux server server.

func Command added in v0.13.0

func Command(ctx context.Context, args ...string) *exec.Cmd

Command builds a tmux invocation bound to ctx on the server UseServer pinned, else the one LOOM_TMUX_SOCKET selects. Every tmux exec in loom goes through Command or CommandOnSocket (TestNoRawTmuxExec enforces it): an explicit -S or -L outranks $TMUX, which is what keeps a dev build started inside a loom pane from sweeping the host's sessions.

func CommandOnSocket added in v0.13.0

func CommandOnSocket(ctx context.Context, socket string, args ...string) *exec.Cmd

CommandOnSocket is Command with an explicit socket name, which outranks UseServer's pin; "" selects the default server. The caller's args slice is never modified.

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. It reads this process's LOOM_PANE_RENDERER: a TUI's for its own panes, the daemon's for the model's tick (core's tickInterval).

func EnclosingSessionName added in v0.13.0

func EnclosingSessionName() (string, error)

EnclosingSessionName returns the name of the tmux session this process runs inside, asking the server named by $TMUX (pinned to $TMUX_PANE when set). It deliberately ignores LOOM_TMUX_SOCKET — the question is about the enclosing server, not the one loom would manage — which is why it lives in the one file allowed to exec tmux directly.

func ExactlyTargetable added in v0.13.0

func ExactlyTargetable(name string) bool

ExactlyTargetable reports whether SessionTarget and PaneTarget can name the session called name. A name holding ':' or '.' cannot be targeted exactly: "=loom_feat:0" names window 0 of "loom_feat". Every name ToLoomTmuxName produces is targetable; a session some older loom (or another tool) created may not be, and must then be left alone.

func IsOption added in v0.14.0

func IsOption(selected, option string) bool

IsOption reports whether selected (SelectedOption) is option, by text: a number before it ("2. ") and spacing aside.

func PaneTarget added in v0.13.0

func PaneTarget(name string) string

PaneTarget returns the -t value naming the current window and active pane of the session called name, and nothing else, for pane- and window-typed commands: capture-pane, display-message, send-keys, paste-buffer, set-option, resize-window, list-panes. SessionTarget does not work there: tmux reads a colon-free target as a window or pane and fails with "can't find pane: =loom_x". The trailing ':' makes "=name" the session part. A missing session fails cleanly.

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) may then kill. The log makes that diagnosable.

func ResolveServer added in v0.14.0

func ResolveServer() (string, error)

ResolveServer is the socket path of the tmux server this process's environment selects, as tmux itself resolves it: LOOM_TMUX_SOCKET's socket in tmux's socket dir; else the server $TMUX names (its first comma-separated field), inside tmux; else the default socket in tmux's socket dir. The socket dir is tmux-<uid> in $TMUX_TMPDIR when that is absolute, else in /tmp. The daemon pins the answer (UseServer) and publishes it, so its clients reach its server whatever their own environment says.

func SameServer added in v0.14.0

func SameServer(a, b string) bool

SameServer reports whether two tmux socket paths name one server: equal once cleaned, or once their symlinks are resolved (tmux resolves its socket dir, so $TMUX can name /private/tmp where a daemon resolved /tmp).

func SelectedOption added in v0.14.0

func SelectedOption(content string) (string, bool)

SelectedOption returns the option content's selection menu marks with its cursor (menuCursor): the rest of the one line holding the marker, without escapes, surrounding spaces or a box's border. It reports false when no line holds the marker, or more than one does: there is no telling which option is selected then.

func ServerRunning added in v0.14.0

func ServerRunning(path string) bool

ServerRunning reports whether a tmux server answers at the socket path: one with sessions, since a server exits with its last. A probe that times out says yes: a server too loaded to answer is still there.

func SessionTarget added in v0.13.0

func SessionTarget(name string) string

SessionTarget returns the -t value naming the session called name, and nothing else, for session-typed commands: attach-session, has-session, kill-session, rename-session, switch-client. A missing session is an error ("can't find session"), never a sibling.

func SetLivenessProbeTimeoutForTest added in v0.13.0

func SetLivenessProbeTimeoutForTest(d time.Duration) (restore func())

SetLivenessProbeTimeoutForTest shortens (or lengthens) the has-session probe's deadline, so a test can make a probe go unanswered without waiting out the real 5s, and returns a func restoring the previous one. Test-only: the name and doc comment are guardrails, nothing about the function enforces test-only use. Not safe to call while probes run.

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 Socket added in v0.13.0

func Socket() string

Socket returns the private tmux socket name from LOOM_TMUX_SOCKET, or "" for the default server. It is read on every call so tests can t.Setenv it.

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. The result never holds ':' or '.', so SessionTarget and PaneTarget can always name it exactly.

func UseServer added in v0.14.0

func UseServer(path string)

UseServer pins every later Command to the tmux server whose socket is path (`tmux -S path`), whatever LOOM_TMUX_SOCKET and $TMUX say; "" lifts the pin. The loom daemon pins the server it resolved at start (ResolveServer), and a TUI the one the daemon names in its hello: which server a process reaches otherwise depends on its environment, and a daemon started from another (an ssh login without $TMUX_TMPDIR, say) would see every agent's session dead and start it again on its own.

Types

type Liveness added in v0.13.0

type Liveness int

Liveness is the outcome of a tmux session liveness probe.

const (
	// LivenessDead means tmux answered and the session is not there.
	LivenessDead Liveness = iota
	// LivenessAlive means tmux answered and the session exists.
	LivenessAlive
	// LivenessUnknown means the probe never got an answer, so the state
	// is simply not known. Callers must not treat this as death.
	LivenessUnknown
)

type NestedError added in v0.13.0

type NestedError struct {
	// Session is the enclosing loom-managed tmux session.
	Session string
	// Lookup is why the enclosing session, on that server, could not be
	// named (Session is then ""): it may be one of loom's.
	Lookup error
}

NestedError reports that a loom process that sweeps tmux sessions (the daemon, reset) was started inside one of loom's own tmux sessions, on the very server it would manage.

func (*NestedError) Error added in v0.13.0

func (e *NestedError) Error() string

Error implements error.

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

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. 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 Session added in v0.14.0

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

Session is one tmux session on the server as session lifecycle sees it: launched, probed, typed into and killed through tmux commands. It never attaches a client (no PTY, output pump or emulator), so a process that holds only Sessions renders no pane and takes no part in the window-size negotiation between attached clients. TmuxSession embeds one and adds the attach client the TUI renders from.

func NewSession added in v0.14.0

func NewSession(name, program string, env ...string) *Session

NewSession returns the Session for the instance titled name, wired to the production PTY factory and executor. Nothing runs until Start. env, if given, is applied to the session via `new-session -e`.

func NewSessionNamed added in v0.14.0

func NewSessionNamed(name, program string) *Session

NewSessionNamed is NewSession for a name that is already a loom tmux session name (Session.SessionName's, as a client that holds only the name carries it): the name is used as it is, where NewSession would prefix and sanitize it again. The TUI's full-screen attach and liveness probe use it, so they reach the session by name rather than through an instance.

func NewSessionNamedWithDeps added in v0.14.0

func NewSessionNamedWithDeps(name, program string, ptyFactory PtyFactory, cmdExec internalexec.Executor) *Session

NewSessionNamedWithDeps is NewSessionNamed with injected dependencies: the daemon's launch watch (core) reaches a session by name with the model's executor, which its tests replace.

func NewSessionWithDeps added in v0.14.0

func NewSessionWithDeps(name, program string, ptyFactory PtyFactory, cmdExec internalexec.Executor, env ...string) *Session

NewSessionWithDeps is NewSession with injected dependencies, so tests never spawn tmux or allocate a PTY.

func (*Session) AnswerTrustPrompt added in v0.14.0

func (s *Session) AnswerTrustPrompt() error

AnswerTrustPrompt sends the adapter's keys for a trust prompt answered as shown (TrustPromptResponse), through send-keys.

func (*Session) AnswersTrustPrompt added in v0.14.0

func (s *Session) AnswersTrustPrompt() bool

AnswersTrustPrompt reports whether the session's agent has a trust prompt AnswerTrustPrompt can answer: patterns to find it by and keys to answer it with. The fallback adapter (a shell, an unknown program) has neither, so there is nothing to watch its launch for.

func (*Session) CaptureHistory added in v0.14.0

func (s *Session) 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. Only the no-emulator path (snapshot mode / Windows) windows this; the emulator path windows SeedHistory plus the emulator's own scrollback (ui.ScrollModel).

func (*Session) CapturePaneContent added in v0.14.0

func (s *Session) CapturePaneContent() (string, error)

CapturePaneContent captures the content of the tmux pane

func (*Session) Close added in v0.14.0

func (s *Session) Close() error

Close kills the tmux session by exact name (see SessionTarget). Close runs on sessions that may already be dead, so with a prefix match, closing "api" after its agent exited would kill a live "api-v2".

func (*Session) CloseRelatedSession added in v0.14.0

func (s *Session) CloseRelatedSession(rawName string) error

CloseRelatedSession best-effort kills another tmux session identified by its raw (pre-ToLoomTmuxName) name, reusing this session's cmdExec. It leaves s's own tmux session alone.

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 not otherwise tracked by session lifecycle) 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 (*Session) DoesSessionExist added in v0.14.0

func (s *Session) DoesSessionExist() bool

DoesSessionExist reports whether the session is known to be alive on the tmux server. Used as a sanity check before attach and for orphan detection during reconcile. An inconclusive probe reads as false here, preserving the original semantics for callers that only gate reads on it; callers that act destructively on a negative should use SessionLiveness instead.

func (*Session) Env added in v0.14.0

func (s *Session) Env() []string

Env returns a clone of the tmux session environment this session was constructed with — the "KEY=VALUE" entries applied via `new-session -e` (see NewSession). Read-only: env is set once at construction (or by WithProgram/WithProgramEnv building a new session) and never mutated afterward; the clone means a caller mutating the result cannot corrupt it.

func (*Session) FullScreenAttachCmd added in v0.14.0

func (s *Session) 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 (*Session) IsAlternateScreen added in v0.14.0

func (s *Session) 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 (*Session) PressKeys added in v0.14.0

func (s *Session) PressKeys(keys ...string) error

PressKeys presses keys in order, each given as a tmux key name ("Enter", "D", "C-c"). An empty list runs nothing.

func (*Session) Program added in v0.14.0

func (s *Session) Program() string

Program returns the command line the session was launched with.

func (*Session) SendPrompt added in v0.14.0

func (s *Session) SendPrompt(prompt string) error

SendPrompt types prompt into the session and submits it with Enter.

func (*Session) SessionLiveness added in v0.14.0

func (s *Session) SessionLiveness() Liveness

SessionLiveness probes whether the tmux session exists, distinguishing "tmux said no" from "tmux never answered". The distinction matters: the probe is a subprocess, and under heavy load it can be killed at its deadline while the session is perfectly healthy. Collapsing that into a plain false is what let one loaded machine mark every running session Paused at once.

func (*Session) SessionName added in v0.14.0

func (s *Session) SessionName() string

SessionName returns the tmux session name. It is the identity pane events (Notifier callbacks) carry and the key the TUI's pane clients use.

func (*Session) SetCmdExecForTest added in v0.14.0

func (s *Session) 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 NewSessionWithDeps or NewTmuxSessionWithDeps already exercises for other purposes. Test-only: the name and doc comment are guardrails, nothing about the method enforces test-only use.

func (*Session) Start added in v0.14.0

func (s *Session) Start(workDir string) (err error)

Start creates the tmux session, running program in workDir, and sets the options every client attached to it relies on: scroll-back history, mouse, no status line, and C-q to detach a full-screen attach. It attaches nothing; TmuxSession.Start does that for a caller that renders the session itself. If a session of the same name is already alive, Start refuses with ErrSessionExists before launching anything. Any other error may come after the program was launched, so the caller must not assume it is not running in workDir (see SessionLiveness).

The program's environment is the tmux server's global environment, the variables its update-environment option lists (SSH_AUTH_SOCK, DISPLAY, SSH_CONNECTION, …) as the process calling Start has them, and s.env. The caller's environment decides only the update-environment variables; everything else not in s.env (ANTHROPIC_API_KEY and the other credential overrides, the default account's CLAUDE_CONFIG_DIR, PATH, …) comes from the global environment, which is the environment of whatever started the tmux server. Since daemon stage 3B an agent's caller is the daemon (loom serve), spawned by whichever loom first needed it: a TUI attached later, or from another terminal or SSH session, changes nothing an agent sees. The global environment is the daemon's only when the daemon started the server; on a server the user started, or an earlier daemon did (the next keeps it), it is that starter's. The terminal pane's shells are started by the TUI, and their update-environment variables are its own.

func (*Session) StartDir added in v0.14.0

func (s *Session) StartDir() (dir string, found bool, err error)

StartDir lists the server's sessions and returns the directory this session was started in (session_path: the -c directory of its new-session, which a cd in the pane does not change); found is false when no session has its name. err is the listing's failure, no server running included. A session's name is unique per server, not per workspace, so the directory is what says whose session holds the name.

func (*Session) TrustPromptChoice added in v0.14.0

func (s *Session) TrustPromptChoice(pattern string) string

TrustPromptChoice returns the option the trust prompt found by pattern (TrustPromptShown) is answered with by moving its menu's cursor onto it (SelectedOption), or "" when AnswerTrustPrompt's keys answer it as shown. A prompt with a choice must never get those keys: they confirm whatever its menu selects, which may be "No, exit".

func (*Session) TrustPromptShown added in v0.14.0

func (s *Session) TrustPromptShown(content string) string

TrustPromptShown returns the adapter's trust-prompt pattern that content (the pane's screen) shows, the first in the adapter's order, or "" when it shows none or the adapter has no keys to answer one with. It sends nothing: a caller watching a pane tells one prompt from the next by it.

func (*Session) TypeText added in v0.14.0

func (s *Session) TypeText(text string) error

TypeText types text into the session's active pane: it loads text into a fresh paste buffer (`load-buffer`, text on stdin) and pastes that buffer into the pane (`paste-buffer -d -r`), which deletes it. The program receives exactly text's raw bytes, in one paste that no other input can interleave with: the same bytes a write to an attach client's PTY delivers (TestTypeTextMatchesPTYWrite_RealTmux), with no client needed. -r keeps LF as LF instead of turning it into CR, and without -p tmux adds no bracketed-paste markers. Empty text runs nothing.

Not `send-keys -l -- text`, for two reasons. tmux refuses any command over about 16 KiB ("command too long"), and an issue-born prompt carries the whole issue body. It also parses an argument ending in ';' as a command separator even after "--", so "abc;" types "abc". Text on stdin is never parsed and has no such limit.

func (*Session) WithProgram added in v0.14.0

func (s *Session) WithProgram(program string) *Session

WithProgram is WithProgramEnv with s's own env carried over.

func (*Session) WithProgramEnv added in v0.14.0

func (s *Session) WithProgramEnv(program string, env []string) *Session

WithProgramEnv returns a new, unstarted Session for the same tmux session that runs program with env in place of s's program and env. It keeps s's PTY factory and executor and resolves its adapter from program, as NewSession does. s itself is unchanged: the caller Closes s and Starts the result. Instance.Restart uses it to relaunch a dead session with a freshly composed command and a freshly resolved env, since the account's CLAUDE_CONFIG_DIR in particular may have changed since s was built.

type TmuxSession

type TmuxSession struct {
	*Session
	// contains filtered or unexported fields
}

TmuxSession is an attach client of one tmux session. It holds a PTY running `tmux attach-session`, an output pump draining it, and (on the emulator path) an in-process emulator mirroring its screen, plus the embedded Session for the session itself. The TUI renders every pane from one. Session lifecycle holds only a Session and never attaches. The zero value is not usable: construct via NewTmuxSession or NewAttachClient (or their WithDeps variants in tests). Its fields are touched off the TUI's Update goroutine: the TUI's status scans (DetectStatus, run in a Cmd on a pane's quiet event and, on the snapshot path, at each health tick) read the emulator and update monitor, and a client release (PausePreview in a Cmd) closes ptmx, while the Update loop's attach lifecycle (Restore/PausePreview/Close) reassigns or closes them. They are therefore guarded by stateMu (see its doc). Input written to its PTY (SendKeys, SendKeysRaw, TapEnter, Paste, the Forward* methods) is the interactive path, while the promoted TypeText, PressKeys and SendPrompt go through tmux commands and need no attach.

func NewAttachClient added in v0.14.0

func NewAttachClient(sessionName, program string) *TmuxSession

NewAttachClient returns an unattached client for the existing session named sessionName, which the TUI then Restores. sessionName is already a tmux session name, as Session.SessionName returns, not a title. program only selects the agent adapter for the client's status scan (DetectStatus); a client launches nothing. Since session lifecycle never attaches, this is how the TUI gets into a session lifecycle launched.

func NewAttachClientWithDeps added in v0.14.0

func NewAttachClientWithDeps(sessionName, program string, ptyFactory PtyFactory, cmdExec internalexec.Executor) *TmuxSession

NewAttachClientWithDeps is NewAttachClient with injected dependencies, for tests.

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) Attached added in v0.14.0

func (t *TmuxSession) Attached() bool

Attached reports whether this client is attached and still reading its session: a PTY is open (PtmxAlive) and the output pump draining it has not stopped on its own. A pump stops on its own when a read fails with no stop requested, at EOF once the session or its tmux client is gone. PtmxAlive still reads true then, and a client that went by it would keep showing a dead session's last screen, even after a new session of the same name has started. Whoever decides whether a client is usable (the TUI's pane registry) asks this instead; Restore re-attaches a client that is not.

func (*TmuxSession) CaptureAndProcess

func (t *TmuxSession) CaptureAndProcess() (content string, updated bool, hasPrompt bool, err error)

CaptureAndProcess captures pane content once and runs both the pending prompt and update detection checks, avoiding duplicate CapturePaneContent calls. It sends nothing to the pane: trust prompts are the daemon's to answer (its launch watch, core's watchLaunch), so a TUI scanning a pane never types into it. 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) Close

func (t *TmuxSession) Close() error

Close detaches this client (PTY, output pump, emulator) and then kills the session (Session.Close).

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) DetectStatus added in v0.14.0

func (t *TmuxSession) DetectStatus() (updated, hasPrompt bool, err error)

DetectStatus scans the pane's current screen once for the status ladder. It reports whether the screen changed since the last scan and whether it shows the agent's pending-input prompt. It sends nothing to the pane: the daemon answers trust prompts (core's launch watch). An agent with no adapter patterns gets only the change check. err reports a failed capture on the snapshot path; it never means "no change".

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) 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) 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 handle is currently open. 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. It stays true after the pump hit EOF, so it says only that there is a handle to close; whether the client still reads its session is Attached.

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) RenderWindow added in v0.13.0

func (t *TmuxSession) RenderWindow(offset, rows int) (string, bool)

RenderWindow renders `rows` lines ending `offset` lines above the live bottom from the emulator's scrollback + screen; ok=false without an emulator.

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) ScrollbackLen added in v0.13.0

func (t *TmuxSession) ScrollbackLen() (int, bool)

ScrollbackLen returns the emulator's scrollback line count; ok=false on the snapshot path (no emulator).

func (*TmuxSession) SeedHistory added in v0.13.0

func (t *TmuxSession) SeedHistory() []string

SeedHistory returns the pre-attach history rows captured at the last Restore. Callers must treat the slice as immutable.

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

Start launches the session (Session.Start) and attaches this client to it. The terminal pane starts its shells this way. Agent sessions are different: session.Instance launches one through its own Session, and the TUI then attaches a client to it by name (NewAttachClient).

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