Files
claude-config/bin/loop_claude/tmux.py
T

102 lines
5.0 KiB
Python

"""The tmux commands loop-claude runs: each chunk's loop runs in its own window of one tmux session named for the project (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
import dataclasses
import re
import subprocess
import typing
from failure import Failure
# Runs tmux with these arguments and returns what it printed; exit 127 where tmux cannot start.
Tmux = typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
# The oldest tmux that has every command and option used here. Its CHANGES file dates the newest two to 3.2: `remain-on-exit failed` and `new-session -e`.
NEEDED = (3, 2)
# What a window's name ends in while its chunk waits for the human. tmux's status bar shows the name, and `!` after it once the bell rang.
WAITS = " ?"
BELL = "\a"
# The session option that names the checkout whose chunks the session runs, since two checkouts' keys may map to one session name.
OWNER = "@loop-root"
@dataclasses.dataclass(frozen=True)
class Window:
"""The tmux window a chunk's loop runs in."""
session: str
# Without WAITS.
name: str
# The ID of the loop's pane, which $TMUX_PANE holds. It targets the window whatever its name is.
pane: str
@property
def target(self) -> str:
"""What `tmux attach -t` and `tmux select-window -t` take to reach the window."""
return f"{self.session}:{self.name}"
@dataclasses.dataclass(frozen=True)
class Listed:
"""A window of the project's session, as tmux lists it."""
# Without WAITS.
name: str
# tmux's ID of the window, such as `@3`.
id: str
# Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable.
dead: bool
def unusable(run: Tmux) -> str | None:
"""Why loop-claude cannot use this machine's tmux, naming the version found and the one needed; None where it is NEEDED or later."""
found = run(["-V"]).stdout.strip()
version = re.search(r"([0-9]+)\.([0-9]+)", found)
if version and (int(version[1]), int(version[2])) >= NEEDED:
return None
return f"loop-claude runs each chunk in a tmux window, and needs tmux {NEEDED[0]}.{NEEDED[1]} or later; it found {found or 'no tmux'}"
def session_name(key: str) -> str:
"""The tmux session of the project with this key, such as `loop-claude-config`. tmux reads `.` and `:` in a target as separators, so every character but a letter, a digit, `_` and `-` becomes a dash."""
return "loop-" + re.sub(r"[^A-Za-z0-9_-]", "-", key)
def listed(session: str, run: Tmux) -> list[Listed]:
"""The windows of session; none where tmux lists none, as while the session doesn't exist or no tmux server runs."""
done = run(["list-windows", "-t", f"={session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"])
rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else []
return [Listed(row[0].removesuffix(WAITS), row[2], row[1] == "1") for row in rows if len(row) == 3]
def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], first: bool, run: Tmux) -> Failure | None:
"""Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too. A Failure says why tmux started none."""
make = ["new-session", "-d", "-s", window.session] if first else ["new-window", "-d", "-t", f"={window.session}:"]
variables = [flag for name, value in env.items() for flag in ("-e", f"{name}={value}")]
# tmux reads a `;` that ends an argument as the end of the command, unless a backslash precedes it.
words = [re.sub(r";$", r"\\;", word) for word in command]
done = run([*make, "-n", window.name, "-c", cwd, *variables, "-P", "-F", "#{window_id}", "--", *words])
if done.returncode:
return Failure(f"tmux could not start the window {window.target}: {done.stderr.strip() or f'it exited {done.returncode}'}")
if first:
# set-option and show-options read a target as a pane's, so `=session` alone names no session.
run(["set-option", "-t", f"={window.session}:", OWNER, cwd])
# By the ID, since a window of the same name may still be closing. A loop that fails before the option is set closes its window, and its stop is still sent as a DM.
run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"])
return None
def owner(session: str, run: Tmux) -> str:
"""The checkout whose chunks session runs, as OWNER names it; empty where it names none."""
return run(["show-options", "-qv", "-t", f"={session}:", OWNER]).stdout.strip()
def close(window: Listed, run: Tmux) -> None:
run(["kill-window", "-t", window.id])
def mark(window: Window, waits: bool, run: Tmux) -> None:
"""Renames window to end in WAITS while its chunk waits for the human, and back once it doesn't."""
run(["rename-window", "-t", window.pane, window.name + (WAITS if waits else "")])
def show(session: str, inside: bool) -> list[str]:
"""The tmux arguments that put session on the human's terminal: inside tmux the client switches to it, and outside a new client attaches."""
return ["switch-client" if inside else "attach-session", "-t", f"={session}"]