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
- Variables
- func CheckNesting(getenv func(string) string, enclosing func() (string, error), server string) error
- func CheckNestingFromEnv(server string) error
- func Command(ctx context.Context, args ...string) *exec.Cmd
- func CommandOnSocket(ctx context.Context, socket string, args ...string) *exec.Cmd
- func EmulatorEnabled() bool
- func EnclosingSessionName() (string, error)
- func ExactlyTargetable(name string) bool
- func IsOption(selected, option string) bool
- func PaneTarget(name string) string
- func RenameLegacySessions(titles []string, cmdExec internalexec.Executor)
- func ResolveServer() (string, error)
- func SameServer(a, b string) bool
- func SelectedOption(content string) (string, bool)
- func ServerRunning(path string) bool
- func SessionTarget(name string) string
- func SetLivenessProbeTimeoutForTest(d time.Duration) (restore func())
- func SetNotifier(n Notifier)
- func Socket() string
- func TerminalSessionName(title string) string
- func ToLegacyTmuxName(str string) string
- func ToLoomTmuxName(str string) string
- func UseServer(path string)
- type Liveness
- type NestedError
- type Notifier
- type Pty
- type PtyFactory
- type Session
- func NewSession(name, program string, env ...string) *Session
- func NewSessionNamed(name, program string) *Session
- func NewSessionNamedWithDeps(name, program string, ptyFactory PtyFactory, cmdExec internalexec.Executor) *Session
- func NewSessionWithDeps(name, program string, ptyFactory PtyFactory, cmdExec internalexec.Executor, ...) *Session
- func (s *Session) AnswerTrustPrompt() error
- func (s *Session) AnswersTrustPrompt() bool
- func (s *Session) CaptureHistory() (string, bool)
- func (s *Session) CapturePaneContent() (string, error)
- func (s *Session) Close() error
- func (s *Session) CloseRelatedSession(rawName string) error
- func (s *Session) DoesSessionExist() bool
- func (s *Session) Env() []string
- func (s *Session) FullScreenAttachCmd() *exec.Cmd
- func (s *Session) IsAlternateScreen() bool
- func (s *Session) PressKeys(keys ...string) error
- func (s *Session) Program() string
- func (s *Session) SendPrompt(prompt string) error
- func (s *Session) SessionLiveness() Liveness
- func (s *Session) SessionName() string
- func (s *Session) SetCmdExecForTest(cmdExec internalexec.Executor)
- func (s *Session) Start(workDir string) (err error)
- func (s *Session) StartDir() (dir string, found bool, err error)
- func (s *Session) TrustPromptChoice(pattern string) string
- func (s *Session) TrustPromptShown(content string) string
- func (s *Session) TypeText(text string) error
- func (s *Session) WithProgram(program string) *Session
- func (s *Session) WithProgramEnv(program string, env []string) *Session
- type TmuxSession
- func NewAttachClient(sessionName, program string) *TmuxSession
- func NewAttachClientWithDeps(sessionName, program string, ptyFactory PtyFactory, ...) *TmuxSession
- func NewTmuxSession(name string, program string, env ...string) *TmuxSession
- func NewTmuxSessionWithDeps(name string, program string, ptyFactory PtyFactory, ...) *TmuxSession
- func (t *TmuxSession) Attached() bool
- func (t *TmuxSession) CaptureAndProcess() (content string, updated bool, hasPrompt bool, err error)
- func (t *TmuxSession) Close() error
- func (t *TmuxSession) CursorState() (vt.Cursor, bool)
- func (t *TmuxSession) DetectStatus() (updated, hasPrompt bool, err error)
- 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) GetContentHash() []byte
- func (t *TmuxSession) HasEmulator() bool
- func (t *TmuxSession) HasUpdated() (updated bool, hasPrompt 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) RenderWindow(offset, rows int) (string, bool)
- func (t *TmuxSession) Restore() error
- func (t *TmuxSession) ResumePreview() error
- func (t *TmuxSession) ScrollbackLen() (int, bool)
- func (t *TmuxSession) SeedHistory() []string
- func (t *TmuxSession) SendKeys(keys string) error
- func (t *TmuxSession) SendKeysRaw(b []byte) error
- 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) 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 EnvAllowNested = "LOOM_ALLOW_NESTED"
EnvAllowNested bypasses CheckNesting when set to "1".
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.
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 ¶
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
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
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
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
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
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
IsOption reports whether selected (SelectedOption) is option, by text: a number before it ("2. ") and spacing aside.
func PaneTarget ¶ added in v0.13.0
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
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
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
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
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
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
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
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. 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 ¶
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
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
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
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
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
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
CapturePaneContent captures the content of the tmux pane
func (*Session) Close ¶ added in v0.14.0
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
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
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
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
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
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
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
Program returns the command line the session was launched with.
func (*Session) SendPrompt ¶ added in v0.14.0
SendPrompt types prompt into the session and submits it with Enter.
func (*Session) SessionLiveness ¶ added in v0.14.0
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
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
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
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
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
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
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
WithProgram is WithProgramEnv with s's own env carried over.
func (*Session) WithProgramEnv ¶ added in v0.14.0
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.