cli-setu 0.3.6 → 0.3.8

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cli-setu",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
4
4
  "description": "Bridge your terminal to your phone — run and approve Claude Code, Codex CLI and other AI coding agents from anywhere.",
5
5
  "type": "commonjs",
6
6
  "bin": {
@@ -161,7 +161,11 @@ const ESC_FOOTER_RE = /esc to cancel/i;
161
161
  // match PROCEED_RE is never mistaken for this one's.
162
162
  function distinguishingTextFor(event) {
163
163
  const { tool_name, tool_input } = event || {};
164
- if ((tool_name === 'Write' || tool_name === 'Edit' || tool_name === 'Read') && tool_input?.file_path) return tool_input.file_path;
164
+ // 2026-11-16 (real bug, found with the owner's own session log): the FULL path (C:\demo\python.txt) was
165
+ // used here, but Claude Code's prompt line only shows the file NAME ("Do you want to create python.txt?"),
166
+ // so isMenuStillOnScreen never found the path, the first 500 ms poll decided the menu was gone and the
167
+ // phone showed "Resolved at the laptop" for a prompt nobody had answered. The file name is what is on screen.
168
+ if ((tool_name === 'Write' || tool_name === 'Edit' || tool_name === 'Read') && tool_input?.file_path) return String(tool_input.file_path).split(/[\\/]/).pop();
165
169
  if ((tool_name === 'Bash' || tool_name === 'PowerShell') && tool_input?.command) return tool_input.command;
166
170
  return null;
167
171
  }
@@ -370,7 +374,8 @@ module.exports = {
370
374
  isMenuStillOnScreen: (scrollbackWindow, distinguishingText) => {
371
375
  const clean = stripAnsi(scrollbackWindow);
372
376
  if (!PROCEED_RE.test(clean)) return false;
373
- if (distinguishingText && !clean.includes(distinguishingText)) return false;
377
+ // Whitespace-insensitive: a long command wraps across screen lines, which would otherwise hide it.
378
+ if (distinguishingText && !clean.replace(/\s+/g, '').includes(String(distinguishingText).replace(/\s+/g, ''))) return false;
374
379
  return true;
375
380
  },
376
381
  distinguishingTextFor,
package/src/pair.js CHANGED
@@ -92,8 +92,12 @@ async function pair(authServer, authServerPublic) {
92
92
 
93
93
  console.log('');
94
94
  qrcode.generate(scanUrl, { small: true });
95
- console.log('[cli-setu] Scan this with your phone camera.');
96
- console.log(`[cli-setu] (Testing on one PC? Paste this URL into a browser tab instead: ${scanUrl})`);
95
+ // 2026-11-16: this used to say "Scan this with your phone camera". A QR scanned with the phone's CAMERA app opens
96
+ // a web page, which registers an encryption key that lives in the browser: the app never gets the matching key,
97
+ // shows "The encryption key for this laptop does not match" and a blank terminal (found on a Linux test). The
98
+ // reliable ways are the app's own Pair button (scan or typed code).
99
+ console.log('[cli-setu] Scan this QR code with the Pair button INSIDE the CLI Setu app (not the phone\'s camera app).');
100
+ console.log(`[cli-setu] (Testing on one PC without a phone? Paste this URL into a browser tab instead: ${scanUrl})`);
97
101
 
98
102
  const codeRes = await fetch(`${authServer}/device/pair/start`, {
99
103
  method: 'POST',
@@ -101,7 +105,7 @@ async function pair(authServer, authServerPublic) {
101
105
  body: JSON.stringify({ deviceName: config.deviceName, devicePublicKey: config.devicePublicKey }),
102
106
  });
103
107
  const { code: typedCode, pairId: typedPairId } = await codeRes.json();
104
- console.log(`[cli-setu] Or type this code in the app's Devices tab: ${typedCode}`);
108
+ console.log(`[cli-setu] Or, most reliable: in the CLI Setu app tap Pair, choose "Enter code" and type this code: ${typedCode}`);
105
109
  console.log('[cli-setu] Waiting for scan or code entry...');
106
110
 
107
111
  let confirmed = false;
@@ -12,6 +12,15 @@
12
12
 
13
13
  const crypto = require('node:crypto');
14
14
 
15
+ // The readable prefix of a session ID. It is the device name from ~/.cli-setu/config.json (what the
16
+ // Devices tab shows, and what the owner can rename) when there is one, else the machine name, so a
17
+ // renamed device no longer leaks the real computer name through the session ID shown on the phone.
18
+ // Only letters, digits and dashes are kept. Added 2026-11-16 for Play Console screenshots.
19
+ function sessionPrefix(deviceName, hostname) {
20
+ const clean = String(deviceName || '').replace(/[^a-zA-Z0-9-]+/g, '-').replace(/^-+|-+$/g, '');
21
+ return clean || hostname;
22
+ }
23
+
15
24
  function newSessionId({ hostname, workingDir }) {
16
25
  const dirHash = crypto.createHash('sha1').update(workingDir).digest('hex').slice(0, 8);
17
26
  return `${hostname}-${dirHash}-${crypto.randomBytes(8).toString('hex')}`;
@@ -42,4 +51,4 @@ function isSessionEndedResponse(res) {
42
51
  return !!res && res.status === 410;
43
52
  }
44
53
 
45
- module.exports = { newSessionId, endSessionOnBackend, isSessionEndedResponse };
54
+ module.exports = { newSessionId, sessionPrefix, endSessionOnBackend, isSessionEndedResponse };
package/src/supervisor.js CHANGED
@@ -47,7 +47,8 @@ const { createDiagnostics } = require('./diagnostics');
47
47
  const { attachStdinForwarder } = require('./stdinForwarder');
48
48
  const { adoptPhoneKey } = require('./sharedKey');
49
49
  const { approvalFingerprint, createApprovalDeduper, relayWithRetry } = require('./approvalRelay');
50
- const { newSessionId, endSessionOnBackend, isSessionEndedResponse } = require('./sessionLifecycle');
50
+ const { newSessionId, sessionPrefix, endSessionOnBackend, isSessionEndedResponse } = require('./sessionLifecycle');
51
+ const { createUnpairedDetector } = require('./unpairedDetector');
51
52
 
52
53
  // Real bug found by testing: this script's own console.log/console.error
53
54
  // calls write to the SAME process.stdout the PTY's raw output is echoed
@@ -148,7 +149,8 @@ const WORKING_DIR = process.cwd();
148
149
  // `cli-setu` in the same folder twice at once (e.g. two terminal tabs) never
149
150
  // silently shares one session.
150
151
  // PROD-003: minted fresh every run and never reused (see sessionLifecycle.js).
151
- const SESSION_ID = newSessionId({ hostname: os.hostname(), workingDir: WORKING_DIR });
152
+ // The prefix is the device name from config.json (renamable, shown on the phone) when set, else the machine name.
153
+ const SESSION_ID = newSessionId({ hostname: sessionPrefix(config.deviceName, os.hostname()), workingDir: WORKING_DIR });
152
154
 
153
155
  // SETU-005: the real identity a duplicate-session check needs - resolves
154
156
  // symlinks (fs.realpathSync) so two different-looking paths to the SAME
@@ -372,7 +374,36 @@ async function pollFocus() {
372
374
  }
373
375
  }
374
376
 
377
+ // 2026-11-16 (real bug, found on a Linux/WSL test): a session that was already running when its device was unpaired
378
+ // (or paired again) kept sending output, got HTTP 401 for every piece and only logged it: the phone showed a blank
379
+ // terminal and the laptop never said why. Three 401s in a row from the output relay now stop the session with a
380
+ // clear message, the same way /device/connect already does for a 401. See unpairedDetector.js.
381
+ function stopBecauseUnpaired() {
382
+ diag.say('[supervisor] This device is no longer paired (it was unpaired, or paired again, from the app or another terminal), so your phone cannot see this session.', { error: true, showAtExit: true });
383
+ diag.say('[supervisor] This session is stopping. Pair again with `cli-setu pair`, then start a new session with `cli-setu session`.', { error: true, showAtExit: true });
384
+ log('[supervisor] The relay rejected this device token (HTTP 401) several times in a row: the device is no longer paired. Stopping this session.');
385
+ process.exitCode = 1;
386
+ if (ptyProcess) { ptyProcess.kill(); } else { process.exit(1); return; }
387
+ setTimeout(() => process.exit(1), 1500).unref();
388
+ }
389
+ const unpairedDetector = createUnpairedDetector({ onUnpaired: stopBecauseUnpaired });
390
+
391
+ // 2026-11-16 (real bug, found on a Linux/WSL test): when the very first /device/connect call could not even reach
392
+ // the server (connection timed out, DNS failure, refused), fetch() THROWS instead of returning a failed response.
393
+ // Only a failed RESPONSE was handled (retry with backoff), so a thrown network error became an unhandled promise
394
+ // rejection and crashed the whole session with a raw stack trace ("TypeError: fetch failed"). Every call now goes
395
+ // through this wrapper: any failure is logged and retried with the same backoff as a failed response.
375
396
  async function connectToAzure() {
397
+ try {
398
+ await connectToAzureOnce();
399
+ } catch (err) {
400
+ const why = (err && err.cause && (err.cause.code || err.cause.message)) || (err && err.message) || String(err);
401
+ log(`[supervisor] /device/connect could not complete (${why}); will retry.`);
402
+ reconnectManager.scheduleRetry();
403
+ }
404
+ }
405
+
406
+ async function connectToAzureOnce() {
376
407
  // cliType lets Devices/Profile show which CLI this paired laptop is
377
408
  // actually running (see auth-server.js's /device/connect handler and
378
409
  // db.js's devices.cli_type column) - sent on every connect (not just
@@ -742,6 +773,7 @@ async function sendSnapshot() {
742
773
  });
743
774
  if (!res.ok) {
744
775
  log(`[supervisor] Snapshot part ${i + 1}/${parts.length} was refused by the backend (HTTP ${res.status}); stopping.`);
776
+ unpairedDetector.note(res.status);
745
777
  return;
746
778
  }
747
779
  }
@@ -864,6 +896,7 @@ function flushOutputBuffer() {
864
896
  body: JSON.stringify({ sessionId: SESSION_ID, seq: ++outputSeq, data, encrypted: true }),
865
897
  });
866
898
  if (!res.ok) log(`[supervisor] Output piece seq=${outputSeq} was refused by the backend (HTTP ${res.status}, ${data.length} chars).`);
899
+ unpairedDetector.note(res.status);
867
900
  } catch (err) {
868
901
  // A dropped terminal.output batch isn't fatal the way a dropped
869
902
  // confirmation would be - the next batch (or a fresh session.attach
@@ -0,0 +1,37 @@
1
+ // Notices that this device is no longer paired (found 2026-11-16 on a Linux test).
2
+ // After `cli-setu unpair`, or after the same device is paired again, the server rejects the old device token with
3
+ // HTTP 401. /device/connect already stopped the session on a 401, but a session that was ALREADY running kept sending
4
+ // output, got HTTP 401 for every piece, logged it and carried on: the phone showed a blank terminal and the laptop
5
+ // never said why. The output sender now reports every response status here; a few 401s in a row mean "no longer
6
+ // paired", and the session stops with a clear message.
7
+ //
8
+ // "In a row" matters: one odd 401 must not end a session. Any successful response resets the count. Pure and tested
9
+ // (test/unpairedDetector.test.js).
10
+ 'use strict';
11
+
12
+ const DEFAULT_THRESHOLD = 3;
13
+
14
+ function createUnpairedDetector({ threshold = DEFAULT_THRESHOLD, onUnpaired }) {
15
+ let consecutive = 0;
16
+ let fired = false;
17
+ return {
18
+ // Call with the HTTP status of every authenticated relay response.
19
+ note(status) {
20
+ if (fired) return;
21
+ if (status === 401) {
22
+ consecutive += 1;
23
+ if (consecutive >= threshold) {
24
+ fired = true;
25
+ if (typeof onUnpaired === 'function') onUnpaired();
26
+ }
27
+ } else if (status >= 200 && status < 300) {
28
+ consecutive = 0;
29
+ }
30
+ // Other statuses (403, 410, 429, 5xx) neither count nor reset: they mean something else.
31
+ },
32
+ get consecutive() { return consecutive; },
33
+ get fired() { return fired; },
34
+ };
35
+ }
36
+
37
+ module.exports = { createUnpairedDetector, DEFAULT_THRESHOLD };