| 1 | package tmux |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "strings" |
| 10 | "time" |
| 11 | "unicode/utf8" |
| 12 | ) |
| 13 | |
| 14 | // defaultTimeout is the timeout for tmux commands. These are local IPC calls |
| 15 | // to the tmux server and should complete almost instantly. |
| 16 | const defaultTimeout = 5 * time.Second |
| 17 | |
| 18 | // SocketEnv holds the shared server's socket path for a process klaus starts |
| 19 | // with $TMUX removed: a worker, and everything it runs. klaus's own tmux calls |
| 20 | // there reach the server with -S; tmux itself never reads it, so a worker's |
| 21 | // bare `tmux kill-server` misses the server every agent's pane is on. |
| 22 | const SocketEnv = "KLAUS_TMUX_SOCKET" |
| 23 | |
| 24 | // InSession returns true if we're currently inside a tmux session. |
| 25 | func InSession() bool { |
| 26 | return os.Getenv("TMUX") != "" |
| 27 | } |
| 28 | |
| 29 | // SocketPath is the socket of the server klaus's tmux calls reach: the one |
| 30 | // $TMUX names, cut at the first comma as tmux reads it, or else the one in |
| 31 | // SocketEnv. "" means tmux's default. |
| 32 | func SocketPath() string { |
| 33 | if t := os.Getenv("TMUX"); t != "" { |
| 34 | path, _, _ := strings.Cut(t, ",") |
| 35 | return path |
| 36 | } |
| 37 | return os.Getenv(SocketEnv) |
| 38 | } |
| 39 | |
| 40 | // serverArgs aims a tmux call at SocketPath. $TMUX wins: a process in a pane |
| 41 | // belongs to that pane's server (a test's private one, say), whatever |
| 42 | // SocketEnv it inherited, and tmux finds that server on its own. |
| 43 | func serverArgs() []string { |
| 44 | if os.Getenv("TMUX") == "" { |
| 45 | if sock := os.Getenv(SocketEnv); sock != "" { |
| 46 | return []string{"-S", sock} |
| 47 | } |
| 48 | } |
| 49 | return nil |
| 50 | } |
| 51 | |
| 52 | // SplitWindow creates a new tmux pane by splitting vertically. |
| 53 | // Returns the new pane ID. The command runs in the specified dir. |
| 54 | // targetPane specifies which pane to split (e.g. from $TMUX_PANE). |
| 55 | func SplitWindow(ctx context.Context, targetPane, dir, command string) (string, error) { |
| 56 | args := []string{ |
| 57 | "split-window", |
| 58 | "-t", targetPane, |
| 59 | "-v", "-d", |
| 60 | "-P", "-F", "#{pane_id}", |
| 61 | "-c", dir, |
| 62 | command, |
| 63 | } |
| 64 | out, err := runTmux(ctx, args...) |
| 65 | if err != nil { |
| 66 | return "", fmt.Errorf("split-window: %w", err) |
| 67 | } |
| 68 | return out, nil |
| 69 | } |
| 70 | |
| 71 | // SplitWindowSized creates a new tmux pane with a specified size. |
| 72 | // orientation is "-v" for top/bottom or "-h" for left/right. |
| 73 | // size is passed to tmux's -l flag (e.g. "30%" or "15"). |
| 74 | func SplitWindowSized(ctx context.Context, targetPane, dir, command, orientation, size string) (string, error) { |
| 75 | args := []string{ |
| 76 | "split-window", |
| 77 | "-t", targetPane, |
| 78 | orientation, "-d", |
| 79 | "-l", size, |
| 80 | "-P", "-F", "#{pane_id}", |
| 81 | "-c", dir, |
| 82 | command, |
| 83 | } |
| 84 | out, err := runTmux(ctx, args...) |
| 85 | if err != nil { |
| 86 | return "", fmt.Errorf("split-window: %w", err) |
| 87 | } |
| 88 | return out, nil |
| 89 | } |
| 90 | |
| 91 | // detachedWidth and detachedHeight size the detached agents session. Nobody |
| 92 | // watches these panes, but capture-pane (klaus logs) reads what they rendered, |
| 93 | // so they get a roomy window rather than tmux's 80x24 default. |
| 94 | const ( |
| 95 | detachedWidth = "200" |
| 96 | detachedHeight = "50" |
| 97 | ) |
| 98 | |
| 99 | // SessionExists reports whether a tmux session with exactly this name exists. |
| 100 | func SessionExists(ctx context.Context, session string) bool { |
| 101 | _, err := runTmux(ctx, "has-session", "-t", "="+session) |
| 102 | return err == nil |
| 103 | } |
| 104 | |
| 105 | // NewDetachedWindow creates a window running command in the named detached |
| 106 | // session, creating that session if it does not exist yet. Returns the new |
| 107 | // pane ID. The command runs in dir. |
| 108 | func NewDetachedWindow(ctx context.Context, session, window, dir, command string) (string, error) { |
| 109 | if !SessionExists(ctx, session) { |
| 110 | out, err := runTmux(ctx, |
| 111 | "new-session", "-d", "-s", session, "-n", window, |
| 112 | "-x", detachedWidth, "-y", detachedHeight, |
| 113 | "-c", dir, "-P", "-F", "#{pane_id}", command) |
| 114 | if err == nil { |
| 115 | return out, nil |
| 116 | } |
| 117 | // Concurrent launches race here: another one may have created the |
| 118 | // session between the check and now. Only that is recoverable. |
| 119 | if !SessionExists(ctx, session) { |
| 120 | return "", fmt.Errorf("new-session: %w", err) |
| 121 | } |
| 122 | } |
| 123 | out, err := runTmux(ctx, |
| 124 | "new-window", "-t", session+":", "-n", window, "-d", |
| 125 | "-c", dir, "-P", "-F", "#{pane_id}", command) |
| 126 | if err != nil { |
| 127 | return "", fmt.Errorf("new-window: %w", err) |
| 128 | } |
| 129 | return out, nil |
| 130 | } |
| 131 | |
| 132 | // SessionPanes returns the pane IDs in the named session, or an error if the |
| 133 | // session does not exist. |
| 134 | func SessionPanes(ctx context.Context, session string) ([]string, error) { |
| 135 | out, err := runTmux(ctx, "list-panes", "-s", "-t", "="+session, "-F", "#{pane_id}") |
| 136 | if err != nil { |
| 137 | return nil, fmt.Errorf("list-panes: %w", err) |
| 138 | } |
| 139 | var panes []string |
| 140 | for _, line := range strings.Split(out, "\n") { |
| 141 | if s := strings.TrimSpace(line); s != "" { |
| 142 | panes = append(panes, s) |
| 143 | } |
| 144 | } |
| 145 | return panes, nil |
| 146 | } |
| 147 | |
| 148 | // KillSession kills a tmux session by name. |
| 149 | func KillSession(ctx context.Context, session string) error { |
| 150 | _, err := runTmux(ctx, "kill-session", "-t", "="+session) |
| 151 | return err |
| 152 | } |
| 153 | |
| 154 | // SetPaneTitle sets the title of a tmux pane. |
| 155 | // Uses select-pane -T which correctly handles titles with spaces, |
| 156 | // unlike set-option -p pane-title which breaks in tmux 3.6+. |
| 157 | func SetPaneTitle(ctx context.Context, paneID, title string) error { |
| 158 | _, err := runTmux(ctx, "select-pane", "-t", paneID, "-T", title) |
| 159 | return err |
| 160 | } |
| 161 | |
| 162 | // LockPaneTitle prevents applications in the pane from overriding the title. |
| 163 | func LockPaneTitle(ctx context.Context, paneID string) error { |
| 164 | _, err := runTmux(ctx, "set-option", "-p", "-t", paneID, "allow-rename", "off") |
| 165 | return err |
| 166 | } |
| 167 | |
| 168 | // RebalanceLayout rebalances the pane layout for the window containing targetPane. |
| 169 | func RebalanceLayout(ctx context.Context, targetPane string) error { |
| 170 | if targetPane == "" { |
| 171 | return fmt.Errorf("targetPane cannot be empty") |
| 172 | } |
| 173 | _, err := runTmux(ctx, "select-layout", "-t", targetPane, "even-vertical") |
| 174 | return err |
| 175 | } |
| 176 | |
| 177 | // SwapPane swaps two tmux panes. |
| 178 | func SwapPane(ctx context.Context, src, dst string) error { |
| 179 | _, err := runTmux(ctx, "swap-pane", "-s", src, "-t", dst) |
| 180 | return err |
| 181 | } |
| 182 | |
| 183 | // ListWindowPanes returns the pane IDs for the window containing targetPane, in layout order (top to bottom). |
| 184 | func ListWindowPanes(ctx context.Context, targetPane string) ([]string, error) { |
| 185 | out, err := runTmux(ctx, "list-panes", "-t", targetPane, "-F", "#{pane_id}") |
| 186 | if err != nil { |
| 187 | return nil, fmt.Errorf("list-panes: %w", err) |
| 188 | } |
| 189 | var panes []string |
| 190 | for _, line := range strings.Split(out, "\n") { |
| 191 | line = strings.TrimSpace(line) |
| 192 | if line != "" { |
| 193 | panes = append(panes, line) |
| 194 | } |
| 195 | } |
| 196 | return panes, nil |
| 197 | } |
| 198 | |
| 199 | // PaneExists checks if a tmux pane is still alive. |
| 200 | func PaneExists(ctx context.Context, paneID string) bool { |
| 201 | out, err := runTmux(ctx, "list-panes", "-a", "-F", "#{pane_id}") |
| 202 | if err != nil { |
| 203 | return false |
| 204 | } |
| 205 | for _, line := range strings.Split(out, "\n") { |
| 206 | if strings.TrimSpace(line) == paneID { |
| 207 | return true |
| 208 | } |
| 209 | } |
| 210 | return false |
| 211 | } |
| 212 | |
| 213 | // PaneStartedWith reports whether a live pane on the server was started |
| 214 | // with a command that contains s. A server that isn't running has no such |
| 215 | // pane; any other failure to ask is an error. |
| 216 | func PaneStartedWith(ctx context.Context, s string) (bool, error) { |
| 217 | out, err := runTmux(ctx, "list-panes", "-a", "-F", "#{pane_dead} #{pane_start_command}") |
| 218 | if err != nil { |
| 219 | if msg := err.Error(); strings.Contains(msg, "no server running") || strings.Contains(msg, "error connecting to") { |
| 220 | return false, nil |
| 221 | } |
| 222 | return false, err |
| 223 | } |
| 224 | for _, line := range strings.Split(out, "\n") { |
| 225 | dead, cmd, _ := strings.Cut(line, " ") |
| 226 | if dead != "1" && strings.Contains(cmd, s) { |
| 227 | return true, nil |
| 228 | } |
| 229 | } |
| 230 | return false, nil |
| 231 | } |
| 232 | |
| 233 | // CapturePane captures the visible content of a pane. |
| 234 | // history controls how many lines of scrollback to include. |
| 235 | func CapturePane(ctx context.Context, paneID string, history int) (string, error) { |
| 236 | histStr := fmt.Sprintf("-%d", history) |
| 237 | return runTmux(ctx, "capture-pane", "-t", paneID, "-p", "-S", histStr) |
| 238 | } |
| 239 | |
| 240 | // KillPane kills a tmux pane. |
| 241 | func KillPane(ctx context.Context, paneID string) error { |
| 242 | _, err := runTmux(ctx, "kill-pane", "-t", paneID) |
| 243 | return err |
| 244 | } |
| 245 | |
| 246 | // SetWindowOption sets a tmux window option for the window containing target pane. |
| 247 | func SetWindowOption(ctx context.Context, target, option, value string) error { |
| 248 | _, err := runTmux(ctx, "set-option", "-w", "-t", target, option, value) |
| 249 | return err |
| 250 | } |
| 251 | |
| 252 | // RenameWindow renames the tmux window containing the target pane. |
| 253 | func RenameWindow(ctx context.Context, target, name string) error { |
| 254 | _, err := runTmux(ctx, "rename-window", "-t", target, name) |
| 255 | return err |
| 256 | } |
| 257 | |
| 258 | // PaneIsDead checks if a tmux pane's command has exited. |
| 259 | // Only returns true when remain-on-exit is set and the process is gone. |
| 260 | func PaneIsDead(ctx context.Context, paneID string) bool { |
| 261 | out, err := runTmux(ctx, "display-message", "-t", paneID, "-p", "#{pane_dead}") |
| 262 | return err == nil && strings.TrimSpace(out) == "1" |
| 263 | } |
| 264 | |
| 265 | // PaneIsIdle checks if a tmux pane's command has finished running. |
| 266 | // Returns true when the pane is dead (command exited) or the only |
| 267 | // running foreground process is a shell — which indicates the |
| 268 | // command pipeline has likely completed. Note that this may return |
| 269 | // true for active agents that are currently executing shell scripts. |
| 270 | func PaneIsIdle(ctx context.Context, paneID string) bool { |
| 271 | if PaneIsDead(ctx, paneID) { |
| 272 | return true |
| 273 | } |
| 274 | |
| 275 | // Check the current foreground command in the pane. While the agent's |
| 276 | // command pipeline is active, pane_current_command will be "claude", |
| 277 | // "tee", "klaus", etc. Once finished, only the shell remains. |
| 278 | out, err := runTmux(ctx, "display-message", "-t", paneID, "-p", "#{pane_current_command}") |
| 279 | if err != nil { |
| 280 | return false |
| 281 | } |
| 282 | cmd := strings.TrimSpace(out) |
| 283 | switch cmd { |
| 284 | case "bash", "zsh", "sh", "fish", "dash": |
| 285 | return true |
| 286 | default: |
| 287 | return false |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // BuildArgs returns the tmux command arguments for a given operation. |
| 292 | // Exported for testing command construction without actually running tmux. |
| 293 | func BuildArgs(op string, args ...string) []string { |
| 294 | return append([]string{op}, args...) |
| 295 | } |
| 296 | |
| 297 | // ensureTimeout returns a context with defaultTimeout applied if the parent |
| 298 | // context has no deadline set. If the parent already has a shorter deadline, |
| 299 | // it is returned unchanged. |
| 300 | func ensureTimeout(ctx context.Context) (context.Context, context.CancelFunc) { |
| 301 | if ctx == nil { |
| 302 | ctx = context.Background() |
| 303 | } |
| 304 | if _, ok := ctx.Deadline(); ok { |
| 305 | return ctx, func() {} |
| 306 | } |
| 307 | return context.WithTimeout(ctx, defaultTimeout) |
| 308 | } |
| 309 | |
| 310 | // SendKeys types the given keys into a pane. The -l flag sends the keys |
| 311 | // literally (as text input) rather than interpreting them as tmux key names, |
| 312 | // so a string like "WRT PR#583: " is typed verbatim. |
| 313 | func SendKeys(ctx context.Context, paneID, keys string) error { |
| 314 | _, err := runTmux(ctx, "send-keys", "-t", paneID, "-l", keys) |
| 315 | return err |
| 316 | } |
| 317 | |
| 318 | // SelectPane moves tmux focus to the given pane. |
| 319 | func SelectPane(ctx context.Context, paneID string) error { |
| 320 | _, err := runTmux(ctx, "select-pane", "-t", paneID) |
| 321 | return err |
| 322 | } |
| 323 | |
| 324 | func runTmux(ctx context.Context, args ...string) (string, error) { |
| 325 | ctx, cancel := ensureTimeout(ctx) |
| 326 | defer cancel() |
| 327 | |
| 328 | cmd := exec.CommandContext(ctx, "tmux", append(serverArgs(), args...)...) |
| 329 | var stdout, stderr bytes.Buffer |
| 330 | cmd.Stdout = &stdout |
| 331 | cmd.Stderr = &stderr |
| 332 | if err := cmd.Run(); err != nil { |
| 333 | if ctx.Err() == context.DeadlineExceeded { |
| 334 | return "", fmt.Errorf("tmux %s timed out after %s", args[0], defaultTimeout) |
| 335 | } |
| 336 | msg := strings.TrimSpace(stderr.String()) |
| 337 | if msg == "" { |
| 338 | msg = err.Error() |
| 339 | } |
| 340 | return "", fmt.Errorf("tmux %s: %s (args: %s)", args[0], msg, truncateBytes("tmux "+strings.Join(args, " "), maxErrArgsBytes)) |
| 341 | } |
| 342 | return strings.TrimSpace(stdout.String()), nil |
| 343 | } |
| 344 | |
| 345 | // maxErrArgsBytes caps the argv echoed in a tmux error; a pane command can run |
| 346 | // to kilobytes and would bury tmux's own message. |
| 347 | const maxErrArgsBytes = 200 |
| 348 | |
| 349 | func truncateBytes(s string, n int) string { |
| 350 | if len(s) <= n { |
| 351 | return s |
| 352 | } |
| 353 | for n > 0 && !utf8.RuneStart(s[n]) { |
| 354 | n-- |
| 355 | } |
| 356 | return fmt.Sprintf("%s… [truncated %d bytes]", s[:n], len(s)-n) |
| 357 | } |