workcrew 0.1.0__py3-none-any.whl
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.
- workcrew/__init__.py +1 -0
- workcrew/__main__.py +6 -0
- workcrew/board.py +555 -0
- workcrew/cli.py +2340 -0
- workcrew/harness/__init__.py +51 -0
- workcrew/harness/claude.py +523 -0
- workcrew/harness/claude_screen.py +84 -0
- workcrew/link.py +1061 -0
- workcrew/notes/leader.md +21 -0
- workcrew/notes/worker.md +5 -0
- workcrew/picker.py +107 -0
- workcrew/place.py +97 -0
- workcrew/prompt.py +386 -0
- workcrew/reconcile.py +411 -0
- workcrew/send.py +244 -0
- workcrew/state.py +516 -0
- workcrew/tmux.py +992 -0
- workcrew/width.py +30 -0
- workcrew-0.1.0.dist-info/METADATA +173 -0
- workcrew-0.1.0.dist-info/RECORD +23 -0
- workcrew-0.1.0.dist-info/WHEEL +4 -0
- workcrew-0.1.0.dist-info/entry_points.txt +2 -0
- workcrew-0.1.0.dist-info/licenses/LICENSE +18 -0
workcrew/tmux.py
ADDED
|
@@ -0,0 +1,992 @@
|
|
|
1
|
+
"""The team's private tmux server, and the only module that runs tmux.
|
|
2
|
+
|
|
3
|
+
Each team has its own server, `tmux -L workcrew-<key>`, started with its own config. Every
|
|
4
|
+
difference between tmux 3.2a and later releases is handled here.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import shutil
|
|
12
|
+
import signal
|
|
13
|
+
import socket
|
|
14
|
+
import subprocess
|
|
15
|
+
import time
|
|
16
|
+
import uuid
|
|
17
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Literal, NamedTuple, NoReturn
|
|
21
|
+
|
|
22
|
+
from workcrew.place import ASPECT, LEADER, TEAM, Cell
|
|
23
|
+
from workcrew.state import Arrangement, Refused, StateError, noted
|
|
24
|
+
from workcrew.width import cols
|
|
25
|
+
|
|
26
|
+
# The session boot makes is the server's first, and its id, unlike its name, the owner cannot
|
|
27
|
+
# change: the tool addresses it by the id only.
|
|
28
|
+
SESSION = "$0"
|
|
29
|
+
# tmux's words for a target that is gone, the same on 3.2a, 3.6 and 3.8. A server that ended is
|
|
30
|
+
# every pane gone, and a command's client (client.c, 3.2a and 3.8) says so two ways: before the
|
|
31
|
+
# command, client_main finds its socket refusing ("no server running": a server leaves its socket
|
|
32
|
+
# behind); during it, client_dispatch loses the connection (client_exit_message's "server exited
|
|
33
|
+
# unexpectedly"). Its other words are a failure: "error connecting to" (no server ever made the
|
|
34
|
+
# socket, or no permission), a protocol or version mismatch, "failed to send command", "command
|
|
35
|
+
# too long". "server exited" reaches only an attached client.
|
|
36
|
+
_GONE_ERRORS = (
|
|
37
|
+
"can't find pane",
|
|
38
|
+
"can't find window",
|
|
39
|
+
"no such pane",
|
|
40
|
+
"no server running",
|
|
41
|
+
"server exited unexpectedly",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Gone(StateError):
|
|
46
|
+
"""A pane, a window or the server that closed after it was seen."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
OFF_TEAM = (
|
|
50
|
+
"you are no longer on this team, so nothing was changed.\n"
|
|
51
|
+
"Ask your user what to do; your transcript is intact."
|
|
52
|
+
)
|
|
53
|
+
# Membership changes. A resize is tmux's to scale: a layout run on it undid the owner's own pane
|
|
54
|
+
# sizes within 2 s (3.2a, 3.8), and left no pane more readable.
|
|
55
|
+
HOOKS = (
|
|
56
|
+
"pane-died",
|
|
57
|
+
"pane-exited",
|
|
58
|
+
"after-kill-pane",
|
|
59
|
+
"window-unlinked", # kill-window fires none of the others
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# Setting any option repaints every client (options_push_changes), so the option holds only the
|
|
63
|
+
# drawn wait; set-environment redraws nothing, and -h keeps the variable out of panes.
|
|
64
|
+
_HIDDEN = "workcrew_state"
|
|
65
|
+
Lay = Literal["join", "grid", "restore"]
|
|
66
|
+
_FRESH = "WORKCREW_FRESH" # the window, laid out or restored, awaits the first client's size
|
|
67
|
+
# The window the members are in. A mark, not its name: the owner may rename it.
|
|
68
|
+
_TEAM_WINDOW = "@workcrew_team_window"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _left_wait(state: str) -> str:
|
|
72
|
+
"""One tmux call reads the option and sets the variable; a second only on leaving wait."""
|
|
73
|
+
return (
|
|
74
|
+
'[ "$(tmux display -p -t "$TMUX_PANE" "#{@workcrew_state}" \\; '
|
|
75
|
+
f'set-environment -gh "{_HIDDEN}$TMUX_PANE" {state})" != wait ] || '
|
|
76
|
+
'tmux set -pu -t "$TMUX_PANE" @workcrew_state'
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
STATE_HOOKS: Mapping[str, str] = {
|
|
81
|
+
"wait": (
|
|
82
|
+
'printf \'\\a\' > "$(tmux set -p -t "$TMUX_PANE" @workcrew_state wait \\; '
|
|
83
|
+
'display -p -t "$TMUX_PANE" \'#{pane_tty}\')"'
|
|
84
|
+
),
|
|
85
|
+
"busy": _left_wait("busy"),
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
# What the guard is compared with in the Escape binding. Evaluated anywhere else, with no client
|
|
89
|
+
# attached, this format crashed a tmux 3.2a server.
|
|
90
|
+
_GUARD = "#{e|<=:#{client_activity},#{@workcrew_esc_guard}}"
|
|
91
|
+
_PASTE_END = "\x1b[201~"
|
|
92
|
+
_RECONCILE = "run-shell -b '\"$WORKCREW_BIN\" _reconcile'"
|
|
93
|
+
# What each screen shows in place of tmux's bare `[exited]` when `exit` stops its team. tmux runs
|
|
94
|
+
# a detach's -E string with sh and does not expand it as a format (3.2a, 3.6, 3.8), so it holds
|
|
95
|
+
# fixed words only: no name or count goes into a command string.
|
|
96
|
+
_STOPPING = "printf '%s\\n' 'workcrew: this team is stopping. workcrew -r brings a team back.'"
|
|
97
|
+
# A forgotten team cannot come back, so its screens are not told how; they are told where its
|
|
98
|
+
# state goes, which only the owner deletes. The line shows before the state is set aside.
|
|
99
|
+
_FORGOTTEN = (
|
|
100
|
+
"printf '%s\\n' 'workcrew: this team is stopping and being forgotten. Its state is set aside,"
|
|
101
|
+
" not deleted, as NAME-CODE.forgotten-TIME in ~/.local/state/workcrew/ (or"
|
|
102
|
+
" $XDG_STATE_HOME/workcrew/); delete it when you are sure.'"
|
|
103
|
+
)
|
|
104
|
+
_SHOWN = "workcrew-show" # the buffer a result of several lines waits in
|
|
105
|
+
_SHOW_W, _SHOW_H = 90, 80 # the result popup's size, in percent of the client
|
|
106
|
+
# Shows the result once, and an Esc that closes it guards the member below it for a second.
|
|
107
|
+
_SHOW = (
|
|
108
|
+
f"tmux show-buffer -b {_SHOWN}; tmux delete-buffer -b {_SHOWN}; stty raw -echo; "
|
|
109
|
+
'k=$(dd bs=1 count=1 2>/dev/null); [ "$k" != "$(printf "\\033")" ] || '
|
|
110
|
+
"tmux set -g @workcrew_esc_guard $(( $(date +%s) + 1 ))"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _bin() -> str:
|
|
115
|
+
path = shutil.which("tmux")
|
|
116
|
+
if path is None:
|
|
117
|
+
raise Refused(
|
|
118
|
+
"tmux is not on PATH, and workcrew needs tmux 3.2 or newer to hold the team.\n"
|
|
119
|
+
"Install it (apt install tmux, brew install tmux), then run workcrew again."
|
|
120
|
+
)
|
|
121
|
+
return path
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def check_version() -> None:
|
|
125
|
+
v = subprocess.run([_bin(), "-V"], capture_output=True, text=True, check=False)
|
|
126
|
+
version = v.stdout.split()[-1]
|
|
127
|
+
m = re.match(r"(\d+)\.(\d+)", version)
|
|
128
|
+
if m and (int(m[1]), int(m[2])) < (3, 2):
|
|
129
|
+
raise Refused(
|
|
130
|
+
f"tmux {version} is too old; workcrew needs 3.2 or newer.\n"
|
|
131
|
+
"Upgrade tmux, then run workcrew again."
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def conf_text(name: str) -> str:
|
|
136
|
+
"""The server's config. Safe to source into a live server: it sets no member marks. It holds
|
|
137
|
+
no path: `boot` and `setup` set `WORKCREW_BIN` by an argument, so no quote in a path can
|
|
138
|
+
break the config."""
|
|
139
|
+
lines = [
|
|
140
|
+
# 3.2a waits 500 ms after each Esc; 50 ms still tells a lone Esc from an Alt chord on a
|
|
141
|
+
# slow link, which delivers a key's bytes up to about 33 ms apart.
|
|
142
|
+
"set -s escape-time 50",
|
|
143
|
+
"set -s extended-keys on",
|
|
144
|
+
"set -s terminal-features[99] '*:extkeys'", # a fixed index: sourcing again adds nothing
|
|
145
|
+
"set -s focus-events on",
|
|
146
|
+
# Below 3.4 tmux hands ncurses' tparm a string for OSC 52 (Ms, a copy; `load-buffer -w`
|
|
147
|
+
# ignores set-clipboard) and OSC 12 (Cs, a cursor colour). Newer ncurses refuse it, and tmux
|
|
148
|
+
# uses the null, which ends the server (tmux 3.4 CHANGES). Without them it writes neither.
|
|
149
|
+
# Named by pattern: tmux compares versions as integers (3.2 >= 3.4), and reads a lettered
|
|
150
|
+
# one (3.6a) as nothing.
|
|
151
|
+
'%if "#{m:3.[23]*,#{version}}"',
|
|
152
|
+
"set -s terminal-overrides[99] '*:Ms@:Cs@'", # a fixed index: sourcing again adds nothing
|
|
153
|
+
"%else",
|
|
154
|
+
"set -s set-clipboard on",
|
|
155
|
+
"%endif",
|
|
156
|
+
"set -gq allow-passthrough on", # newer than 3.2a
|
|
157
|
+
"set -g mouse on",
|
|
158
|
+
f"set -g @workcrew_team '{name}'",
|
|
159
|
+
"set -g display-time 6000",
|
|
160
|
+
"set -g status-interval 5",
|
|
161
|
+
# Each client's own width less the window list and status-right, expanded as it draws:
|
|
162
|
+
# no stored length to go stale when a client resizes, and none per client to share.
|
|
163
|
+
f"set -g status-left '#(\"$WORKCREW_BIN\" _line {_LEFT})'",
|
|
164
|
+
"set -g status-left-length 1000", # `_line` cuts its own text to the width it is handed
|
|
165
|
+
# Only the terminal's own colours and the ANSI names, which each user's theme sets.
|
|
166
|
+
# A bar on any theme, readable wherever the terminal's text is: tmux's green bar fails on
|
|
167
|
+
# themes whose green is dark, and no text colour holds on blue across themes.
|
|
168
|
+
"set -g status-style reverse",
|
|
169
|
+
# tmux marks a window whose pane rang (a member's prompt) with reverse, which a reversed
|
|
170
|
+
# bar would hide.
|
|
171
|
+
"set -g window-status-bell-style noreverse",
|
|
172
|
+
"set -g status-right ' #{@workcrew_team}'",
|
|
173
|
+
"set -g status-right-style bold", # outside status-right, whose length _LEFT counts
|
|
174
|
+
"set -g window-status-current-style bold",
|
|
175
|
+
# Centred, the window list stands apart from the counts on its left and the team's name on
|
|
176
|
+
# its right; run together, they read as one value.
|
|
177
|
+
"set -g status-justify centre",
|
|
178
|
+
# The space leads each entry: a space ending status-left is cut with the text, and two
|
|
179
|
+
# fields run together. tmux draws a window that is not current only beside another, but
|
|
180
|
+
# a lone window's entry read as one of the counts: it shows only when zoomed, where Z is
|
|
181
|
+
# the one sign that panes are hidden.
|
|
182
|
+
"set -g window-status-format ' #I:#W#F'",
|
|
183
|
+
"set -g window-status-current-format '#{?#{||:#{e|>:#{session_windows},1},"
|
|
184
|
+
"#{window_zoomed_flag}}, #I:#W#F,}'",
|
|
185
|
+
"set -g window-status-separator ''",
|
|
186
|
+
"set -g pane-border-status top",
|
|
187
|
+
"set -g pane-border-lines single",
|
|
188
|
+
# Blue, not a grey: Claude Code draws its own rules grey, and a grey border reads as one.
|
|
189
|
+
"set -g pane-border-style fg=blue",
|
|
190
|
+
# tmux lights the active pane's border, whose top line runs under the input box of the pane
|
|
191
|
+
# above and reads as that pane's.
|
|
192
|
+
"set -g pane-active-border-style fg=blue",
|
|
193
|
+
# In a border, `default` is the border's colour; `terminal` is the terminal's own. A
|
|
194
|
+
# name is a user option, whose value tmux does not expand, but draws a `#[` in it as a
|
|
195
|
+
# style, on 3.2a with no escape: a name holds no `#`. The owner's labels are no name.
|
|
196
|
+
# A pane made to run the board closes when it ends, so its label cannot outlive it. tmux
|
|
197
|
+
# quotes a path with a space in the command it shows: "/a b/workcrew" board. A name or a
|
|
198
|
+
# key holds nothing tmux quotes.
|
|
199
|
+
# Claude Code draws no cursor in an inactive pane: only the mark shows where keys go. A
|
|
200
|
+
# waiting pane's box is reversed too; the ► tells the active one apart.
|
|
201
|
+
"set -g pane-border-format '#[fg=terminal]#{?pane_active,► #[reverse],}"
|
|
202
|
+
"#{?@workcrew_member,#[bold] #{@workcrew_name} ,"
|
|
203
|
+
'#{?#{m/r:workcrew"?( -r [^ ]+)? board,#{pane_start_command}}, (board) , (you) }}#[default]'
|
|
204
|
+
"#{?@workcrew_died, EXITED "
|
|
205
|
+
"#{?pane_dead_signal,#{?#{m:[0-9]*,#{pane_dead_signal}},"
|
|
206
|
+
"#{e|+:128,#{pane_dead_signal}},#{pane_dead_signal}},#{pane_dead_status}},"
|
|
207
|
+
"#{?#{==:#{@workcrew_state},wait},#[reverse] WAITING #[default],}} '",
|
|
208
|
+
# A popup's own command cannot open a second popup, but a binding runs its second
|
|
209
|
+
# command after the first popup has closed. `tmux` from PATH is the binary that started
|
|
210
|
+
# the server: the server's PATH is that of the shell that started it.
|
|
211
|
+
# Keys read with C-] are queued before the popup exists and run once the binding ends:
|
|
212
|
+
# into the active pane (tmux 3.2a to 3.8, server-client.c), where `exit` and Enter ended
|
|
213
|
+
# a member. Its input is off while they run, and on again from the end of the client's
|
|
214
|
+
# queue, behind them: run-shell -b -C appends there, inside the server, on the next
|
|
215
|
+
# loop turn, while the result check's job runs, so a key typed after it goes through.
|
|
216
|
+
"bind -n C-] { display-popup -E -w 100% -h 3 -y S '\"$WORKCREW_BIN\" _prompt' ; "
|
|
217
|
+
"select-pane -d ; run-shell -b -C 'select-pane -e -t #{pane_id}' ; "
|
|
218
|
+
f"if-shell 'tmux show-buffer -b {_SHOWN} >/dev/null 2>&1' "
|
|
219
|
+
f"{{ display-popup -E -w {_SHOW_W}% -h {_SHOW_H}% '{_SHOW}' }} }}",
|
|
220
|
+
f"bind -n Escape if -F '{_GUARD}' '' 'send-keys Escape'",
|
|
221
|
+
# tmux reads a pane as dead when its pty closes, but reaps its status later, and runs
|
|
222
|
+
# pane-died only then: the mark says the status is in.
|
|
223
|
+
f"set-hook -g pane-died {{ set -p @workcrew_died 1 ; {_RECONCILE} }}",
|
|
224
|
+
*(f"set-hook -g {h} {{ {_RECONCILE} }}" for h in HOOKS if h != "pane-died"),
|
|
225
|
+
# A start lays the team out with no client, at tmux's 80x24: the owner's attach lays it
|
|
226
|
+
# out again at the owner's size, which it is handed, since the hook can run before the
|
|
227
|
+
# window has taken it (3.8).
|
|
228
|
+
"set-hook -g client-attached { run-shell -b"
|
|
229
|
+
" '\"$WORKCREW_BIN\" _reconcile attached #{client_width} #{client_height}' }",
|
|
230
|
+
]
|
|
231
|
+
return "\n".join(lines) + "\n"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def show_size(view: ServerView) -> tuple[int, int]:
|
|
235
|
+
"""The columns and lines a result has inside the result popup. tmux takes the popup's
|
|
236
|
+
percentages of the client, which is the team window and the status line's one row, and the
|
|
237
|
+
popup's border takes one column or line on each side."""
|
|
238
|
+
return view.width * _SHOW_W // 100 - 2, (view.height + 1) * _SHOW_H // 100 - 2
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _more(n: int, team: str) -> str:
|
|
242
|
+
return f"+{n} more line{'s' * (n != 1)}: run workcrew -r {team} <command> in a shell."
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _drawn(line: str, width: int) -> int:
|
|
246
|
+
"""The rows a line takes, as tmux wraps it at the popup's width. tmux does not split a wide
|
|
247
|
+
character across the last column, so a row can end one column short and the columns alone
|
|
248
|
+
do not say how many rows a line takes."""
|
|
249
|
+
rows, used = 1, 0
|
|
250
|
+
for ch in line:
|
|
251
|
+
if used + cols(ch) > width:
|
|
252
|
+
rows, used = rows + 1, 0
|
|
253
|
+
used += cols(ch)
|
|
254
|
+
return rows
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _capped(text: str, width: int, rows: int, team: str) -> str:
|
|
258
|
+
"""A result for the popup, which shows it once and has no way back to its top. One taller
|
|
259
|
+
than the popup keeps its top, and its last row says what is not shown. Rows are counted as
|
|
260
|
+
tmux draws them: a line wider than the popup wraps and takes more than one."""
|
|
261
|
+
lines = text.rstrip("\n").split("\n")
|
|
262
|
+
if sum(_drawn(line, width) for line in lines) > rows:
|
|
263
|
+
# The saying is widest when every line is left out, and its rows come off before any
|
|
264
|
+
# line is kept, so the one finally written always fits.
|
|
265
|
+
room = rows - _drawn(_more(len(lines), team), width)
|
|
266
|
+
kept: list[str] = []
|
|
267
|
+
used = 0
|
|
268
|
+
for line in lines:
|
|
269
|
+
if used + _drawn(line, width) > room:
|
|
270
|
+
break
|
|
271
|
+
kept.append(line)
|
|
272
|
+
used += _drawn(line, width)
|
|
273
|
+
lines = [*kept, _more(len(lines) - len(kept), team)]
|
|
274
|
+
# No line break after the last row: it would put the cursor past the popup's last line and
|
|
275
|
+
# scroll the first one away, which is the whole of what this guards against.
|
|
276
|
+
return "\n".join(lines)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def socket_team(env: Mapping[str, str]) -> str | None:
|
|
280
|
+
"""The team whose server `$TMUX` names, by the socket's name; None for any other server."""
|
|
281
|
+
parts = env.get("TMUX", "").rsplit(",", 2)
|
|
282
|
+
name = Path(parts[0]).name
|
|
283
|
+
return (
|
|
284
|
+
name.removeprefix("workcrew-") if len(parts) == 3 and name.startswith("workcrew-") else None
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def whoami(env: Mapping[str, str]) -> tuple[str | None, str]:
|
|
289
|
+
"""(team key or None, member id or "owner"): by the caller's pane on one of our servers;
|
|
290
|
+
with no pane, or outside them, the member it descends from, else the owner."""
|
|
291
|
+
key = socket_team(env)
|
|
292
|
+
if key is None:
|
|
293
|
+
return _descent() or (None, "owner")
|
|
294
|
+
parts = env["TMUX"].rsplit(",", 2)
|
|
295
|
+
socket = parts[0]
|
|
296
|
+
pane = env.get("TMUX_PANE")
|
|
297
|
+
target = ["-t", pane] if pane else []
|
|
298
|
+
fmt = "#{pid}\t#{pane_id}\t#{pane_dead}\t#{@workcrew_member}"
|
|
299
|
+
r = subprocess.run(
|
|
300
|
+
[_bin(), "-S", socket, "display", "-p", *target, fmt],
|
|
301
|
+
capture_output=True,
|
|
302
|
+
text=True,
|
|
303
|
+
check=False,
|
|
304
|
+
)
|
|
305
|
+
pid, got, dead, member = [*r.stdout.rstrip("\n").split("\t"), "", "", "", ""][:4]
|
|
306
|
+
# A server restarted on the same socket reuses pane ids: its pid tells it from the dead one.
|
|
307
|
+
if r.returncode or pid != parts[1]:
|
|
308
|
+
raise Refused(OFF_TEAM)
|
|
309
|
+
# A hook's job and the command line's popup have no TMUX_PANE; a member's command can drop it.
|
|
310
|
+
if not pane:
|
|
311
|
+
return _descent() or (key, "owner")
|
|
312
|
+
# tmux 3.6 answers for a pane that is gone with another pane, so the id must match.
|
|
313
|
+
if dead == "1" or got != pane:
|
|
314
|
+
raise Refused(OFF_TEAM)
|
|
315
|
+
return key, member or "owner"
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _descent() -> tuple[str, str] | None:
|
|
319
|
+
"""The member a caller that the environment makes the owner descends from: a member can
|
|
320
|
+
remove any variable on its way out of Claude Code's sandbox, but not change an ancestor's
|
|
321
|
+
argv. The outermost note wins, since a member can start a process that names another's."""
|
|
322
|
+
out = subprocess.run(
|
|
323
|
+
["ps", "-A", "-ww", "-o", "pid=,ppid=,args="], # noqa: S607 - by name, as tmux is: a member can only remove PATH, and then the default path applies
|
|
324
|
+
capture_output=True,
|
|
325
|
+
text=True,
|
|
326
|
+
check=False,
|
|
327
|
+
).stdout
|
|
328
|
+
procs: dict[int, tuple[int, str]] = {}
|
|
329
|
+
for row in out.splitlines():
|
|
330
|
+
p, pp, *argv = row.split(None, 2)
|
|
331
|
+
procs[int(p)] = int(pp), "".join(argv)
|
|
332
|
+
found: tuple[str, str] | None = None
|
|
333
|
+
pid = os.getppid()
|
|
334
|
+
while pid in procs:
|
|
335
|
+
pid, args = procs.pop(pid)
|
|
336
|
+
found = noted(args) or found
|
|
337
|
+
return found
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
@dataclass(frozen=True)
|
|
341
|
+
class PaneView:
|
|
342
|
+
id: str
|
|
343
|
+
window_id: str
|
|
344
|
+
window: str
|
|
345
|
+
member: str | None
|
|
346
|
+
name: str | None
|
|
347
|
+
dead: bool
|
|
348
|
+
status: int | None
|
|
349
|
+
state: str | None
|
|
350
|
+
zoomed: bool
|
|
351
|
+
# Its window carries the tool's mark, set where the tool makes a window: it stays the tool's
|
|
352
|
+
# while only an owner's pane is left in it, so the next layout puts members there, not in a
|
|
353
|
+
# second window of the same name.
|
|
354
|
+
ours: bool
|
|
355
|
+
# None for a dead pane, and wherever tmux prints none: 3.8 prints none once the pane's pty
|
|
356
|
+
# has closed, and older releases print the pid of a process already reaped, which another
|
|
357
|
+
# process may now hold.
|
|
358
|
+
pid: int | None
|
|
359
|
+
team_window: bool
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
@dataclass(frozen=True)
|
|
363
|
+
class ServerView:
|
|
364
|
+
pid: int
|
|
365
|
+
width: int
|
|
366
|
+
height: int
|
|
367
|
+
panes: tuple[PaneView, ...]
|
|
368
|
+
started: frozenset[str]
|
|
369
|
+
exited: frozenset[str]
|
|
370
|
+
clients: tuple[str, ...]
|
|
371
|
+
socket_path: str
|
|
372
|
+
team: str = "" # the team name the server shows: reconcile brings it to the roster's
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
_CLIENT = "C\t#{client_name}"
|
|
376
|
+
_WINDOWS = "#{W:#{E:window-status-format},#{E:window-status-current-format}}"
|
|
377
|
+
_LEFT = f"#{{e|-:#{{e|-:#{{client_width}},#{{n:{_WINDOWS}}}}},#{{n:#{{E:status-right}}}}}}"
|
|
378
|
+
_PANE = "\t".join(
|
|
379
|
+
[
|
|
380
|
+
"P",
|
|
381
|
+
"#{pane_id}",
|
|
382
|
+
"#{window_id}",
|
|
383
|
+
"#{window_name}",
|
|
384
|
+
"#{@workcrew_member}",
|
|
385
|
+
"#{@workcrew_name}",
|
|
386
|
+
"#{@workcrew_died}",
|
|
387
|
+
"#{pane_dead_status}",
|
|
388
|
+
"#{pane_dead_signal}",
|
|
389
|
+
"#{@workcrew_state}",
|
|
390
|
+
"#{window_zoomed_flag}",
|
|
391
|
+
"#{pane_pid}",
|
|
392
|
+
"#{window_width}",
|
|
393
|
+
"#{window_height}",
|
|
394
|
+
"#{@workcrew_window}",
|
|
395
|
+
f"#{{{_TEAM_WINDOW}}}",
|
|
396
|
+
]
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
class Server:
|
|
401
|
+
def __init__(self, key: str) -> None:
|
|
402
|
+
self.socket = f"workcrew-{key}"
|
|
403
|
+
|
|
404
|
+
def _run(self, *args: str, stdin: str | None = None) -> subprocess.CompletedProcess[str]:
|
|
405
|
+
# A server keeps the environment of the command that starts it: an inherited TMUX_PANE
|
|
406
|
+
# would make the owner's popup look like a pane.
|
|
407
|
+
env = {k: v for k, v in os.environ.items() if k not in ("TMUX", "TMUX_PANE")}
|
|
408
|
+
# Without TMUX, tmux takes a client's UTF-8 from its locale, and for a client without it
|
|
409
|
+
# turns every byte outside printable ASCII in its output into "_" (utf8_sanitize): the
|
|
410
|
+
# tabs between fields and any non-ASCII path. -u marks the client UTF-8; then its output
|
|
411
|
+
# is UTF-8 whatever the locale.
|
|
412
|
+
return subprocess.run(
|
|
413
|
+
[_bin(), "-u", "-L", self.socket, *args],
|
|
414
|
+
input=stdin,
|
|
415
|
+
env=env,
|
|
416
|
+
capture_output=True,
|
|
417
|
+
encoding="utf-8",
|
|
418
|
+
check=False,
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
def _do(self, *args: str, stdin: str | None = None) -> str:
|
|
422
|
+
r = self._run(*args, stdin=stdin)
|
|
423
|
+
if r.returncode:
|
|
424
|
+
err = r.stderr.strip()
|
|
425
|
+
raise (Gone if err.startswith(_GONE_ERRORS) else StateError)(f"tmux {args[0]}: {err}")
|
|
426
|
+
return r.stdout
|
|
427
|
+
|
|
428
|
+
def alive(self) -> bool:
|
|
429
|
+
return self._run("list-sessions").returncode == 0
|
|
430
|
+
|
|
431
|
+
def view(self) -> ServerView:
|
|
432
|
+
out = self._do(
|
|
433
|
+
"list-panes", "-a", "-F", _PANE, ";",
|
|
434
|
+
"list-clients", "-F", _CLIENT, ";",
|
|
435
|
+
"display", "-p",
|
|
436
|
+
"S\t#{pid}\t#{@workcrew_started}\t#{@workcrew_exited}\t#{socket_path}\t#{@workcrew_team}",
|
|
437
|
+
";", "show-environment", "-gh",
|
|
438
|
+
) # fmt: skip
|
|
439
|
+
lines = out.splitlines()
|
|
440
|
+
# A pane's variable outlives the pane, and is harmless: tmux never gives a pane id twice
|
|
441
|
+
# in a server's life, and respawn, which keeps the id, unsets it.
|
|
442
|
+
hidden = dict(
|
|
443
|
+
ln.removeprefix(_HIDDEN).split("=", 1) for ln in lines if ln.startswith(_HIDDEN)
|
|
444
|
+
)
|
|
445
|
+
panes, clients, server = [], [], ["", "0", "", "", "", ""]
|
|
446
|
+
for line in lines:
|
|
447
|
+
f = line.split("\t")
|
|
448
|
+
if f[0] == "P":
|
|
449
|
+
dead = f[6] == "1"
|
|
450
|
+
status = _exit_status(f[7], f[8])
|
|
451
|
+
pid = None if dead or not f[11] else int(f[11])
|
|
452
|
+
state = f[9] or hidden.get(f[1])
|
|
453
|
+
panes.append(
|
|
454
|
+
PaneView(
|
|
455
|
+
f[1], f[2], f[3], f[4] or None, f[5] or None, dead,
|
|
456
|
+
status, state, f[10] == "1", f[14] == "1", pid, f[15] == "1",
|
|
457
|
+
)
|
|
458
|
+
) # fmt: skip
|
|
459
|
+
if f[15] == "1" or not panes[:-1]:
|
|
460
|
+
window = (int(f[12]), int(f[13]))
|
|
461
|
+
elif f[0] == "C":
|
|
462
|
+
clients.append(f[1])
|
|
463
|
+
elif f[0] == "S":
|
|
464
|
+
server = f
|
|
465
|
+
return ServerView(
|
|
466
|
+
int(server[1]), *window, tuple(panes),
|
|
467
|
+
frozenset(server[2].split()), frozenset(server[3].split()), tuple(clients), server[4],
|
|
468
|
+
server[5],
|
|
469
|
+
) # fmt: skip
|
|
470
|
+
|
|
471
|
+
def boot(self, conf: str, bin: str, argv: Sequence[str], cwd: str, member: str) -> str:
|
|
472
|
+
target = f"{SESSION}:"
|
|
473
|
+
out = self._do(
|
|
474
|
+
"-f", _arg(conf), "set-environment", "-g", "WORKCREW_BIN", _arg(bin), ";",
|
|
475
|
+
"new-session", "-d", "-s", TEAM, "-n", TEAM, "-c", _unexpanded(cwd),
|
|
476
|
+
"-P", "-F", "#{pane_id}", *map(_arg, argv), ";",
|
|
477
|
+
"set", "-p", "-t", target, "@workcrew_member", member, ";",
|
|
478
|
+
"set", "-p", "-t", target, "remain-on-exit", "failed", ";",
|
|
479
|
+
"set", "-w", "-t", target, "@workcrew_window", "1", ";",
|
|
480
|
+
"set", "-w", "-t", target, _TEAM_WINDOW, "1", ";",
|
|
481
|
+
# Placed where it stands, as a joined pane is: one the owner moves out stays out.
|
|
482
|
+
"set", "-p", "-t", target, "@workcrew_placed", "1", ";",
|
|
483
|
+
*_marks({member}, ()),
|
|
484
|
+
) # fmt: skip
|
|
485
|
+
return out.split()[0]
|
|
486
|
+
|
|
487
|
+
def bin(self) -> str:
|
|
488
|
+
"""The tool's path as the server holds it: reconcile starts members and the poller by it,
|
|
489
|
+
and a member's command keeps it (cli._tool)."""
|
|
490
|
+
return self._do("show-environment", "-g", "WORKCREW_BIN").strip().split("=", 1)[1]
|
|
491
|
+
|
|
492
|
+
def has_env(self, name: str) -> bool:
|
|
493
|
+
"""Whether the server's global environment sets `name`: that is the environment a member's
|
|
494
|
+
pane is given, and never the environment of the command asking. tmux prints `NAME=value`
|
|
495
|
+
for one that is set, `-NAME` for one marked unset, and fails for one it does not hold."""
|
|
496
|
+
return "=" in self._run("show-environment", "-g", name).stdout
|
|
497
|
+
|
|
498
|
+
def setup(self, conf: str, bin: str) -> None:
|
|
499
|
+
self._do("set-environment", "-g", "WORKCREW_BIN", _arg(bin), ";", "source-file", _arg(conf))
|
|
500
|
+
|
|
501
|
+
def spawn(
|
|
502
|
+
self,
|
|
503
|
+
argv: Sequence[str],
|
|
504
|
+
cwd: str,
|
|
505
|
+
member: str,
|
|
506
|
+
started: Iterable[str],
|
|
507
|
+
exited: Iterable[str],
|
|
508
|
+
) -> str:
|
|
509
|
+
"""A new window whose pane is tagged, and the marks set, in the same tmux command, so no
|
|
510
|
+
reconcile sees it untagged and no crash leaves it unmarked. It goes after the last window,
|
|
511
|
+
which the rest of the command can then name: no index is chosen first for the owner to
|
|
512
|
+
take."""
|
|
513
|
+
target = f"{SESSION}:{{end}}."
|
|
514
|
+
out = self._do(
|
|
515
|
+
"new-window", "-d", "-a", "-t", target[:-1], "-c", _unexpanded(cwd),
|
|
516
|
+
"-P", "-F", "#{pane_id}", *map(_arg, argv), ";",
|
|
517
|
+
"set", "-p", "-t", target, "@workcrew_member", member, ";",
|
|
518
|
+
"set", "-p", "-t", target, "remain-on-exit", "failed", ";",
|
|
519
|
+
"set", "-w", "-t", target, "@workcrew_window", "1", ";",
|
|
520
|
+
*_marks(started, exited),
|
|
521
|
+
) # fmt: skip
|
|
522
|
+
return out.split()[0]
|
|
523
|
+
|
|
524
|
+
def respawn(
|
|
525
|
+
self,
|
|
526
|
+
pane: str,
|
|
527
|
+
argv: Sequence[str],
|
|
528
|
+
cwd: str,
|
|
529
|
+
started: Iterable[str],
|
|
530
|
+
exited: Iterable[str],
|
|
531
|
+
) -> None:
|
|
532
|
+
"""Restarts a dead pane in place, and sets the marks in the same tmux command: its id,
|
|
533
|
+
options and cell stay, and no window closes. Without -k, tmux refuses a running pane."""
|
|
534
|
+
self._do(
|
|
535
|
+
"respawn-pane", "-t", pane, "-c", _unexpanded(cwd), *map(_arg, argv), ";",
|
|
536
|
+
"set", "-pu", "-t", pane, "@workcrew_died", ";",
|
|
537
|
+
# The pane keeps its options and its id: a member killed while waiting or busy would
|
|
538
|
+
# come back so.
|
|
539
|
+
"set", "-pu", "-t", pane, "@workcrew_state", ";",
|
|
540
|
+
"set-environment", "-gu", _HIDDEN + pane, ";",
|
|
541
|
+
*_marks(started, exited),
|
|
542
|
+
) # fmt: skip
|
|
543
|
+
|
|
544
|
+
def apply(
|
|
545
|
+
self,
|
|
546
|
+
view: ServerView,
|
|
547
|
+
cells: Sequence[Cell],
|
|
548
|
+
how: Lay = "join",
|
|
549
|
+
kept: Arrangement | None = None,
|
|
550
|
+
least: tuple[int, int] = (0, 0),
|
|
551
|
+
) -> None:
|
|
552
|
+
"""Moves the members' panes into the team window. `join` puts each member never placed
|
|
553
|
+
into the largest worker pane and leaves every other pane where the owner has it; `grid`
|
|
554
|
+
lays the tool's grid out with every member brought back; `restore` puts `kept` back when
|
|
555
|
+
the panes match it and leave each member's at least `least` columns and rows, with each
|
|
556
|
+
member the owner had moved out in a window of its own, else the grid. A zoomed window is
|
|
557
|
+
left as it is unless a member joins it, since moving a pane unzooms its window."""
|
|
558
|
+
if not cells:
|
|
559
|
+
return
|
|
560
|
+
zoomed = {p.window_id for p in view.panes if p.zoomed}
|
|
561
|
+
stay = set(kept.out) if how == "restore" and kept else set()
|
|
562
|
+
loose = self._loose(view, {c.member for c in cells if c.member} - stay, how, zoomed)
|
|
563
|
+
panes = self.view().panes
|
|
564
|
+
wid = next(
|
|
565
|
+
(
|
|
566
|
+
p.window_id
|
|
567
|
+
for p in panes
|
|
568
|
+
if p.team_window and (p.member or p.ours) and p.id not in loose
|
|
569
|
+
),
|
|
570
|
+
None,
|
|
571
|
+
)
|
|
572
|
+
if how == "join" and not loose:
|
|
573
|
+
return
|
|
574
|
+
where = {p.member: p for p in panes if p.member}
|
|
575
|
+
joins = [q.id for c in cells if c.member and (q := where.get(c.member)) and q.id in loose]
|
|
576
|
+
# The member would wait unseen until the owner unzoomed: it joins, and the pane that was
|
|
577
|
+
# zoomed, the window's active one, is zoomed again.
|
|
578
|
+
zoom = self._do("display", "-p", "-t", wid, "#{pane_id}").strip() if wid in zoomed else ""
|
|
579
|
+
# A worker's pane that closed since the view leaves none to split: the grid, as with none.
|
|
580
|
+
if how != "join" or wid is None or not all(self._into_largest(wid, p) for p in joins):
|
|
581
|
+
wid = self._join(wid, cells, where, loose)
|
|
582
|
+
seen = bool(view.clients)
|
|
583
|
+
if wid is not None and not (
|
|
584
|
+
how == "restore" and kept and self._restore(wid, kept, seen, least)
|
|
585
|
+
):
|
|
586
|
+
if stay: # the grid has a cell for every member, those moved out included
|
|
587
|
+
panes = self.view().panes
|
|
588
|
+
self._join(
|
|
589
|
+
wid,
|
|
590
|
+
cells,
|
|
591
|
+
where,
|
|
592
|
+
{p.id for p in panes if p.member in stay and p.window_id != wid},
|
|
593
|
+
)
|
|
594
|
+
self._lay_out(wid, cells)
|
|
595
|
+
if not seen: # laid out for a size nobody sees: the first attach's
|
|
596
|
+
self.mark_fresh("grid")
|
|
597
|
+
# Placed, as a joined member is: the passes that follow leave it where it is.
|
|
598
|
+
for pane in loose | {q.id for m, q in where.items() if m in stay}:
|
|
599
|
+
self._do("set", "-p", "-t", pane, "@workcrew_placed", "1")
|
|
600
|
+
if zoom:
|
|
601
|
+
self._do("resize-pane", "-Z", "-t", zoom)
|
|
602
|
+
|
|
603
|
+
def _loose(self, view: ServerView, members: set[str], how: Lay, zoomed: set[str]) -> set[str]:
|
|
604
|
+
"""The members' panes to bring into the team window, each alone in its window. A member
|
|
605
|
+
the owner broke out stays where they put it, short of a grid: a new one was never placed.
|
|
606
|
+
A pane is not moved out of a zoomed window."""
|
|
607
|
+
outside = [p for p in view.panes if p.member in members and not p.team_window]
|
|
608
|
+
placed: set[str] = set()
|
|
609
|
+
if how == "join" and outside:
|
|
610
|
+
out = self._do("list-panes", "-a", "-F", "#{pane_id}\t#{@workcrew_placed}")
|
|
611
|
+
placed = {pane for pane, mark in (r.split("\t") for r in out.splitlines()) if mark}
|
|
612
|
+
count: dict[str, int] = {}
|
|
613
|
+
for p in view.panes:
|
|
614
|
+
count[p.window_id] = count.get(p.window_id, 0) + 1
|
|
615
|
+
loose = set()
|
|
616
|
+
for p in outside:
|
|
617
|
+
if p.window_id not in zoomed and p.id not in placed:
|
|
618
|
+
if count[p.window_id] > 1:
|
|
619
|
+
self._do(
|
|
620
|
+
"break-pane", "-d", "-s", p.id, ";",
|
|
621
|
+
"set", "-w", "-t", p.id, "@workcrew_window", "1",
|
|
622
|
+
) # fmt: skip
|
|
623
|
+
count[p.window_id] -= 1
|
|
624
|
+
loose.add(p.id)
|
|
625
|
+
return loose
|
|
626
|
+
|
|
627
|
+
def _into_largest(self, wid: str, pane: str) -> bool:
|
|
628
|
+
"""Into the largest worker pane, split across its longer side by the grid's shape rule:
|
|
629
|
+
the leader's pane and the owner's are never split. False, joining nothing, when the
|
|
630
|
+
window has no worker pane."""
|
|
631
|
+
out = self._do(
|
|
632
|
+
"list-panes", "-t", wid, "-F",
|
|
633
|
+
"#{pane_id}\t#{@workcrew_member}\t#{pane_width}\t#{pane_height}",
|
|
634
|
+
) # fmt: skip
|
|
635
|
+
rows = [r.split("\t") for r in out.splitlines()]
|
|
636
|
+
workers = [r for r in rows if r[1] and r[1] != LEADER]
|
|
637
|
+
if not workers:
|
|
638
|
+
return False
|
|
639
|
+
big = max(workers, key=lambda r: int(r[2]) * int(r[3]))
|
|
640
|
+
side = "-h" if int(big[2]) / ASPECT > int(big[3]) else "-v"
|
|
641
|
+
self._do("join-pane", "-d", side, "-s", pane, "-t", big[0])
|
|
642
|
+
return True
|
|
643
|
+
|
|
644
|
+
def _join(
|
|
645
|
+
self, wid: str | None, cells: Sequence[Cell], where: Mapping[str, PaneView], loose: set[str]
|
|
646
|
+
) -> str | None:
|
|
647
|
+
"""Joins the loose members into the window, or makes the first one's window it."""
|
|
648
|
+
for c in cells:
|
|
649
|
+
q = where.get(c.member) if c.member else None
|
|
650
|
+
if q is None or q.id not in loose:
|
|
651
|
+
continue
|
|
652
|
+
if wid is None:
|
|
653
|
+
wid = q.window_id
|
|
654
|
+
self._do(
|
|
655
|
+
"set", "-w", "-t", wid, _TEAM_WINDOW, "1", ";", "rename-window", "-t", wid, TEAM
|
|
656
|
+
) # fmt: skip
|
|
657
|
+
else:
|
|
658
|
+
self._do("select-layout", "-t", wid, "tiled") # room for one more pane
|
|
659
|
+
self._do("join-pane", "-d", "-s", q.id, "-t", wid)
|
|
660
|
+
return wid
|
|
661
|
+
|
|
662
|
+
def _panes_of(self, wid: str) -> tuple[list[str], dict[str, str], list[str], str]:
|
|
663
|
+
"""The window's panes in index order, its members' panes by member, its owner's panes,
|
|
664
|
+
and its active pane."""
|
|
665
|
+
out = self._do(
|
|
666
|
+
"list-panes", "-t", wid, "-F", "#{pane_id}\t#{@workcrew_member}\t#{pane_active}"
|
|
667
|
+
)
|
|
668
|
+
rows = [r.split("\t") for r in out.splitlines()]
|
|
669
|
+
return (
|
|
670
|
+
[pane for pane, _, _ in rows],
|
|
671
|
+
{member: pane for pane, member, _ in rows if member},
|
|
672
|
+
[pane for pane, member, _ in rows if not member],
|
|
673
|
+
next(pane for pane, _, active in rows if active == "1"),
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
def _order(self, cur: list[str], want: Sequence[str], active: str) -> None:
|
|
677
|
+
"""tmux fills a layout's cells in pane-index order, whatever pane ids the string holds.
|
|
678
|
+
The owner's active pane stays active: a swap with -d gives its place, and with it the
|
|
679
|
+
focus, to the other pane, while one without makes its target active (cmd-swap-pane.c)."""
|
|
680
|
+
for k, pid in enumerate(want):
|
|
681
|
+
if cur[k] != pid:
|
|
682
|
+
j = cur.index(pid)
|
|
683
|
+
if active in (pid, cur[k]):
|
|
684
|
+
other = cur[k] if pid == active else pid
|
|
685
|
+
self._do("swap-pane", "-s", other, "-t", active)
|
|
686
|
+
else:
|
|
687
|
+
self._do("swap-pane", "-d", "-s", pid, "-t", cur[k])
|
|
688
|
+
cur[k], cur[j] = cur[j], cur[k]
|
|
689
|
+
|
|
690
|
+
def _lay_out(self, wid: str, cells: Sequence[Cell]) -> None:
|
|
691
|
+
cur, tags, owners, active = self._panes_of(wid)
|
|
692
|
+
layout, order = _layout(cells)
|
|
693
|
+
want = [
|
|
694
|
+
tags.get(c.member, "") if c.member else (owners.pop(0) if owners else "") for c in order
|
|
695
|
+
]
|
|
696
|
+
if sorted(want) != sorted(cur):
|
|
697
|
+
return # a planned member without a pane here: tmux needs one cell per pane
|
|
698
|
+
self._order(cur, want, active)
|
|
699
|
+
self._do("select-layout", "-t", wid, layout)
|
|
700
|
+
|
|
701
|
+
def _restore(self, wid: str, kept: Arrangement, seen: bool, least: tuple[int, int]) -> bool:
|
|
702
|
+
"""The owner's arrangement back, when the window holds the same members and as many of
|
|
703
|
+
the owner's panes: tmux lays five panes out by a six-pane string without a word. Put
|
|
704
|
+
back where nobody sees it, the first attach puts it back again at its size; put back
|
|
705
|
+
where a client sees it, it must leave every member's pane readable."""
|
|
706
|
+
cur, tags, owners, active = self._panes_of(wid)
|
|
707
|
+
# The team window holds the leader from the start: one the owner had moved out goes out.
|
|
708
|
+
moved = [tags.pop(m) for m in kept.out if m in tags]
|
|
709
|
+
if sorted([*tags, *[""] * len(owners)]) != sorted(kept.order):
|
|
710
|
+
return False
|
|
711
|
+
if moved:
|
|
712
|
+
for pane in moved:
|
|
713
|
+
self._do(
|
|
714
|
+
"break-pane", "-d", "-s", pane, ";",
|
|
715
|
+
"set", "-w", "-t", pane, "@workcrew_window", "1",
|
|
716
|
+
) # fmt: skip
|
|
717
|
+
cur, tags, owners, active = self._panes_of(wid)
|
|
718
|
+
self._order(cur, [tags[m] if m else owners.pop(0) for m in kept.order], active)
|
|
719
|
+
if not _readable(kept.layout, self._do("display", "-p", "-t", wid, "#{window_layout}")):
|
|
720
|
+
return False
|
|
721
|
+
try: # in a form this tmux reads and still refused, a wrong four-digit sum among them
|
|
722
|
+
self._do("select-layout", "-t", wid, kept.layout)
|
|
723
|
+
except StateError:
|
|
724
|
+
return False
|
|
725
|
+
if not seen:
|
|
726
|
+
self.mark_fresh("restore")
|
|
727
|
+
else:
|
|
728
|
+
# tmux scales a layout to the client from the string's size: a border the owner
|
|
729
|
+
# dragged at a larger size can leave a pane 1 column wide.
|
|
730
|
+
out = self._do(
|
|
731
|
+
"list-panes", "-t", wid, "-F", "#{@workcrew_member}\t#{pane_width}\t#{pane_height}"
|
|
732
|
+
)
|
|
733
|
+
rows = [r.split("\t") for r in out.splitlines()]
|
|
734
|
+
if any(m and (int(w) < least[0] or int(h) < least[1]) for m, w, h in rows):
|
|
735
|
+
return False
|
|
736
|
+
if kept.zoomed in tags:
|
|
737
|
+
self._do("resize-pane", "-Z", "-t", tags[kept.zoomed])
|
|
738
|
+
return True
|
|
739
|
+
|
|
740
|
+
def arrangement(self) -> Arrangement | None:
|
|
741
|
+
"""The team window as it is now, to keep across `exit` and a start."""
|
|
742
|
+
out = self._do(
|
|
743
|
+
"list-panes", "-a", "-F",
|
|
744
|
+
f"#{{{_TEAM_WINDOW}}}\t#{{pane_index}}\t#{{@workcrew_member}}\t#{{window_layout}}"
|
|
745
|
+
"\t#{window_zoomed_flag}\t#{pane_active}\t#{@workcrew_placed}",
|
|
746
|
+
) # fmt: skip
|
|
747
|
+
every = [r.split("\t") for r in out.splitlines()]
|
|
748
|
+
rows = sorted((r for r in every if r[0] == "1"), key=lambda r: int(r[1]))
|
|
749
|
+
if not rows:
|
|
750
|
+
return None
|
|
751
|
+
zoomed = next((r[2] for r in rows if r[4] == "1" and r[5] == "1" and r[2]), None)
|
|
752
|
+
# Placed and elsewhere: moved out by the owner. The poller, and a member started but not
|
|
753
|
+
# yet joined, were never placed.
|
|
754
|
+
moved = tuple(sorted(r[2] for r in every if r[0] != "1" and r[2] and r[6]))
|
|
755
|
+
return Arrangement(rows[0][3], tuple(r[2] for r in rows), zoomed, moved)
|
|
756
|
+
|
|
757
|
+
# A hidden server variable: writing it repaints no client, as an option's write does.
|
|
758
|
+
def mark_fresh(self, how: Lay) -> None:
|
|
759
|
+
self._do("set-environment", "-gh", _FRESH, how)
|
|
760
|
+
|
|
761
|
+
def take_fresh(self) -> Lay | None:
|
|
762
|
+
"""How the window was laid out for a size nobody saw yet, if it was; the mark goes."""
|
|
763
|
+
got = self._run("show-environment", "-gh", _FRESH)
|
|
764
|
+
if got.returncode:
|
|
765
|
+
return None
|
|
766
|
+
self._do("set-environment", "-ghu", _FRESH)
|
|
767
|
+
return "restore" if got.stdout.strip() == f"{_FRESH}=restore" else "grid"
|
|
768
|
+
|
|
769
|
+
def kill_pane(self, pane: str) -> None:
|
|
770
|
+
self._do("kill-pane", "-t", pane)
|
|
771
|
+
|
|
772
|
+
def wait_exit(self, path: str) -> None:
|
|
773
|
+
"""Returns once nothing listens on the socket at `path`, or after 5 s. A server exits
|
|
774
|
+
after the command that closed its last session has returned, and a hook's job it forked
|
|
775
|
+
holds the listening socket until it execs: tmux 3.6 first asks systemd for a cgroup, for
|
|
776
|
+
some 20 ms. A client that connects meanwhile reaches no server and fails."""
|
|
777
|
+
deadline = time.monotonic() + 5
|
|
778
|
+
while time.monotonic() < deadline:
|
|
779
|
+
with socket.socket(socket.AF_UNIX) as s:
|
|
780
|
+
try:
|
|
781
|
+
s.connect(path)
|
|
782
|
+
except ConnectionRefusedError:
|
|
783
|
+
return
|
|
784
|
+
time.sleep(0.01)
|
|
785
|
+
|
|
786
|
+
def set_marks(self, started: Iterable[str], exited: Iterable[str]) -> None:
|
|
787
|
+
self._do(*_marks(started, exited))
|
|
788
|
+
|
|
789
|
+
def set_name(self, pane: str, name: str) -> None:
|
|
790
|
+
self._do("set", "-p", "-t", pane, "@workcrew_name", name)
|
|
791
|
+
|
|
792
|
+
def set_state(self, pane: str, state: str) -> None:
|
|
793
|
+
"""What STATE_HOOKS["busy"] does, for busy or idle, from the tool."""
|
|
794
|
+
was = self._do(
|
|
795
|
+
"display", "-p", "-t", pane, "#{@workcrew_state}", ";",
|
|
796
|
+
"set-environment", "-gh", _HIDDEN + pane, state,
|
|
797
|
+
) # fmt: skip
|
|
798
|
+
# Any option goes: a team started before this version still marks busy with it.
|
|
799
|
+
if was.strip():
|
|
800
|
+
self._do("set", "-pu", "-t", pane, "@workcrew_state")
|
|
801
|
+
|
|
802
|
+
def paste(self, pane: str, text: str) -> None:
|
|
803
|
+
"""tmux passes a paste-end sequence inside the text through, and what follows it would
|
|
804
|
+
reach the pane as keys. A removal can join a new one, so it repeats until none is left."""
|
|
805
|
+
while _PASTE_END in text:
|
|
806
|
+
text = text.replace(_PASTE_END, "")
|
|
807
|
+
buf = f"workcrew-{uuid.uuid4().hex[:8]}"
|
|
808
|
+
try:
|
|
809
|
+
self._paste(pane, buf, text)
|
|
810
|
+
except StateError:
|
|
811
|
+
# The pane can go while the text is still loading: the owner's text must not wait in
|
|
812
|
+
# a buffer that tmux's own paste key would put into whichever pane has the focus.
|
|
813
|
+
self._run("delete-buffer", "-b", buf)
|
|
814
|
+
raise
|
|
815
|
+
|
|
816
|
+
def _paste(self, pane: str, buf: str, text: str) -> None:
|
|
817
|
+
self._do(
|
|
818
|
+
*_there(pane),
|
|
819
|
+
"load-buffer",
|
|
820
|
+
"-b",
|
|
821
|
+
buf,
|
|
822
|
+
"-",
|
|
823
|
+
";",
|
|
824
|
+
# tmux 3.2a ends its whole server when it pastes into a dead pane, and a pane in copy
|
|
825
|
+
# mode drops a paste, so the paste checks in the same command: a pane that died or
|
|
826
|
+
# was scrolled back after the look is pasted nothing.
|
|
827
|
+
"if-shell",
|
|
828
|
+
"-F",
|
|
829
|
+
"-t",
|
|
830
|
+
pane,
|
|
831
|
+
"#{||:#{pane_dead},#{pane_in_mode}}",
|
|
832
|
+
f"delete-buffer -b {buf}",
|
|
833
|
+
f"paste-buffer -d -p -b {buf} -t {pane}",
|
|
834
|
+
stdin=text,
|
|
835
|
+
)
|
|
836
|
+
|
|
837
|
+
def state(self, pane: str) -> str:
|
|
838
|
+
"""`dead` for a pane whose process has ended, `copy-mode` for one scrolled back, which
|
|
839
|
+
drops a paste, else its columns and rows."""
|
|
840
|
+
fmt = "#{?pane_dead,dead,#{?pane_in_mode,copy-mode,#{pane_width} #{pane_height}}}"
|
|
841
|
+
return self._do(*_there(pane), "display", "-p", "-t", pane, fmt).strip()
|
|
842
|
+
|
|
843
|
+
def enter(self, pane: str) -> None:
|
|
844
|
+
self._do("send-keys", "-t", pane, "Enter")
|
|
845
|
+
|
|
846
|
+
def capture(self, pane: str) -> str:
|
|
847
|
+
# With escapes: a dim placeholder and typed text differ only in their attributes.
|
|
848
|
+
return self._do("capture-pane", "-p", "-e", "-t", pane)
|
|
849
|
+
|
|
850
|
+
def let_go(self, back: bool) -> None:
|
|
851
|
+
"""Every screen of the team leaves it, each with our line and then its own shell."""
|
|
852
|
+
self._do("detach-client", "-s", SESSION, "-E", _STOPPING if back else _FORGOTTEN)
|
|
853
|
+
|
|
854
|
+
def esc_guard(self) -> None:
|
|
855
|
+
self._do("set", "-g", "@workcrew_esc_guard", str(int(time.time()) + 1))
|
|
856
|
+
|
|
857
|
+
def show(self, text: str) -> None:
|
|
858
|
+
"""One line goes to the message line. More wait in a buffer, which the C-] binding shows
|
|
859
|
+
once the command line's popup has closed."""
|
|
860
|
+
if "\n" not in text.rstrip("\n"):
|
|
861
|
+
# tmux 3.2a refuses display-message -c.
|
|
862
|
+
self._do("display-message", "--", _arg(_literal(text)))
|
|
863
|
+
return
|
|
864
|
+
view = self.view()
|
|
865
|
+
self._do("load-buffer", "-b", _SHOWN, "-", stdin=_capped(text, *show_size(view), view.team))
|
|
866
|
+
|
|
867
|
+
def attach(self) -> NoReturn:
|
|
868
|
+
"""Outside tmux the caller becomes the team's client. Inside tmux, one new window of the
|
|
869
|
+
caller's own session runs that client, so the window closes when the client ends."""
|
|
870
|
+
tmux = _bin()
|
|
871
|
+
socket, name = (
|
|
872
|
+
self._do("display", "-p", "#{socket_path}\t#{@workcrew_team}").rstrip("\n").split("\t")
|
|
873
|
+
)
|
|
874
|
+
client = [tmux, "-S", socket, "attach", "-t", SESSION]
|
|
875
|
+
if os.environ.get("TMUX"):
|
|
876
|
+
# With TMUX set, tmux refuses an attach as nested when the client's tty is one of the
|
|
877
|
+
# server's panes', and a dead pane keeps its tty's name: a reused pty is refused.
|
|
878
|
+
window = [tmux, "new-window", "-n", _unexpanded(name), "env", "-u", "TMUX", *client]
|
|
879
|
+
os.execvp(tmux, window) # noqa: S606 tmux itself, argv list
|
|
880
|
+
os.execvp(tmux, client) # noqa: S606 tmux itself, argv list
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def _arg(s: str) -> str:
|
|
884
|
+
# tmux(1): "Individual semicolons or trailing semicolons that should be interpreted as
|
|
885
|
+
# arguments should be escaped twice: once according to the shell conventions and a second
|
|
886
|
+
# time for tmux". An argument list passes no shell, so once.
|
|
887
|
+
return s[:-1] + "\\;" if s.endswith(";") else s
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
def _there(pane: str) -> list[str]:
|
|
891
|
+
"""A first command that fails for a pane that is gone, which `_do` reads as Gone. With a
|
|
892
|
+
client attached, `display -t` and `if-shell -F -t` read such a pane as the client's active
|
|
893
|
+
one instead (3.2a, 3.6, 3.8). Unsetting an option nothing sets changes nothing, and tmux runs
|
|
894
|
+
the rest of the command before any other, so the pane is still there for it."""
|
|
895
|
+
return ["set", "-pu", "-t", pane, "@workcrew_there", ";"]
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _unexpanded(s: str) -> str:
|
|
899
|
+
"""`s` for an argument tmux expands once as a format, as it does every `-c`: there `##` is one
|
|
900
|
+
`#`, and a run of `#` before `[` is kept as it is (measured on tmux 3.2a, 3.6 and 3.8)."""
|
|
901
|
+
return _arg(re.sub(r"(#+)(\[?)", lambda m: m[1] * (1 if m[2] else 2) + m[2], s))
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
def _literal(text: str) -> str:
|
|
905
|
+
"""`text` for display-message to show as it is. tmux expands the message twice, and the second
|
|
906
|
+
pass reads `##` as `#` but keeps `##[`, so a run of k `#` takes 2k before `[` and 4k
|
|
907
|
+
elsewhere; `%` is strftime's (measured on tmux 3.2a and 3.6)."""
|
|
908
|
+
hashes = re.sub(r"(#+)(\[?)", lambda m: "#" * len(m[1]) * (2 if m[2] else 4) + m[2], text)
|
|
909
|
+
return hashes.replace("%", "%%")
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def _marks(started: Iterable[str], exited: Iterable[str]) -> list[str]:
|
|
913
|
+
return [
|
|
914
|
+
"set", "-s", "@workcrew_started", " ".join(sorted(started)), ";",
|
|
915
|
+
"set", "-s", "@workcrew_exited", " ".join(sorted(exited)),
|
|
916
|
+
] # fmt: skip
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
def _exit_status(status: str, sig: str) -> int | None:
|
|
920
|
+
"""A dead pane's exit status, 128 + n for signal n as a shell gives it. tmux prints the signal
|
|
921
|
+
as a number, as a name where the C library names signals (macOS: `kill`), or, on 3.2a, not
|
|
922
|
+
at all; then the status is unknown."""
|
|
923
|
+
if sig:
|
|
924
|
+
return 128 + (int(sig) if sig.isdigit() else signal.Signals[f"SIG{sig.upper()}"])
|
|
925
|
+
return int(status) if status else None
|
|
926
|
+
|
|
927
|
+
|
|
928
|
+
class _Rect(NamedTuple):
|
|
929
|
+
x: int
|
|
930
|
+
y: int
|
|
931
|
+
w: int
|
|
932
|
+
h: int
|
|
933
|
+
cell: Cell
|
|
934
|
+
|
|
935
|
+
def lo(self, across: bool) -> int:
|
|
936
|
+
return self.x if across else self.y
|
|
937
|
+
|
|
938
|
+
def hi(self, across: bool) -> int:
|
|
939
|
+
return self.x + self.w if across else self.y + self.h
|
|
940
|
+
|
|
941
|
+
|
|
942
|
+
# A layout tmux wrote: the classic `c195,80x24,0,0[…]` form of every release up to 3.6, or the
|
|
943
|
+
# JSON of 3.8 and master. What a release writes is the only thing that says what it reads.
|
|
944
|
+
_CLASSIC_LAYOUT = re.compile(r"[0-9a-f]{4},")
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def _readable(saved: str, written: str) -> bool:
|
|
948
|
+
"""Whether this tmux may be handed `saved`, the layout a roster holds, when it writes
|
|
949
|
+
`written` for a window of its own. tmux 3.3a ends its own server on a string that begins `{`,
|
|
950
|
+
and on an empty one, where it refuses a classic string with an error; a team saved under 3.8,
|
|
951
|
+
whose layouts are JSON, could then never be opened again under it. Every release from 3.2a to
|
|
952
|
+
master reads the classic form, so only JSON needs a tmux that writes JSON (ran: 3.2a, 3.3a,
|
|
953
|
+
3.4, 3.6, 3.8, master)."""
|
|
954
|
+
return bool(_CLASSIC_LAYOUT.match(saved)) or (saved.startswith("{") and written.startswith("{"))
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
def _layout(cells: Sequence[Cell]) -> tuple[str, list[Cell]]:
|
|
958
|
+
"""A tmux layout string for the cells, and the cells in the order tmux gives them to panes.
|
|
959
|
+
The cells leave the top row to the pane border; in the layout the top cells take it. The
|
|
960
|
+
size is the plan's, not the window's: tmux 3.2a resizes the window after the client."""
|
|
961
|
+
rects = [
|
|
962
|
+
_Rect(c.x, 0 if c.y == 0 else c.y + 1, c.w, c.h + 1 if c.y == 0 else c.h, c) for c in cells
|
|
963
|
+
]
|
|
964
|
+
width = max(r.x + r.w for r in rects)
|
|
965
|
+
body, order = _tree(rects, 0, 0, width, max(r.y + r.h for r in rects))
|
|
966
|
+
check = 0
|
|
967
|
+
for ch in body.encode():
|
|
968
|
+
check = ((check >> 1) + ((check & 1) << 15) + ch) & 0xFFFF
|
|
969
|
+
return f"{check:04x},{body}", order
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def _tree(rects: list[_Rect], x: int, y: int, w: int, h: int) -> tuple[str, list[Cell]]:
|
|
973
|
+
if len(rects) == 1:
|
|
974
|
+
return f"{w}x{h},{x},{y},0", [rects[0].cell]
|
|
975
|
+
# place's cells always split into columns, or failing that into rows.
|
|
976
|
+
across = bool(_cuts(rects, across=True))
|
|
977
|
+
children, order = [], []
|
|
978
|
+
lo = x if across else y
|
|
979
|
+
for hi in [*_cuts(rects, across), x + w if across else y + h]:
|
|
980
|
+
group = [r for r in rects if lo <= r.lo(across) < hi]
|
|
981
|
+
s, o = _tree(group, lo, y, hi - lo, h) if across else _tree(group, x, lo, w, hi - lo)
|
|
982
|
+
children.append(s)
|
|
983
|
+
order += o
|
|
984
|
+
lo = hi + 1
|
|
985
|
+
a, b = "{}" if across else "[]"
|
|
986
|
+
return f"{w}x{h},{x},{y}{a}{','.join(children)}{b}", order
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
def _cuts(rects: list[_Rect], across: bool) -> list[int]:
|
|
990
|
+
"""The lines no cell crosses, across (between columns) or down (between rows)."""
|
|
991
|
+
ends = sorted({r.hi(across) for r in rects})[:-1]
|
|
992
|
+
return [e for e in ends if all(r.hi(across) <= e or r.lo(across) > e for r in rects)]
|