cli-setu 0.3.4 → 0.3.5
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/package.json +1 -1
- package/src/sessionLifecycle.js +45 -0
- package/src/supervisor.js +35 -4
package/package.json
CHANGED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Session identity and shutdown (PROD-003).
|
|
2
|
+
//
|
|
3
|
+
// - A session ID is minted fresh on every run and is never reused. It keeps a
|
|
4
|
+
// readable prefix (machine name + short folder hash, so a person can tell which
|
|
5
|
+
// project it is) and ends in 64 bits of randomness, so two runs can never share
|
|
6
|
+
// one. The backend also refuses any ID it has already ended.
|
|
7
|
+
// - When the session ends for good (shell exited, Ctrl+C, window closed) the CLI
|
|
8
|
+
// tells the backend straight away, so the phone drops it at once instead of
|
|
9
|
+
// showing it until the reconnect grace runs out. This is best effort and bounded:
|
|
10
|
+
// it must never delay or block the laptop's own exit.
|
|
11
|
+
'use strict';
|
|
12
|
+
|
|
13
|
+
const crypto = require('node:crypto');
|
|
14
|
+
|
|
15
|
+
function newSessionId({ hostname, workingDir }) {
|
|
16
|
+
const dirHash = crypto.createHash('sha1').update(workingDir).digest('hex').slice(0, 8);
|
|
17
|
+
return `${hostname}-${dirHash}-${crypto.randomBytes(8).toString('hex')}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Resolves { ok, status? , reason? }; never rejects and never takes longer than timeoutMs.
|
|
21
|
+
async function endSessionOnBackend({ fetchImpl, authServer, deviceToken, sessionId, reason = 'exit', timeoutMs = 2000 }) {
|
|
22
|
+
if (!deviceToken || !sessionId) return { ok: false, reason: 'not_paired' };
|
|
23
|
+
const ctl = typeof AbortController === 'function' ? new AbortController() : null;
|
|
24
|
+
const timer = ctl ? setTimeout(() => ctl.abort(), timeoutMs) : null;
|
|
25
|
+
try {
|
|
26
|
+
const res = await fetchImpl(`${authServer}/device/session-end`, {
|
|
27
|
+
method: 'POST',
|
|
28
|
+
headers: { Authorization: `Bearer ${deviceToken}`, 'Content-Type': 'application/json' },
|
|
29
|
+
body: JSON.stringify({ sessionId, reason }),
|
|
30
|
+
signal: ctl ? ctl.signal : undefined,
|
|
31
|
+
});
|
|
32
|
+
return { ok: !!res.ok, status: res.status };
|
|
33
|
+
} catch (err) {
|
|
34
|
+
return { ok: false, reason: err && err.name === 'AbortError' ? 'timeout' : 'network' };
|
|
35
|
+
} finally {
|
|
36
|
+
if (timer) clearTimeout(timer);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The backend answers 410 to a heartbeat or reconnect for a session it has already ended.
|
|
41
|
+
function isSessionEndedResponse(res) {
|
|
42
|
+
return !!res && res.status === 410;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = { newSessionId, endSessionOnBackend, isSessionEndedResponse };
|
package/src/supervisor.js
CHANGED
|
@@ -45,6 +45,7 @@ const { createDiagnostics } = require('./diagnostics');
|
|
|
45
45
|
const { attachStdinForwarder } = require('./stdinForwarder');
|
|
46
46
|
const { adoptPhoneKey } = require('./sharedKey');
|
|
47
47
|
const { approvalFingerprint, createApprovalDeduper, relayWithRetry } = require('./approvalRelay');
|
|
48
|
+
const { newSessionId, endSessionOnBackend, isSessionEndedResponse } = require('./sessionLifecycle');
|
|
48
49
|
|
|
49
50
|
// Real bug found by testing: this script's own console.log/console.error
|
|
50
51
|
// calls write to the SAME process.stdout the PTY's raw output is echoed
|
|
@@ -144,8 +145,8 @@ const WORKING_DIR = process.cwd();
|
|
|
144
145
|
// "app" on the same machine) plus a short random suffix so re-running
|
|
145
146
|
// `cli-setu` in the same folder twice at once (e.g. two terminal tabs) never
|
|
146
147
|
// silently shares one session.
|
|
147
|
-
|
|
148
|
-
const SESSION_ID =
|
|
148
|
+
// PROD-003: minted fresh every run and never reused (see sessionLifecycle.js).
|
|
149
|
+
const SESSION_ID = newSessionId({ hostname: os.hostname(), workingDir: WORKING_DIR });
|
|
149
150
|
|
|
150
151
|
// SETU-005: the real identity a duplicate-session check needs - resolves
|
|
151
152
|
// symlinks (fs.realpathSync) so two different-looking paths to the SAME
|
|
@@ -323,7 +324,19 @@ let outputSeq = 0;
|
|
|
323
324
|
// reused here for consistency (one unified "how patient are we before
|
|
324
325
|
// saying something" policy, not two different numbers to reason about).
|
|
325
326
|
let pollFocusFailureCount = 0;
|
|
327
|
+
// PROD-003: set when the backend says this session already ended (it was offline
|
|
328
|
+
// longer than the reconnect grace, or was closed). The ID is never revived: the
|
|
329
|
+
// laptop terminal keeps working, but nothing more is sent under it.
|
|
330
|
+
let sessionEndedByServer = false;
|
|
331
|
+
function handleSessionEndedByServer() {
|
|
332
|
+
if (sessionEndedByServer) return;
|
|
333
|
+
sessionEndedByServer = true;
|
|
334
|
+
if (focusTimer) clearInterval(focusTimer);
|
|
335
|
+
log('[supervisor] The backend reports this session has ended (HTTP 410); no further updates will be sent for it.');
|
|
336
|
+
diag.say('[supervisor] This session has ended on the server (it was offline too long, or was closed), so your phone can no longer see it. Your terminal here keeps working. Run `cli-setu session` again to start a new session.', { showAtExit: true });
|
|
337
|
+
}
|
|
326
338
|
async function pollFocus() {
|
|
339
|
+
if (sessionEndedByServer) return;
|
|
327
340
|
try {
|
|
328
341
|
// detectedCliType (see detectRunningAdapter's own comment, further
|
|
329
342
|
// down this file) piggybacks on this same already-running poll so
|
|
@@ -335,9 +348,10 @@ async function pollFocus() {
|
|
|
335
348
|
// incorrectly downgrade a session that started with `--cli claude`
|
|
336
349
|
// before this poll even has real data to report.
|
|
337
350
|
const detectedParam = lastDetectedCliType ? `&detectedCliType=${encodeURIComponent(lastDetectedCliType)}` : '';
|
|
338
|
-
await fetch(
|
|
351
|
+
const focusRes = await fetch(
|
|
339
352
|
`${AUTH_SERVER}/terminal/is-focused?sessionId=${encodeURIComponent(SESSION_ID)}${deviceId ? `&deviceId=${encodeURIComponent(deviceId)}` : ''}${detectedParam}`
|
|
340
353
|
);
|
|
354
|
+
if (isSessionEndedResponse(focusRes)) { handleSessionEndedByServer(); return; }
|
|
341
355
|
if (pollFocusFailureCount >= WARN_AFTER_ATTEMPTS) {
|
|
342
356
|
diag.say('[supervisor] Heartbeat to the backend recovered.');
|
|
343
357
|
log('[supervisor] pollFocus heartbeat recovered after failures');
|
|
@@ -437,6 +451,13 @@ async function connectToAzure() {
|
|
|
437
451
|
}
|
|
438
452
|
setTimeout(() => process.exit(1), 1500).unref();
|
|
439
453
|
};
|
|
454
|
+
// PROD-003: 410 means this session ID already ended (e.g. the laptop was
|
|
455
|
+
// asleep longer than the reconnect grace). Retrying would never help and the ID
|
|
456
|
+
// is never revived, so say so clearly instead of looping.
|
|
457
|
+
if (isSessionEndedResponse(res)) {
|
|
458
|
+
handleSessionEndedByServer();
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
440
461
|
if (res.status === 403) {
|
|
441
462
|
diag.say(`[supervisor] Connection rejected: ${err.error || 'the server declined this session.'}`, { error: true, showAtExit: true });
|
|
442
463
|
log(`[supervisor] /device/connect rejected (403): ${err.error || 'no reason given'}`);
|
|
@@ -824,6 +845,7 @@ function flushOutputBuffer() {
|
|
|
824
845
|
// immediately and broadcasts to Azure in the background, so this
|
|
825
846
|
// fetch() itself should resolve quickly regardless of Azure's own cost.
|
|
826
847
|
sendInFlight = sendInFlight.then(async () => {
|
|
848
|
+
if (sessionEndedByServer) return; // PROD-003: an ended session is never revived
|
|
827
849
|
// A batch can be far bigger than BATCH_MAX_BYTES (one large chunk from
|
|
828
850
|
// the terminal), and the realtime provider refuses any single message
|
|
829
851
|
// over its limit (Ably Free/Standard: 64 KiB). Each piece gets its own
|
|
@@ -2138,7 +2160,16 @@ async function main() {
|
|
|
2138
2160
|
// of the PTY's own exit code - a plan-limit rejection should exit
|
|
2139
2161
|
// non-zero even though PowerShell itself was killed cleanly
|
|
2140
2162
|
// (exitCode 0 from its own perspective).
|
|
2141
|
-
process.
|
|
2163
|
+
const finalCode = process.exitCode ?? exitCode ?? 0;
|
|
2164
|
+
// PROD-003: tell the backend this session is over (shell exited, Ctrl+C or the
|
|
2165
|
+
// window was closed) so the phone drops it now instead of waiting out the
|
|
2166
|
+
// reconnect grace. Bounded to 2s and best effort: it can never keep the
|
|
2167
|
+
// laptop from exiting, and a crash or power loss is still covered by the
|
|
2168
|
+
// backend's own grace expiry.
|
|
2169
|
+
endSessionOnBackend({ fetchImpl: fetch, authServer: AUTH_SERVER, deviceToken, sessionId: SESSION_ID, reason: 'exit' })
|
|
2170
|
+
.then((r) => log(`[supervisor] session-end sent: ${JSON.stringify(r)}`))
|
|
2171
|
+
.catch(() => {})
|
|
2172
|
+
.finally(() => process.exit(finalCode));
|
|
2142
2173
|
});
|
|
2143
2174
|
|
|
2144
2175
|
// Real feedback: an automatic timer used to run here (every 5 minutes,
|