ccdeck 3.82.4 → 4.0.1
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.
- package/LICENSING.md +42 -4
- package/README.md +183 -72
- package/THIRD_PARTY_NOTICES.md +243 -17
- package/bin/cli/tui.js +58 -4
- package/bin/deck.js +27 -1
- package/dist/web/assets/AccountBridge-fp-fsMx-.js +1 -0
- package/dist/web/assets/AccountSection-Cu-96Q00.js +1 -0
- package/dist/web/assets/BrowserWatchModal-CvUx07C6.js +1 -0
- package/dist/web/assets/FeedbackConversations-BgVk0nkA.js +1 -0
- package/dist/web/assets/IntegrationModal-CEj5oJg4.js +7 -0
- package/dist/web/assets/IntegrationSkeleton-DD7YiFgd.js +1 -0
- package/dist/web/assets/RadioPanel-BhnzWRCT.js +1 -0
- package/dist/web/assets/StageShell-DmJu3dU1.js +4 -0
- package/dist/web/assets/TrafficRadar-C8-ieIw5.js +8 -0
- package/dist/web/assets/UsageHistoryModal-BThv9Kja.js +1 -0
- package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
- package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
- package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
- package/dist/web/assets/app-DtosBis5.css +1 -0
- package/dist/web/assets/app-ZMmmEHxF.js +361 -0
- package/dist/web/assets/{index-B-l-VxLm.js → index-zSxC5ueJ.js} +1 -1
- package/dist/web/assets/inspector-status-pane-BgQG0bQi.js +1 -0
- package/dist/web/assets/screens-DD0uCtat.js +12 -0
- package/dist/web/assets/screens-DUniTTbC.css +1 -0
- package/dist/web/assets/stage-board-J2rKA9Pg.js +2 -0
- package/dist/web/assets/use-account-DvFObI4M.js +1 -0
- package/dist/web/assets/xterm-4jYizCpg.js +27 -0
- package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
- package/dist/web/index.html +16 -6
- package/package.json +13 -1
- package/release-notes.json +69 -1
- package/src/server/account-client.mjs +196 -0
- package/src/server/account-connect.mjs +238 -0
- package/src/server/account-flag.mjs +106 -0
- package/src/server/account-projects.mjs +1 -1
- package/src/server/account-service.mjs +532 -0
- package/src/server/account-status.mjs +293 -0
- package/src/server/account-store.mjs +137 -0
- package/src/server/account-sync.mjs +473 -0
- package/src/server/account-token-store.mjs +216 -0
- package/src/server/account-ui-fields.mjs +126 -0
- package/src/server/account-watch.mjs +1 -1
- package/src/server/browser-watch-log.mjs +1 -1
- package/src/server/browser-watch-store.mjs +1 -1
- package/src/server/ccdeck-account-routes.mjs +252 -0
- package/src/server/ccusage-install.mjs +2 -2
- package/src/server/ccusage-registry.mjs +4 -4
- package/src/server/ccusage-session.mjs +11 -0
- package/src/server/claude-accounts.mjs +1 -1
- package/src/server/claude-recovery.mjs +9 -4
- package/src/server/claude-settings-catalog.mjs +6 -6
- package/src/server/claude-settings.mjs +1 -1
- package/src/server/codex-auto.mjs +1 -1
- package/src/server/codex-cost-usage.mjs +7 -2
- package/src/server/codex-live-checkpoint.mjs +24 -9
- package/src/server/codex-live-engine.mjs +14 -4
- package/src/server/codex-live-handoff.mjs +53 -9
- package/src/server/codex-names.mjs +49 -0
- package/src/server/codex-translate.mjs +1 -1
- package/src/server/codex-ultrafast.d.mts +3 -0
- package/src/server/codex-ultrafast.mjs +5 -0
- package/src/server/codex-watch.mjs +25 -0
- package/src/server/command-panel-engine.mjs +300 -0
- package/src/server/command-panel-platform.mjs +99 -0
- package/src/server/cswap-auto-choice.mjs +1 -1
- package/src/server/cswap-auto-loop.mjs +1 -1
- package/src/server/cswap-install.mjs +21 -40
- package/src/server/deck-home.mjs +6 -0
- package/src/server/deck-prefs.mjs +53 -1
- package/src/server/detach.mjs +1 -1
- package/src/server/engine-download.mjs +277 -0
- package/src/server/engine-install.mjs +378 -0
- package/src/server/engine-package.mjs +267 -0
- package/src/server/event-log.mjs +7 -1
- package/src/server/event-pipeline.mjs +29 -1
- package/src/server/ghostty-handoff.mjs +81 -0
- package/src/server/index.mjs +143 -5
- package/src/server/installer.mjs +4 -1
- package/src/server/integrations/jira-write-guard.mjs +14 -208
- package/src/server/integrations/store.mjs +37 -19
- package/src/server/integrations/write-guard.mjs +223 -0
- package/src/server/intel-cpu-temperature.mjs +26 -0
- package/src/server/lifecycle.mjs +69 -6
- package/src/server/log-replay.mjs +4 -0
- package/src/server/login-service.mjs +7 -1
- package/src/server/macmon.mjs +1 -1
- package/src/server/npm-latest.mjs +1 -1
- package/src/server/org-telemetry.mjs +1 -1
- package/src/server/output-watch.mjs +4 -1
- package/src/server/panel-provenance.mjs +390 -0
- package/src/server/pinned-build.mjs +14 -0
- package/src/server/prefs-refusal.mjs +8 -1
- package/src/server/prefs-routes.mjs +60 -11
- package/src/server/pro-engine-client.mjs +339 -0
- package/src/server/pro-engine-install.mjs +294 -0
- package/src/server/pro-engine-terminal.mjs +308 -0
- package/src/server/project-discovery.mjs +139 -0
- package/src/server/provider-session-name.mjs +58 -0
- package/src/server/quota-closes.mjs +1 -1
- package/src/server/quota-history.mjs +1 -1
- package/src/server/reports.mjs +86 -21
- package/src/server/request-gates.mjs +34 -5
- package/src/server/restart-note.mjs +1 -1
- package/src/server/seed-boundary.mjs +489 -0
- package/src/server/session-counts.mjs +244 -0
- package/src/server/session-deck-names.mjs +143 -0
- package/src/server/session-enrichment.mjs +43 -6
- package/src/server/session-name-route.mjs +73 -0
- package/src/server/session-summary.mjs +12 -1
- package/src/server/session-transcript-routes.mjs +167 -0
- package/src/server/swap-log.mjs +1 -1
- package/src/server/system-metrics.mjs +57 -0
- package/src/server/terminal-bridge.mjs +485 -0
- package/src/server/terminal-folder.mjs +61 -0
- package/src/server/terminal-js-routes.mjs +752 -0
- package/src/server/terminal-routes.mjs +553 -0
- package/src/server/terminal-sessions.mjs +759 -0
- package/src/server/terminal-socket.mjs +403 -0
- package/src/server/terminal-target.mjs +928 -0
- package/src/server/thermal-metrics.mjs +13 -9
- package/src/server/tmux-control.mjs +1319 -0
- package/src/server/tmux-download.mjs +220 -0
- package/src/server/tmux.mjs +542 -0
- package/src/server/token-redact.mjs +42 -3
- package/src/server/tool-audit-report.mjs +44 -6
- package/src/server/tool-audit-routes.mjs +12 -1
- package/src/server/tool-audit.mjs +42 -8
- package/src/server/traffic-radar-monitor.mjs +1 -1
- package/src/server/traffic-radar-permission.mjs +1 -1
- package/src/server/transcript-gate.mjs +1 -1
- package/src/server/transcript-scan.mjs +15 -7
- package/src/server/transcript-turns.mjs +154 -0
- package/src/server/tui-network.mjs +1 -0
- package/src/server/tui-view.mjs +28 -0
- package/src/server/utf8-carry.mjs +159 -0
- package/src/server/uv-bootstrap.mjs +2 -2
- package/src/server/windows-acl.mjs +158 -0
- package/src/server/ws-frames.mjs +690 -0
- package/dist/web/assets/BrowserWatchModal-CWVooKxD.js +0 -1
- package/dist/web/assets/IntegrationModal-DLX43RIK.js +0 -7
- package/dist/web/assets/RadioPanel-Cj6PjrvQ.js +0 -1
- package/dist/web/assets/TrafficRadar-Bq1YcuHB.js +0 -8
- package/dist/web/assets/UsageHistoryModal-CMSCca5_.js +0 -1
- package/dist/web/assets/app-BHxsMz3-.js +0 -358
- package/dist/web/assets/app-CbXmr9rC.css +0 -1
|
@@ -0,0 +1,1319 @@
|
|
|
1
|
+
// One tmux control-mode connection: the wire under the terminal panel.
|
|
2
|
+
//
|
|
3
|
+
// WHY CONTROL MODE AND NOT A PTY. A browser terminal is normally a pty the
|
|
4
|
+
// server owns, and a pty from Node means node-pty, a native module. package.json
|
|
5
|
+
// has no `dependencies` key at all — `npx ccdeck` is one tarball with nothing to
|
|
6
|
+
// compile — and a terminal is not worth spending that on. `tmux -C` is a child
|
|
7
|
+
// with three pipes: tmux owns the pty, keeps the session alive when the deck
|
|
8
|
+
// goes away, and reports what the pane writes as `%output` lines that carry the
|
|
9
|
+
// bytes exactly.
|
|
10
|
+
//
|
|
11
|
+
// MEASURED BEFORE IT WAS BUILT. The phase-0 spike fed the raw `%output` stream
|
|
12
|
+
// into xterm.js and compared it, after every repaint, with tmux's own screen as
|
|
13
|
+
// `capture-pane` reads it back: text row by row, attributes cell by cell, and
|
|
14
|
+
// the cursor. Claude Code and Codex were identical in 11 of 11 scenarios each,
|
|
15
|
+
// and a synthetic TUI that tees what it writes showed the 519,400 bytes that
|
|
16
|
+
// arrived as `%output` to be a byte-identical suffix of what it wrote. What this
|
|
17
|
+
// module adds to that spike is everything a connection needs around the stream.
|
|
18
|
+
//
|
|
19
|
+
// THE RULES IT KEEPS, each one learned from the spike or from tmux's source:
|
|
20
|
+
//
|
|
21
|
+
// Bytes, never strings. `%output` escapes every byte below 0x20 and the
|
|
22
|
+
// backslash as \ooo and sends every other byte as itself, UTF-8 included. A
|
|
23
|
+
// line is therefore split on 0x0a, which can never be data, and decoded as a
|
|
24
|
+
// Buffer: a multi-byte character cut by a chunk boundary is reassembled by the
|
|
25
|
+
// line, not by a string decoder.
|
|
26
|
+
//
|
|
27
|
+
// The seed boundary. A browser terminal that opens late starts from
|
|
28
|
+
// `capture-pane`, then applies `%output`. tmux writes pane output and command
|
|
29
|
+
// replies on ONE ordered stream, so output that arrives before the capture's
|
|
30
|
+
// reply is already in the capture and must be dropped, and everything after it
|
|
31
|
+
// is new. The spike attached mid-burst with that rule and stayed an exact
|
|
32
|
+
// suffix of the wire (628,114 of 752,988 bytes).
|
|
33
|
+
//
|
|
34
|
+
// A capture can also land between two of tmux's reads of ONE write by the
|
|
35
|
+
// pane — a macOS pty hands tmux a large frame in pieces — and tmux's parser
|
|
36
|
+
// then holds what the cut left it in: the pen the rest of a row is drawn
|
|
37
|
+
// with, the start of an escape sequence or of a character. No capture shows
|
|
38
|
+
// it, so the client reads it from the stream as well, the output it drops
|
|
39
|
+
// included, and writes it after the seed (seed-boundary.mjs). The one seed
|
|
40
|
+
// is exact, and nothing is drawn twice.
|
|
41
|
+
//
|
|
42
|
+
// Modes set before the attach never pass through `%output`. Claude Code runs
|
|
43
|
+
// on the alternate screen with any-event mouse on; an emulator that was not
|
|
44
|
+
// told so sends no mouse events. The seed restates every mode tmux has a
|
|
45
|
+
// format for; bracketed paste, focus events and extended keys have none in
|
|
46
|
+
// 3.6, which is why paste goes through tmux rather than through the emulator.
|
|
47
|
+
//
|
|
48
|
+
// Flow control. With `pause-after`, tmux stops sending a pane's output to a
|
|
49
|
+
// client that has fallen behind and says `%pause`; the screen it skipped is
|
|
50
|
+
// gone from the stream, so the only honest recovery is to continue the pane
|
|
51
|
+
// and capture it again — the 'reseed' event.
|
|
52
|
+
//
|
|
53
|
+
// That capture, too, can land while tmux holds part of one write by the
|
|
54
|
+
// pane, and after a %pause nothing in the stream says where tmux's parser
|
|
55
|
+
// stands, because tmux skipped the start of that write. An emulator reset
|
|
56
|
+
// by the seed then prints the rest as text ("26m" where a colour was cut)
|
|
57
|
+
// until the program draws over it. So once the pane has written past the
|
|
58
|
+
// seed that followed a %pause and then been quiet for PAUSE_QUIET_MS (between
|
|
59
|
+
// writes, where a program's output is whole), the client asks for one more
|
|
60
|
+
// seed: 'reseed' again, once per %pause.
|
|
61
|
+
//
|
|
62
|
+
// Nothing here spawns tmux SERVERS or shells: the one child is `tmux -C attach`
|
|
63
|
+
// on a socket the caller names, registered with exec-children.mjs so the deck's
|
|
64
|
+
// shutdown reaps it. Closing the client detaches it and leaves the tmux session
|
|
65
|
+
// running, which is the point of having one.
|
|
66
|
+
import { EventEmitter } from "node:events";
|
|
67
|
+
import { execFile as nodeExecFile, spawn as nodeSpawn } from "node:child_process";
|
|
68
|
+
import { randomBytes } from "node:crypto";
|
|
69
|
+
import { killTree, watchChild } from "./exec-children.mjs";
|
|
70
|
+
import { seedBoundary } from "./seed-boundary.mjs";
|
|
71
|
+
// The one spelling of a tmux invocation (binary, -u, socket, then arguments),
|
|
72
|
+
// of an argument tmux could split, and of the environment a tmux client gets.
|
|
73
|
+
import { parseTmuxVersion, tmuxArg, tmuxCommand, tmuxEnv, tmuxTimedOut } from "./tmux.mjs";
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The most bytes one `send-keys -H` carries. Each byte is three characters on
|
|
77
|
+
* the command line, so a 512-byte chunk is a 1.5 KB line: small enough that a
|
|
78
|
+
* pasted-in-by-typing burst never becomes one enormous command, large enough
|
|
79
|
+
* that ordinary typing is always one command per keystroke batch.
|
|
80
|
+
*/
|
|
81
|
+
export const INPUT_CHUNK = 512;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The most characters one `set-buffer` carries. A paste is staged in pieces
|
|
85
|
+
* appended with `set-buffer -a`, so a large clipboard is many ordinary command
|
|
86
|
+
* lines rather than one line of unbounded length.
|
|
87
|
+
*/
|
|
88
|
+
export const PASTE_CHUNK = 16 * 1024;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* How long a client may fall behind, in seconds, before tmux pauses a pane for
|
|
92
|
+
* it. Two seconds is long enough that a busy event loop never trips it and short
|
|
93
|
+
* enough that a stalled browser tab stops costing tmux memory.
|
|
94
|
+
*/
|
|
95
|
+
export const PAUSE_AFTER = 2;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* After a %pause, how long the pane must be quiet, once it has written past the
|
|
99
|
+
* seed that followed, before the client asks for one more seed (the "Flow
|
|
100
|
+
* control" note above). Frames of a busy TUI come every few milliseconds.
|
|
101
|
+
*/
|
|
102
|
+
export const PAUSE_QUIET_MS = 100;
|
|
103
|
+
|
|
104
|
+
// The subscription that reports a pane dying. It is subscribed for EVERY pane
|
|
105
|
+
// in the session (`%*`) and filtered here, because tmux 3.6 does not report a
|
|
106
|
+
// change of `#{pane_dead}` to a subscription on the single pane (`%5`) — the
|
|
107
|
+
// first value arrives and the death never does — while the `%*` form reports
|
|
108
|
+
// it within a second. Measured, and tmux-control-tmux.test.ts holds it there:
|
|
109
|
+
// a program exits under remain-on-exit and 'exit' must say 'ended'.
|
|
110
|
+
const DEAD_SUBSCRIPTION = "ccdeck-dead";
|
|
111
|
+
|
|
112
|
+
// What the subscription reports: whether the pane is dead, then how its
|
|
113
|
+
// program ended — the exit status, or the signal that killed it (tmux 3.3+;
|
|
114
|
+
// an older tmux leaves the field empty). The stage closes a pane whose agent
|
|
115
|
+
// ended itself with status 0 (internal #104), so the ending has to say how.
|
|
116
|
+
export const DEAD_FORMAT = "#{pane_dead}:#{pane_dead_status}:#{pane_dead_signal}";
|
|
117
|
+
|
|
118
|
+
// Before tmux 3.7, `#{pane_dead}` can say 1 a tick before the exit status is
|
|
119
|
+
// known: the pane is marked dead at its pty's end, the status when the child
|
|
120
|
+
// is reaped. A death that comes without either waits this long for them, and
|
|
121
|
+
// is said without them if they do not come.
|
|
122
|
+
export const DEAD_GRACE_MS = 2500;
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Read a DEAD_FORMAT value: `{ dead }`, with `status` (0 or more) and
|
|
126
|
+
* `signal` (1 or more) when tmux gave them. A value with fewer fields — a
|
|
127
|
+
* blank, or `#{pane_dead}` alone — is read for `dead` only.
|
|
128
|
+
*/
|
|
129
|
+
export function parseDeadValue(value) {
|
|
130
|
+
const [dead, status = "", signal = ""] = String(value ?? "").split(":");
|
|
131
|
+
const out = { dead: dead === "1" };
|
|
132
|
+
if (!out.dead) return out;
|
|
133
|
+
if (/^\d{1,9}$/.test(status)) out.status = Number(status);
|
|
134
|
+
if (/^\d{1,9}$/.test(signal) && Number(signal) > 0) out.signal = Number(signal);
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// A line longer than this without a newline is not tmux talking. It caps what a
|
|
139
|
+
// broken peer can make this process buffer.
|
|
140
|
+
const MAX_LINE = 64 << 20;
|
|
141
|
+
|
|
142
|
+
// How long close() waits for tmux to detach on its own before killing it.
|
|
143
|
+
const CLOSE_GRACE_MS = 2000;
|
|
144
|
+
|
|
145
|
+
const isOct = (c) => c >= 48 && c <= 55;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Decode the value of one `%output` line into the bytes the pane wrote.
|
|
149
|
+
*
|
|
150
|
+
* tmux escapes a byte below 0x20, and the backslash itself, as a backslash and
|
|
151
|
+
* three octal digits; every other byte, UTF-8 included, arrives as itself. So
|
|
152
|
+
* this works on bytes and never on a string: a string decoder would mangle
|
|
153
|
+
* the escapes' neighbours, and the pane may legitimately write bytes that are
|
|
154
|
+
* not UTF-8 at all. A backslash that is not followed by three octal digits
|
|
155
|
+
* cannot come from tmux and is kept as it is rather than guessed at.
|
|
156
|
+
*
|
|
157
|
+
* Takes and returns a Buffer. The common line has no escapes at all, and then
|
|
158
|
+
* the input is returned as it is, without a copy.
|
|
159
|
+
*/
|
|
160
|
+
export function unescapeOutput(buf) {
|
|
161
|
+
if (buf.indexOf(0x5c) < 0) return buf;
|
|
162
|
+
const out = Buffer.allocUnsafe(buf.length);
|
|
163
|
+
let n = 0;
|
|
164
|
+
for (let i = 0; i < buf.length; i++) {
|
|
165
|
+
const b = buf[i];
|
|
166
|
+
if (b === 0x5c && i + 3 < buf.length && isOct(buf[i + 1]) && isOct(buf[i + 2]) && isOct(buf[i + 3])) {
|
|
167
|
+
out[n++] = (((buf[i + 1] - 48) << 6) | ((buf[i + 2] - 48) << 3) | (buf[i + 3] - 48)) & 0xff;
|
|
168
|
+
i += 3;
|
|
169
|
+
} else {
|
|
170
|
+
out[n++] = b;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return out.subarray(0, n);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// The text after "<word> " in a notification, as latin1 so a byte is a char.
|
|
177
|
+
const rest = (buf, from) => buf.subarray(from).toString("latin1");
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Classify one line tmux wrote in control mode, without its newline.
|
|
181
|
+
*
|
|
182
|
+
* Pure, and deliberately unaware of context: a line INSIDE a %begin/%end block
|
|
183
|
+
* is command output and may itself start with "%" (`display-message -p
|
|
184
|
+
* '#{pane_id}'` prints "%5"), so the caller decides whether a line is a reply
|
|
185
|
+
* before asking what it is. Shapes:
|
|
186
|
+
*
|
|
187
|
+
* { type: "output", pane, data, age? } — %output, or %extended-output (the
|
|
188
|
+
* form tmux uses once pause-after is
|
|
189
|
+
* set; age is in milliseconds)
|
|
190
|
+
* { type: "begin" | "end" | "error", time, number, flags, guard }
|
|
191
|
+
* { type: "pause" | "continue", pane }
|
|
192
|
+
* { type: "exit", reason } — reason is "" when tmux gave none
|
|
193
|
+
* { type: "layout-change", window, layout, visibleLayout, flags }
|
|
194
|
+
* { type: "window-close" | "unlinked-window-close", window }
|
|
195
|
+
* { type: "session-changed", session, name }
|
|
196
|
+
* { type: "subscription-changed", name, session, window, index, pane, value }
|
|
197
|
+
* { type: "notification", name, args } — every other %word
|
|
198
|
+
* { type: "line", text } — anything not starting with "%"
|
|
199
|
+
*
|
|
200
|
+
* Accepts a Buffer or, for tests, a string (encoded as UTF-8).
|
|
201
|
+
*/
|
|
202
|
+
export function parseControlLine(line) {
|
|
203
|
+
const buf = typeof line === "string" ? Buffer.from(line, "utf8") : line;
|
|
204
|
+
if (buf[0] !== 0x25) return { type: "line", text: buf.toString("utf8") };
|
|
205
|
+
const sp = buf.indexOf(0x20);
|
|
206
|
+
const word = buf.subarray(1, sp < 0 ? buf.length : sp).toString("latin1");
|
|
207
|
+
const args = sp < 0 ? "" : rest(buf, sp + 1);
|
|
208
|
+
switch (word) {
|
|
209
|
+
case "output": {
|
|
210
|
+
const sp2 = buf.indexOf(0x20, sp + 1);
|
|
211
|
+
if (sp2 < 0) return { type: "output", pane: args, data: Buffer.alloc(0) };
|
|
212
|
+
return { type: "output", pane: buf.subarray(sp + 1, sp2).toString("latin1"), data: unescapeOutput(buf.subarray(sp2 + 1)) };
|
|
213
|
+
}
|
|
214
|
+
case "extended-output": {
|
|
215
|
+
// "%extended-output %5 12 ... : value" — the arguments between the age and
|
|
216
|
+
// a lone ":" are reserved for future use, and none of them contains a
|
|
217
|
+
// space, so the first " : " is the separator.
|
|
218
|
+
const sep = buf.indexOf(" : ", sp + 1, "latin1");
|
|
219
|
+
const head = (sep < 0 ? args : rest(buf, sp + 1).slice(0, sep - sp - 1)).split(" ");
|
|
220
|
+
const data = sep < 0 ? Buffer.alloc(0) : unescapeOutput(buf.subarray(sep + 3));
|
|
221
|
+
return { type: "output", pane: head[0], age: Number(head[1]) || 0, data };
|
|
222
|
+
}
|
|
223
|
+
case "begin":
|
|
224
|
+
case "end":
|
|
225
|
+
case "error": {
|
|
226
|
+
const [time, number, flags] = args.split(" ");
|
|
227
|
+
return { type: word, time, number, flags, guard: args };
|
|
228
|
+
}
|
|
229
|
+
case "pause":
|
|
230
|
+
case "continue":
|
|
231
|
+
return { type: word, pane: args.split(" ")[0] };
|
|
232
|
+
case "exit":
|
|
233
|
+
return { type: "exit", reason: args };
|
|
234
|
+
case "layout-change": {
|
|
235
|
+
const [window, layout, visibleLayout, flags = ""] = args.split(" ");
|
|
236
|
+
return { type: word, window, layout, visibleLayout, flags };
|
|
237
|
+
}
|
|
238
|
+
case "window-close":
|
|
239
|
+
case "unlinked-window-close":
|
|
240
|
+
return { type: word, window: args.split(" ")[0] };
|
|
241
|
+
case "session-changed": {
|
|
242
|
+
const i = args.indexOf(" ");
|
|
243
|
+
return { type: word, session: i < 0 ? args : args.slice(0, i), name: i < 0 ? "" : args.slice(i + 1) };
|
|
244
|
+
}
|
|
245
|
+
case "subscription-changed": {
|
|
246
|
+
const sep = args.indexOf(" : ");
|
|
247
|
+
const head = (sep < 0 ? args : args.slice(0, sep)).split(" ");
|
|
248
|
+
const value = sep < 0 ? "" : Buffer.from(args.slice(sep + 3), "latin1").toString("utf8");
|
|
249
|
+
return { type: word, name: head[0], session: head[1], window: head[2], index: head[3], pane: head[4], value };
|
|
250
|
+
}
|
|
251
|
+
default:
|
|
252
|
+
return { type: "notification", name: word, args };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Quote one argument for tmux's command parser, so it arrives as exactly this
|
|
258
|
+
* string whatever it contains.
|
|
259
|
+
*
|
|
260
|
+
* Control mode reads one command per LINE, so a newline in an argument cannot
|
|
261
|
+
* be sent as itself — it would end the command, and tmux also strips the
|
|
262
|
+
* indentation after a literal newline inside quotes. Inside double quotes the
|
|
263
|
+
* parser understands backslash escapes (\n, \r, \t, \ooo, and backslash before
|
|
264
|
+
* anything else meaning that character), and it EXPANDS three things: `$NAME`
|
|
265
|
+
* from the server's environment, `~` to a home directory at the start of a
|
|
266
|
+
* word — even a quoted one — and the escapes themselves. So the backslash,
|
|
267
|
+
* the double quote, `$` and `~` are escaped, the C0 controls and DEL become
|
|
268
|
+
* octal, and every other character, UTF-8 included, passes as itself. `;`, `#`,
|
|
269
|
+
* `{` and spaces are inert inside quotes.
|
|
270
|
+
*
|
|
271
|
+
* A NUL cannot be carried — tmux's arguments are C strings — and throws rather
|
|
272
|
+
* than being dropped without a word; paste() strips it first, on purpose.
|
|
273
|
+
*/
|
|
274
|
+
export function quoteTmuxArg(value) {
|
|
275
|
+
const s = String(value);
|
|
276
|
+
if (s.includes("\0")) throw new TypeError("a tmux argument cannot carry a NUL character");
|
|
277
|
+
let out = "\"";
|
|
278
|
+
for (const ch of s) {
|
|
279
|
+
const c = ch.codePointAt(0);
|
|
280
|
+
if (ch === "\\" || ch === "\"" || ch === "$" || ch === "~") out += `\\${ch}`;
|
|
281
|
+
else if (ch === "\n") out += "\\n";
|
|
282
|
+
else if (ch === "\r") out += "\\r";
|
|
283
|
+
else if (ch === "\t") out += "\\t";
|
|
284
|
+
else if (c < 0x20 || c === 0x7f) out += `\\${c.toString(8).padStart(3, "0")}`;
|
|
285
|
+
else out += ch;
|
|
286
|
+
}
|
|
287
|
+
return `${out}"`;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* The `send-keys` commands that deliver these bytes to the pane unchanged.
|
|
292
|
+
*
|
|
293
|
+
* `-H` takes each key as a hex byte and tmux writes it to the pane as a
|
|
294
|
+
* literal, so the bytes xterm.js produced for a keystroke — in whatever
|
|
295
|
+
* encoding the pane asked xterm for — reach the program exactly. One command
|
|
296
|
+
* per INPUT_CHUNK bytes.
|
|
297
|
+
*/
|
|
298
|
+
export function sendKeysCommands(pane, bytes) {
|
|
299
|
+
const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
|
|
300
|
+
const out = [];
|
|
301
|
+
for (let i = 0; i < buf.length; i += INPUT_CHUNK) {
|
|
302
|
+
const hex = [];
|
|
303
|
+
for (const b of buf.subarray(i, i + INPUT_CHUNK)) hex.push(b.toString(16).padStart(2, "0"));
|
|
304
|
+
out.push(`send-keys -t ${pane} -H ${hex.join(" ")}`);
|
|
305
|
+
}
|
|
306
|
+
return out;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* The commands that paste `text` into the pane the way a terminal would.
|
|
311
|
+
*
|
|
312
|
+
* Staged in a paste buffer and delivered with `paste-buffer -p`, which wraps
|
|
313
|
+
* it in bracketed-paste markers only if the program in the pane asked for
|
|
314
|
+
* them. tmux 3.6 exposes no format for that mode, so the browser cannot know
|
|
315
|
+
* it, and tmux is the one party that does. paste-buffer also turns each LF into
|
|
316
|
+
* CR, as a terminal paste does; a CRLF is folded to LF first, as xterm.js does,
|
|
317
|
+
* so Windows line ends do not paste as two Enters. NUL is dropped: no terminal
|
|
318
|
+
* pastes one, and tmux could not carry it. `-d` deletes the buffer once used,
|
|
319
|
+
* so a paste does not linger in the user's `choose-buffer` list.
|
|
320
|
+
*/
|
|
321
|
+
export function pasteCommands(pane, text, buffer) {
|
|
322
|
+
const body = String(text).replace(/\r\n/g, "\n").replace(/\0/g, "");
|
|
323
|
+
if (!body) return [];
|
|
324
|
+
const out = [];
|
|
325
|
+
for (let i = 0; i < body.length;) {
|
|
326
|
+
let end = Math.min(body.length, i + PASTE_CHUNK);
|
|
327
|
+
// Never split a surrogate pair: half an emoji in each buffer append would
|
|
328
|
+
// reach tmux as two replacement characters.
|
|
329
|
+
if (end < body.length && /[\ud800-\udbff]/.test(body[end - 1])) end--;
|
|
330
|
+
out.push(`set-buffer ${i ? "-a " : ""}-b ${buffer} -- ${quoteTmuxArg(body.slice(i, end))}`);
|
|
331
|
+
i = end;
|
|
332
|
+
}
|
|
333
|
+
out.push(`paste-buffer -p -d -b ${buffer} -t ${pane}`);
|
|
334
|
+
return out;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Every pane in a tmux layout string, with its size.
|
|
339
|
+
*
|
|
340
|
+
* A layout is "checksum,WxH,X,Y" followed by ",ID" for a pane, or by
|
|
341
|
+
* "{...}" / "[...]" around the cells of a split. Only a pane cell has four
|
|
342
|
+
* numbers in a row, so the panes are exactly the WxH,X,Y,ID runs. Returns
|
|
343
|
+
* `[{ pane: "%ID", cols, rows }]`.
|
|
344
|
+
*/
|
|
345
|
+
export function layoutPanes(layout) {
|
|
346
|
+
const out = [];
|
|
347
|
+
for (const m of String(layout).matchAll(/(\d+)x(\d+),\d+,\d+,(\d+)/g)) {
|
|
348
|
+
out.push({ pane: `%${m[3]}`, cols: Number(m[1]), rows: Number(m[2]) });
|
|
349
|
+
}
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// The format the seed asks tmux for. Named fields, because an older tmux
|
|
354
|
+
// expands a variable it does not know to nothing, and a positional list would
|
|
355
|
+
// then shift every value after it.
|
|
356
|
+
const SEED_FIELDS = [
|
|
357
|
+
"alternate_on", "cursor_x", "cursor_y", "pane_width", "pane_height", "cursor_flag",
|
|
358
|
+
"keypad_cursor_flag", "keypad_flag", "mouse_standard_flag", "mouse_button_flag", "mouse_all_flag",
|
|
359
|
+
"mouse_sgr_flag", "mouse_utf8_flag", "insert_flag", "origin_flag", "wrap_flag",
|
|
360
|
+
"scroll_region_upper", "scroll_region_lower", "cursor_shape", "cursor_blinking",
|
|
361
|
+
];
|
|
362
|
+
const SEED_FORMAT = SEED_FIELDS.map(f => `${f}=#{${f}}`).join(" ");
|
|
363
|
+
|
|
364
|
+
/** The seed's display-message answer (key=value pairs) as numbers and flags. */
|
|
365
|
+
export function parseSeedInfo(line) {
|
|
366
|
+
const raw = {};
|
|
367
|
+
for (const pair of String(line ?? "").split(" ")) {
|
|
368
|
+
const eq = pair.indexOf("=");
|
|
369
|
+
if (eq > 0) raw[pair.slice(0, eq)] = pair.slice(eq + 1);
|
|
370
|
+
}
|
|
371
|
+
const num = (k, d = 0) => (raw[k] === undefined || raw[k] === "" ? d : Number(raw[k]) || 0);
|
|
372
|
+
const on = (k) => raw[k] === "1";
|
|
373
|
+
const rows = num("pane_height", 24);
|
|
374
|
+
return {
|
|
375
|
+
alternate: on("alternate_on"),
|
|
376
|
+
cursorX: num("cursor_x"),
|
|
377
|
+
cursorY: num("cursor_y"),
|
|
378
|
+
cols: num("pane_width", 80),
|
|
379
|
+
rows,
|
|
380
|
+
cursorVisible: raw.cursor_flag !== "0",
|
|
381
|
+
keypadCursor: on("keypad_cursor_flag"),
|
|
382
|
+
keypad: on("keypad_flag"),
|
|
383
|
+
mouseStandard: on("mouse_standard_flag"),
|
|
384
|
+
mouseButton: on("mouse_button_flag"),
|
|
385
|
+
mouseAll: on("mouse_all_flag"),
|
|
386
|
+
mouseSgr: on("mouse_sgr_flag"),
|
|
387
|
+
mouseUtf8: on("mouse_utf8_flag"),
|
|
388
|
+
insert: on("insert_flag"),
|
|
389
|
+
origin: on("origin_flag"),
|
|
390
|
+
wrap: raw.wrap_flag !== "0",
|
|
391
|
+
scrollTop: num("scroll_region_upper", 0),
|
|
392
|
+
scrollBottom: num("scroll_region_lower", rows - 1),
|
|
393
|
+
cursorShape: raw.cursor_shape || "",
|
|
394
|
+
cursorBlinking: on("cursor_blinking"),
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* The background a run of `capture-pane -e` text leaves in force, as the SGR
|
|
400
|
+
* sequence that sets it, or "" for the default.
|
|
401
|
+
*
|
|
402
|
+
* Needed because capture-pane carries attributes ACROSS line ends — it states
|
|
403
|
+
* an attribute when it changes, not on every line — and a newline that
|
|
404
|
+
* scrolls a terminal fills the new bottom row with the current background
|
|
405
|
+
* (xterm.js erases with it, as a VT does). Writing history into the emulator
|
|
406
|
+
* scrolls, so a coloured line end would paint the next row's empty cells. The
|
|
407
|
+
* seed switches to the default background for the newline itself and then
|
|
408
|
+
* restates this one, which leaves the carried attributes exactly as they were.
|
|
409
|
+
*/
|
|
410
|
+
export function trailingBackground(text, bg = "") {
|
|
411
|
+
for (const m of String(text).matchAll(/\x1b\[([0-9;:]*)m/g)) {
|
|
412
|
+
const ps = m[1] === "" ? ["0"] : m[1].split(";");
|
|
413
|
+
for (let i = 0; i < ps.length; i++) {
|
|
414
|
+
const p = ps[i];
|
|
415
|
+
const n = Number(p.split(":")[0] || "0");
|
|
416
|
+
if (n === 0 || n === 49) bg = "";
|
|
417
|
+
else if ((n >= 40 && n <= 47) || (n >= 100 && n <= 107)) bg = `\x1b[${n}m`;
|
|
418
|
+
else if (n === 38 || n === 48 || n === 58) {
|
|
419
|
+
// Colon form keeps the whole colour in one parameter; the semicolon form
|
|
420
|
+
// spends the next two (5;n) or four (2;r;g;b).
|
|
421
|
+
if (p.includes(":")) { if (n === 48) bg = `\x1b[${p}m`; continue; }
|
|
422
|
+
const take = ps[i + 1] === "5" ? 2 : ps[i + 1] === "2" ? 4 : 0;
|
|
423
|
+
if (n === 48) bg = take ? `\x1b[${ps.slice(i, i + 1 + take).join(";")}m` : bg;
|
|
424
|
+
i += take;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return bg;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// Lines written one under another from the top, so that what does not fit
|
|
432
|
+
// scrolls into the emulator's scrollback, with the background guard above.
|
|
433
|
+
function stackLines(lines) {
|
|
434
|
+
let s = "";
|
|
435
|
+
let bg = "";
|
|
436
|
+
lines.forEach((line, i) => {
|
|
437
|
+
s += line;
|
|
438
|
+
if (i === lines.length - 1) return;
|
|
439
|
+
bg = trailingBackground(line, bg);
|
|
440
|
+
s += bg ? `\x1b[49m\r\n${bg}` : "\r\n";
|
|
441
|
+
});
|
|
442
|
+
return s;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const plainText = (line) => line.replace(/\x1b\[[0-9;:?]*[A-Za-z]/g, "").trimEnd();
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* The bytes that make a freshly reset emulator show what tmux shows.
|
|
449
|
+
*
|
|
450
|
+
* `info` is parseSeedInfo's answer, `lines` is `capture-pane -p -e -N -S -<n>`
|
|
451
|
+
* (history, then the visible rows) and `saved` is `capture-pane -a -q`, the
|
|
452
|
+
* normal screen tmux keeps aside while a program is on the alternate one.
|
|
453
|
+
*
|
|
454
|
+
* NORMAL SCREEN: history and visible rows are written top to bottom, so the
|
|
455
|
+
* history scrolls into scrollback and the last `rows` lines are the screen.
|
|
456
|
+
*
|
|
457
|
+
* ALTERNATE SCREEN: the normal buffer is built first — the history, then the
|
|
458
|
+
* screen tmux saved — and only then `?1049h` and the alternate rows, each
|
|
459
|
+
* placed by row. The DESIGN asked only for the visible alternate rows; the
|
|
460
|
+
* saved screen costs one more capture in the same atomic batch and means that
|
|
461
|
+
* when the TUI exits, the emulator shows the shell tmux shows instead of a
|
|
462
|
+
* blank page. tmux does not expose the cursor it saved at `?1049h`, so the one
|
|
463
|
+
* this seed saves is a guess with a reason: a shell launched the TUI from the
|
|
464
|
+
* line after its last output, which is where the cursor sat.
|
|
465
|
+
*
|
|
466
|
+
* Then the state no `%output` will ever restate: scroll region, origin, insert
|
|
467
|
+
* and wrap modes, cursor-key and keypad modes, mouse reporting, cursor
|
|
468
|
+
* position, visibility and shape. Order matters: setting the scroll region or
|
|
469
|
+
* origin mode homes the cursor, so the cursor goes last.
|
|
470
|
+
*/
|
|
471
|
+
export function buildSeed({ info, lines = [], saved = [] }) {
|
|
472
|
+
const rows = Math.max(1, info.rows);
|
|
473
|
+
const cols = Math.max(1, info.cols);
|
|
474
|
+
const history = lines.length > rows ? lines.slice(0, lines.length - rows) : [];
|
|
475
|
+
const visible = lines.slice(history.length);
|
|
476
|
+
while (visible.length < rows) visible.push("");
|
|
477
|
+
|
|
478
|
+
let s = "\x1bc";
|
|
479
|
+
if (!info.alternate) {
|
|
480
|
+
s += stackLines([...history, ...visible]);
|
|
481
|
+
} else {
|
|
482
|
+
const normal = saved.slice(0, rows);
|
|
483
|
+
s += stackLines([...history, ...normal]);
|
|
484
|
+
let last = -1;
|
|
485
|
+
normal.forEach((line, y) => { if (plainText(line)) last = y; });
|
|
486
|
+
s += `\x1b[0m\x1b[${Math.min(last + 1, rows - 1) + 1};1H\x1b[?1049h`;
|
|
487
|
+
visible.forEach((line, y) => { s += `\x1b[${y + 1};1H${line}`; });
|
|
488
|
+
}
|
|
489
|
+
s += "\x1b[0m";
|
|
490
|
+
const top = Math.max(0, Math.min(info.scrollTop, rows - 1));
|
|
491
|
+
const bottom = Math.max(top, Math.min(info.scrollBottom, rows - 1));
|
|
492
|
+
if (top !== 0 || bottom !== rows - 1) s += `\x1b[${top + 1};${bottom + 1}r`;
|
|
493
|
+
if (info.origin) s += "\x1b[?6h";
|
|
494
|
+
if (info.insert) s += "\x1b[4h";
|
|
495
|
+
if (!info.wrap) s += "\x1b[?7l";
|
|
496
|
+
if (info.keypadCursor) s += "\x1b[?1h";
|
|
497
|
+
if (info.keypad) s += "\x1b=";
|
|
498
|
+
if (info.mouseStandard) s += "\x1b[?1000h";
|
|
499
|
+
if (info.mouseButton) s += "\x1b[?1002h";
|
|
500
|
+
if (info.mouseAll) s += "\x1b[?1003h";
|
|
501
|
+
if (info.mouseUtf8) s += "\x1b[?1005h";
|
|
502
|
+
if (info.mouseSgr) s += "\x1b[?1006h";
|
|
503
|
+
const x = Math.max(0, Math.min(info.cursorX, cols - 1));
|
|
504
|
+
const y = Math.max(0, Math.min(info.cursorY, rows - 1));
|
|
505
|
+
const row = info.origin ? Math.max(0, y - top) : y;
|
|
506
|
+
s += `\x1b[${row + 1};${x + 1}H`;
|
|
507
|
+
s += info.cursorVisible ? "\x1b[?25h" : "\x1b[?25l";
|
|
508
|
+
const shape = { block: 1, underline: 3, bar: 5 }[info.cursorShape];
|
|
509
|
+
if (shape) s += `\x1b[${info.cursorBlinking ? shape : shape + 1} q`;
|
|
510
|
+
return Buffer.from(s, "utf8");
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* The socket a control client may use: `{ name }` or `{ path }`, and nothing
|
|
515
|
+
* else. tmuxCommand reads a missing socket as the user's default server, which
|
|
516
|
+
* is right for the one lookup that wants it (terminal-target on macOS) and
|
|
517
|
+
* never right here: case A is the deck's own socket and case B names the
|
|
518
|
+
* user's socket path, so an unnamed socket is a bug, refused rather than
|
|
519
|
+
* defaulted.
|
|
520
|
+
*/
|
|
521
|
+
function requireSocket(socket) {
|
|
522
|
+
const named = typeof socket?.name === "string" && socket.name !== "";
|
|
523
|
+
const pathed = typeof socket?.path === "string" && socket.path !== "";
|
|
524
|
+
if (!named && !pathed) throw new TypeError("openControl needs a socket: { name } or { path }");
|
|
525
|
+
return socket;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const toBuffer = (bytes) =>
|
|
529
|
+
Buffer.isBuffer(bytes) ? bytes
|
|
530
|
+
: typeof bytes === "string" ? Buffer.from(bytes, "utf8")
|
|
531
|
+
: bytes instanceof ArrayBuffer ? Buffer.from(bytes)
|
|
532
|
+
: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
533
|
+
|
|
534
|
+
const failed = (why) => ({ ok: false, lines: [why] });
|
|
535
|
+
|
|
536
|
+
/** The first tmux whose control clients can tell it their colours. */
|
|
537
|
+
export const COLOURS_TMUX = Object.freeze([3, 5]);
|
|
538
|
+
|
|
539
|
+
/** A colour the panel may hand tmux: six lowercase hex digits after a #. */
|
|
540
|
+
const HEX_COLOUR = /^#[0-9a-f]{6}$/;
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* The OSC 10 (foreground) or 11 (background) reply a terminal would give for
|
|
544
|
+
* `hex`, as `refresh-client -r` takes it: 16 bits a channel, each byte
|
|
545
|
+
* doubled ("#1e1e2e" → rgb:1e1e/1e1e/2e2e), ended by ST. Pure.
|
|
546
|
+
*/
|
|
547
|
+
export function oscColourReport(which, hex) {
|
|
548
|
+
const h = String(hex).slice(1);
|
|
549
|
+
const channel = (i) => h.slice(i, i + 2).repeat(2);
|
|
550
|
+
return `\x1b]${which};rgb:${channel(0)}/${channel(2)}/${channel(4)}\x1b\\`;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** Several replies as one: ok when every command was, lines concatenated. */
|
|
554
|
+
async function allOf(promises) {
|
|
555
|
+
const replies = await Promise.all(promises);
|
|
556
|
+
return { ok: replies.every(r => r.ok), lines: replies.flatMap(r => r.lines) };
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* A live control-mode connection to one pane. Construct with openControl().
|
|
561
|
+
*
|
|
562
|
+
* Events, all emitted synchronously from the line that caused them so that
|
|
563
|
+
* their order is the stream's order:
|
|
564
|
+
* 'output' (Buffer) bytes the chosen pane wrote after the latest
|
|
565
|
+
* seed() resolved; never before the first one
|
|
566
|
+
* 'reseed' () the stream lost bytes (a %pause); call seed()
|
|
567
|
+
* again and reset the emulator with it. After a
|
|
568
|
+
* %pause it comes once more, from a timer, when
|
|
569
|
+
* the pane has written past that seed and gone
|
|
570
|
+
* quiet (the "Flow control" note above)
|
|
571
|
+
* 'size' ({ cols, rows }) the pane changed size, at the point in the
|
|
572
|
+
* stream where tmux changed it
|
|
573
|
+
* 'exit' ({ reason, message? }) exactly once, whatever ended it:
|
|
574
|
+
* 'ended' the pane died, or its window/session/server went away
|
|
575
|
+
* 'detached' tmux detached this client (another client ran attach -d,
|
|
576
|
+
* or the pane moved out of this session); the pane lives on
|
|
577
|
+
* 'closed' close() was called
|
|
578
|
+
* 'error' tmux could not be run or failed in a way it did not explain
|
|
579
|
+
* After a pane death the client stays attached, so a seed() can still read
|
|
580
|
+
* the last frame; call close() when done with it.
|
|
581
|
+
*
|
|
582
|
+
* Never emits 'error', so an absent listener cannot crash the deck, and none of
|
|
583
|
+
* the command methods reject: a failure is a `{ ok: false, lines }` answer.
|
|
584
|
+
* seed() is the exception, because it has no partial answer to give.
|
|
585
|
+
*/
|
|
586
|
+
class ControlClient extends EventEmitter {
|
|
587
|
+
#tmux;
|
|
588
|
+
#socket;
|
|
589
|
+
#env;
|
|
590
|
+
#target;
|
|
591
|
+
#ignoreSize;
|
|
592
|
+
/** The server's [major, minor] once asked (colours), or null. */
|
|
593
|
+
#serverVersion = null;
|
|
594
|
+
#readOnly;
|
|
595
|
+
#pauseAfter;
|
|
596
|
+
#spawn;
|
|
597
|
+
#execFile;
|
|
598
|
+
#child = null;
|
|
599
|
+
#childClosed = false;
|
|
600
|
+
#pre = []; // command text written before the child exists
|
|
601
|
+
#waiters = []; // one per command sent, in order
|
|
602
|
+
#partial = [];
|
|
603
|
+
#partialBytes = 0;
|
|
604
|
+
#block = null;
|
|
605
|
+
#attached = false;
|
|
606
|
+
#isReady = false;
|
|
607
|
+
#readyResolve;
|
|
608
|
+
#readyReject;
|
|
609
|
+
#beforeReady = [];
|
|
610
|
+
#pane = "";
|
|
611
|
+
#window = "";
|
|
612
|
+
#session = "";
|
|
613
|
+
#size = null;
|
|
614
|
+
#streaming = false;
|
|
615
|
+
#folding = null; // output past a seed's boundary, held until seed() resolves
|
|
616
|
+
#boundary = seedBoundary(); // what tmux's parser holds, read from the pane's output
|
|
617
|
+
#seedSeq = 0;
|
|
618
|
+
#pauseEpoch = 0;
|
|
619
|
+
// 1 from a %pause until a seed opens the stream again, then 2 until the pane
|
|
620
|
+
// has written past that seed and gone quiet; 0 otherwise.
|
|
621
|
+
#afterPause = 0;
|
|
622
|
+
#quietTimer = null;
|
|
623
|
+
#exitEmitted = false;
|
|
624
|
+
#torn = false;
|
|
625
|
+
#closing = false;
|
|
626
|
+
#exitClassifying = false;
|
|
627
|
+
#stderr = "";
|
|
628
|
+
#closedPromise;
|
|
629
|
+
#closedResolve;
|
|
630
|
+
#killTimer = null;
|
|
631
|
+
#deadTimer = null;
|
|
632
|
+
#deadGraceMs;
|
|
633
|
+
#pasteBuffer = `ccdeck-paste-${randomBytes(4).toString("hex")}`;
|
|
634
|
+
|
|
635
|
+
/** Resolves `{ pane, window, session, cols, rows, dead }` once attached. */
|
|
636
|
+
ready;
|
|
637
|
+
|
|
638
|
+
constructor({ tmux, socket, target, pane, ignoreSize = false, readOnly = false,
|
|
639
|
+
pauseAfter = PAUSE_AFTER, spawn = nodeSpawn, execFile = nodeExecFile, env = process.env,
|
|
640
|
+
deadGraceMs = DEAD_GRACE_MS }) {
|
|
641
|
+
super();
|
|
642
|
+
this.#tmux = typeof tmux === "string" ? tmux : tmux?.path;
|
|
643
|
+
if (!this.#tmux) throw new TypeError("openControl needs the tmux binary");
|
|
644
|
+
this.#socket = requireSocket(socket);
|
|
645
|
+
// Spelled once now, so a socket tmuxCommand refuses (a name with a path
|
|
646
|
+
// separator in it) is refused here, where the caller can see it, and not
|
|
647
|
+
// later inside #start where it would only reach 'exit'.
|
|
648
|
+
this.#argv([]);
|
|
649
|
+
if (!target && !pane) throw new TypeError("openControl needs a target session or pane");
|
|
650
|
+
this.#target = String(target || pane);
|
|
651
|
+
// A pane id as the target is also the pane to stream, unless told otherwise.
|
|
652
|
+
this.#pane = pane ? String(pane) : this.#target.startsWith("%") ? this.#target : "";
|
|
653
|
+
this.#ignoreSize = !!ignoreSize;
|
|
654
|
+
this.#readOnly = !!readOnly;
|
|
655
|
+
this.#pauseAfter = Math.max(0, Math.floor(Number(pauseAfter) || 0));
|
|
656
|
+
this.#deadGraceMs = Math.max(0, Number(deadGraceMs) || 0);
|
|
657
|
+
this.#spawn = spawn;
|
|
658
|
+
this.#execFile = execFile;
|
|
659
|
+
// tmux.mjs's client environment: the deck's own, without TMUX and
|
|
660
|
+
// TMUX_PANE — a client that thinks it is nested may refuse to attach — and
|
|
661
|
+
// without the deck's and a parent agent's variables, which a tmux client
|
|
662
|
+
// never reads and which a user's `update-environment` could otherwise copy
|
|
663
|
+
// into their own session when case B attaches to it.
|
|
664
|
+
this.#env = tmuxEnv(env);
|
|
665
|
+
this.ready = new Promise((resolve, reject) => { this.#readyResolve = resolve; this.#readyReject = reject; });
|
|
666
|
+
// A caller that only listens for 'exit' never awaits `ready`; its rejection
|
|
667
|
+
// must not become an unhandled rejection that takes the deck down.
|
|
668
|
+
this.ready.catch(() => {});
|
|
669
|
+
this.#closedPromise = new Promise(r => { this.#closedResolve = r; });
|
|
670
|
+
|
|
671
|
+
// The first thing on the wire after attach: which pane, how big, and a
|
|
672
|
+
// subscription to its death. Queued now so they precede anything a caller
|
|
673
|
+
// sends, and answered in this order.
|
|
674
|
+
const fmt = quoteTmuxArg("#{session_id} #{window_id} #{pane_id} #{pane_width} #{pane_height} #{pane_dead}");
|
|
675
|
+
this.#send([`display-message -p${this.#pane ? ` -t ${this.#pane}` : ""} ${fmt}`], (reply) => this.#onPaneInfo(reply));
|
|
676
|
+
this.#send([`refresh-client -B ${quoteTmuxArg(`${DEAD_SUBSCRIPTION}:%*:${DEAD_FORMAT}`)}`]);
|
|
677
|
+
// #start is async (a pane target is looked up first); nothing in it should
|
|
678
|
+
// throw, and if something does, it is this connection's error, not the deck's.
|
|
679
|
+
this.#start().catch((err) => this.#fail("error", err?.message || String(err)));
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** The pane this client streams, e.g. "%5" ("" until ready). */
|
|
683
|
+
get pane() { return this.#pane; }
|
|
684
|
+
/** The pane's last known size, `{ cols, rows }`, or null before ready. */
|
|
685
|
+
get size() { return this.#size ? { ...this.#size } : null; }
|
|
686
|
+
/** The control client's pid, for liveChildPids and diagnostics. */
|
|
687
|
+
get pid() { return this.#child?.pid; }
|
|
688
|
+
/** True once the connection is over (exit emitted and tmux gone). */
|
|
689
|
+
get closed() { return this.#torn; }
|
|
690
|
+
|
|
691
|
+
// The arguments after the binary for one tmux invocation on this client's
|
|
692
|
+
// socket, as tmux.mjs spells every invocation: `-u` (the deck may run under
|
|
693
|
+
// LANG=C — launchd, systemd — and tmux decides from the locale whether a
|
|
694
|
+
// client speaks UTF-8), the socket, then `args`.
|
|
695
|
+
#argv(args) {
|
|
696
|
+
return tmuxCommand(this.#tmux, this.#socket, args).slice(1);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
async #start() {
|
|
700
|
+
let attachTo = this.#target;
|
|
701
|
+
if (attachTo.startsWith("%")) {
|
|
702
|
+
// ATTACHING BY PANE MOVES THE USER. `attach-session -t %5` selects that
|
|
703
|
+
// pane's window as the session's current window — measured on tmux 3.6
|
|
704
|
+
// with two windows — so in the user's own tmux (case B) the panel would
|
|
705
|
+
// yank their terminal to another window. Attaching to the pane's SESSION
|
|
706
|
+
// leaves their current window alone; output for every window of the
|
|
707
|
+
// session reaches a control client anyway.
|
|
708
|
+
const found = await new Promise((resolve) => {
|
|
709
|
+
let child;
|
|
710
|
+
try {
|
|
711
|
+
child = this.#execFile(this.#tmux, this.#argv(["display-message", "-p", "-t", attachTo, "#{session_id}"]),
|
|
712
|
+
{ timeout: 3000, env: this.#env, windowsHide: true },
|
|
713
|
+
(err, stdout) => resolve(tmuxTimedOut(child, err) ? { silent: true } : { id: err ? "" : String(stdout).trim() }));
|
|
714
|
+
} catch { resolve({ id: "" }); }
|
|
715
|
+
});
|
|
716
|
+
if (this.#closing) return this.#teardown("closed");
|
|
717
|
+
// A tmux that did not answer in time has not said the pane is gone.
|
|
718
|
+
if (found.silent) return this.#fail("error", "tmux did not answer in time");
|
|
719
|
+
if (!found.id) return this.#fail("ended", `tmux has no pane ${attachTo}`);
|
|
720
|
+
attachTo = found.id;
|
|
721
|
+
} else if (!/^[$@=]/.test(attachTo)) {
|
|
722
|
+
// "=name" is an exact match. A bare name would also match by prefix.
|
|
723
|
+
attachTo = `=${attachTo}`;
|
|
724
|
+
}
|
|
725
|
+
if (this.#closing) return this.#teardown("closed");
|
|
726
|
+
|
|
727
|
+
const flags = [];
|
|
728
|
+
if (this.#pauseAfter) flags.push(`pause-after=${this.#pauseAfter}`);
|
|
729
|
+
// At attach, not by a later refresh-client: between the two, a client that
|
|
730
|
+
// does not ignore size could already have resized the user's window.
|
|
731
|
+
if (this.#ignoreSize) flags.push("ignore-size");
|
|
732
|
+
// -E: an attaching client copies every variable named in the session's
|
|
733
|
+
// update-environment from its own environment into the session's, and
|
|
734
|
+
// removes the ones it lacks. The deck's environment is a login item's or a
|
|
735
|
+
// service's, not the user's shell, so without -E opening the user's own
|
|
736
|
+
// session here would strip its SSH_AUTH_SOCK and DISPLAY for every window
|
|
737
|
+
// they open afterwards — long after the panel has closed.
|
|
738
|
+
// tmux's command line ends a command at any argument that ENDS in ";", so a
|
|
739
|
+
// session named "notes;" is passed as "notes\;" (tmuxArg), tmux's escape
|
|
740
|
+
// for it.
|
|
741
|
+
const argv = this.#argv(["-C", "attach-session", "-E", ...(flags.length ? ["-f", flags.join(",")] : []), "-t", tmuxArg(attachTo)]);
|
|
742
|
+
let child;
|
|
743
|
+
try {
|
|
744
|
+
child = this.#spawn(this.#tmux, argv, { stdio: ["pipe", "pipe", "pipe"], env: this.#env, windowsHide: true });
|
|
745
|
+
} catch (err) {
|
|
746
|
+
return this.#fail("error", err?.message || String(err));
|
|
747
|
+
}
|
|
748
|
+
this.#child = watchChild(child);
|
|
749
|
+
child.on("error", (err) => this.#fail("error", err?.message || String(err)));
|
|
750
|
+
child.on("close", (code) => this.#onChildClose(code));
|
|
751
|
+
child.stdin?.on("error", () => { /* EPIPE once tmux has gone; 'close' says the rest */ });
|
|
752
|
+
child.stdout?.on("data", (d) => this.#onData(d));
|
|
753
|
+
child.stderr?.on("data", (d) => { this.#stderr = (this.#stderr + d.toString("utf8")).slice(-2000); });
|
|
754
|
+
if (this.#pre.length) {
|
|
755
|
+
child.stdin.write(this.#pre.join(""));
|
|
756
|
+
this.#pre = [];
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
#onData(chunk) {
|
|
761
|
+
let start = 0;
|
|
762
|
+
for (;;) {
|
|
763
|
+
const nl = chunk.indexOf(10, start);
|
|
764
|
+
if (nl < 0) break;
|
|
765
|
+
let line = chunk.subarray(start, nl);
|
|
766
|
+
if (this.#partial.length) {
|
|
767
|
+
this.#partial.push(line);
|
|
768
|
+
line = Buffer.concat(this.#partial);
|
|
769
|
+
this.#partial = [];
|
|
770
|
+
this.#partialBytes = 0;
|
|
771
|
+
}
|
|
772
|
+
start = nl + 1;
|
|
773
|
+
this.#line(line);
|
|
774
|
+
}
|
|
775
|
+
if (start < chunk.length) {
|
|
776
|
+
this.#partial.push(chunk.subarray(start));
|
|
777
|
+
this.#partialBytes += chunk.length - start;
|
|
778
|
+
if (this.#partialBytes > MAX_LINE) {
|
|
779
|
+
this.#partial = [];
|
|
780
|
+
this.#partialBytes = 0;
|
|
781
|
+
this.#fail("error", "tmux sent a line longer than any it writes");
|
|
782
|
+
this.#kill();
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
#line(raw) {
|
|
788
|
+
if (this.#block) {
|
|
789
|
+
// Inside a reply, only this block's OWN guard ends it — same time, number
|
|
790
|
+
// and flags. Command output is not escaped, so a pane showing the text
|
|
791
|
+
// "%end 1 2 1" must not be able to close a capture early.
|
|
792
|
+
if (raw[0] === 0x25) {
|
|
793
|
+
const text = raw.toString("latin1");
|
|
794
|
+
const g = this.#block.guard;
|
|
795
|
+
if (text === `%end ${g}` || text === `%error ${g}`) {
|
|
796
|
+
const block = this.#block;
|
|
797
|
+
this.#block = null;
|
|
798
|
+
this.#settle(block, text.startsWith("%end "));
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
this.#block.lines.push(raw.toString("utf8"));
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
const msg = parseControlLine(raw);
|
|
806
|
+
switch (msg.type) {
|
|
807
|
+
case "begin":
|
|
808
|
+
this.#block = { guard: msg.guard, flags: msg.flags, lines: [] };
|
|
809
|
+
return;
|
|
810
|
+
case "output":
|
|
811
|
+
if (msg.pane !== this.#pane || !msg.data.length || this.#exitEmitted) return;
|
|
812
|
+
// All of it, dropped or not: the next seed hands on where it leaves
|
|
813
|
+
// tmux's parser.
|
|
814
|
+
this.#boundary.feed(msg.data);
|
|
815
|
+
if (this.#streaming) {
|
|
816
|
+
this.emit("output", msg.data);
|
|
817
|
+
if (this.#afterPause === 2) this.#armQuiet();
|
|
818
|
+
} else if (this.#folding) this.#folding.chunks.push(msg.data);
|
|
819
|
+
return;
|
|
820
|
+
case "pause":
|
|
821
|
+
if (msg.pane === this.#pane) this.#onPause();
|
|
822
|
+
return;
|
|
823
|
+
case "layout-change":
|
|
824
|
+
if (msg.window === this.#window) this.#onLayout(msg.layout);
|
|
825
|
+
return;
|
|
826
|
+
case "window-close":
|
|
827
|
+
case "unlinked-window-close":
|
|
828
|
+
if (msg.window === this.#window) this.#verifyPane("detached");
|
|
829
|
+
return;
|
|
830
|
+
case "session-changed":
|
|
831
|
+
// Our client moved to another session: the user's own config may say
|
|
832
|
+
// detach-on-destroy off, which switches clients instead of detaching.
|
|
833
|
+
if (this.#isReady && msg.session !== this.#session) this.#verifyPane("detached", true);
|
|
834
|
+
return;
|
|
835
|
+
case "subscription-changed":
|
|
836
|
+
if (msg.name === DEAD_SUBSCRIPTION && msg.pane === this.#pane) this.#onDeadValue(msg.value);
|
|
837
|
+
return;
|
|
838
|
+
case "exit":
|
|
839
|
+
this.#onExitLine(msg.reason);
|
|
840
|
+
return;
|
|
841
|
+
default:
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
// A complete %begin…%end block. The first one is attach-session's own
|
|
846
|
+
// reply; after that, tmux marks a command read from THIS client's stdin with
|
|
847
|
+
// flags 1 and anything else — a hook's command, say — with 0.
|
|
848
|
+
#settle(block, ok) {
|
|
849
|
+
if (!this.#attached) {
|
|
850
|
+
this.#attached = true;
|
|
851
|
+
if (!ok) {
|
|
852
|
+
const why = block.lines.join(" ").trim() || "tmux refused to attach";
|
|
853
|
+
this.#fail(/can't find|no such|no sessions|not found/i.test(why) ? "ended" : "error", why);
|
|
854
|
+
}
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
if (block.flags === "0") return;
|
|
858
|
+
const w = this.#waiters.shift();
|
|
859
|
+
if (!w) return;
|
|
860
|
+
const reply = { ok, lines: block.lines };
|
|
861
|
+
w.onReply?.(reply);
|
|
862
|
+
w.resolve(reply);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Queue command lines as ONE write, so tmux reads them together and runs them
|
|
867
|
+
* back to back with no pane output between them. `onLast` runs synchronously
|
|
868
|
+
* at the last reply, before the next line of the stream is read — which is
|
|
869
|
+
* what lets a seed say exactly where its capture ends.
|
|
870
|
+
*/
|
|
871
|
+
#send(lines, onLast) {
|
|
872
|
+
const promises = lines.map((_, i) => new Promise((resolve) => {
|
|
873
|
+
this.#waiters.push({ resolve, onReply: i === lines.length - 1 ? onLast : undefined });
|
|
874
|
+
}));
|
|
875
|
+
const text = lines.map(l => `${l}\n`).join("");
|
|
876
|
+
if (this.#torn) {
|
|
877
|
+
// Nothing will answer; settle what was just queued.
|
|
878
|
+
for (const w of this.#waiters.splice(0)) w.resolve(failed("the control client has exited"));
|
|
879
|
+
} else if (this.#child) {
|
|
880
|
+
this.#child.stdin.write(text);
|
|
881
|
+
} else {
|
|
882
|
+
this.#pre.push(text);
|
|
883
|
+
}
|
|
884
|
+
return promises;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
#onPaneInfo(reply) {
|
|
888
|
+
if (!reply.ok) {
|
|
889
|
+
const why = reply.lines.join(" ").trim() || "tmux could not find the pane";
|
|
890
|
+
this.#fail("ended", why);
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
const [session, window, pane, w, h, dead] = (reply.lines[0] ?? "").split(" ");
|
|
894
|
+
this.#session = session;
|
|
895
|
+
this.#window = window;
|
|
896
|
+
this.#pane = pane;
|
|
897
|
+
this.#size = { cols: Number(w) || 0, rows: Number(h) || 0 };
|
|
898
|
+
this.#isReady = true;
|
|
899
|
+
this.#readyResolve({ pane, window, session, ...this.#size, dead: dead === "1" });
|
|
900
|
+
// Run what callers queued while waiting, in their order, right here: a call
|
|
901
|
+
// made after this point would otherwise overtake them.
|
|
902
|
+
const queued = this.#beforeReady.splice(0);
|
|
903
|
+
for (const run of queued) run();
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
// Run `fn` once the pane is known — immediately if it already is. Never
|
|
907
|
+
// rejects: a client that never got ready answers `{ ok: false }`.
|
|
908
|
+
#whenReady(fn) {
|
|
909
|
+
if (this.#isReady) return Promise.resolve(fn());
|
|
910
|
+
if (this.#torn) return Promise.resolve(failed("the control client has exited"));
|
|
911
|
+
return new Promise((resolve) => { this.#beforeReady.push(() => resolve(fn())); });
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
#onPause() {
|
|
915
|
+
// The bytes tmux skipped are gone from the stream for good, so nothing the
|
|
916
|
+
// stream says until a new capture can be trusted: stop forwarding now, ask
|
|
917
|
+
// tmux to continue, and have the owner seed again. The continue is written
|
|
918
|
+
// before 'reseed' is emitted, so a seed() made in the handler is queued
|
|
919
|
+
// after it and captures a screen that the continued stream follows.
|
|
920
|
+
this.#pauseEpoch++;
|
|
921
|
+
this.#streaming = false;
|
|
922
|
+
this.#folding = null;
|
|
923
|
+
this.#afterPause = 1;
|
|
924
|
+
this.#boundary.lose();
|
|
925
|
+
this.#clearQuiet();
|
|
926
|
+
this.#send([`refresh-client -A ${quoteTmuxArg(`${this.#pane}:continue`)}`]);
|
|
927
|
+
this.emit("reseed");
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// After a %pause and the seed that followed it, each output restarts the
|
|
931
|
+
// wait; PAUSE_QUIET_MS of quiet after the last one asks for one more seed
|
|
932
|
+
// (the "Flow control" note above). A seed in flight when it fires covers it:
|
|
933
|
+
// the stream that seed opens arms the wait again.
|
|
934
|
+
#armQuiet() {
|
|
935
|
+
clearTimeout(this.#quietTimer);
|
|
936
|
+
this.#quietTimer = setTimeout(() => {
|
|
937
|
+
this.#quietTimer = null;
|
|
938
|
+
if (this.#afterPause !== 2 || !this.#streaming || this.#exitEmitted) return;
|
|
939
|
+
this.#afterPause = 0;
|
|
940
|
+
this.#boundary.presume();
|
|
941
|
+
this.emit("reseed");
|
|
942
|
+
}, PAUSE_QUIET_MS);
|
|
943
|
+
this.#quietTimer.unref?.();
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
#clearQuiet() {
|
|
947
|
+
clearTimeout(this.#quietTimer);
|
|
948
|
+
this.#quietTimer = null;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
#onLayout(layout) {
|
|
952
|
+
const mine = layoutPanes(layout).find(p => p.pane === this.#pane);
|
|
953
|
+
if (!mine) {
|
|
954
|
+
// Not in its window's layout any more: killed, or moved by break-pane.
|
|
955
|
+
this.#verifyPane("detached");
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
this.#setSize(mine.cols, mine.rows);
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
#setSize(cols, rows) {
|
|
962
|
+
if (this.#size && this.#size.cols === cols && this.#size.rows === rows) return;
|
|
963
|
+
this.#size = { cols, rows };
|
|
964
|
+
// Between a seed's capture and its delivery there is no event a consumer
|
|
965
|
+
// could place correctly — the seed it has not received yet is at the old
|
|
966
|
+
// size — so the seed is marked stale and replaced, size and all.
|
|
967
|
+
if (this.#folding) { this.#folding.stale = true; return; }
|
|
968
|
+
if (!this.#exitEmitted) this.emit("size", { cols, rows });
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// Ask tmux about the pane after a notification that it may be gone. Gone or
|
|
972
|
+
// dead is 'ended'; alive but somewhere this client no longer sees is `ifAlive`
|
|
973
|
+
// — in another session, or anywhere at all once this client itself has been
|
|
974
|
+
// switched to another session (`left`), since only the attached session's
|
|
975
|
+
// panes send it output.
|
|
976
|
+
#verifyPane(ifAlive, left = false) {
|
|
977
|
+
if (!this.#pane || this.#exitEmitted) return;
|
|
978
|
+
const [p] = this.#send([`display-message -p -t ${this.#pane} ${quoteTmuxArg("#{pane_dead} #{pane_width} #{pane_height} #{window_id} #{session_id}")}`]);
|
|
979
|
+
p.then((r) => {
|
|
980
|
+
if (this.#torn) return;
|
|
981
|
+
if (!r.ok) return this.#emitExit("ended");
|
|
982
|
+
const [dead, w, h, window, session] = (r.lines[0] ?? "").split(" ");
|
|
983
|
+
if (dead === "1") return this.#emitExit("ended");
|
|
984
|
+
if (left || session !== this.#session) return this.#emitExit(ifAlive);
|
|
985
|
+
this.#window = window;
|
|
986
|
+
this.#setSize(Number(w) || 0, Number(h) || 0);
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
#onExitLine(reason) {
|
|
991
|
+
if (this.#closing || this.#exitEmitted) return;
|
|
992
|
+
// tmux's %exit says why only sometimes, and a detach and a destroyed
|
|
993
|
+
// session both arrive as a bare "%exit". Whether the session and the pane
|
|
994
|
+
// are still there tells them apart, and this client can no longer ask, so
|
|
995
|
+
// a one-shot tmux does. The SESSION is asked first, and has to be: right
|
|
996
|
+
// after kill-session the pane can still answer as alive for a moment —
|
|
997
|
+
// tmux keeps a destroyed window referenced until the notifications about
|
|
998
|
+
// it have run — while the session is gone at once. Measured.
|
|
999
|
+
this.#exitClassifying = true;
|
|
1000
|
+
const why = reason || "";
|
|
1001
|
+
const done = (r) => { this.#emitExit(r, why || undefined); this.#teardown(r); };
|
|
1002
|
+
if (!this.#pane || !this.#session) return done("ended");
|
|
1003
|
+
let child;
|
|
1004
|
+
try {
|
|
1005
|
+
// A lone ";" argument separates tmux commands; no shell is involved.
|
|
1006
|
+
// One that did not answer in time has said neither, so it is an error:
|
|
1007
|
+
// "ended" would offer to reopen a session that may still be running.
|
|
1008
|
+
child = this.#execFile(this.#tmux, this.#argv(["has-session", "-t", this.#session, ";",
|
|
1009
|
+
"display-message", "-p", "-t", this.#pane, "#{pane_dead}"]),
|
|
1010
|
+
{ timeout: 3000, env: this.#env, windowsHide: true },
|
|
1011
|
+
(err, stdout) => done(tmuxTimedOut(child, err) ? "error"
|
|
1012
|
+
: err || String(stdout).trim() !== "0" ? "ended" : "detached"));
|
|
1013
|
+
} catch {
|
|
1014
|
+
done("ended");
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
#onChildClose(code) {
|
|
1019
|
+
clearTimeout(this.#killTimer);
|
|
1020
|
+
this.#childClosed = true;
|
|
1021
|
+
if (this.#closing) {
|
|
1022
|
+
this.#teardown("closed");
|
|
1023
|
+
} else if (!this.#exitClassifying) {
|
|
1024
|
+
// When %exit came first, its answer is on the way and decides the reason.
|
|
1025
|
+
const why = this.#stderr.trim().split("\n").pop() || `tmux exited with code ${code}`;
|
|
1026
|
+
this.#fail(/no server running|can't find|no sessions/i.test(why) ? "ended" : "error", why);
|
|
1027
|
+
}
|
|
1028
|
+
if (this.#torn) this.#closedResolve();
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
// The pane died: said with how its program ended, or, when tmux has not
|
|
1032
|
+
// said that yet, after DEAD_GRACE_MS for it (see DEAD_FORMAT).
|
|
1033
|
+
#onDeadValue(value) {
|
|
1034
|
+
const d = parseDeadValue(value);
|
|
1035
|
+
if (!d.dead || this.#exitEmitted) return;
|
|
1036
|
+
if (d.status !== undefined || d.signal !== undefined) {
|
|
1037
|
+
this.#emitExit("ended", undefined, d);
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
if (this.#deadTimer) return;
|
|
1041
|
+
this.#deadTimer = setTimeout(() => {
|
|
1042
|
+
this.#deadTimer = null;
|
|
1043
|
+
this.#emitExit("ended");
|
|
1044
|
+
}, this.#deadGraceMs);
|
|
1045
|
+
this.#deadTimer.unref?.();
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// `how`: the dead pane's `status` and `signal`, only for "ended" from the
|
|
1049
|
+
// subscription; every other ending says neither.
|
|
1050
|
+
#emitExit(reason, message, how = {}) {
|
|
1051
|
+
if (this.#exitEmitted) return;
|
|
1052
|
+
this.#exitEmitted = true;
|
|
1053
|
+
clearTimeout(this.#deadTimer);
|
|
1054
|
+
this.#deadTimer = null;
|
|
1055
|
+
this.#clearQuiet();
|
|
1056
|
+
this.#streaming = false;
|
|
1057
|
+
this.#folding = null;
|
|
1058
|
+
this.emit("exit", {
|
|
1059
|
+
reason,
|
|
1060
|
+
...(message ? { message } : {}),
|
|
1061
|
+
...(how.status !== undefined ? { exitStatus: how.status } : {}),
|
|
1062
|
+
...(how.signal !== undefined ? { exitSignal: how.signal } : {}),
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
#fail(reason, message) {
|
|
1067
|
+
this.#emitExit(reason, message);
|
|
1068
|
+
this.#teardown(reason, message);
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// The connection is over: settle every waiter and the ready promise.
|
|
1072
|
+
#teardown(reason, message) {
|
|
1073
|
+
if (this.#torn) return;
|
|
1074
|
+
this.#torn = true;
|
|
1075
|
+
if (!this.#exitEmitted) this.#emitExit(reason, message);
|
|
1076
|
+
const why = message || `the control client has ${reason === "closed" ? "closed" : "exited"}`;
|
|
1077
|
+
for (const w of this.#waiters.splice(0)) w.resolve(failed(why));
|
|
1078
|
+
if (!this.#isReady) this.#readyReject(new Error(why));
|
|
1079
|
+
for (const run of this.#beforeReady.splice(0)) run();
|
|
1080
|
+
// A connection can be over while tmux is still attached — the pane could not
|
|
1081
|
+
// be found, or tmux said something it never says. Detach it the same way
|
|
1082
|
+
// close() does; `closed` resolves when it has really gone.
|
|
1083
|
+
// A child with no pid never started (ENOENT), and may never say 'close'.
|
|
1084
|
+
if (!this.#child || this.#childClosed || !this.#child.pid) this.#closedResolve();
|
|
1085
|
+
else this.#stopChild();
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// End of input is how a control client is told to detach; one that has not
|
|
1089
|
+
// gone within the grace period is killed.
|
|
1090
|
+
#stopChild() {
|
|
1091
|
+
try { this.#child.stdin.end(); } catch { /* already closed */ }
|
|
1092
|
+
clearTimeout(this.#killTimer);
|
|
1093
|
+
this.#killTimer = setTimeout(() => this.#kill(), CLOSE_GRACE_MS);
|
|
1094
|
+
this.#killTimer.unref?.();
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
#kill() {
|
|
1098
|
+
if (this.#child && this.#child.exitCode === null && this.#child.signalCode === null) killTree(this.#child, "SIGTERM");
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
/**
|
|
1102
|
+
* Send one tmux command line and get its reply, `{ ok, lines }`. Commands are
|
|
1103
|
+
* answered in the order sent. A line break would make it two commands and an
|
|
1104
|
+
* empty line would detach the client, so both are refused.
|
|
1105
|
+
*/
|
|
1106
|
+
cmd(line) {
|
|
1107
|
+
const text = String(line);
|
|
1108
|
+
if (!text.trim() || /[\r\n]/.test(text)) return Promise.resolve(failed("one non-empty command line at a time"));
|
|
1109
|
+
return this.#send([text])[0];
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
/**
|
|
1113
|
+
* Capture what tmux shows for the pane, as the bytes to write into a RESET
|
|
1114
|
+
* emulator: `{ bytes, cols, rows, cursor: [x, y], alternate }`.
|
|
1115
|
+
*
|
|
1116
|
+
* The questions go out as one write so tmux answers them back to back with no
|
|
1117
|
+
* output in between, and the seed boundary is the last answer: pane output
|
|
1118
|
+
* that arrived before it is already in the capture and is dropped.
|
|
1119
|
+
*
|
|
1120
|
+
* OUTPUT JUST PAST THE BOUNDARY IS IN THE SEED, NOT IN 'output'. The rest of
|
|
1121
|
+
* the chunk that carried the last answer is read synchronously, before this
|
|
1122
|
+
* promise can resolve, so any pane output in it would reach an 'output'
|
|
1123
|
+
* listener BEFORE the caller had the seed to write — and a consumer that
|
|
1124
|
+
* resets its emulator with the seed would wipe those bytes. They are
|
|
1125
|
+
* appended to `bytes` instead, and 'output' starts with what arrives after.
|
|
1126
|
+
* The caller must therefore write the seed before it awaits anything else:
|
|
1127
|
+
* `const s = await c.seed(); send(s.bytes)` is exactly right.
|
|
1128
|
+
*
|
|
1129
|
+
* If several seeds overlap, only the newest opens the stream; a %pause
|
|
1130
|
+
* while one is in flight keeps it shut, since 'reseed' has asked for
|
|
1131
|
+
* another; and a size change in that last window emits 'reseed' too, because
|
|
1132
|
+
* a seed at the old size followed by output at the new one cannot be
|
|
1133
|
+
* written correctly by anyone.
|
|
1134
|
+
*
|
|
1135
|
+
* Rejects when tmux cannot capture the pane (it has gone).
|
|
1136
|
+
*/
|
|
1137
|
+
async seed({ history = 2000 } = {}) {
|
|
1138
|
+
await this.ready;
|
|
1139
|
+
const id = ++this.#seedSeq;
|
|
1140
|
+
const epoch = this.#pauseEpoch;
|
|
1141
|
+
this.#streaming = false;
|
|
1142
|
+
this.#folding = null;
|
|
1143
|
+
const p = this.#pane;
|
|
1144
|
+
const h = Math.max(0, Math.floor(Number(history) || 0));
|
|
1145
|
+
const [infoP, capP, savedP] = this.#send([
|
|
1146
|
+
`display-message -p -t ${p} ${quoteTmuxArg(SEED_FORMAT)}`,
|
|
1147
|
+
`capture-pane -p -e -N${h ? ` -S -${h}` : ""} -t ${p}`,
|
|
1148
|
+
`capture-pane -p -e -N -a -q -t ${p}`,
|
|
1149
|
+
], (reply) => {
|
|
1150
|
+
if (reply.ok && id === this.#seedSeq && epoch === this.#pauseEpoch && !this.#exitEmitted) {
|
|
1151
|
+
// The capture's own boundary: what tmux's parser holds here goes
|
|
1152
|
+
// between the seed and the output after it.
|
|
1153
|
+
this.#folding = { id, chunks: [], stale: false, tail: this.#boundary.tail() };
|
|
1154
|
+
}
|
|
1155
|
+
});
|
|
1156
|
+
const [infoR, capR, savedR] = await Promise.all([infoP, capP, savedP]);
|
|
1157
|
+
const fold = this.#folding?.id === id ? this.#folding : null;
|
|
1158
|
+
if (fold) this.#folding = null;
|
|
1159
|
+
if (!infoR.ok || !capR.ok) throw new Error((infoR.ok ? capR : infoR).lines.join(" ").trim() || "tmux could not capture the pane");
|
|
1160
|
+
const info = parseSeedInfo(infoR.lines[0]);
|
|
1161
|
+
let bytes = buildSeed({ info, lines: capR.lines, saved: savedR.ok ? savedR.lines : [] });
|
|
1162
|
+
if (fold && !fold.stale) {
|
|
1163
|
+
if (fold.tail.length || fold.chunks.length) bytes = Buffer.concat([bytes, fold.tail, ...fold.chunks]);
|
|
1164
|
+
this.#size = { cols: info.cols, rows: info.rows };
|
|
1165
|
+
this.#streaming = !this.#exitEmitted;
|
|
1166
|
+
if (this.#afterPause && this.#streaming) {
|
|
1167
|
+
// The stream a %pause shut is open again: wait for the pane to write
|
|
1168
|
+
// past this seed and go quiet. Output folded in already has.
|
|
1169
|
+
this.#afterPause = 2;
|
|
1170
|
+
this.#clearQuiet();
|
|
1171
|
+
if (fold.chunks.length) this.#armQuiet();
|
|
1172
|
+
}
|
|
1173
|
+
} else if (fold) {
|
|
1174
|
+
this.emit("reseed");
|
|
1175
|
+
}
|
|
1176
|
+
return { bytes, cols: info.cols, rows: info.rows, cursor: [info.cursorX, info.cursorY], alternate: info.alternate };
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
/**
|
|
1180
|
+
* Make this client's size `cols` x `rows`, and the window's (case A).
|
|
1181
|
+
* Resolves at tmux's reply — the point in the stream from which output is
|
|
1182
|
+
* drawn at the new size. A no-op answering ok when the client was opened
|
|
1183
|
+
* with ignoreSize (case B), where the pane's size belongs to the user's own
|
|
1184
|
+
* terminal and arrives as 'size'.
|
|
1185
|
+
*
|
|
1186
|
+
* With more than one client on the window — a second tab, `tmux attach` by
|
|
1187
|
+
* hand — tmux's default window-size, latest, sizes it for the latest client
|
|
1188
|
+
* alone, and a control client's send-keys never makes it the latest: only
|
|
1189
|
+
* attaching or select-window do. So once attached, a resize is also a
|
|
1190
|
+
* select-window of the pane's own window from this client, which makes it
|
|
1191
|
+
* the latest and the window its size. That is how the view that last typed
|
|
1192
|
+
* or resized is the one the pane is drawn for (terminal-socket's bridge).
|
|
1193
|
+
*/
|
|
1194
|
+
resize(cols, rows) {
|
|
1195
|
+
if (this.#ignoreSize) return Promise.resolve({ ok: true, lines: [] });
|
|
1196
|
+
const c = Math.floor(Number(cols));
|
|
1197
|
+
const r = Math.floor(Number(rows));
|
|
1198
|
+
if (!(c >= 1 && c <= 10000 && r >= 1 && r <= 10000)) return Promise.resolve(failed("a size is two positive whole numbers"));
|
|
1199
|
+
const commands = [`refresh-client -C ${c}x${r}`];
|
|
1200
|
+
// Before attach the window is not known yet, and needs no claim: tmux
|
|
1201
|
+
// makes the client that attaches the latest.
|
|
1202
|
+
if (this.#window) commands.push(`select-window -t ${this.#window}`);
|
|
1203
|
+
return allOf(this.#send(commands));
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
/**
|
|
1207
|
+
* Type raw bytes (a Buffer, Uint8Array or string) into the pane — exactly
|
|
1208
|
+
* what xterm.js's onData produced, chunked into `send-keys -H` commands.
|
|
1209
|
+
* Refused on a read-only client.
|
|
1210
|
+
*/
|
|
1211
|
+
input(bytes) {
|
|
1212
|
+
if (this.#readOnly) return Promise.resolve(failed("read-only"));
|
|
1213
|
+
const buf = toBuffer(bytes ?? "");
|
|
1214
|
+
if (!buf.length) return Promise.resolve({ ok: true, lines: [] });
|
|
1215
|
+
return this.#whenReady(() => allOf(this.#send(sendKeysCommands(this.#pane, buf))));
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
/**
|
|
1219
|
+
* Paste text into the pane through a paste buffer, so tmux brackets it if
|
|
1220
|
+
* and only if the program asked for bracketed paste. The buffer name is this
|
|
1221
|
+
* client's own: two panels pasting at once into one server would otherwise
|
|
1222
|
+
* paste each other's text. Refused on a read-only client.
|
|
1223
|
+
*/
|
|
1224
|
+
paste(text) {
|
|
1225
|
+
if (this.#readOnly) return Promise.resolve(failed("read-only"));
|
|
1226
|
+
return this.#whenReady(() => {
|
|
1227
|
+
const cmds = pasteCommands(this.#pane, text ?? "", this.#pasteBuffer);
|
|
1228
|
+
return cmds.length ? allOf(this.#send(cmds)) : { ok: true, lines: [] };
|
|
1229
|
+
});
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
/**
|
|
1233
|
+
* The tmux SERVER's version as [major, minor], asked of the server once and
|
|
1234
|
+
* shared: null when it will not say in numbers (an "openbsd-7.4", a server
|
|
1235
|
+
* that has gone). The server's, not the binary's — a server started by an
|
|
1236
|
+
* older tmux keeps running after an upgrade, and it is the one that answers
|
|
1237
|
+
* the pane and takes this client's commands. Safe to call before attach:
|
|
1238
|
+
* the question is queued behind attach-session and answered right after it,
|
|
1239
|
+
* ahead of anything asked later.
|
|
1240
|
+
*/
|
|
1241
|
+
serverVersion() {
|
|
1242
|
+
this.#serverVersion ??= this.cmd('display-message -p "#{version}"')
|
|
1243
|
+
.then(r => (r.ok ? parseTmuxVersion(`tmux ${r.lines[0] ?? ""}`) : null), () => null);
|
|
1244
|
+
return this.#serverVersion;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
/**
|
|
1248
|
+
* Tell tmux the colours this client draws the pane with — the panel's own
|
|
1249
|
+
* foreground and background, six-digit hex — so a program in the pane that
|
|
1250
|
+
* asks for them (OSC 10/11; Claude Code's auto theme does) is answered with
|
|
1251
|
+
* the deck's theme instead of the black tmux answers when no client has
|
|
1252
|
+
* said. tmux keeps them per pane and flags a theme change when the
|
|
1253
|
+
* background moves, which reaches programs that subscribed to it (mode
|
|
1254
|
+
* 2031, tmux 3.6+).
|
|
1255
|
+
*
|
|
1256
|
+
* The window's style is set to them too, on every tmux: it is what tmux
|
|
1257
|
+
* answers from when no control client has reported (3.2–3.4 always; later
|
|
1258
|
+
* ones once this client has gone), and what the launch set them in first
|
|
1259
|
+
* (terminal-sessions.mjs), so a theme switch must not leave it behind.
|
|
1260
|
+
*
|
|
1261
|
+
* Refused on a read-only client and on an ignoreSize one: that pane is in
|
|
1262
|
+
* the user's own tmux, where these colours would change what the user's own
|
|
1263
|
+
* terminal programs are told. `refresh-client -r` only from tmux 3.5 —
|
|
1264
|
+
* asked of the server itself, once, since it is the server's version that
|
|
1265
|
+
* decides and it may be older than the binary that started this client.
|
|
1266
|
+
*/
|
|
1267
|
+
colours(fg, bg) {
|
|
1268
|
+
if (this.#readOnly) return Promise.resolve(failed("read-only"));
|
|
1269
|
+
if (this.#ignoreSize) return Promise.resolve(failed("the pane's colours belong to the user's own terminal"));
|
|
1270
|
+
if (!HEX_COLOUR.test(String(fg)) || !HEX_COLOUR.test(String(bg))) return Promise.resolve(failed("a colour is #rrggbb"));
|
|
1271
|
+
return this.#whenReady(async () => {
|
|
1272
|
+
const v = await this.serverVersion();
|
|
1273
|
+
const [major, minor] = COLOURS_TMUX;
|
|
1274
|
+
const reports = v && (v[0] > major || (v[0] === major && v[1] >= minor));
|
|
1275
|
+
return allOf(this.#send([
|
|
1276
|
+
`set-option -w -t ${quoteTmuxArg(this.#pane)} window-style ${quoteTmuxArg(`fg=${fg},bg=${bg}`)}`,
|
|
1277
|
+
...(reports ? [
|
|
1278
|
+
`refresh-client -r ${quoteTmuxArg(`${this.#pane}:${oscColourReport(10, fg)}`)}`,
|
|
1279
|
+
`refresh-client -r ${quoteTmuxArg(`${this.#pane}:${oscColourReport(11, bg)}`)}`,
|
|
1280
|
+
] : []),
|
|
1281
|
+
]));
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
/**
|
|
1286
|
+
* Detach and stop the control client. The tmux session keeps running — that
|
|
1287
|
+
* is what makes closing the panel safe. Resolves once tmux has gone; a tmux
|
|
1288
|
+
* that has not left within two seconds of losing its stdin is killed.
|
|
1289
|
+
*/
|
|
1290
|
+
close() {
|
|
1291
|
+
if (this.#torn) return this.#closedPromise;
|
|
1292
|
+
this.#closing = true;
|
|
1293
|
+
// With no child yet, #start is still resolving the pane's session; it sees
|
|
1294
|
+
// the flag and stops there.
|
|
1295
|
+
if (this.#child) this.#stopChild();
|
|
1296
|
+
return this.#closedPromise;
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
/**
|
|
1301
|
+
* Attach a control client to a tmux session and stream one of its panes.
|
|
1302
|
+
*
|
|
1303
|
+
* tmux the tmux binary: a path, or findTmux()'s answer ({ path })
|
|
1304
|
+
* socket { name } for `-L name` or { path } for `-S path` — required
|
|
1305
|
+
* target session name, "$id", or a pane id "%N" (then its session is
|
|
1306
|
+
* looked up first, so the user's current window is not moved)
|
|
1307
|
+
* pane the pane to stream; defaults to the target's active pane
|
|
1308
|
+
* ignoreSize attach with `ignore-size` (case B: the user's terminal owns the
|
|
1309
|
+
* size; resize() becomes a no-op and 'size' reports the pane's)
|
|
1310
|
+
* readOnly input() and paste() are refused
|
|
1311
|
+
* pauseAfter seconds behind before tmux pauses the pane (0 = never)
|
|
1312
|
+
* spawn, execFile, env seams for tests; real defaults
|
|
1313
|
+
*
|
|
1314
|
+
* Returns the ControlClient synchronously; await `.ready` before relying on
|
|
1315
|
+
* `.pane`.
|
|
1316
|
+
*/
|
|
1317
|
+
export function openControl(options) {
|
|
1318
|
+
return new ControlClient(options);
|
|
1319
|
+
}
|