mtmux 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mtmux-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: mtmux
3
+ Version: 0.1.0
4
+ Summary: Outer tmux cockpit for local and SSH tmux sessions
5
+ Requires-Python: >=3.11
mtmux-0.1.0/README.md ADDED
@@ -0,0 +1,179 @@
1
+ <p align="center">
2
+ <img src="logo.png" alt="mtmux logo" width="280">
3
+ </p>
4
+
5
+ <h1 align="center">mtmux</h1>
6
+
7
+ <p align="center">
8
+ Every tmux session, local or remote, at your fingertips.
9
+ </p>
10
+
11
+ `mtmux` runs inside your existing terminal and works on top of tmux. No new terminal app, no replacement tmux setup, no retraining your keyboard muscle memory. Keep your terminal, tmux configuration, keybindings, plugins, and workflows while adding a persistent sidebar for finding, opening, and switching between sessions across your machine and SSH hosts. Your sessions remain ordinary tmux sessions; mtmux simply puts them within reach.
12
+
13
+ Star important sessions, see at a glance which ones need attention, and jump between local and remote work without hunting through terminal tabs.
14
+
15
+ ## Why mtmux?
16
+
17
+ - **Keep your terminal and tmux setup**: unlike cmux, mtmux runs inside your current terminal and builds on tmux instead of forcing a new terminal app. Your configuration, keybindings, plugins, and workflows keep working.
18
+ - **One view across machines**: local and remote sessions live in the same sidebar.
19
+ - **Fast context switches**: see which sessions need your attention via tmux bells, then jump straight to them.
20
+
21
+ ## Quick start
22
+
23
+ Requires Python 3.11+, tmux, and OpenSSH. Automatic coding-agent discovery additionally requires [astatus](https://github.com/julsemaan/astatus) locally and on configured remote hosts.
24
+
25
+ ```sh
26
+ git clone https://github.com/julsemaan/mtmux.git
27
+ cd mtmux
28
+ pip install -e .
29
+ mtmux cockpit
30
+ ```
31
+
32
+ That opens an outer tmux workspace with the mtmux sidebar on the left and your selected session on the right. Press `Enter` on a session to step into it; press `q` to close the sidebar, then `C-s s` to reopen it on Sessions.
33
+
34
+ ## Development
35
+
36
+ ```sh
37
+ make dev-install
38
+ make test
39
+ ```
40
+
41
+ ## How it works
42
+
43
+ `mtmux cockpit` creates or attaches to a dedicated outer tmux server. That outer layer owns only the layout:
44
+
45
+ - outer prefix: `C-s`
46
+ - focus/open Sessions: `C-s s`
47
+ - add session: `C-s +`
48
+ - focus/open Agents: `C-s a`
49
+ - hide sidebar: `C-s h`
50
+ - quit cockpit: `C-s q`
51
+ - show help: `C-s ?`
52
+ - detach cockpit: `C-s d`
53
+ - forward outer prefix to inner session: `C-s C-s`
54
+ - standard outer tmux prefix bindings: disabled
55
+ - outer status: off
56
+ - left pane: `mtmux` sidebar, 40 columns by default
57
+ - right pane: selected local/remote tmux attach client
58
+
59
+ Inner local and remote sessions keep their normal tmux prefix and bindings, and remain alive when you switch away. Only mtmux's outer `prefix` key table is restricted.
60
+
61
+ ## Configuration
62
+
63
+ Files live in `~/.config/mtmux/`:
64
+
65
+ ```toml
66
+ hosts = ["my-remote-machine"]
67
+ prefix = "C-s"
68
+ sidebar_width = 40
69
+ status_timeout = 5
70
+ persistent_ssh = true
71
+ ```
72
+
73
+ ### Prefix
74
+
75
+ `prefix` accepts one non-empty, printable tmux key token without whitespace. `sidebar_width` sets left pane width in columns. `status_timeout` controls how many seconds sidebar feedback remains visible. Both numeric settings must be positive integers. Restart sidebar by rerunning `mtmux cockpit` after changing these values.
76
+
77
+ `C-s` normally sends XOFF when terminal `IXON` flow control is enabled. Attached tmux disables flow control on outer tty, so outer prefix works without global `stty` changes. Readline, Emacs, or Vim `C-s` commands require `C-s C-s` to forward literal `C-s`; inner tty may still treat it as XOFF, in which case `C-q` resumes output.
78
+
79
+ To restore old prefix, set `prefix = "C-g"` and rerun `mtmux cockpit`.
80
+
81
+ ### Remote hosts
82
+
83
+ Hosts are SSH aliases only. Keep host-specific users, ports, keys, proxies, IPv6, and other connection settings in `~/.ssh/config`.
84
+
85
+ By default, mtmux makes OpenSSH reuse one authenticated transport per host with `ControlMaster=auto`, `ControlPersist=10m`, and `ControlPath=~/.ssh/mtmux-%C`. Later discovery polls, switches, creates, and kills avoid repeating TCP setup, key exchange, and authentication. Control sockets remain for 10 minutes after last use.
86
+
87
+ Every mtmux SSH connection also uses `ServerAliveInterval=60` and `ServerAliveCountMax=3` to detect dead connections and keep idle sessions active through network and NAT timeouts. Keepalive remains enabled when `persistent_ssh` is disabled.
88
+
89
+ To omit mtmux's persistence options, set:
90
+
91
+ ```toml
92
+ persistent_ssh = false
93
+ ```
94
+
95
+ SSH config still applies, so this opt-out does not disable multiplexing configured there.
96
+
97
+ Names of the hosts must match:
98
+
99
+ ```text
100
+ [A-Za-z0-9_.-]{1,64}
101
+ ```
102
+
103
+ ## CLI commands
104
+
105
+ ```sh
106
+ mtmux list
107
+ mtmux switch local:<session>
108
+ mtmux switch ssh:<host>:<session>
109
+ mtmux switch-star <1-9>
110
+ mtmux create local <session>
111
+ mtmux create ssh <host> <session>
112
+ mtmux kill local:<session>
113
+ mtmux kill ssh:<host>:<session>
114
+ ```
115
+
116
+ Switching uses outer tmux `respawn-pane` on right pane. Real tmux sessions stay alive.
117
+
118
+ ## Sidebar keys
119
+
120
+ - `C-s s`: focus Sessions; recreates sidebar if quit
121
+ - `C-s +`: focus Sessions and open Add session menu
122
+ - `C-s a`: focus Agents; recreates sidebar if quit
123
+ - `C-s h`: hide sidebar
124
+ - `C-s q`: quit outer mtmux cockpit
125
+ - `C-s ?`: show help in right pane
126
+ - `C-s d`: detach outer mtmux cockpit
127
+ - `C-s C-s`: forward `C-s` to inner session
128
+ - `C-s 1`–`C-s 9`: switch directly to numbered starred target
129
+ - `j` / `k` or arrows: move selection pointer (`›`) in focused region
130
+ - `[` / `]`: give Agents/Sessions region more rows for current run
131
+ - `h` / `l`: cycle agent ordering mode (Priority / Session) when ordering row is selected
132
+ - `Enter`: switch selected session or exact agent pane, or activate selected Add row
133
+ - `a`: open Add session menu from Sessions or Agents
134
+ - `r`: remove selected target without killing it
135
+ - `K` / `J`: move selected starred target up/down without wrapping
136
+ - `x`: kill selected session but retain its star (asks first)
137
+ - `/`: open existing-session search directly
138
+ - `?`: open help in right pane
139
+ - `q`: quit sidebar only
140
+
141
+ `›` marks keyboard selection; mint reverse highlight marks active cockpit session. Both appear independently while sidebar is focused. Unfocused sidebar hides pointer and keeps active session highlighted and visible.
142
+
143
+ Normal sidebar lists sessions in persisted order. Add menu separates `New session` from `Existing session`. New-session flow skips location selection when exactly one local/SSH location is available; multiple locations use dedicated picker, then dedicated name input. Existing-session search lists only untracked sessions. Selecting or creating one persists it and switches immediately. Independently navigable Agents region remains visible below `AGENTS` divider when Add menu is closed. First nine sessions receive shortcut numbers; `K`/`J` updates order. Missing sessions remain launchers: `Enter` uses tmux `new-session -A` to recreate and attach. Sessions persist in `~/.config/mtmux/stars`. Only tracked sessions trigger sidebar bell indicators and beeps. Set `MTMUX_ASCII=1` for text-only labels and ellipses.
144
+
145
+ Agent records are read from `$AGENT_STATUS_DIR`, `$XDG_STATE_HOME/agent-status`, or `~/.local/state/agent-status`, in that order. Local and remote running agents updated within 60 seconds are correlated by exact tmux socket and pane ID. Selecting agent navigates to exact server, window, and pane; active agent name and location remain orange independently of keyboard selection. Working agents show `for <duration>`; other states show no duration. Working durations prefer `task.status_timestamp` and fall back to `runtime.updated_at`; unusable optional timestamps omit duration. Each agent row starts with a semantic status icon; working agents use an animated Braille spinner. Focused selection replaces that icon with `›`, and moving focus away restores it. Status icon and text share semantic color; selection cursor stays orange. `MTMUX_ASCII=1` uses ASCII icons, spinner frames, and `>` cursor. Attention states remain bold and idle/canceled remain dim without color. Agents are discovered automatically, but only agents in tracked sessions appear. Agents cannot be added, removed, reordered, or killed as favorites.
146
+
147
+ When a tracked agent changes from `working` to `idle`, `completed`, `input-required`, `auth-required`, `failed`, `rejected`, or `canceled`, sidebar beeps once and marks that exact pane/agent with `🔔` (`BELL` in ASCII mode). Initial discovery does not alert. Marker survives later state changes until exact pane opens, is already active during discovery, disappears from discovery, or sidebar restarts.
148
+
149
+ ## Mouse controls
150
+
151
+ - click session row: select and switch
152
+ - click `+ add`, Add choice, or available location row: activate same flow as `Enter`
153
+ - wheel over sidebar: navigate selectable session and host rows
154
+ - right-pane mouse events: forwarded by outer tmux to mouse-aware applications
155
+ - live border dragging: disabled so text selection can cross the sidebar divider without resizing it
156
+
157
+ Tmux mouse capture may require holding `Shift` for terminal-native text selection.
158
+
159
+ ## Clipboard
160
+
161
+ Native tmux copy mode forwards copied text through nested sessions using OSC 52. Physical terminal must support and enable OSC 52 clipboard access. mtmux declares inner clients as `clipboard` capable and sets outer server option `set-clipboard on`; inner tmux configuration remains unchanged, including explicit `set-clipboard off`.
162
+
163
+ **Security:** `set-clipboard on` permits processes in local and remote panes to set system clipboard through OSC 52. Only connect to trusted hosts and run trusted pane processes.
164
+
165
+ ## Recovery
166
+
167
+ Press `C-s s` to reopen Sessions, `C-s a` to reopen Agents, or rerun:
168
+
169
+ ```sh
170
+ mtmux cockpit
171
+ ```
172
+
173
+ It reuses valid cockpit, repairs broken window, and respawns missing sidebar.
174
+
175
+ Missing cockpit for switch/create prints:
176
+
177
+ ```text
178
+ No valid mtmux cockpit. Run: mtmux cockpit
179
+ ```
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,112 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+ import subprocess
6
+ import sys
7
+
8
+ from . import cockpit, sessions
9
+ from .config import ensure_config, load_sessions
10
+ from .discovery import discover
11
+ from .names import Target, parse_target
12
+
13
+
14
+ def build_parser() -> argparse.ArgumentParser:
15
+ parser = argparse.ArgumentParser(prog="mtmux")
16
+ sub = parser.add_subparsers(dest="command", required=True)
17
+
18
+ sub.add_parser("cockpit", help="launch or attach cockpit")
19
+ focus_sidebar = sub.add_parser("focus-sidebar", help="focus/open cockpit sidebar")
20
+ focus_sidebar.add_argument("region", nargs="?", choices=("sessions", "agents", "add"), default="sessions")
21
+ sub.add_parser("init", help="create missing config files")
22
+ sub.add_parser("list", help="list discovered targets")
23
+
24
+ switch = sub.add_parser("switch", help="switch cockpit target")
25
+ switch.add_argument("target")
26
+
27
+ switch_star = sub.add_parser("switch-session", help="switch to numbered tracked target")
28
+ switch_star.add_argument("slot", type=int, choices=range(1, 10))
29
+
30
+ kill_parser = sub.add_parser("kill", help="kill target tmux session")
31
+ kill_parser.add_argument("target")
32
+
33
+ create = sub.add_parser("create", help="create target then switch")
34
+ create_sub = create.add_subparsers(dest="create_kind", required=True)
35
+ local = create_sub.add_parser("local", help="create local tmux session")
36
+ local.add_argument("session")
37
+ ssh = create_sub.add_parser("ssh", help="create remote tmux session")
38
+ ssh.add_argument("host")
39
+ ssh.add_argument("session")
40
+ return parser
41
+
42
+
43
+ def main(argv: list[str] | None = None) -> int:
44
+ argv = sys.argv[1:] if argv is None else argv
45
+ if argv[:1] == ["sidebar"]:
46
+ from .sidebar import main as sidebar_main
47
+ return sidebar_main()
48
+ args = build_parser().parse_args(argv)
49
+ if args.command == "init":
50
+ cfg, wrapper = ensure_config()
51
+ print(f"Config: {cfg}")
52
+ print(f"Wrapper: {wrapper}")
53
+ return 0
54
+ if args.command == "cockpit":
55
+ return cockpit.cockpit()
56
+ if args.command == "focus-sidebar":
57
+ return cockpit.focus_sidebar(args.region)
58
+ if args.command == "list":
59
+ snapshot = discover()
60
+ if not snapshot.local.available:
61
+ print(f"local unavailable: {snapshot.local.error or 'unknown error'}")
62
+ else:
63
+ for target in snapshot.local.sessions:
64
+ print(target.format())
65
+ for host, source in snapshot.remotes.items():
66
+ if not source or not source.available:
67
+ print(f"ssh:{host} unavailable")
68
+ else:
69
+ for target in source.sessions:
70
+ print(target.format())
71
+ return 0
72
+ if args.command == "switch":
73
+ target = parse_target(args.target)
74
+ cockpit.switch(target, sessions.attach_command(target))
75
+ return 0
76
+ if args.command == "switch-session":
77
+ favorites = load_sessions()
78
+ if args.slot > len(favorites):
79
+ raise SystemExit(f"No session in slot {args.slot}")
80
+ target = favorites[args.slot - 1]
81
+ cockpit.switch(target, sessions.attach_command(target))
82
+ return 0
83
+ if args.command == "kill":
84
+ sessions.kill(parse_target(args.target))
85
+ return 0
86
+ if args.command == "create":
87
+ target = Target("local", args.session) if args.create_kind == "local" else Target("ssh", args.session, args.host)
88
+ sessions.create(target)
89
+ cockpit.switch(target, sessions.attach_command(target))
90
+ return 0
91
+
92
+
93
+ def run_cli(argv: list[str] | None = None) -> int:
94
+ try:
95
+ return main(argv)
96
+ except subprocess.CalledProcessError as error:
97
+ command = Path(str(error.cmd[0] if isinstance(error.cmd, (list, tuple)) else error.cmd)).name
98
+ reason = (error.stderr or error.stdout or "").strip() or f"exit status {error.returncode}"
99
+ print(f"mtmux: {command} failed: {reason}", file=sys.stderr)
100
+ except OSError as error:
101
+ reason = error.strerror or str(error)
102
+ detail = f"{error.filename}: {reason}" if error.filename else reason
103
+ print(f"mtmux: {detail}", file=sys.stderr)
104
+ except UnicodeError as error:
105
+ print(f"mtmux: text decoding failed: {error}", file=sys.stderr)
106
+ except subprocess.SubprocessError as error:
107
+ print(f"mtmux: subprocess failed: {error}", file=sys.stderr)
108
+ return 1
109
+
110
+
111
+ if __name__ == "__main__":
112
+ raise SystemExit(run_cli())
@@ -0,0 +1,356 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import re
5
+ import shlex
6
+ import shutil
7
+ import sys
8
+
9
+ from .config import ensure_config, load_prefix, load_sidebar_width
10
+ from .names import Target, parse_target
11
+ from . import tmux
12
+
13
+
14
+ def _truecolor_enabled() -> bool:
15
+ """Detect whether the host terminal supports truecolor (24-bit color)."""
16
+ colorterm = os.environ.get("COLORTERM", "").lower()
17
+ return colorterm in ("truecolor", "24bit")
18
+
19
+ def help_command(prefix: str) -> str:
20
+ text = f"""mtmux cockpit
21
+
22
+ Navigation
23
+ {prefix} a focus/open Agents
24
+ {prefix} s focus/open Sessions
25
+ {prefix} + add session
26
+ {prefix} h hide sidebar
27
+ {prefix} q quit cockpit
28
+ {prefix} 1-9 switch session
29
+ {prefix} ? open help
30
+ ? open help from sidebar
31
+ q quit sidebar only
32
+
33
+ Session actions
34
+ Enter switch session / select Add choice
35
+ a open Add session menu
36
+ r remove selected session (session keeps running)
37
+ K/J move session up/down
38
+ x kill selected session
39
+ / search untracked existing sessions
40
+
41
+ Agent actions
42
+ j/k navigate agents
43
+ Enter switch to agent pane
44
+ h/l cycle agent ordering (Priority / Session)
45
+ [ / ] resize agent panel
46
+
47
+ Recovery
48
+ {prefix} d detach cockpit
49
+ {prefix} s restart/focus Sessions
50
+ Esc cancel prompts/filter
51
+
52
+ Examples
53
+ /work find available sessions matching work
54
+ Enter recreate missing session or activate selected Add row
55
+ """
56
+ return f"printf %s {shlex.quote(text)}; exec tail -f /dev/null"
57
+
58
+
59
+ SIDEBAR = f"{shlex.quote(sys.executable)} -m mtmux sidebar"
60
+ FOCUS_SIDEBAR = f"{shlex.quote(sys.executable)} -m mtmux focus-sidebar"
61
+ TARGET = f"{tmux.SESSION}:{tmux.WINDOW}"
62
+ COCKPIT_OPTION = "@mtmux_cockpit"
63
+ SIDEBAR_PANE_OPTION = "@mtmux_sidebar_pane"
64
+ SIDEBAR_WIDTH_OPTION = "@mtmux_sidebar_width"
65
+ RIGHT_PANE_OPTION = "@mtmux_right_pane"
66
+ CURRENT_TARGET_OPTION = "@mtmux_current_target"
67
+ CURRENT_AGENT_OPTION = "@mtmux_current_agent"
68
+ BELL_TARGET_OPTION = "@mtmux_bell_target"
69
+ NO_COCKPIT = "No valid mtmux cockpit. Run: mtmux cockpit"
70
+
71
+
72
+ def _option(name: str) -> str:
73
+ return tmux.out("show-options", "-v", "-t", tmux.SESSION, name, check=False)
74
+
75
+
76
+ def _window_exists() -> bool:
77
+ return tmux.tmux("has-session", "-t", TARGET, check=False).returncode == 0
78
+
79
+
80
+ def _valid() -> bool:
81
+ if _option(COCKPIT_OPTION) != "1":
82
+ return False
83
+ left = _option(SIDEBAR_PANE_OPTION)
84
+ right = _option(RIGHT_PANE_OPTION)
85
+ return bool(left and right and tmux.has_pane(left) and tmux.has_pane(right))
86
+
87
+
88
+ def _set_markers(left: str, right: str) -> None:
89
+ tmux.tmux("set-option", "-t", tmux.SESSION, COCKPIT_OPTION, "1")
90
+ tmux.tmux("set-option", "-t", tmux.SESSION, SIDEBAR_PANE_OPTION, left)
91
+ tmux.tmux("set-option", "-t", tmux.SESSION, RIGHT_PANE_OPTION, right)
92
+
93
+
94
+ def _fix_layout(left: str, sidebar_width: int) -> None:
95
+ tmux.tmux("set-window-option", "-t", TARGET, SIDEBAR_WIDTH_OPTION, str(sidebar_width))
96
+ tmux.tmux("set-window-option", "-t", TARGET, "main-pane-width", str(sidebar_width))
97
+ tmux.tmux("set-window-option", "-u", "-t", TARGET, "window-style")
98
+ tmux.tmux("set-window-option", "-u", "-t", TARGET, "window-active-style")
99
+ tmux.tmux("set-window-option", "-t", TARGET, "pane-border-style", "fg=terminal")
100
+ tmux.tmux("set-window-option", "-t", TARGET, "pane-active-border-style", "fg=terminal")
101
+ tmux.tmux("set-window-option", "-t", TARGET, "pane-border-lines", "single")
102
+ tmux.tmux("resize-pane", "-t", left, "-x", str(sidebar_width), check=False)
103
+
104
+
105
+ def repair_layout(left: str) -> None:
106
+ state = tmux.out(
107
+ "display-message", "-p", "-t", left,
108
+ f"#{{pane_width}}:#{{{SIDEBAR_WIDTH_OPTION}}}:#{{window_width}}:#{{client_width}}:#{{window_offset_x}}",
109
+ check=False,
110
+ ).split(":")
111
+ if len(state) == 5 and state[0] == state[1] and state[2] == state[3] and state[4] in ("", "0"):
112
+ return
113
+ command = f"resize-window -a -t {TARGET} ; resize-pane -t {left} -x '#{{{SIDEBAR_WIDTH_OPTION}}}'"
114
+ tmux.tmux("run-shell", "-C", "-t", left, command, check=False)
115
+
116
+
117
+ def _install_layout_hooks(left: str, sidebar_width: int) -> None:
118
+ tmux.tmux("set-hook", "-u", "-t", tmux.SESSION, "client-attached")
119
+ tmux.tmux("set-hook", "-u", "-t", tmux.SESSION, "client-resized")
120
+ tmux.tmux("set-hook", "-w", "-t", TARGET, "window-resized", f"resize-pane -t {left} -x {sidebar_width}")
121
+
122
+
123
+ def _install_bindings(prefix: str, sidebar_pane: str, right_pane: str) -> None:
124
+ tmux.tmux("unbind-key", "-a", "-T", "prefix")
125
+ tmux.tmux("bind-key", prefix, "send-prefix")
126
+ tmux.tmux("bind-key", "d", "detach-client")
127
+ tmux.tmux("bind-key", "h", "kill-pane", "-t", sidebar_pane)
128
+ tmux.tmux("bind-key", "q", "kill-session", "-t", tmux.SESSION)
129
+ tmux.tmux("bind-key", "a", "run-shell", f"{FOCUS_SIDEBAR} agents")
130
+ tmux.tmux("bind-key", "s", "run-shell", f"{FOCUS_SIDEBAR} sessions")
131
+ tmux.tmux("bind-key", "+", "run-shell", f"{FOCUS_SIDEBAR} add")
132
+ tmux.tmux("bind-key", "?", "respawn-pane", "-k", "-t", right_pane, help_command(prefix))
133
+ for slot in range(1, 10):
134
+ tmux.tmux("bind-key", str(slot), "run-shell", f"{shlex.quote(sys.executable)} -m mtmux switch-session {slot}")
135
+
136
+
137
+ def _enable_mouse() -> None:
138
+ tmux.tmux("set-option", "-t", tmux.SESSION, "mouse", "on")
139
+ tmux.tmux("unbind-key", "-q", "-T", "root", "MouseDrag1Border")
140
+
141
+
142
+ def _enable_clipboard() -> None:
143
+ tmux.tmux("set-option", "-s", "set-clipboard", "on")
144
+
145
+
146
+ def _enable_truecolor() -> None:
147
+ """Propagate RGB terminal capability when the host reports truecolor."""
148
+ if _truecolor_enabled():
149
+ tmux.tmux("set-option", "-as", "terminal-features", ",xterm-256color:RGB")
150
+
151
+
152
+ def _install_bell_hook() -> None:
153
+ tmux.tmux("set-window-option", "-t", TARGET, "monitor-bell", "on")
154
+ tmux.tmux("set-option", "-t", tmux.SESSION, "bell-action", "any")
155
+ tmux.tmux("set-hook", "-t", tmux.SESSION, "alert-bell", "set-option -F -t mtmux @mtmux_bell_target '#{@mtmux_current_target}'")
156
+
157
+
158
+ def _unavailable_command(target: Target | None = None) -> str:
159
+ name = f"Session {target.format()}" if target else "Active session"
160
+ text = f"{name} is unavailable.\n\nSelect another session from the sidebar.\n"
161
+ return f"printf %s {shlex.quote(text)}; exec sh"
162
+
163
+
164
+ def _reconnecting_command(target: Target) -> str:
165
+ reset, cyan, dim = "\033[0m", "\033[38;5;81m", "\033[2m"
166
+ ascii_mode = os.environ.get("MTMUX_ASCII") == "1"
167
+ banner = "+-- Connection interrupted --+" if ascii_mode else "╭─ Connection interrupted ─╮"
168
+ underline = "+----------------------------+" if ascii_mode else "╰──────────────────────────╯"
169
+ indent = " "
170
+ text = f"\n{indent}{cyan}{banner}\n{indent}{underline}{reset}\n\n{indent}{dim}Session{reset} {target.session}\n{indent}{dim}Host{reset} {target.host or 'local'}\n\n"
171
+ frames = ("|", "/", "-", "\\") if ascii_mode else ("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")
172
+ dots = (". ", ".. ", "...") if ascii_mode else ("· ", "·· ", "···", " ··", " ·")
173
+ colors = (45, 51, 87, 123, 159, 123, 87, 51)
174
+ states = " ".join(shlex.quote(f"{color}:{frame}:{dots[index % len(dots)]}") for index, (color, frame) in enumerate(zip(colors, frames)))
175
+ save_cursor = shlex.quote("\0337")
176
+ spinner = shlex.quote(f"\0338\033[2K{indent}\033[38;5;%sm%s\033[0m Reconnecting%s")
177
+ animate = 'color=${state%%:*}; rest=${state#*:}; frame=${rest%%:*}; dots=${rest#*:}'
178
+ return f"printf %s {shlex.quote(text)}; printf %s {save_cursor}; while :; do for state in {states}; do {animate}; printf {spinner} \"$color\" \"$frame\" \"$dots\"; sleep 0.1; done; done"
179
+
180
+
181
+ def _install_right_pane_reset(left: str, right: str) -> None:
182
+ tmux.tmux("set-option", "-p", "-t", right, "remain-on-exit", "on")
183
+ command = f"if-shell -F '#{{==:#{{hook_pane}},{right}}}' {{ set-option -u -t {tmux.SESSION} @mtmux_current_agent ; set-option -u -t {tmux.SESSION} @mtmux_bell_target ; respawn-pane -k -t {right} {shlex.quote(_unavailable_command())} ; select-pane -t {left} }}"
184
+ tmux.tmux("set-hook", "-t", tmux.SESSION, "pane-died", command)
185
+
186
+
187
+ def _configure_cockpit(left: str, right: str, prefix: str, sidebar_width: int) -> None:
188
+ _set_markers(left, right)
189
+ _fix_layout(left, sidebar_width)
190
+ _install_layout_hooks(left, sidebar_width)
191
+ _install_bell_hook()
192
+ _install_right_pane_reset(left, right)
193
+ tmux.tmux("set-option", "-t", tmux.SESSION, "prefix", prefix)
194
+ tmux.tmux("set-option", "-t", tmux.SESSION, "status", "off")
195
+ tmux.tmux("set-option", "-s", "escape-time", "0")
196
+ _enable_mouse()
197
+ _enable_clipboard()
198
+ _enable_truecolor()
199
+ _install_bindings(prefix, left, right)
200
+
201
+
202
+ def _build(prefix: str, sidebar_width: int) -> None:
203
+ _, wrapper = ensure_config()
204
+ help_cmd = help_command(prefix)
205
+ if _window_exists():
206
+ tmux.tmux("kill-window", "-t", TARGET, check=False)
207
+ if tmux.tmux("has-session", "-t", tmux.SESSION, check=False).returncode != 0:
208
+ tmux.tmux("new-session", "-d", "-s", tmux.SESSION, "-n", tmux.WINDOW, help_cmd, config=wrapper)
209
+ else:
210
+ tmux.tmux("new-window", "-d", "-t", tmux.SESSION, "-n", tmux.WINDOW, help_cmd)
211
+ right = tmux.out("display-message", "-p", "-t", TARGET, "#{pane_id}")
212
+ left = tmux.out("split-window", "-h", "-b", "-l", str(sidebar_width), "-P", "-F", "#{pane_id}", "-t", right, SIDEBAR)
213
+ _configure_cockpit(left, right, prefix, sidebar_width)
214
+
215
+
216
+ def ensure_cockpit() -> None:
217
+ prefix = load_prefix()
218
+ sidebar_width = load_sidebar_width()
219
+ if _valid():
220
+ left = _option(SIDEBAR_PANE_OPTION)
221
+ right = _option(RIGHT_PANE_OPTION)
222
+ _configure_cockpit(left, right, prefix, sidebar_width)
223
+ return
224
+ if _option(COCKPIT_OPTION) == "1":
225
+ right = _option(RIGHT_PANE_OPTION)
226
+ if right and tmux.has_pane(right):
227
+ left = tmux.out("split-window", "-h", "-b", "-l", str(sidebar_width), "-P", "-F", "#{pane_id}", "-t", right, SIDEBAR)
228
+ _configure_cockpit(left, right, prefix, sidebar_width)
229
+ return
230
+ _build(prefix, sidebar_width)
231
+
232
+
233
+ def _attach() -> int:
234
+ attach_cmd = "tmux -L mtmux attach -d -t mtmux:cockpit"
235
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
236
+ print(f"Cockpit ready. Attach from a real terminal: {attach_cmd}")
237
+ return 0
238
+ try:
239
+ tty = os.ttyname(0)
240
+ except OSError:
241
+ tty = ""
242
+ if tty == "/dev/tty":
243
+ print(f"Cockpit ready. Current fd is /dev/tty; tmux refuses it. Run: {attach_cmd}")
244
+ return 0
245
+ cmd = ["tmux", "-L", tmux.SOCKET, "attach-session", "-d", "-t", TARGET]
246
+ if shutil.which("script"):
247
+ shell_cmd = " ".join(shlex.quote(part) for part in cmd)
248
+ os.execvp("script", ["script", "-q", "-c", shell_cmd, "/dev/null"])
249
+ os.execvp("tmux", cmd)
250
+ return 0
251
+
252
+
253
+ def cockpit() -> int:
254
+ ensure_config()
255
+ width = shutil.get_terminal_size((80, 24)).columns
256
+ if width < 90:
257
+ print("Terminal too narrow for mtmux cockpit: need at least 90 columns.", file=sys.stderr)
258
+ return 2
259
+ ensure_cockpit()
260
+ return _attach()
261
+
262
+
263
+ def focus_sidebar(region: str = "sessions") -> int:
264
+ ensure_config()
265
+ ensure_cockpit()
266
+ pane = _option(SIDEBAR_PANE_OPTION)
267
+ tmux.tmux("select-pane", "-t", pane)
268
+ keys = {"sessions": ("F6",), "agents": ("F7",), "add": ("F6", "a")}[region]
269
+ tmux.tmux("send-keys", "-t", pane, *keys)
270
+ return 0
271
+
272
+
273
+ def right_pane() -> str | None:
274
+ if not _valid():
275
+ return None
276
+ pane = _option(RIGHT_PANE_OPTION)
277
+ return pane if pane and tmux.has_pane(pane) else None
278
+
279
+
280
+ def _require_right_pane() -> str:
281
+ pane = right_pane()
282
+ if not pane:
283
+ raise SystemExit(NO_COCKPIT)
284
+ return pane
285
+
286
+
287
+ def switch(target: Target, attach_command: str, agent_id: str | None = None) -> None:
288
+ pane = _require_right_pane()
289
+ tmux.tmux("set-option", "-t", tmux.SESSION, CURRENT_TARGET_OPTION, target.format())
290
+ if agent_id:
291
+ tmux.tmux("set-option", "-t", tmux.SESSION, CURRENT_AGENT_OPTION, agent_id)
292
+ else:
293
+ tmux.tmux("set-option", "-u", "-t", tmux.SESSION, CURRENT_AGENT_OPTION)
294
+ tmux.tmux("set-option", "-u", "-t", tmux.SESSION, BELL_TARGET_OPTION)
295
+ tmux.tmux("respawn-pane", "-k", "-t", pane, attach_command)
296
+ tmux.tmux("select-pane", "-t", pane)
297
+
298
+
299
+ def show_help() -> None:
300
+ tmux.tmux("respawn-pane", "-k", "-t", _require_right_pane(), help_command(load_prefix()))
301
+
302
+
303
+ def show_unavailable(target: Target) -> None:
304
+ tmux.tmux("respawn-pane", "-k", "-t", _require_right_pane(), _unavailable_command(target))
305
+
306
+
307
+ def show_reconnecting(target: Target) -> None:
308
+ tmux.tmux("respawn-pane", "-k", "-t", _require_right_pane(), _reconnecting_command(target))
309
+
310
+
311
+ def _target_option(name: str) -> Target | None:
312
+ text = _option(name)
313
+ if not text:
314
+ return None
315
+ try:
316
+ return parse_target(text)
317
+ except SystemExit:
318
+ return None
319
+
320
+
321
+ def current_target() -> Target | None:
322
+ if target := _target_option(CURRENT_TARGET_OPTION):
323
+ return target
324
+ pane = right_pane()
325
+ command = tmux.out("display-message", "-p", "-t", pane or "", "#{pane_start_command}", check=False)
326
+ try:
327
+ parts = shlex.split(command)
328
+ if parts and parts[0] == "ssh":
329
+ index = 1
330
+ while index < len(parts):
331
+ if parts[index] == "-o":
332
+ index += 2
333
+ elif parts[index].startswith("-"):
334
+ index += 1
335
+ else:
336
+ break
337
+ if index < len(parts) and (match := re.search(r"(?:^| )tmux .* -s ([A-Za-z0-9_.-]+)", " ".join(parts[index + 1:]))):
338
+ return Target("ssh", match.group(1), parts[index])
339
+ if match := re.search(r"(?:^| )tmux new-session .* -s ([A-Za-z0-9_.-]+)", command):
340
+ return Target("local", match.group(1))
341
+ except SystemExit:
342
+ pass
343
+ return None
344
+
345
+
346
+ def current_agent() -> str | None:
347
+ return _option(CURRENT_AGENT_OPTION) or None
348
+
349
+
350
+ def bell_target() -> Target | None:
351
+ return _target_option(BELL_TARGET_OPTION)
352
+
353
+
354
+ def sidebar_active() -> bool:
355
+ pane = _option(SIDEBAR_PANE_OPTION)
356
+ return not pane or tmux.out("display-message", "-p", "-t", pane, "#{pane_active}", check=False) == "1"