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.
- package/LICENSING.md +42 -4
- package/README.md +183 -72
- package/THIRD_PARTY_NOTICES.md +243 -17
- package/bin/cli/login-item.js +5 -0
- package/bin/cli/tui.js +58 -4
- package/bin/deck.js +27 -1
- package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
- package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
- package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
- package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
- package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
- package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
- package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
- package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
- package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
- package/dist/web/assets/UsageHistoryModal-ckawZGoe.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-40gNTTfq.js +361 -0
- package/dist/web/assets/app-BRjYF6oD.css +1 -0
- package/dist/web/assets/{index-B4c5MZCc.js → index-XIY3yFiN.js} +1 -1
- package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
- package/dist/web/assets/screens-9_ivqfcF.js +12 -0
- package/dist/web/assets/screens-DUniTTbC.css +1 -0
- package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
- package/dist/web/assets/use-account-BUmI-A8e.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 +79 -0
- 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 +116 -14
- 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-BmRTh_xT.js +0 -1
- package/dist/web/assets/IntegrationModal-C_f526aV.js +0 -7
- package/dist/web/assets/RadioPanel-D2rkf9cg.js +0 -1
- package/dist/web/assets/TrafficRadar-BOgVBLIN.js +0 -8
- package/dist/web/assets/UsageHistoryModal-BJPTFwM9.js +0 -1
- package/dist/web/assets/app-CbXmr9rC.css +0 -1
- package/dist/web/assets/app-DZdZoqJ6.js +0 -358
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
// The JS terminal backend's six route handlers: the deck's own tmux, asked
|
|
2
|
+
// from this process. TESTS ONLY.
|
|
3
|
+
//
|
|
4
|
+
// status is tmux here, and new enough? No paths.
|
|
5
|
+
// target can this session be attached to, and how?
|
|
6
|
+
// open attach: a ticket for the socket, or why not
|
|
7
|
+
// adopt reopen a session started outside the deck, here
|
|
8
|
+
// launch start a new agent in a deck-owned tmux session
|
|
9
|
+
// claim is this new Codex the one a launch started?
|
|
10
|
+
//
|
|
11
|
+
// NOT ON THE PRODUCT'S PATH. The deck serves the Command Panel only through
|
|
12
|
+
// the optional local engine (terminal-routes.mjs), and nothing the deck runs
|
|
13
|
+
// imports this file or what it reaches — terminal-bridge.mjs, tmux.mjs,
|
|
14
|
+
// tmux-control.mjs, terminal-target.mjs, terminal-sessions.mjs and
|
|
15
|
+
// tmux-download.mjs (terminal-js-offpath.test.ts walks the import graph from
|
|
16
|
+
// bin/deck.js and index.mjs to hold that). A test hands `jsTerminalBackend`
|
|
17
|
+
// to startServer as `terminal.jsBackend`; no setting, environment variable,
|
|
18
|
+
// flag or request can. It stays as the parity oracle the engine is checked
|
|
19
|
+
// against, with its tests; removing it is a separate decision.
|
|
20
|
+
//
|
|
21
|
+
// terminal-routes.mjs keeps everything HTTP in front of these: the switch
|
|
22
|
+
// (404), the gates, the body's cap (413) and the ticket store. Each handler
|
|
23
|
+
// here is handed the route's parsed question and the routes' deps.
|
|
24
|
+
//
|
|
25
|
+
// THE PAGE NEVER NAMES A PANE. It names a session — an id, a provider, a
|
|
26
|
+
// folder — and the server works out the rest on every request
|
|
27
|
+
// (terminal-target.mjs): which tmux, which pane, whether the session runs at
|
|
28
|
+
// all. The answer the page gets is describeTarget's one sentence; the pane,
|
|
29
|
+
// the socket and the tmux binary go into the ticket's binding and stay in
|
|
30
|
+
// this process. A forged event in the ring (POST /api/event takes no
|
|
31
|
+
// credential) can put a session on the board; it cannot point the panel at a
|
|
32
|
+
// pane, because nothing the page sends is ever used as one.
|
|
33
|
+
//
|
|
34
|
+
// ERRORS ARE SENTENCES. A refusal carries `error`, one short sentence with no
|
|
35
|
+
// path in it — terminal-sessions.mjs writes them that way — and the deck's
|
|
36
|
+
// log gets what tmux actually said. "Not attachable" is not an error: open
|
|
37
|
+
// answers it with HTTP 200 and `{ ok: false, target }`, a state for the panel
|
|
38
|
+
// to draw.
|
|
39
|
+
import { execFile } from "node:child_process";
|
|
40
|
+
import { statSync } from "node:fs";
|
|
41
|
+
import { homedir } from "node:os";
|
|
42
|
+
import { PRODUCT } from "./brand.mjs";
|
|
43
|
+
import { send } from "./http-io.mjs";
|
|
44
|
+
import {
|
|
45
|
+
AGENTS, checkCwd, findDeckSession, findLaunchedSession, isLaunchKey, killDeckSession, labelDeckSession, launchSession,
|
|
46
|
+
listDeckSessions, pruneDeadDeckSessions, resizeWrapper, resolveAgentBin,
|
|
47
|
+
} from "./terminal-sessions.mjs";
|
|
48
|
+
import { terminalBridge } from "./terminal-bridge.mjs";
|
|
49
|
+
import { TICKET_TTL_MS } from "./terminal-socket.mjs";
|
|
50
|
+
import { checkTargetQuery, describeTarget, resolveTarget } from "./terminal-target.mjs";
|
|
51
|
+
import { DECK_SOCKET, findTmux, resetTmuxCache } from "./tmux.mjs";
|
|
52
|
+
import { ensureManagedTmux, recentTmuxFailure, tmuxDownloadBlocked, tmuxDownloadProgress } from "./tmux-download.mjs";
|
|
53
|
+
import { deckDataDir } from "./deck-home.mjs";
|
|
54
|
+
|
|
55
|
+
/** Adopt's refusal while the session's own process still runs: two agents
|
|
56
|
+
* resuming one conversation would write one log from two places. The page
|
|
57
|
+
* matches on this word (terminal-api.ts STILL_RUNNING), not on a sentence. */
|
|
58
|
+
export const STILL_RUNNING = "still-running";
|
|
59
|
+
|
|
60
|
+
/** What claude attach may be handed. terminal-target's attachIdOf already
|
|
61
|
+
* holds the short id to this; it is asked again here because this is where
|
|
62
|
+
* the value becomes an argument, and an argument that starts with a dash is
|
|
63
|
+
* a flag. */
|
|
64
|
+
const ATTACH_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
65
|
+
|
|
66
|
+
/** How each TerminalSessionError code is answered. A caller's mistake is a
|
|
67
|
+
* 400; the machine not having what it takes is a 409, a state the panel can
|
|
68
|
+
* say; tmux failing in a way it did not explain is the deck's 500. */
|
|
69
|
+
const SESSION_STATUS = Object.freeze({
|
|
70
|
+
"bad-agent": 400, "bad-kind": 400, "bad-cwd": 400, "bad-session-id": 400, "bad-argv": 400, "bad-name": 400, "bad-options": 400, "bad-launch-key": 400,
|
|
71
|
+
"agent-missing": 409, "tmux-unavailable": 409, "exists": 409,
|
|
72
|
+
"tmux-failed": 500,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// Sessions an adopt is resuming right now. A double click must not start two
|
|
76
|
+
// agents on one conversation, and resolveTarget cannot see the first one
|
|
77
|
+
// until its tmux session exists.
|
|
78
|
+
const adopting = new Set();
|
|
79
|
+
|
|
80
|
+
// Launches starting right now, by the page's key for them (launchOnce).
|
|
81
|
+
const launching = new Map();
|
|
82
|
+
|
|
83
|
+
// The asks under a launch key whose listing of the deck's sessions is still
|
|
84
|
+
// out, and the launches under that key that finished meanwhile (launchOnce):
|
|
85
|
+
// key → { asks, finished, last }.
|
|
86
|
+
const looking = new Map();
|
|
87
|
+
|
|
88
|
+
/** How often the deck clears old dead sessions off its server, at most: on
|
|
89
|
+
* the first status or launch after this long. Dead panes pile up over days,
|
|
90
|
+
* not minutes, and the prune is a listing plus a kill per corpse. */
|
|
91
|
+
export const PRUNE_EVERY_MS = 60 * 60_000;
|
|
92
|
+
let lastPrune = -Infinity;
|
|
93
|
+
|
|
94
|
+
/** For tests: let the next status or launch prune again. */
|
|
95
|
+
export function resetPruneClock() { lastPrune = -Infinity; }
|
|
96
|
+
|
|
97
|
+
/** Start a prune of dead deck sessions if none ran for PRUNE_EVERY_MS. Not
|
|
98
|
+
* awaited: the answer the panel is waiting for never waits on cleanup. */
|
|
99
|
+
function maybePrune(d, tmux) {
|
|
100
|
+
const now = d.now();
|
|
101
|
+
if (!tmux?.ok || now - lastPrune < PRUNE_EVERY_MS) return;
|
|
102
|
+
lastPrune = now;
|
|
103
|
+
void Promise.resolve()
|
|
104
|
+
.then(() => d.pruneDeadDeckSessions({ tmux, socket: d.deckSocket, env: d.env }))
|
|
105
|
+
.catch(() => {});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Everything these handlers reach outside themselves, with the real ones as
|
|
110
|
+
* defaults: the platform and environment, the deck's tmux socket, tmux itself
|
|
111
|
+
* and the session and target modules (the session module's launch, list, kill
|
|
112
|
+
* and label). `routes` is terminal-routes' deps — the switch, the ticket store
|
|
113
|
+
* and whatever stand-ins the test handed startServer as `terminal` — which win
|
|
114
|
+
* over every default here.
|
|
115
|
+
*/
|
|
116
|
+
export function jsTerminalDeps(routes = {}) {
|
|
117
|
+
const d = {
|
|
118
|
+
platform: process.platform,
|
|
119
|
+
env: process.env,
|
|
120
|
+
deckSocket: DECK_SOCKET,
|
|
121
|
+
findTmux: null,
|
|
122
|
+
resolveTarget,
|
|
123
|
+
launchSession,
|
|
124
|
+
listDeckSessions,
|
|
125
|
+
killDeckSession,
|
|
126
|
+
labelDeckSession,
|
|
127
|
+
pruneDeadDeckSessions,
|
|
128
|
+
resizeWrapper,
|
|
129
|
+
now: Date.now,
|
|
130
|
+
claudeBin: null,
|
|
131
|
+
isDir,
|
|
132
|
+
home: homedir,
|
|
133
|
+
ttySize: null,
|
|
134
|
+
openControl: null,
|
|
135
|
+
// ccdeck's own tmux, for a machine with none (tmux-download.mjs).
|
|
136
|
+
downloadBlocked: null,
|
|
137
|
+
downloadTmux: null,
|
|
138
|
+
downloadProgress: tmuxDownloadProgress,
|
|
139
|
+
recentDownloadFailure: recentTmuxFailure,
|
|
140
|
+
forgetTmux: resetTmuxCache,
|
|
141
|
+
...(routes ?? {}),
|
|
142
|
+
};
|
|
143
|
+
d.downloadBlocked ??= () => tmuxDownloadBlocked({ env: d.env, platform: d.platform });
|
|
144
|
+
// Into the folder tmuxCandidates looks in, which is decided by the same env.
|
|
145
|
+
d.downloadTmux ??= () => ensureManagedTmux({ env: d.env, platform: d.platform, dataDir: deckDataDir(d.platform, d.env) });
|
|
146
|
+
d.findTmux ??= () => findTmux({ env: d.env, platform: d.platform });
|
|
147
|
+
d.claudeBin ??= () => resolveAgentBin("claude", { env: d.env, platform: d.platform });
|
|
148
|
+
d.ttySize ??= (tty) => ttySize(tty, d.platform);
|
|
149
|
+
return d;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The bridge installTerminalUpgrade's `openBridge` starts for a ticket these
|
|
154
|
+
* handlers minted, for `routes` (terminal-routes' deps): terminalBridge on
|
|
155
|
+
* the ticket's pane, and the `claude attach` wrapper's count kept for a
|
|
156
|
+
* background session's.
|
|
157
|
+
*/
|
|
158
|
+
function openBridge(routes) {
|
|
159
|
+
const d = jsTerminalDeps(routes);
|
|
160
|
+
return (ctx) => {
|
|
161
|
+
const bridge = terminalBridge(d.openControl ? { ...ctx, open: d.openControl } : ctx);
|
|
162
|
+
if (ctx.binding?.kind !== "D") return bridge;
|
|
163
|
+
const gone = showWrapper(ctx.binding, d);
|
|
164
|
+
return {
|
|
165
|
+
...bridge,
|
|
166
|
+
closed: (...args) => {
|
|
167
|
+
try { return bridge.closed(...args); } finally { gone(); }
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* THE WRAPPER GOES WHEN THE LAST PANEL ON IT DOES. Every view of a background
|
|
175
|
+
* session shares one pty, and it takes the size of whichever `claude attach`
|
|
176
|
+
* came last; a wrapper left attached went on holding the session at the
|
|
177
|
+
* stage's size after the stage had closed, so the user's own `claude agents`
|
|
178
|
+
* drew it for a width it did not have — words run together, lines broken
|
|
179
|
+
* mid-word — until they resized their window. So a wrapper no panel shows is
|
|
180
|
+
* closed, its session first put back to the size it had before a panel
|
|
181
|
+
* fitted it (putBack), and the session goes back to the views still on it.
|
|
182
|
+
* After a grace: a reopen closes one socket and then opens the next, and
|
|
183
|
+
* should find the wrapper still there. The background session itself keeps
|
|
184
|
+
* running.
|
|
185
|
+
*/
|
|
186
|
+
export const WRAPPER_GRACE_MS = 3_000;
|
|
187
|
+
/** The longest a closing wrapper waits for the size it put back to reach the
|
|
188
|
+
* background session: its `claude attach` passes it on when it notices. */
|
|
189
|
+
export const RESTORE_WAIT_MS = 2_000;
|
|
190
|
+
const RESTORE_POLL_MS = 100;
|
|
191
|
+
/** Wrapper name → how many panels show it, the close waiting to happen, and
|
|
192
|
+
* the session's size before a panel showed it: `{ tty, size }` or null. */
|
|
193
|
+
const wrappers = new Map();
|
|
194
|
+
|
|
195
|
+
function wrapperEntry(name) {
|
|
196
|
+
let w = wrappers.get(name);
|
|
197
|
+
if (!w) { w = { open: 0, timer: null, restore: null }; wrappers.set(name, w); }
|
|
198
|
+
return w;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Close `binding`'s wrapper in `ms`, unless a panel shows it by then; its
|
|
202
|
+
* session's own size put back first, while its `claude attach` still runs. */
|
|
203
|
+
function closeWrapperIn(binding, d, ms) {
|
|
204
|
+
const name = binding.target;
|
|
205
|
+
const w = wrapperEntry(name);
|
|
206
|
+
clearTimeout(w.timer);
|
|
207
|
+
const timer = setTimeout(() => {
|
|
208
|
+
// A panel back (showWrapper clears the timer) or a later close owns it now.
|
|
209
|
+
const mine = () => wrappers.get(name) === w && w.open === 0 && w.timer === timer;
|
|
210
|
+
if (!mine()) return;
|
|
211
|
+
const kill = () => {
|
|
212
|
+
if (!mine()) return;
|
|
213
|
+
wrappers.delete(name);
|
|
214
|
+
// Already gone, or tmux would not: the next open replaces a dead one.
|
|
215
|
+
try {
|
|
216
|
+
void Promise.resolve(d.killDeckSession({ tmux: binding.tmux, name, socket: binding.socket, env: d.env })).catch(() => {});
|
|
217
|
+
} catch { /* see above */ }
|
|
218
|
+
};
|
|
219
|
+
if (!w.restore) return kill();
|
|
220
|
+
void putBack(binding, d, w.restore, mine).catch(() => {}).then(kill);
|
|
221
|
+
}, ms);
|
|
222
|
+
timer.unref?.();
|
|
223
|
+
w.timer = timer;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Keep `size`, read off a background session's terminal `tty`, to put back
|
|
227
|
+
* as wrapper `name` closes. The first reading stands while the wrapper
|
|
228
|
+
* lives, and none is taken while a panel shows it: by then a panel may have
|
|
229
|
+
* fitted the session to itself. */
|
|
230
|
+
function keepSize(name, tty, size) {
|
|
231
|
+
if (!tty || !size) return;
|
|
232
|
+
const w = wrapperEntry(name);
|
|
233
|
+
if (!w.restore && w.open === 0) w.restore = { tty, size: { cols: size.cols, rows: size.rows } };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Put a background session back to the size `restore` kept, through its
|
|
238
|
+
* wrapper's `claude attach`, which passes the window's size on as it would a
|
|
239
|
+
* terminal's. Nothing when the session reads that size already or its
|
|
240
|
+
* terminal is gone. Then waits, at most RESTORE_WAIT_MS, for the session to
|
|
241
|
+
* read it: killing the wrapper sooner can cut that off. Stops early once
|
|
242
|
+
* `mine()` says a panel came back, which fits the session to itself again.
|
|
243
|
+
*/
|
|
244
|
+
async function putBack(binding, d, restore, mine) {
|
|
245
|
+
const { cols, rows } = restore.size;
|
|
246
|
+
const side = (n) => Number.isInteger(n) && n >= 1 && n <= 10_000;
|
|
247
|
+
if (!side(cols) || !side(rows)) return;
|
|
248
|
+
const reads = async () => {
|
|
249
|
+
const now = await Promise.resolve(d.ttySize(restore.tty)).catch(() => null);
|
|
250
|
+
return now ? now.cols === cols && now.rows === rows : null;
|
|
251
|
+
};
|
|
252
|
+
// Unreadable (null) is a terminal gone; true is a size never changed.
|
|
253
|
+
if ((await reads()) !== false) return;
|
|
254
|
+
const resized = await Promise.resolve(d.resizeWrapper({
|
|
255
|
+
tmux: binding.tmux, name: binding.target, cols, rows, socket: binding.socket, env: d.env,
|
|
256
|
+
})).catch(() => false);
|
|
257
|
+
if (resized !== true) return;
|
|
258
|
+
// Counted and timed both: a fake clock cannot stall it, nor a slow stty.
|
|
259
|
+
const until = Date.now() + RESTORE_WAIT_MS;
|
|
260
|
+
for (let i = 0; i < RESTORE_WAIT_MS / RESTORE_POLL_MS && Date.now() < until; i++) {
|
|
261
|
+
await new Promise(r => setTimeout(r, RESTORE_POLL_MS).unref?.());
|
|
262
|
+
if (!mine() || (await reads()) === true) return;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** A panel now shows `binding`'s wrapper; answers the call for when it stops. */
|
|
267
|
+
function showWrapper(binding, d) {
|
|
268
|
+
const w = wrapperEntry(binding.target);
|
|
269
|
+
clearTimeout(w.timer);
|
|
270
|
+
w.timer = null;
|
|
271
|
+
w.open += 1;
|
|
272
|
+
let done = false;
|
|
273
|
+
return () => {
|
|
274
|
+
if (done) return;
|
|
275
|
+
done = true;
|
|
276
|
+
w.open -= 1;
|
|
277
|
+
if (w.open <= 0) closeWrapperIn(binding, d, WRAPPER_GRACE_MS);
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** A ticket for `binding`'s wrapper was handed out: it stays while the ticket
|
|
282
|
+
* can still be redeemed, and goes after it if no panel ever opened. */
|
|
283
|
+
function holdWrapper(binding, d) {
|
|
284
|
+
const w = wrapperEntry(binding.target);
|
|
285
|
+
if (w.open === 0) closeWrapperIn(binding, d, TICKET_TTL_MS + WRAPPER_GRACE_MS);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Forget every wrapper this process was counting; for tests. */
|
|
289
|
+
export function resetWrappers() {
|
|
290
|
+
for (const w of wrappers.values()) clearTimeout(w.timer);
|
|
291
|
+
wrappers.clear();
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* The size of the terminal at `tty`, as `stty size` reads it, or null.
|
|
296
|
+
*
|
|
297
|
+
* What a wrapper for a background session starts at, and what it puts back as
|
|
298
|
+
* it closes: the session's own pty is at the size its viewers gave it, and a
|
|
299
|
+
* `claude attach` at any other size takes it there.
|
|
300
|
+
*/
|
|
301
|
+
export function ttySize(tty, platform = process.platform) {
|
|
302
|
+
return new Promise((resolve) => {
|
|
303
|
+
if (!/^\/dev\/[A-Za-z0-9/]+$/.test(String(tty ?? ""))) return resolve(null);
|
|
304
|
+
execFile("stty", [platform === "linux" ? "-F" : "-f", String(tty), "size"], { timeout: 1_000 }, (err, out) => {
|
|
305
|
+
const m = /^(\d+) (\d+)\s*$/.exec(String(out ?? ""));
|
|
306
|
+
const rows = m ? Number(m[1]) : 0, cols = m ? Number(m[2]) : 0;
|
|
307
|
+
resolve(err || !rows || !cols ? null : { cols, rows });
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The tmux half of GET /api/terminal/status, from findTmux's answer: whether
|
|
314
|
+
* it works, its version, and why not with the line that installs it. Never
|
|
315
|
+
* the path or the raw `-V` text — the panel needs neither, and a path is a
|
|
316
|
+
* fact about the machine a page has no business holding.
|
|
317
|
+
*/
|
|
318
|
+
export function tmuxStatus(found) {
|
|
319
|
+
const version = Array.isArray(found?.version) ? found.version.join(".") : "";
|
|
320
|
+
return {
|
|
321
|
+
ok: found?.ok === true,
|
|
322
|
+
...(version ? { version } : {}),
|
|
323
|
+
...(found?.ok === true ? {} : { reason: typeof found?.reason === "string" && found.reason ? found.reason : "missing" }),
|
|
324
|
+
...(typeof found?.warning === "string" && found.warning ? { warning: found.warning } : {}),
|
|
325
|
+
...(typeof found?.install === "string" && found.install ? { install: found.install } : {}),
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* status → `{ ok: true, platform, tmux }`.
|
|
331
|
+
*
|
|
332
|
+
* With no usable tmux, the first ask starts fetching ccdeck's own build
|
|
333
|
+
* (tmux-download.mjs) and answers `reason: "installing"`, with `progress` once
|
|
334
|
+
* the download has said how far it is; the panel asks again until it is `ok`. A download that failed is answered for RETRY_AFTER_MS as
|
|
335
|
+
* the plain missing or too-old state with `download: <why>`, so the panel can
|
|
336
|
+
* offer the install line instead, and is tried again after that.
|
|
337
|
+
*/
|
|
338
|
+
async function status(req, res, _input, routes) {
|
|
339
|
+
const d = jsTerminalDeps(routes);
|
|
340
|
+
const found = await d.findTmux();
|
|
341
|
+
const fixable = !found?.ok && (found?.reason === "missing" || found?.reason === "too-old");
|
|
342
|
+
if (fixable && !d.downloadBlocked()) {
|
|
343
|
+
const failed = d.recentDownloadFailure();
|
|
344
|
+
if (failed) return send(res, 200, { ok: true, platform: d.platform, tmux: { ...tmuxStatus(found), download: failed.reason } });
|
|
345
|
+
// Not awaited: a download is seconds, a status is answered now. The
|
|
346
|
+
// answer it remembers is forgotten when the build lands, so the next ask
|
|
347
|
+
// finds it.
|
|
348
|
+
void d.downloadTmux().then((r) => { if (r?.ok) d.forgetTmux(); });
|
|
349
|
+
const progress = d.downloadProgress();
|
|
350
|
+
return send(res, 200, { ok: true, platform: d.platform, tmux: { ok: false, reason: "installing", ...(progress ? { progress } : {}) } });
|
|
351
|
+
}
|
|
352
|
+
maybePrune(d, found);
|
|
353
|
+
return send(res, 200, { ok: true, platform: d.platform, tmux: tmuxStatus(found) });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** target `{ sessionId, provider, cwd }` (the query's three values) → `{ ok:
|
|
357
|
+
* true, target }`, where target is describeTarget's answer. */
|
|
358
|
+
async function target(req, res, query, routes) {
|
|
359
|
+
const d = jsTerminalDeps(routes);
|
|
360
|
+
const q = checkTargetQuery(query);
|
|
361
|
+
if (!q.ok) return send(res, 400, { ok: false, error: q.error });
|
|
362
|
+
const { target } = await locate(q, d);
|
|
363
|
+
return send(res, 200, { ok: true, target: describeTarget(target) });
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* claim `{ key, sessionId, provider, cwd }` → `{ ok: true,
|
|
368
|
+
* claimed, target }`: whether the session runs in the pane the page launched
|
|
369
|
+
* under `key` — and, when it does, that pane is labelled with its id.
|
|
370
|
+
*
|
|
371
|
+
* A Codex chooses its own id once it starts writing, so the launch route
|
|
372
|
+
* cannot name it; the page asks this of each new Codex the board hears of
|
|
373
|
+
* while the stage shows the launch (codex-launch.ts). Only the deck can tell
|
|
374
|
+
* two of them apart, and it says yes or no, never which pane. The label is
|
|
375
|
+
* what keeps the next launch in the same folder recognisable: an unlabelled
|
|
376
|
+
* pane is one more that the next session could have begun in
|
|
377
|
+
* (terminal-target's launchedCodexPane), and the stage keeps the connection
|
|
378
|
+
* it has, so no open comes along to write it.
|
|
379
|
+
*/
|
|
380
|
+
async function claim(req, res, body, routes) {
|
|
381
|
+
const d = jsTerminalDeps(routes);
|
|
382
|
+
if (!body) return send(res, 400, { ok: false, error: "The request did not name a session." });
|
|
383
|
+
if (!isLaunchKey(body.key)) return send(res, 400, { ok: false, error: "The launch's key is not one the deck can keep." });
|
|
384
|
+
const q = checkTargetQuery(body);
|
|
385
|
+
if (!q.ok) return send(res, 400, { ok: false, error: q.error });
|
|
386
|
+
try {
|
|
387
|
+
const { tmux, target } = await locate(q, d);
|
|
388
|
+
const claimed = target.kind === "A" && target.launchKey === body.key;
|
|
389
|
+
if (claimed) await learn(target, tmux, d);
|
|
390
|
+
return send(res, 200, { ok: true, claimed, target: describeTarget(target) });
|
|
391
|
+
} catch (err) {
|
|
392
|
+
return sessionFailure(res, err);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* open `{ sessionId, provider, cwd }`.
|
|
398
|
+
*
|
|
399
|
+
* A session in a deck pane (A) or in the user's own tmux (B) is answered with
|
|
400
|
+
* a ticket for that pane. A Claude background session (D) is reached through
|
|
401
|
+
* a deck pane running `claude attach` — the live one for that session when
|
|
402
|
+
* there is one, else a new one — and the ticket is for that pane. Anything
|
|
403
|
+
* else is `{ ok: false, target }` with HTTP 200: not attachable is a state.
|
|
404
|
+
*/
|
|
405
|
+
async function open(req, res, body, routes) {
|
|
406
|
+
const d = jsTerminalDeps(routes);
|
|
407
|
+
if (!body) return send(res, 400, { ok: false, error: "The request did not name a session." });
|
|
408
|
+
const q = checkTargetQuery(body);
|
|
409
|
+
if (!q.ok) return send(res, 400, { ok: false, error: q.error });
|
|
410
|
+
try {
|
|
411
|
+
const { tmux, target } = await locate(q, d);
|
|
412
|
+
let binding;
|
|
413
|
+
if (target.kind === "A") {
|
|
414
|
+
await learn(target, tmux, d);
|
|
415
|
+
binding = { kind: "A", socket: target.socket, target: target.name, pane: target.pane, ignoreSize: false };
|
|
416
|
+
} else if (target.kind === "B") {
|
|
417
|
+
// The user's own tmux: their terminal owns the pane's size, and the
|
|
418
|
+
// panel joins it at that size rather than resizing it under them.
|
|
419
|
+
binding = { kind: "B", socket: target.socket, target: target.pane, pane: target.pane, ignoreSize: true };
|
|
420
|
+
} else if (target.kind === "D") {
|
|
421
|
+
// Fitted to the panel, which is usually the session's only view. Every
|
|
422
|
+
// view shares one pty, at the size of the `claude attach` that came
|
|
423
|
+
// last, so the size it had before is kept and put back as the wrapper
|
|
424
|
+
// closes: a terminal attached beside the panel gets its own size back
|
|
425
|
+
// (see WRAPPER_GRACE_MS).
|
|
426
|
+
const tty = typeof target.tty === "string" ? target.tty : "";
|
|
427
|
+
const size = await sessionSize(tty, d);
|
|
428
|
+
const wrapper = target.wrapper ?? await attachWrapper(q, target, tmux, d, size);
|
|
429
|
+
keepSize(wrapper.name, tty, size);
|
|
430
|
+
binding = { kind: "D", socket: d.deckSocket, target: wrapper.name, pane: wrapper.pane, ignoreSize: false };
|
|
431
|
+
} else if (target.kind === "gone" && target.deadSessions?.length) {
|
|
432
|
+
// An ended session whose deck pane is still there under remain-on-exit:
|
|
433
|
+
// its last frame is the most useful thing the stage can show, so the
|
|
434
|
+
// panel attaches to that pane and the bridge seeds it and says `ended`
|
|
435
|
+
// at once — the frozen frame with "Reopen here" under it, instead of a
|
|
436
|
+
// sentence over an empty stage. The newest pane is the latest word on
|
|
437
|
+
// the conversation. Read-only, because nothing typed reaches a dead
|
|
438
|
+
// pane; at the pane's own size, because resizing it would only cut the
|
|
439
|
+
// frame it kept.
|
|
440
|
+
const newest = target.deadSessions[target.deadSessions.length - 1];
|
|
441
|
+
binding = { kind: "A", socket: d.deckSocket, target: newest, ignoreSize: true, readOnly: true };
|
|
442
|
+
} else {
|
|
443
|
+
return send(res, 200, { ok: false, target: describeTarget(target) });
|
|
444
|
+
}
|
|
445
|
+
const ticket = mint(d, req, tmux, binding);
|
|
446
|
+
if (binding.kind === "D") holdWrapper({ ...binding, tmux }, d);
|
|
447
|
+
return send(res, 200, { ok: true, ticket, target: describeTarget(target) });
|
|
448
|
+
} catch (err) {
|
|
449
|
+
return sessionFailure(res, err);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* adopt `{ sessionId, provider, cwd }`: reopen a session
|
|
455
|
+
* that ended, or that was started outside the deck and has since stopped, in
|
|
456
|
+
* a deck pane with `--resume` (Claude) or `resume` (Codex).
|
|
457
|
+
*
|
|
458
|
+
* Refused with 409 `still-running` while any process still holds the session
|
|
459
|
+
* — the C case, but also A, B and D, which a panel that raced the session's
|
|
460
|
+
* own start could ask about. The check is terminal-target's, with the blind
|
|
461
|
+
* spot its header names: an idle plain `codex` outside the deck holds nothing
|
|
462
|
+
* this can see, and reads as ended.
|
|
463
|
+
*
|
|
464
|
+
* The dead deck panes the session left behind are closed first (clearDead):
|
|
465
|
+
* the reopened session is the one the panel shows from now on.
|
|
466
|
+
*/
|
|
467
|
+
async function adopt(req, res, body, routes) {
|
|
468
|
+
const d = jsTerminalDeps(routes);
|
|
469
|
+
if (!body) return send(res, 400, { ok: false, error: "The request did not name a session." });
|
|
470
|
+
const q = checkTargetQuery(body);
|
|
471
|
+
if (!q.ok) return send(res, 400, { ok: false, error: q.error });
|
|
472
|
+
if (!q.cwd) return send(res, 400, { ok: false, error: "The project folder has to be a full path." });
|
|
473
|
+
if (adopting.has(q.sessionId)) return send(res, 409, { ok: false, error: "This session is already being reopened." });
|
|
474
|
+
adopting.add(q.sessionId);
|
|
475
|
+
try {
|
|
476
|
+
const { tmux, target } = await locate(q, d);
|
|
477
|
+
if (["A", "B", "C", "D"].includes(target.kind)) return send(res, 409, { ok: false, error: STILL_RUNNING });
|
|
478
|
+
if (target.kind !== "gone" || !target.adoptable) {
|
|
479
|
+
const said = describeTarget(target);
|
|
480
|
+
return send(res, 409, { ok: false, error: said.label, ...(said.install ? { install: said.install } : {}) });
|
|
481
|
+
}
|
|
482
|
+
await clearDead(target, tmux, d);
|
|
483
|
+
const started = await d.launchSession({
|
|
484
|
+
tmux, agent: q.provider, kind: "resume", sessionId: q.sessionId, cwd: q.cwd,
|
|
485
|
+
// At the panel's size and in its colours from its first frame (see
|
|
486
|
+
// the launch below).
|
|
487
|
+
cols: body.cols, rows: body.rows, colours: body.colours ?? null,
|
|
488
|
+
socket: d.deckSocket, env: d.env, platform: d.platform,
|
|
489
|
+
});
|
|
490
|
+
const opened = { kind: "A", socket: d.deckSocket, pane: started.pane, name: started.name };
|
|
491
|
+
const ticket = mint(d, req, tmux, { kind: "A", socket: d.deckSocket, target: started.name, pane: started.pane, ignoreSize: false });
|
|
492
|
+
return send(res, 200, { ok: true, ticket, target: describeTarget(opened) });
|
|
493
|
+
} catch (err) {
|
|
494
|
+
return sessionFailure(res, err);
|
|
495
|
+
} finally {
|
|
496
|
+
adopting.delete(q.sessionId);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* launch `{ agent, cwd }` → `{ ok: true, sessionId, name,
|
|
502
|
+
* ticket }`: a new Claude or Codex in a deck-owned tmux session, and a ticket
|
|
503
|
+
* to attach to it. `sessionId` is the id the new Claude was told to use, or ""
|
|
504
|
+
* for Codex, which chooses its own once it starts writing. An optional `key`,
|
|
505
|
+
* the page's name for this launch, makes asking again safe (launchOnce).
|
|
506
|
+
*/
|
|
507
|
+
async function launch(req, res, body, routes) {
|
|
508
|
+
const d = jsTerminalDeps(routes);
|
|
509
|
+
if (!body) return send(res, 400, { ok: false, error: "The request did not say what to start." });
|
|
510
|
+
if (!AGENTS.includes(body.agent)) {
|
|
511
|
+
return send(res, 400, { ok: false, error: "The deck can start Claude or Codex sessions only." });
|
|
512
|
+
}
|
|
513
|
+
if (body.key !== undefined && !isLaunchKey(body.key)) {
|
|
514
|
+
return send(res, 400, { ok: false, error: "The launch's key is not one the deck can keep." });
|
|
515
|
+
}
|
|
516
|
+
try {
|
|
517
|
+
// The folder before tmux: "that folder does not exist" is the answer a
|
|
518
|
+
// person can act on, whether or not tmux is installed.
|
|
519
|
+
await checkCwd(body.cwd);
|
|
520
|
+
const tmux = await d.findTmux();
|
|
521
|
+
if (!tmux?.ok) {
|
|
522
|
+
const said = describeTarget({ kind: "unsupported", reason: tmux?.reason || "missing", install: tmux?.install });
|
|
523
|
+
return send(res, 409, { ok: false, error: said.label, ...(said.install ? { install: said.install } : {}) });
|
|
524
|
+
}
|
|
525
|
+
const key = body.key ?? "";
|
|
526
|
+
const started = await launchOnce(d, tmux, key, () => d.launchSession({
|
|
527
|
+
tmux, agent: body.agent, cwd: body.cwd, socket: d.deckSocket, env: d.env, platform: d.platform,
|
|
528
|
+
// The panel's size, so the agent draws its first screen at the size it
|
|
529
|
+
// is shown at. Started at the fallback instead, Claude Code drew its
|
|
530
|
+
// banner, was resized the moment the panel attached, and drew it again:
|
|
531
|
+
// every launched session began with the header twice in its scrollback.
|
|
532
|
+
// clampSize holds whatever arrives to a sane terminal.
|
|
533
|
+
cols: body.cols, rows: body.rows,
|
|
534
|
+
// And in its colours, so a program asking its terminal's background at
|
|
535
|
+
// its first frame is told the deck's (terminal-sessions.mjs).
|
|
536
|
+
colours: body.colours ?? null,
|
|
537
|
+
options: body.options ?? null,
|
|
538
|
+
...(key ? { launchKey: key } : {}),
|
|
539
|
+
}));
|
|
540
|
+
const ticket = mint(d, req, tmux, { kind: "A", socket: d.deckSocket, target: started.name, pane: started.pane, ignoreSize: false });
|
|
541
|
+
maybePrune(d, tmux);
|
|
542
|
+
return send(res, 200, { ok: true, sessionId: started.sessionId ?? "", name: started.name, ticket });
|
|
543
|
+
} catch (err) {
|
|
544
|
+
return sessionFailure(res, err);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* What a launch named `key` started, starting it with `start` only if nothing
|
|
550
|
+
* has yet. A launch whose answer never reached the page — the deck restarting
|
|
551
|
+
* under it, a connection dropped — leaves an agent running behind an error,
|
|
552
|
+
* and Try again asks with the same key: started again, a second agent opened
|
|
553
|
+
* in the same folder. The key is on the session's labels, so a restarted deck
|
|
554
|
+
* finds it there; a launch still on its way here is waited for, since tmux
|
|
555
|
+
* may not have labelled its session yet. No key, no lookup: every launch new.
|
|
556
|
+
*
|
|
557
|
+
* ONE AGENT PER KEY, ALSO AT A DOUBLE CLICK. Each ask reads the deck's
|
|
558
|
+
* sessions first and looks for a launch under way after, so a launch that
|
|
559
|
+
* finishes while an ask's listing is out can be in neither: the listing was
|
|
560
|
+
* read before its session was made, and it is no longer under way. Starting
|
|
561
|
+
* one there was a second agent. That ask answers the outcome of the launch
|
|
562
|
+
* that finished meanwhile (the newest, if more than one did), a failure as
|
|
563
|
+
* well, which is what it would have answered had its listing come back a
|
|
564
|
+
* moment sooner. An ask whose listing began after a launch's answer is not
|
|
565
|
+
* handed that launch: a failure is still tried again, and a success is in its
|
|
566
|
+
* listing. The engine's own launch answers the same.
|
|
567
|
+
*/
|
|
568
|
+
async function launchOnce(d, tmux, key, start) {
|
|
569
|
+
if (!key) return start();
|
|
570
|
+
const look = looking.get(key) ?? { asks: 0, finished: 0, last: null };
|
|
571
|
+
looking.set(key, look);
|
|
572
|
+
look.asks += 1;
|
|
573
|
+
const seen = look.finished;
|
|
574
|
+
let list = [];
|
|
575
|
+
try {
|
|
576
|
+
list = await d.listDeckSessions({ tmux, socket: d.deckSocket, env: d.env });
|
|
577
|
+
} catch { /* the launch says what is wrong */ } finally {
|
|
578
|
+
look.asks -= 1;
|
|
579
|
+
if (look.asks === 0 && looking.get(key) === look) looking.delete(key);
|
|
580
|
+
}
|
|
581
|
+
const found = findLaunchedSession(list, key);
|
|
582
|
+
if (found) return { name: found.name, sessionId: found.sessionId, pane: found.pane };
|
|
583
|
+
// After the listing, not before: one started while it was being read is
|
|
584
|
+
// not in it.
|
|
585
|
+
const running = launching.get(key);
|
|
586
|
+
if (running) return running;
|
|
587
|
+
if (look.finished > seen) return look.last;
|
|
588
|
+
const started = start();
|
|
589
|
+
launching.set(key, started);
|
|
590
|
+
// Forgotten before the answer, so an ask after it starts afresh; the asks
|
|
591
|
+
// still reading the sessions keep it, since what they read cannot have it.
|
|
592
|
+
const done = () => {
|
|
593
|
+
if (launching.get(key) === started) launching.delete(key);
|
|
594
|
+
const still = looking.get(key);
|
|
595
|
+
if (still) { still.finished += 1; still.last = started; }
|
|
596
|
+
};
|
|
597
|
+
started.then(done, done);
|
|
598
|
+
return started;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// ---------------------------------------------------------------------------
|
|
602
|
+
|
|
603
|
+
/** Find tmux, then the session. The deck's own sessions are listed on the
|
|
604
|
+
* socket the deps name, so the suite's private server stands in for the
|
|
605
|
+
* product's everywhere at once. */
|
|
606
|
+
async function locate(q, d) {
|
|
607
|
+
const tmux = await d.findTmux();
|
|
608
|
+
const target = await d.resolveTarget(q, {
|
|
609
|
+
platform: d.platform,
|
|
610
|
+
tmux,
|
|
611
|
+
deckSocket: d.deckSocket,
|
|
612
|
+
listDeckSessions: () => d.listDeckSessions({ tmux, socket: d.deckSocket, env: d.env }),
|
|
613
|
+
});
|
|
614
|
+
return { tmux, target };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** A ticket for `binding`, with the tmux that found the pane and the page's
|
|
618
|
+
* own origin added — the socket must be opened by the page that asked. */
|
|
619
|
+
function mint(d, req, tmux, binding) {
|
|
620
|
+
const origin = pageOrigin(req);
|
|
621
|
+
return d.tickets.mint({ ...binding, tmux: tmux?.path, ...(origin ? { origin } : {}) });
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function pageOrigin(req) {
|
|
625
|
+
return typeof req?.headers?.origin === "string" ? req.headers.origin.trim().toLowerCase() : "";
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Write the id a deck pane was just recognised by into its `@ccdeck-session`
|
|
630
|
+
* (terminal-target's `learnedId`): a Codex the deck launched, found by the
|
|
631
|
+
* rollout its process holds open because its label was still empty. Once
|
|
632
|
+
* written, the next lookup of that session is the listing alone instead of a
|
|
633
|
+
* walk over every process on the machine.
|
|
634
|
+
*
|
|
635
|
+
* On the attach, not on GET /api/terminal/target, so the read stays a read.
|
|
636
|
+
* And never the reason an attach fails: the label is a shortcut for the next
|
|
637
|
+
* lookup, and a tmux that cannot set it now is asked again on the next open.
|
|
638
|
+
*/
|
|
639
|
+
async function learn(target, tmux, d) {
|
|
640
|
+
if (!target.learnedId) return;
|
|
641
|
+
try {
|
|
642
|
+
await d.labelDeckSession({ tmux, name: target.name, sessionId: target.learnedId, socket: d.deckSocket, env: d.env });
|
|
643
|
+
} catch { /* see above: a missed label costs one more process walk, no more */ }
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Close the dead deck panes an ended session left behind (terminal-target's
|
|
648
|
+
* `deadSessions`), before it is reopened in a new one.
|
|
649
|
+
*
|
|
650
|
+
* remain-on-exit keeps a pane for its last frame, and every reopen would
|
|
651
|
+
* otherwise add one more to the deck's server for good: once the session runs
|
|
652
|
+
* again, nothing can show the old frame. killDeckSession refuses any name the
|
|
653
|
+
* deck did not give, and these names came from the deck's own listing. A pane
|
|
654
|
+
* that will not close is left where it is — the reopen is what was asked for,
|
|
655
|
+
* and the next one tries again.
|
|
656
|
+
*/
|
|
657
|
+
async function clearDead(target, tmux, d) {
|
|
658
|
+
for (const name of target.deadSessions ?? []) {
|
|
659
|
+
try {
|
|
660
|
+
await d.killDeckSession({ tmux, name, socket: d.deckSocket, env: d.env });
|
|
661
|
+
} catch { /* see above */ }
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* The deck pane that runs `claude attach` for a background session: a new one,
|
|
667
|
+
* or — when its name is taken because one is already there — that one if it is
|
|
668
|
+
* alive, else a fresh one in place of the dead. One wrapper per session, by
|
|
669
|
+
* name (terminal-sessions' deckSessionName), so two panels on one background
|
|
670
|
+
* session share a pane instead of running two attaches. Started at `size`,
|
|
671
|
+
* the session's own (sessionSize), so that starting it moves nothing.
|
|
672
|
+
*/
|
|
673
|
+
async function attachWrapper(q, target, tmux, d, size) {
|
|
674
|
+
const bin = d.claudeBin();
|
|
675
|
+
if (!bin) {
|
|
676
|
+
const err = new Error("Claude Code is not installed on this machine.");
|
|
677
|
+
err.code = "agent-missing";
|
|
678
|
+
throw err;
|
|
679
|
+
}
|
|
680
|
+
// The short id terminal-target found, which is what `claude attach` takes.
|
|
681
|
+
const attachId = ATTACH_ID.test(String(target.attachId ?? "")) ? target.attachId : q.sessionId.slice(0, 8);
|
|
682
|
+
// Unread, tmux's default.
|
|
683
|
+
const launch = () => d.launchSession({
|
|
684
|
+
tmux, agent: "claude", kind: "attach", sessionId: q.sessionId, cwd: wrapperCwd(q, d),
|
|
685
|
+
argv: [bin, "attach", attachId], socket: d.deckSocket, env: d.env, platform: d.platform,
|
|
686
|
+
...(size ? { cols: size.cols, rows: size.rows } : {}),
|
|
687
|
+
});
|
|
688
|
+
try {
|
|
689
|
+
return await launch();
|
|
690
|
+
} catch (err) {
|
|
691
|
+
if (err?.code !== "exists") throw err;
|
|
692
|
+
const list = await d.listDeckSessions({ tmux, socket: d.deckSocket, env: d.env });
|
|
693
|
+
const found = findDeckSession(list, q.sessionId, { kinds: ["attach"] });
|
|
694
|
+
if (!found) throw err;
|
|
695
|
+
if (!found.dead) return { name: found.name, pane: found.pane };
|
|
696
|
+
// A wrapper whose `claude attach` has exited is only a frozen frame of a
|
|
697
|
+
// session that is still running elsewhere; it is replaced, not reused.
|
|
698
|
+
await d.killDeckSession({ tmux, name: found.name, socket: d.deckSocket, env: d.env });
|
|
699
|
+
return await launch();
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** A background session's size as its terminal `tty` reads it, or null when
|
|
704
|
+
* there is no terminal or it cannot be read. */
|
|
705
|
+
async function sessionSize(tty, d) {
|
|
706
|
+
if (!tty) return null;
|
|
707
|
+
try { return (await d.ttySize(tty)) ?? null; } catch { return null; }
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/** Where the attach wrapper starts. `claude attach` does not care, so the
|
|
711
|
+
* session's own folder when it is still there, else the home directory. */
|
|
712
|
+
function wrapperCwd(q, d) {
|
|
713
|
+
return q.cwd && d.isDir(q.cwd) ? q.cwd : d.home();
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function isDir(path) {
|
|
717
|
+
try { return statSync(path).isDirectory(); } catch { return false; }
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/** A TerminalSessionError answered as its sentence; anything else is not a
|
|
721
|
+
* state of the machine and goes on to `guard`'s 500. tmux's own words go to
|
|
722
|
+
* the deck's log, never to the page. */
|
|
723
|
+
/** What tmux's stderr means for the person, for the failures with a fix they
|
|
724
|
+
* can make; null for the rest. Never a path. */
|
|
725
|
+
export function tmuxFailureHint(stderr) {
|
|
726
|
+
const t = String(stderr ?? "");
|
|
727
|
+
if (/File name too long|ENAMETOOLONG/i.test(t)) return "The path to tmux's socket is too long here. Point TMUX_TMPDIR at a shorter folder and restart the deck.";
|
|
728
|
+
if (/protocol version mismatch/i.test(t)) return "Another version of tmux is already running the deck's sessions. Restarting the deck after they end fixes it.";
|
|
729
|
+
if (/No space left on device/i.test(t)) return "The disk is full, so tmux could not write its socket.";
|
|
730
|
+
if (/Permission denied|EACCES/i.test(t)) return "tmux may not write its socket folder. Check the permissions of TMUX_TMPDIR, or /tmp.";
|
|
731
|
+
return null;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function sessionFailure(res, err) {
|
|
735
|
+
const status = typeof err?.code === "string" ? SESSION_STATUS[err.code] : undefined;
|
|
736
|
+
if (!status) throw err;
|
|
737
|
+
if (err.detail) console.error(`${PRODUCT}: terminal: ${err.message} (${err.detail})`);
|
|
738
|
+
// tmux's own words stay in the deck's log — they carry paths, and nothing a
|
|
739
|
+
// route here answers does — but the reasons a person can act on are named:
|
|
740
|
+
// "tmux could not start the session" alone left "File name too long" (a
|
|
741
|
+
// socket folder past the limit) in a log the reader never opens.
|
|
742
|
+
const hint = typeof err.detail === "string" ? tmuxFailureHint(err.detail) : null;
|
|
743
|
+
return send(res, status, { ok: false, error: err.message, code: err.code, ...(hint ? { hint } : {}) });
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/**
|
|
747
|
+
* The JS backend as a test hands it to startServer, `terminal.jsBackend`:
|
|
748
|
+
* terminal-routes.mjs asks each route of it with `(req, res, question,
|
|
749
|
+
* routes)` in place of the engine, and the upgrade takes its bridge for the
|
|
750
|
+
* tickets it minted (`openBridge(routes)`).
|
|
751
|
+
*/
|
|
752
|
+
export const jsTerminalBackend = Object.freeze({ status, target, claim, open, adopt, launch, openBridge });
|