ccdeck 3.82.3 → 4.0.0

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.
Files changed (146) hide show
  1. package/LICENSING.md +42 -4
  2. package/README.md +183 -72
  3. package/THIRD_PARTY_NOTICES.md +243 -17
  4. package/bin/cli/login-item.js +5 -0
  5. package/bin/cli/tui.js +58 -4
  6. package/bin/deck.js +27 -1
  7. package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
  8. package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
  9. package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
  10. package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
  11. package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
  12. package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
  13. package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
  14. package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
  15. package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
  16. package/dist/web/assets/UsageHistoryModal-ckawZGoe.js +1 -0
  17. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  18. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  19. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  20. package/dist/web/assets/app-40gNTTfq.js +361 -0
  21. package/dist/web/assets/app-BRjYF6oD.css +1 -0
  22. package/dist/web/assets/{index-B4c5MZCc.js → index-XIY3yFiN.js} +1 -1
  23. package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
  24. package/dist/web/assets/screens-9_ivqfcF.js +12 -0
  25. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  26. package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
  27. package/dist/web/assets/use-account-BUmI-A8e.js +1 -0
  28. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  29. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  30. package/dist/web/index.html +16 -6
  31. package/package.json +13 -1
  32. package/release-notes.json +79 -0
  33. package/src/server/account-client.mjs +196 -0
  34. package/src/server/account-connect.mjs +238 -0
  35. package/src/server/account-flag.mjs +106 -0
  36. package/src/server/account-projects.mjs +1 -1
  37. package/src/server/account-service.mjs +532 -0
  38. package/src/server/account-status.mjs +293 -0
  39. package/src/server/account-store.mjs +137 -0
  40. package/src/server/account-sync.mjs +473 -0
  41. package/src/server/account-token-store.mjs +216 -0
  42. package/src/server/account-ui-fields.mjs +126 -0
  43. package/src/server/account-watch.mjs +1 -1
  44. package/src/server/browser-watch-log.mjs +1 -1
  45. package/src/server/browser-watch-store.mjs +1 -1
  46. package/src/server/ccdeck-account-routes.mjs +252 -0
  47. package/src/server/ccusage-install.mjs +2 -2
  48. package/src/server/ccusage-registry.mjs +4 -4
  49. package/src/server/ccusage-session.mjs +11 -0
  50. package/src/server/claude-accounts.mjs +1 -1
  51. package/src/server/claude-recovery.mjs +9 -4
  52. package/src/server/claude-settings-catalog.mjs +6 -6
  53. package/src/server/claude-settings.mjs +1 -1
  54. package/src/server/codex-auto.mjs +1 -1
  55. package/src/server/codex-cost-usage.mjs +7 -2
  56. package/src/server/codex-live-checkpoint.mjs +24 -9
  57. package/src/server/codex-live-engine.mjs +14 -4
  58. package/src/server/codex-live-handoff.mjs +53 -9
  59. package/src/server/codex-names.mjs +49 -0
  60. package/src/server/codex-translate.mjs +1 -1
  61. package/src/server/codex-ultrafast.d.mts +3 -0
  62. package/src/server/codex-ultrafast.mjs +5 -0
  63. package/src/server/codex-watch.mjs +25 -0
  64. package/src/server/command-panel-engine.mjs +300 -0
  65. package/src/server/command-panel-platform.mjs +99 -0
  66. package/src/server/cswap-auto-choice.mjs +1 -1
  67. package/src/server/cswap-auto-loop.mjs +1 -1
  68. package/src/server/cswap-install.mjs +21 -40
  69. package/src/server/deck-home.mjs +6 -0
  70. package/src/server/deck-prefs.mjs +53 -1
  71. package/src/server/detach.mjs +1 -1
  72. package/src/server/engine-download.mjs +277 -0
  73. package/src/server/engine-install.mjs +378 -0
  74. package/src/server/engine-package.mjs +267 -0
  75. package/src/server/event-log.mjs +7 -1
  76. package/src/server/event-pipeline.mjs +29 -1
  77. package/src/server/ghostty-handoff.mjs +81 -0
  78. package/src/server/index.mjs +143 -5
  79. package/src/server/installer.mjs +4 -1
  80. package/src/server/integrations/jira-write-guard.mjs +14 -208
  81. package/src/server/integrations/store.mjs +37 -19
  82. package/src/server/integrations/write-guard.mjs +223 -0
  83. package/src/server/intel-cpu-temperature.mjs +26 -0
  84. package/src/server/lifecycle.mjs +69 -6
  85. package/src/server/log-replay.mjs +4 -0
  86. package/src/server/login-service.mjs +116 -14
  87. package/src/server/macmon.mjs +1 -1
  88. package/src/server/npm-latest.mjs +1 -1
  89. package/src/server/org-telemetry.mjs +1 -1
  90. package/src/server/output-watch.mjs +4 -1
  91. package/src/server/panel-provenance.mjs +390 -0
  92. package/src/server/pinned-build.mjs +14 -0
  93. package/src/server/prefs-refusal.mjs +8 -1
  94. package/src/server/prefs-routes.mjs +60 -11
  95. package/src/server/pro-engine-client.mjs +339 -0
  96. package/src/server/pro-engine-install.mjs +294 -0
  97. package/src/server/pro-engine-terminal.mjs +308 -0
  98. package/src/server/project-discovery.mjs +139 -0
  99. package/src/server/provider-session-name.mjs +58 -0
  100. package/src/server/quota-closes.mjs +1 -1
  101. package/src/server/quota-history.mjs +1 -1
  102. package/src/server/reports.mjs +86 -21
  103. package/src/server/request-gates.mjs +34 -5
  104. package/src/server/restart-note.mjs +1 -1
  105. package/src/server/seed-boundary.mjs +489 -0
  106. package/src/server/session-counts.mjs +244 -0
  107. package/src/server/session-deck-names.mjs +143 -0
  108. package/src/server/session-enrichment.mjs +43 -6
  109. package/src/server/session-name-route.mjs +73 -0
  110. package/src/server/session-summary.mjs +12 -1
  111. package/src/server/session-transcript-routes.mjs +167 -0
  112. package/src/server/swap-log.mjs +1 -1
  113. package/src/server/system-metrics.mjs +57 -0
  114. package/src/server/terminal-bridge.mjs +485 -0
  115. package/src/server/terminal-folder.mjs +61 -0
  116. package/src/server/terminal-js-routes.mjs +752 -0
  117. package/src/server/terminal-routes.mjs +553 -0
  118. package/src/server/terminal-sessions.mjs +759 -0
  119. package/src/server/terminal-socket.mjs +403 -0
  120. package/src/server/terminal-target.mjs +928 -0
  121. package/src/server/thermal-metrics.mjs +13 -9
  122. package/src/server/tmux-control.mjs +1319 -0
  123. package/src/server/tmux-download.mjs +220 -0
  124. package/src/server/tmux.mjs +542 -0
  125. package/src/server/token-redact.mjs +42 -3
  126. package/src/server/tool-audit-report.mjs +44 -6
  127. package/src/server/tool-audit-routes.mjs +12 -1
  128. package/src/server/tool-audit.mjs +42 -8
  129. package/src/server/traffic-radar-monitor.mjs +1 -1
  130. package/src/server/traffic-radar-permission.mjs +1 -1
  131. package/src/server/transcript-gate.mjs +1 -1
  132. package/src/server/transcript-scan.mjs +15 -7
  133. package/src/server/transcript-turns.mjs +154 -0
  134. package/src/server/tui-network.mjs +1 -0
  135. package/src/server/tui-view.mjs +28 -0
  136. package/src/server/utf8-carry.mjs +159 -0
  137. package/src/server/uv-bootstrap.mjs +2 -2
  138. package/src/server/windows-acl.mjs +158 -0
  139. package/src/server/ws-frames.mjs +690 -0
  140. package/dist/web/assets/BrowserWatchModal-BmRTh_xT.js +0 -1
  141. package/dist/web/assets/IntegrationModal-C_f526aV.js +0 -7
  142. package/dist/web/assets/RadioPanel-D2rkf9cg.js +0 -1
  143. package/dist/web/assets/TrafficRadar-BOgVBLIN.js +0 -8
  144. package/dist/web/assets/UsageHistoryModal-BJPTFwM9.js +0 -1
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
  146. package/dist/web/assets/app-DZdZoqJ6.js +0 -358
@@ -0,0 +1,485 @@
1
+ // The JS terminal backend's session bridge: a tmux control-mode client on a
2
+ // ticket's pane, and the protocol between it and the panel.
3
+ //
4
+ // NOT ON THE PRODUCT'S PATH. The deck serves the Command Panel only through
5
+ // the optional local engine (pro-engine-terminal.mjs relays its streams), and
6
+ // nothing the deck runs imports this file: terminal-js-routes.mjs, the JS
7
+ // backend a test hands startServer as `terminal.jsBackend`, is its one
8
+ // caller. It stays, with tmux.mjs, tmux-control.mjs, terminal-target.mjs and
9
+ // terminal-sessions.mjs, as the parity oracle the engine is checked against;
10
+ // removing it is a separate decision. The engine's bridge speaks this same
11
+ // protocol, so the panel cannot tell the two apart
12
+ // (docs/contracts/pro-engine-host-v1.md, "Terminal streams").
13
+ //
14
+ // THE BRIDGE IS THE PROTOCOL src/web/terminal-protocol.ts SPEAKS, in order:
15
+ // `hello`; then nothing until the panel's first `size`, so the first frame is
16
+ // drawn at the panel's size and not at whatever the pane was; the pane resized
17
+ // to it when the panel owns the size; then `reset` and ONE binary frame of
18
+ // seed — the bytes that make a reset xterm show what tmux shows — and from
19
+ // then on the pane's output as it happens, as fast as the panel says (`ack`)
20
+ // its terminal is parsing it. tmux-control.mjs owns the hard part
21
+ // (the seed boundary, %pause, the pane dying); this file only keeps the order
22
+ // on the wire, never lets two seeds cross, and sends whole characters: a
23
+ // frame never ends inside a UTF-8 character that its next bytes finish
24
+ // (utf8-carry.mjs, and `carry` below), and a frame longer than xterm.js
25
+ // decodes in one piece has no character cut at a piece edge (padPieceEdges,
26
+ // in sendBinary).
27
+ //
28
+ // NOTHING THROWS OUT OF HERE, for the reason terminal-socket.mjs gives: a
29
+ // socket callback has nothing above it to catch it.
30
+ import { clampSize } from "./terminal-sessions.mjs";
31
+ import { openControl } from "./tmux-control.mjs";
32
+ import { padPieceEdges, utf8Carry } from "./utf8-carry.mjs";
33
+
34
+ /** How many bytes may sit unsent on one socket before the pane's output stops
35
+ * being forwarded. A tab in the background, or a slow link, otherwise makes
36
+ * the deck hold every byte a busy TUI writes. Above this the stream is let go
37
+ * and the panel is re-seeded once the socket drains — it then shows what the
38
+ * pane shows, which is all the skipped bytes were ever going to amount to. */
39
+ export const HIGH_WATER_BYTES = 4 << 20;
40
+
41
+ /** How many bytes of output may be on their way to a panel that acknowledges
42
+ * what its terminal has parsed (`ack`) before the stream is let go. The
43
+ * socket's own high-water mark only sees bytes the kernel has not taken, and
44
+ * a browser takes them as fast as they come and queues them for xterm, which
45
+ * parses a few megabytes a second: measured on a long-line `cat` loop, 7–8 MB
46
+ * were still in the browser when Ctrl+C reached the pane, and the flood kept
47
+ * scrolling for a second and a half after it had stopped. With a window, what
48
+ * is in flight is bounded by it, and a panel that falls behind is re-seeded
49
+ * with the screen as it is now — what a native terminal shows when it draws
50
+ * only the latest frame. A page that never acknowledges is never held to it. */
51
+ export const ACK_WINDOW_BYTES = 512 * 1024;
52
+
53
+ /** The panel sends a size on every frame of a drag. tmux redraws the pane for
54
+ * each one, so they are settled for this long and only the last is applied. */
55
+ export const RESIZE_DEBOUNCE_MS = 50;
56
+
57
+ /** The least time between two colour reports to tmux. A theme switch is one
58
+ * message; a page that sends a stream of them gets the latest, this often. */
59
+ export const COLOURS_INTERVAL_MS = 250;
60
+
61
+ /** A colour as the panel may send it: six lowercase hex digits after a #. */
62
+ const HEX_COLOUR = /^#[0-9a-f]{6}$/;
63
+
64
+ /** Lines of scrollback a seed carries above the screen. */
65
+ export const SEED_HISTORY = 2000;
66
+
67
+ /** What tmux-control's exit reasons are called on the wire. `closed` is this
68
+ * bridge's own close() and is never said to the panel. */
69
+ const EXIT_REASONS = Object.freeze({ ended: "ended", detached: "detached", error: "error" });
70
+
71
+ /** The one sentence an `error` exit carries. tmux's own words are not sent:
72
+ * they name socket paths, and the panel has no use for them. */
73
+ const ERROR_SENTENCE = "The deck lost its connection to tmux.";
74
+
75
+ /**
76
+ * The session bridge for one admitted socket: a tmux control-mode client on
77
+ * the ticket's pane, and the protocol between it and the panel. Answers `{
78
+ * message(m), closed(code, reason), shutdown(reason) }` for the upgrade to
79
+ * call. See the header for the conversation.
80
+ *
81
+ * conn the wsConnection
82
+ * socket the raw socket, for its 'drain' (see HIGH_WATER_BYTES)
83
+ * binding what the ticket was minted for: { kind, tmux, socket, target,
84
+ * pane, ignoreSize, readOnly? }
85
+ * open openControl, or a stand-in
86
+ * history, debounceMs, highWater SEED_HISTORY, RESIZE_DEBOUNCE_MS,
87
+ * HIGH_WATER_BYTES
88
+ *
89
+ * The pane owns the size when the binding says ignoreSize (the user's own
90
+ * tmux, case B): the panel is then told the pane's size whenever it changes,
91
+ * and its own sizes after the first are ignored. Otherwise the panel owns it,
92
+ * and its sizes resize the pane.
93
+ */
94
+ export function terminalBridge({
95
+ conn, socket, binding,
96
+ open = openControl, history = SEED_HISTORY, debounceMs = RESIZE_DEBOUNCE_MS, highWater = HIGH_WATER_BYTES,
97
+ coloursMs = COLOURS_INTERVAL_MS, ackWindow = ACK_WINDOW_BYTES,
98
+ }) {
99
+ const paneOwned = binding?.ignoreSize === true;
100
+ const readOnly = binding?.readOnly === true;
101
+ // `ended` once an exit has been said or the socket has gone; nothing is
102
+ // sent after it. `started` once the panel's first size has arrived, which
103
+ // is what the first seed waits for. `seeded` once a reset and its seed have
104
+ // gone out, so an `ended` exit knows whether there is a frame on screen.
105
+ let ended = false;
106
+ let started = false;
107
+ let seeded = false;
108
+ let congested = false;
109
+ // Flow control by acknowledgement (ACK_WINDOW_BYTES). `sentBytes`: every
110
+ // binary byte this bridge has put on the wire, seeds included. `ackedBytes`:
111
+ // the most the panel has said its terminal parsed, -1 until it first says —
112
+ // a page that predates acks is never held to the window. `behind`: output
113
+ // is being let go because the window is full; the next ack that brings it
114
+ // back under half asks for a seed.
115
+ let sentBytes = 0;
116
+ let ackedBytes = -1;
117
+ let behind = false;
118
+ // Where the last seed ended. The window is counted from there: a seed is a
119
+ // one-off, and one larger than the window (2000 lines of coloured history
120
+ // can be) would otherwise let go of the output after it, and the reseed its
121
+ // ack asks for would do the same again, for as long as the pane writes.
122
+ let seedMark = 0;
123
+ const inFlight = () => sentBytes - Math.max(ackedBytes, seedMark);
124
+ // Reseeds asked for, and the latest of those a delivered seed answered. A
125
+ // %pause during a seed asks for another, and the one in flight is then
126
+ // stale: comparing the two is how it knows not to send itself.
127
+ let asks = 0;
128
+ let queued = false;
129
+ let resizeTimer = null;
130
+ let pendingSize = null;
131
+ // Sizes, for a pane the panel sizes (case A, D). `asked`: the last size this
132
+ // panel gave tmux. `shown`: the size its xterm is at, as far as this side
133
+ // knows — every reset, every size it sends and every size the panel says it
134
+ // took. `lost`: the pane went to a size this panel did not ask for, because
135
+ // another view of the same session sized it — a second tab, a `claude
136
+ // attach` wrapper two panels share, `tmux attach` by hand. tmux sizes a
137
+ // shared window for the latest client only, so the two would otherwise draw
138
+ // one pane at two sizes, and the one that lost would garble everything.
139
+ // Instead the loser is told the pane's real size, and takes the pane back
140
+ // the moment it is typed in: the view in use is the one the pane fits.
141
+ let asked = null;
142
+ let shown = null;
143
+ let lost = false;
144
+ // The panel's theme colours, for a pane the deck owns (case A, D): tmux
145
+ // answers a program's OSC 10/11 question itself, from what its control
146
+ // client said, and says black when nobody did — which Claude Code's auto
147
+ // theme reads as a dark terminal on every deck theme. `told` is what tmux
148
+ // has, `wanted` the latest the panel sent, `coloursTimer` the cooldown.
149
+ let told = "";
150
+ let wanted = "";
151
+ let coloursTimer = null;
152
+ // Every seed and the exit go through this one chain, so two seeds never
153
+ // cross on the wire and an exit is never said ahead of the seed before it.
154
+ let chain = Promise.resolve();
155
+ const later = (fn) => {
156
+ chain = chain.then(fn).catch(() => {});
157
+ return chain;
158
+ };
159
+ // Whole characters on the wire. tmux ends a %output line where its read of
160
+ // the pane ended, sometimes inside a character, and the panel's xterm.js
161
+ // loses a character cut right after a 0x80 byte ("—" as E2 80 | 94). So the
162
+ // bytes at a frame's end that begin a character are held — three at most —
163
+ // and sent in front of the next frame (utf8-carry.mjs). They are never
164
+ // counted in `sentBytes` until they are on the wire.
165
+ //
166
+ // Held bytes belong to the stream they came from, which runs from one seed
167
+ // to whatever breaks it, and they are dropped there, never sent late: every
168
+ // break is followed by a seed — the screen as tmux has it, which already
169
+ // shows the character if tmux ever finished it — or by nothing at all. So
170
+ // they are dropped when output is let go (congested, behind: the bytes that
171
+ // would finish them are among the ones let go), when a reseed is asked for
172
+ // (a %pause: tmux skipped output), when a seed is sent (a new stream), and
173
+ // at the end. A new socket is a new bridge, with a carry of its own.
174
+ const carry = utf8Carry();
175
+
176
+ const handle = { message, closed, shutdown };
177
+
178
+ conn.sendText(JSON.stringify({ t: "hello", kind: String(binding?.kind ?? ""), sizeOwner: paneOwned ? "pane" : "dock", readOnly }));
179
+
180
+ let control = null;
181
+ try {
182
+ control = open({
183
+ tmux: binding?.tmux,
184
+ socket: binding?.socket,
185
+ target: binding?.target,
186
+ pane: binding?.pane,
187
+ ignoreSize: paneOwned,
188
+ readOnly,
189
+ });
190
+ } catch {
191
+ end("error", ERROR_SENTENCE);
192
+ return handle;
193
+ }
194
+ control.on("output", onOutput);
195
+ control.on("reseed", askReseed);
196
+ control.on("size", onPaneSize);
197
+ control.on("exit", onExit);
198
+
199
+ // The tmux server's version, for the panel to know which of the pane's
200
+ // questions that tmux answers itself (terminal-replies.ts) — first in the
201
+ // chain, so it is on the wire before the first reset. Asked now, before the
202
+ // panel's size has arrived, and queued behind tmux's attach, so its answer
203
+ // comes back ahead of the resize and the seed it might otherwise delay.
204
+ const version = typeof control.serverVersion === "function" ? control.serverVersion() : Promise.resolve(null);
205
+ later(async () => {
206
+ const v = await version;
207
+ if (ended || !Array.isArray(v)) return;
208
+ conn.sendText(JSON.stringify({ t: "tmux", version: `${v[0]}.${v[1]}` }));
209
+ });
210
+
211
+ /** Capture and send one seed. Nothing is awaited between the capture and
212
+ * the two writes: tmux-control starts the stream the moment seed()
213
+ * resolves, and output must follow the seed on the wire, not precede it. */
214
+ async function deliverSeed() {
215
+ if (ended) return;
216
+ const at = asks;
217
+ let seed;
218
+ try {
219
+ seed = await control.seed({ history });
220
+ } catch {
221
+ // The pane could not be captured: it has gone, and the control client's
222
+ // 'exit' says how.
223
+ return;
224
+ }
225
+ if (ended) return;
226
+ // A reseed was asked for while this one was being captured, and is queued
227
+ // behind it: this frame is already out of date and the stream is shut.
228
+ if (asks !== at && queued) return;
229
+ // A new stream. The seed itself goes through the carry: tmux-control
230
+ // appends the output just past the capture to it, and that can end inside
231
+ // a character the first frame after it finishes. The seed always has
232
+ // bytes left to send — it opens with RIS — so it is still ONE frame.
233
+ carry.drop();
234
+ conn.sendText(JSON.stringify({ t: "reset", cols: seed.cols, rows: seed.rows }));
235
+ sendBinary(carry.frame(seed.bytes));
236
+ seedMark = sentBytes;
237
+ shown = { cols: seed.cols, rows: seed.rows };
238
+ seeded = true;
239
+ }
240
+
241
+ /** A binary frame, counted for the window. The panel writes each frame in
242
+ * one write, and xterm.js decodes a write longer than 131072 bytes in
243
+ * pieces that can cut a character as two writes do — a long seed is the
244
+ * usual one, a long output line could be — so the frame is padded first
245
+ * (utf8-carry.mjs). The filler is counted: the panel acknowledges what it
246
+ * was sent. */
247
+ function sendBinary(bytes) {
248
+ const frame = padPieceEdges(bytes);
249
+ sentBytes += frame.length;
250
+ return conn.sendBinary(frame);
251
+ }
252
+
253
+ /** The panel's terminal has parsed `n` of the bytes sent so far. A count
254
+ * past what was sent, or going backwards, is not believed. */
255
+ function onAck(n) {
256
+ if (!Number.isSafeInteger(n) || n < 0 || n > sentBytes || n <= ackedBytes) return;
257
+ ackedBytes = n;
258
+ if (behind && inFlight() <= ackWindow / 2) {
259
+ behind = false;
260
+ askReseed();
261
+ }
262
+ }
263
+
264
+ function askReseed() {
265
+ asks += 1;
266
+ // The stream has broken (a %pause, output let go): what it held goes
267
+ // with it, and the seed asked for draws the screen as tmux has it.
268
+ carry.drop();
269
+ // Before the first size there is nothing on screen to replace; the first
270
+ // seed, when it comes, is newer than whatever asked.
271
+ if (ended || !started || queued) return;
272
+ queued = true;
273
+ later(async () => {
274
+ queued = false;
275
+ await deliverSeed();
276
+ });
277
+ }
278
+
279
+ function onOutput(data) {
280
+ if (ended || congested || behind) return;
281
+ if (ackedBytes >= 0 && inFlight() > ackWindow) {
282
+ // The panel has more in flight than its terminal has parsed by a whole
283
+ // window: let the stream go, as for a socket that stopped reading, and
284
+ // seed what tmux shows once it has caught up (onAck). A character it
285
+ // had begun is let go with it.
286
+ behind = true;
287
+ carry.drop();
288
+ return;
289
+ }
290
+ if (conn.bufferedAmount > highWater) {
291
+ // Let the stream go rather than queue it: what was skipped is redrawn by
292
+ // a seed once the socket has caught up.
293
+ congested = true;
294
+ carry.drop();
295
+ const drained = () => {
296
+ congested = false;
297
+ askReseed();
298
+ };
299
+ if (typeof socket?.once === "function") socket.once("drain", drained);
300
+ else drained();
301
+ return;
302
+ }
303
+ // Whole characters only. A frame all of whose bytes are held (one byte of
304
+ // a character, say) sends nothing.
305
+ const frame = carry.frame(data);
306
+ if (frame.length) sendBinary(frame);
307
+ }
308
+
309
+ function onPaneSize({ cols, rows }) {
310
+ // Only once a frame is on screen: before that, the reset that comes with
311
+ // the first seed carries the size.
312
+ if (ended || !seeded) return;
313
+ if (paneOwned) return void conn.sendText(JSON.stringify({ t: "size", cols, rows }));
314
+ // A resize of the panel's own is about to claim the pane anyway, and a
315
+ // size seen meanwhile may be the echo of its previous one.
316
+ if (resizeTimer) return;
317
+ // The panel's own resize landing is not news to it; any other size is.
318
+ if (asked && (cols !== asked.cols || rows !== asked.rows)) lost = true;
319
+ if (shown && cols === shown.cols && rows === shown.rows) return;
320
+ shown = { cols, rows };
321
+ conn.sendText(JSON.stringify({ t: "size", cols, rows }));
322
+ }
323
+
324
+ /** Before this panel types into a pane another view has resized, give the
325
+ * pane back its size. Not awaited: tmux runs one client's commands in the
326
+ * order they were written, so the keys land after the resize. */
327
+ function reclaim() {
328
+ if (!lost || paneOwned || !asked) return;
329
+ lost = false;
330
+ control.resize(asked.cols, asked.rows);
331
+ }
332
+
333
+ function onExit({ reason, exitStatus, exitSignal } = {}) {
334
+ if (ended || reason === "closed") return;
335
+ const said = EXIT_REASONS[reason] ?? "error";
336
+ later(async () => {
337
+ if (ended) return;
338
+ // A pane that died under remain-on-exit still has its last frame, and
339
+ // the client stays attached so it can be read: a panel that never got a
340
+ // frame is shown that one, frozen, rather than an empty box — and told
341
+ // the ending came before it was looking (`atOpen`).
342
+ const first = said === "ended" && !seeded;
343
+ if (first) await deliverSeed();
344
+ end(said, said === "error" ? ERROR_SENTENCE : undefined, { atOpen: first, exitStatus, exitSignal });
345
+ });
346
+ }
347
+
348
+ /** Whether tmux said the pane was already dead when this client attached. */
349
+ async function paneWasDead() {
350
+ try {
351
+ return (await control.ready)?.dead === true;
352
+ } catch {
353
+ return false;
354
+ }
355
+ }
356
+
357
+ function message({ type, data } = {}) {
358
+ if (ended) return;
359
+ if (type === "binary") {
360
+ if (!readOnly) {
361
+ reclaim();
362
+ control.input(data);
363
+ }
364
+ return;
365
+ }
366
+ let msg;
367
+ try { msg = JSON.parse(Buffer.from(data ?? "").toString("utf8")); } catch { return; }
368
+ if (!msg || typeof msg !== "object") return;
369
+ if (msg.t === "size") onPanelSize(msg.cols, msg.rows);
370
+ else if (msg.t === "paste" && typeof msg.text === "string" && !readOnly) {
371
+ reclaim();
372
+ control.paste(msg.text);
373
+ } else if (msg.t === "colours") onColours(msg.fg, msg.bg);
374
+ else if (msg.t === "ack") onAck(msg.bytes);
375
+ // Anything else is a newer page saying something this deck has not heard
376
+ // of. Ignored, like the page ignores what it does not know.
377
+ }
378
+
379
+ /** The panel's colours, told to tmux at most once per `coloursMs`, the
380
+ * latest winning. Never for the user's own tmux (case B): tmux keeps them
381
+ * per pane, so they would change what the user's own terminal programs are
382
+ * told about the user's own terminal. Never for a read-only view. */
383
+ function onColours(fg, bg) {
384
+ if (paneOwned || readOnly) return;
385
+ if (typeof fg !== "string" || typeof bg !== "string" || !HEX_COLOUR.test(fg) || !HEX_COLOUR.test(bg)) return;
386
+ wanted = `${fg} ${bg}`;
387
+ if (!coloursTimer) tellColours();
388
+ }
389
+
390
+ function tellColours() {
391
+ coloursTimer = null;
392
+ if (ended || !wanted || wanted === told) return;
393
+ told = wanted;
394
+ const [fg, bg] = told.split(" ");
395
+ control.colours?.(fg, bg);
396
+ coloursTimer = setTimeout(tellColours, coloursMs);
397
+ coloursTimer.unref?.();
398
+ }
399
+
400
+ function onPanelSize(cols, rows) {
401
+ if (!Number.isFinite(cols) || !Number.isFinite(rows)) return;
402
+ const size = clampSize(cols, rows);
403
+ // What the panel's xterm is at now: it resizes itself before it says so.
404
+ shown = { cols: Math.round(cols), rows: Math.round(rows) };
405
+ if (!started) {
406
+ started = true;
407
+ later(async () => {
408
+ if (ended) return;
409
+ // The resize first, and its reply awaited: the seed is then captured
410
+ // at the panel's size, and the first frame is drawn once, not twice.
411
+ if (!paneOwned) {
412
+ asked = size;
413
+ await control.resize(size.cols, size.rows);
414
+ }
415
+ await deliverSeed();
416
+ // A pane that was already dead when this client attached — an ended
417
+ // session's deck pane, opened for its last frame — is said to have
418
+ // ended now, with that frame on screen, rather than whenever tmux's
419
+ // once-a-second dead-pane subscription gets to it: by then the panel
420
+ // has drawn it as live, and would say it ended "just now".
421
+ if (seeded && !ended && await paneWasDead()) end("ended", undefined, { atOpen: true });
422
+ });
423
+ return;
424
+ }
425
+ if (paneOwned) return;
426
+ pendingSize = size;
427
+ clearTimeout(resizeTimer);
428
+ resizeTimer = setTimeout(() => {
429
+ resizeTimer = null;
430
+ if (ended || !pendingSize) return;
431
+ // A resize claims the pane as well (tmux-control's resize), so whatever
432
+ // another view had done to it is undone with it.
433
+ asked = pendingSize;
434
+ lost = false;
435
+ control.resize(pendingSize.cols, pendingSize.rows);
436
+ }, debounceMs);
437
+ resizeTimer.unref?.();
438
+ }
439
+
440
+ // Say why, close, and let the tmux client go. The session it was attached to
441
+ // keeps running whatever the reason — closing a panel is never stopping an
442
+ // agent.
443
+ // `atOpen`: the session had ended before this panel first saw it, so the
444
+ // panel does not say it ended "just now". `exitStatus`/`exitSignal`: how an
445
+ // ended pane's program ended, when tmux said; the stage closes a pane whose
446
+ // agent ended itself with status 0 (internal #104).
447
+ function end(reason, text, { atOpen = false, exitStatus, exitSignal } = {}) {
448
+ if (ended) return;
449
+ ended = true;
450
+ // A character the pane began and never finished is not sent: tmux draws
451
+ // nothing for it either.
452
+ carry.drop();
453
+ clearTimeout(resizeTimer);
454
+ clearTimeout(coloursTimer);
455
+ const how = reason === "ended" ? {
456
+ ...(Number.isInteger(exitStatus) && exitStatus >= 0 ? { exitStatus } : {}),
457
+ ...(Number.isInteger(exitSignal) && exitSignal > 0 ? { exitSignal } : {}),
458
+ } : {};
459
+ conn.sendText(JSON.stringify({ t: "exit", reason, ...(text ? { message: text } : {}), ...(atOpen ? { atOpen: true } : {}), ...how }));
460
+ try {
461
+ conn.close(reason === "server-shutdown" ? 1001 : 1000, reason);
462
+ } catch { /* already closing */ }
463
+ release();
464
+ }
465
+
466
+ function release() {
467
+ try { control?.close(); } catch { /* the client is already gone */ }
468
+ }
469
+
470
+ /** The socket went away, from either side. */
471
+ function closed() {
472
+ ended = true;
473
+ carry.drop();
474
+ clearTimeout(resizeTimer);
475
+ clearTimeout(coloursTimer);
476
+ release();
477
+ }
478
+
479
+ /** The deck is going away, or the switch went off: closeOpenTerminals. */
480
+ function shutdown(reason = "server-shutdown", text) {
481
+ end(reason, text);
482
+ }
483
+
484
+ return handle;
485
+ }
@@ -0,0 +1,61 @@
1
+ // Is this folder one an agent can start in? Asked by the New session picker
2
+ // before it hands the folder to a launch (internal #106), so that a folder
3
+ // that went away, one this user may not open, or a file is said in the picker
4
+ // with the folder still chosen — not as a stage that failed after the picker
5
+ // closed.
6
+ //
7
+ // A QUESTION, NOT A BROWSER. It answers yes or why not for one path the page
8
+ // already has — picked in the desktop app's own folder dialog, typed in full,
9
+ // or one of the page's recent projects — and never lists what a folder holds
10
+ // or reads a file. A page that can call it can already launch an agent in the
11
+ // same path, which answers the same question less kindly; it is behind the
12
+ // same switch and the same gates as that launch (terminal-routes.mjs).
13
+ //
14
+ // THE ENGINE STILL DECIDES. The launch is asked of the engine as before, which
15
+ // checks the folder again; a yes here is a courtesy that can go stale, never a
16
+ // permission. Nothing is ever started in another folder than the one asked.
17
+ import { constants } from "node:fs";
18
+ import { access, stat } from "node:fs/promises";
19
+ import { isAbsolute } from "node:path";
20
+
21
+ /** Why a folder is not one to start in. */
22
+ export const FOLDER_PROBLEMS = Object.freeze(["relative", "missing", "denied", "not-folder"]);
23
+
24
+ const DENIED = new Set(["EACCES", "EPERM"]);
25
+
26
+ /** The path as asked, without trailing separators — but never the root itself
27
+ * ("/", "C:\\"), and never resolved: the folder the reader chose is the one
28
+ * that is started in, links and all. */
29
+ export function trimFolder(path) {
30
+ if (typeof path !== "string") return "";
31
+ const trimmed = path.replace(/[\\/]+$/, "");
32
+ if (trimmed === "") return path.startsWith("/") ? "/" : path;
33
+ // "C:\" keeps its separator; a bare "C:" is a drive's current folder, not a path.
34
+ if (/^[A-Za-z]:$/.test(trimmed)) return path.length > 2 ? `${trimmed}${path[2]}` : path;
35
+ return trimmed;
36
+ }
37
+
38
+ /**
39
+ * `{ ok: true, cwd }` for a folder an agent can be started in, else `{ ok:
40
+ * false, code }` with one of FOLDER_PROBLEMS. `cwd` is the path trimmed of
41
+ * trailing separators and nothing else.
42
+ */
43
+ export async function checkFolder(path, { statFn = stat, accessFn = access } = {}) {
44
+ const cwd = trimFolder(path);
45
+ // A control character is no folder the deck stores (checkCwd): not a path at all.
46
+ if (!cwd || !isAbsolute(cwd) || /[\u0000-\u001f\u007f]/.test(cwd)) return { ok: false, code: "relative" };
47
+ let st;
48
+ try {
49
+ st = await statFn(cwd);
50
+ } catch (err) {
51
+ return { ok: false, code: DENIED.has(err?.code) ? "denied" : "missing" };
52
+ }
53
+ if (!st.isDirectory()) return { ok: false, code: "not-folder" };
54
+ // Seen is not entered: an agent has to list it and to work inside it.
55
+ try {
56
+ await accessFn(cwd, constants.R_OK | constants.X_OK);
57
+ } catch (err) {
58
+ return { ok: false, code: DENIED.has(err?.code) ? "denied" : "missing" };
59
+ }
60
+ return { ok: true, cwd };
61
+ }