cli-setu 0.3.3 → 0.3.4

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.3",
3
+ "version": "0.3.4",
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": {
@@ -0,0 +1,73 @@
1
+ // Reliable, idempotent delivery of approval requests to the backend (P0:
2
+ // "approvals do not arrive" and "approvals appear twice").
3
+ //
4
+ // Missing approvals, confirmed cause: relayApproval() POSTed once. A network
5
+ // error or a 5xx only wrote a log line, while the prompt stayed pending on the
6
+ // laptop, so the phone never learned about it. Delivery is now retried with
7
+ // backoff. Retrying is safe because the same promptId is sent every time and
8
+ // the backend inserts it with ON CONFLICT DO NOTHING; the phone also ignores a
9
+ // promptId it has already shown.
10
+ //
11
+ // Duplicate approvals, confirmed cause: every relay call minted a brand-new
12
+ // random promptId, so one logical permission request that reached the
13
+ // supervisor twice (for example the same hook registered in two settings files,
14
+ // or a repeated queue line) became two different cards. A fingerprint of the
15
+ // request (session, tool, tool_use_id, input) now identifies one logical
16
+ // approval; while an approval with that fingerprint is still pending, a repeat
17
+ // is dropped. Once it is resolved, the same command may legitimately ask again.
18
+ const crypto = require('crypto');
19
+
20
+ function approvalFingerprint(event) {
21
+ const basis = [event.session_id || null, event.tool_name || null, event.tool_use_id || null, event.tool_input === undefined ? null : event.tool_input];
22
+ return crypto.createHash('sha256').update(JSON.stringify(basis)).digest('hex').slice(0, 24);
23
+ }
24
+
25
+ // isPending(promptId) tells whether that prompt is still waiting for an answer.
26
+ function createApprovalDeduper({ isPending }) {
27
+ const byFingerprint = new Map(); // fingerprint -> promptId
28
+ return {
29
+ // Returns true when this is a repeat of a still-pending approval.
30
+ isDuplicate(fingerprint) {
31
+ const existing = byFingerprint.get(fingerprint);
32
+ if (existing && isPending(existing)) return true;
33
+ if (existing) byFingerprint.delete(fingerprint);
34
+ return false;
35
+ },
36
+ remember(fingerprint, promptId) { byFingerprint.set(fingerprint, promptId); },
37
+ size: () => byFingerprint.size,
38
+ };
39
+ }
40
+
41
+ // Statuses that will never succeed by retrying (the request itself is refused).
42
+ function isPermanentFailure(status) {
43
+ return status >= 400 && status < 500 && status !== 408 && status !== 429;
44
+ }
45
+
46
+ const DEFAULT_DELAYS_MS = [500, 1500, 4000, 10000];
47
+
48
+ // send() performs one attempt and resolves { ok, status } or rejects on a network error.
49
+ // isStillPending() lets us stop as soon as the prompt was answered or dismissed elsewhere.
50
+ async function relayWithRetry({ send, isStillPending, log = () => {}, delays = DEFAULT_DELAYS_MS, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
51
+ let attempts = 0;
52
+ for (let i = 0; i <= delays.length; i++) {
53
+ if (i > 0) {
54
+ await sleep(delays[i - 1]);
55
+ if (!isStillPending()) return { delivered: false, attempts, reason: 'no-longer-pending' };
56
+ }
57
+ attempts += 1;
58
+ try {
59
+ const res = await send();
60
+ if (res.ok) return { delivered: true, attempts, reason: null };
61
+ if (isPermanentFailure(res.status)) {
62
+ log(`approval relay refused (HTTP ${res.status}); not retrying`);
63
+ return { delivered: false, attempts, reason: `refused-${res.status}` };
64
+ }
65
+ log(`approval relay attempt ${attempts} failed (HTTP ${res.status})`);
66
+ } catch (err) {
67
+ log(`approval relay attempt ${attempts} failed: ${err.message}`);
68
+ }
69
+ }
70
+ return { delivered: false, attempts, reason: 'gave-up' };
71
+ }
72
+
73
+ module.exports = { approvalFingerprint, createApprovalDeduper, relayWithRetry, isPermanentFailure, DEFAULT_DELAYS_MS };
@@ -0,0 +1,35 @@
1
+ // Supervisor diagnostics routing (P0: "supervisor messages corrupt the prompt").
2
+ //
3
+ // While a PTY owns the terminal, nothing but the PTY's own bytes may be written
4
+ // to stdout/stderr: an interleaved line lands in the middle of the shell prompt
5
+ // or a full-screen TUI and breaks its cursor math (overwritten text, blank
6
+ // lines, a duplicated prompt). So once the terminal is owned:
7
+ // - every diagnostic goes to the log file only;
8
+ // - messages the user still needs to see (a rejected connection, an unpaired
9
+ // device) are kept and printed AFTER the PTY has exited, when the terminal
10
+ // is the user's again.
11
+ // Before the PTY exists, or after it exited, messages print normally.
12
+ function createDiagnostics({ log, isTerminalOwned, out = console }) {
13
+ const deferred = [];
14
+
15
+ function say(message, { error = false, showAtExit = false } = {}) {
16
+ if (isTerminalOwned()) {
17
+ log(`[notice] ${message}`);
18
+ if (showAtExit) deferred.push({ message, error });
19
+ return;
20
+ }
21
+ (error ? out.error : out.log)(message);
22
+ }
23
+
24
+ // Call once the PTY has exited and the terminal is free again.
25
+ function flushAtExit() {
26
+ while (deferred.length) {
27
+ const { message, error } = deferred.shift();
28
+ (error ? out.error : out.log)(message);
29
+ }
30
+ }
31
+
32
+ return { say, flushAtExit, pending: () => deferred.length };
33
+ }
34
+
35
+ module.exports = { createDiagnostics };
package/src/gitDiff.js ADDED
@@ -0,0 +1,200 @@
1
+ // Collects a session's git changes for the phone's Diff pane (SETU-020).
2
+ //
3
+ // Fixes over the old inline version in supervisor.js:
4
+ // - STAGED changes were never listed (`git diff --name-only` only shows
5
+ // unstaged edits), so a staged file simply vanished from the pane.
6
+ // - Renamed, deleted, binary and conflicted files were not distinguished.
7
+ // - Paths with spaces or non-ASCII characters were mis-parsed; `-z` output
8
+ // is used instead of quoted text.
9
+ // - The whole reply was one message with no total size limit, so many changed
10
+ // files could exceed the realtime provider's per-message limit (Ably
11
+ // Free/Standard: 64 KiB) and the diff would never arrive. A byte budget is
12
+ // applied and anything that does not fit is marked, never dropped silently.
13
+ //
14
+ // Backward compatible: every file keeps the legacy `status` ('modified' or
15
+ // 'untracked') and `diff` fields older apps read; the richer fields are extra.
16
+ 'use strict';
17
+
18
+ const { execFile } = require('node:child_process');
19
+ const { promisify } = require('node:util');
20
+
21
+ const execFileAsync = promisify(execFile);
22
+
23
+ const GIT_TIMEOUT_MS = 15_000;
24
+ const MAX_FILES = 200;
25
+ const MAX_DIFF_CHARS_PER_FILE = 20_000;
26
+ const TRUNCATION_NOTE = '\n\n... (diff truncated - too large to send in full)';
27
+
28
+ // Parses `git status --porcelain=v1 -z`. Each entry is `XY path`, and a
29
+ // rename or copy is followed by its ORIGINAL path as a separate field.
30
+ function parseStatusZ(out) {
31
+ const parts = out.split('\0');
32
+ const entries = [];
33
+ for (let i = 0; i < parts.length; i++) {
34
+ const raw = parts[i];
35
+ if (!raw) continue;
36
+ const x = raw[0];
37
+ const y = raw[1];
38
+ const entry = { x, y, path: raw.slice(3), origPath: null };
39
+ if (x === 'R' || x === 'C' || y === 'R' || y === 'C') entry.origPath = parts[++i] || null;
40
+ entries.push(entry);
41
+ }
42
+ return entries;
43
+ }
44
+
45
+ function categoryOf(x, y) {
46
+ if (x === 'U' || y === 'U' || (x === 'A' && y === 'A') || (x === 'D' && y === 'D')) return 'conflict';
47
+ if (x === '?' && y === '?') return 'untracked';
48
+ if (x === 'R' || y === 'R') return 'renamed';
49
+ if (x === 'D' || y === 'D') return 'deleted';
50
+ if (x === 'A' || y === 'A' || x === 'C' || y === 'C') return 'added';
51
+ return 'modified';
52
+ }
53
+
54
+ // Counts only inside hunks, so a removed line whose text starts with "--"
55
+ // (which prints as "---") is not mistaken for a file header.
56
+ function countChanges(diff) {
57
+ let additions = 0;
58
+ let deletions = 0;
59
+ let inHunk = false;
60
+ for (const line of diff.split('\n')) {
61
+ if (line.startsWith('diff --git') || line.startsWith('diff --cc')) inHunk = false;
62
+ else if (line.startsWith('@@')) inHunk = true;
63
+ else if (inHunk && line.startsWith('+')) additions++;
64
+ else if (inHunk && line.startsWith('-')) deletions++;
65
+ }
66
+ return { additions, deletions };
67
+ }
68
+
69
+ function isBinaryDiff(diff) {
70
+ return /^Binary files .* differ$/m.test(diff) || diff.includes('GIT binary patch');
71
+ }
72
+
73
+ function sizeOf(value) {
74
+ return Buffer.byteLength(JSON.stringify(value));
75
+ }
76
+
77
+ // Largest prefix of `text` whose JSON-encoded size fits `maxBytes`.
78
+ function fitPrefix(text, maxBytes) {
79
+ if (sizeOf(text) <= maxBytes) return text;
80
+ let lo = 0;
81
+ let hi = text.length;
82
+ while (lo < hi) {
83
+ const mid = Math.ceil((lo + hi) / 2);
84
+ if (sizeOf(text.slice(0, mid)) <= maxBytes) lo = mid;
85
+ else hi = mid - 1;
86
+ }
87
+ return text.slice(0, lo);
88
+ }
89
+
90
+ async function runGit(cwd, args, { allowFailureOutput = false } = {}) {
91
+ try {
92
+ const { stdout } = await execFileAsync('git', args, { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 10 * 1024 * 1024 });
93
+ return stdout;
94
+ } catch (err) {
95
+ // `git diff --no-index` exits non-zero whenever the files differ, but its
96
+ // stdout still holds the real diff.
97
+ if (allowFailureOutput && err.stdout) return err.stdout;
98
+ throw err;
99
+ }
100
+ }
101
+
102
+ async function diffFor(cwd, entry, hasHead) {
103
+ const category = categoryOf(entry.x, entry.y);
104
+ if (category === 'untracked') {
105
+ return runGit(cwd, ['diff', '--no-index', '--', '/dev/null', entry.path], { allowFailureOutput: true });
106
+ }
107
+ if (category === 'conflict') return runGit(cwd, ['diff', '--', entry.path]);
108
+ const paths = entry.origPath ? [entry.origPath, entry.path] : [entry.path];
109
+ // Against HEAD, so a file with both staged and unstaged edits shows ALL of
110
+ // its changes since the last commit. A repo with no commit yet has no HEAD.
111
+ return hasHead ? runGit(cwd, ['diff', 'HEAD', '-M', '--', ...paths]) : runGit(cwd, ['diff', '--cached', '-M', '--', ...paths]);
112
+ }
113
+
114
+ // maxBodyBytes: the room available for the files list in one message (the
115
+ // caller subtracts its own envelope). Infinity keeps today's no-limit shape.
116
+ async function getGitDiff(cwd, { maxBodyBytes = Infinity, log = () => {} } = {}) {
117
+ try {
118
+ await runGit(cwd, ['rev-parse', '--is-inside-work-tree']);
119
+ } catch {
120
+ return { isGitRepo: false, files: [] };
121
+ }
122
+
123
+ let hasHead = true;
124
+ try {
125
+ await runGit(cwd, ['rev-parse', '--verify', '--quiet', 'HEAD']);
126
+ } catch {
127
+ hasHead = false;
128
+ }
129
+
130
+ const statusOut = await runGit(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
131
+ const allEntries = parseStatusZ(statusOut);
132
+ const rank = (e) => {
133
+ const c = categoryOf(e.x, e.y);
134
+ return c === 'conflict' ? 0 : c === 'untracked' ? 2 : 1;
135
+ };
136
+ const entries = allEntries
137
+ .map((e, i) => ({ e, i }))
138
+ .sort((a, b) => rank(a.e) - rank(b.e) || a.i - b.i)
139
+ .map(({ e }) => e)
140
+ .slice(0, MAX_FILES);
141
+
142
+ const files = [];
143
+ let used = 0;
144
+ for (const entry of entries) {
145
+ const category = categoryOf(entry.x, entry.y);
146
+ let diff = '';
147
+ try {
148
+ diff = await diffFor(cwd, entry, hasHead);
149
+ } catch (err) {
150
+ log(`[supervisor] git diff failed for "${entry.path}":`, err.message);
151
+ }
152
+ const binary = isBinaryDiff(diff);
153
+ const { additions, deletions } = binary ? { additions: 0, deletions: 0 } : countChanges(diff);
154
+ const file = {
155
+ status: category === 'untracked' ? 'untracked' : 'modified',
156
+ category,
157
+ path: entry.path,
158
+ ...(entry.origPath ? { oldPath: entry.origPath } : {}),
159
+ staged: entry.x !== ' ' && entry.x !== '?',
160
+ unstaged: entry.y !== ' ' && entry.y !== '?',
161
+ additions,
162
+ deletions,
163
+ binary,
164
+ diff: '',
165
+ };
166
+
167
+ let text = binary ? '' : diff;
168
+ let truncated = false;
169
+ if (text.length > MAX_DIFF_CHARS_PER_FILE) {
170
+ text = text.slice(0, MAX_DIFF_CHARS_PER_FILE) + TRUNCATION_NOTE;
171
+ truncated = true;
172
+ }
173
+ const base = sizeOf(file) + 20;
174
+ if (used + base > maxBodyBytes) break; // no room even for this file's row
175
+ const room = maxBodyBytes - used - base;
176
+ if (text && sizeOf(text) > room) {
177
+ const prefix = fitPrefix(text, room - sizeOf(TRUNCATION_NOTE));
178
+ if (prefix.length >= 500) {
179
+ text = prefix + TRUNCATION_NOTE;
180
+ truncated = true;
181
+ } else {
182
+ text = '';
183
+ file.omitted = true;
184
+ }
185
+ }
186
+ file.diff = text;
187
+ if (truncated) file.truncated = true;
188
+ used += sizeOf(file) + 2;
189
+ files.push(file);
190
+ }
191
+
192
+ return {
193
+ isGitRepo: true,
194
+ files,
195
+ hasChanges: allEntries.length > 0,
196
+ summary: { total: allEntries.length, listed: files.length },
197
+ };
198
+ }
199
+
200
+ module.exports = { getGitDiff, parseStatusZ, categoryOf, countChanges, isBinaryDiff, fitPrefix, MAX_FILES, MAX_DIFF_CHARS_PER_FILE };
@@ -0,0 +1,40 @@
1
+ // Keeps the laptop's shared encryption secret in step with the phone's CURRENT
2
+ // public key (P0: "could not decrypt output from this device").
3
+ //
4
+ // Confirmed cause: the laptop derived its secret once, from the phone key saved
5
+ // at pair time, and never looked again. The backend is the key directory: it
6
+ // holds the phone key that the phone last registered for this device (pairing,
7
+ // a re-scan, a second phone, a reinstall, a late sync). When that key differed
8
+ // from the one frozen in config.json, every message the laptop encrypted failed
9
+ // the phone's GCM auth check, and the only "recovery" was a full unpair and
10
+ // re-pair.
11
+ //
12
+ // Now /device/connect returns the registered phone key and each session start
13
+ // calls adoptPhoneKey(). Encryption is never weakened: a key that cannot be
14
+ // used is rejected (the old secret is kept), nothing falls back to plaintext
15
+ // because of a key change, and private keys are never logged.
16
+ const setuCrypto = require('./crypto');
17
+
18
+ function deriveFor(config, phonePublicKeyB64) {
19
+ const privateKey = setuCrypto.privateKeyFromBase64(config.devicePrivateKey);
20
+ return setuCrypto.deriveSharedSecret(privateKey, phonePublicKeyB64);
21
+ }
22
+
23
+ // Returns { secret, changed, error }.
24
+ // - secret: the secret to use from now on (unchanged when nothing changed or the new key is unusable)
25
+ // - changed: true when config.phonePublicKey was replaced (caller persists)
26
+ // - error: a short reason when the offered key was rejected, never key material
27
+ function adoptPhoneKey({ config, offeredKey, currentSecret }) {
28
+ if (!config.devicePrivateKey) return { secret: currentSecret, changed: false, error: null };
29
+ if (!offeredKey) return { secret: currentSecret, changed: false, error: null };
30
+ if (offeredKey === config.phonePublicKey && currentSecret) return { secret: currentSecret, changed: false, error: null };
31
+ try {
32
+ const secret = deriveFor(config, offeredKey);
33
+ const changed = offeredKey !== config.phonePublicKey;
34
+ return { secret, changed, error: null };
35
+ } catch (err) {
36
+ return { secret: currentSecret, changed: false, error: `phone public key rejected: ${err.message}` };
37
+ }
38
+ }
39
+
40
+ module.exports = { adoptPhoneKey, deriveFor };
package/src/status.js CHANGED
@@ -93,7 +93,7 @@ async function status(authServer) {
93
93
  }
94
94
 
95
95
  if (running.length === 0) {
96
- console.log('[cli-setu] No sessions currently running. Run `cli-setu` in a project folder to start one.');
96
+ console.log('[cli-setu] No sessions currently running. Run `cli-setu session` in a project folder to start one.');
97
97
  return;
98
98
  }
99
99
 
@@ -0,0 +1,33 @@
1
+ // Forwards the laptop keyboard to the PTY (P0: "first character is dropped").
2
+ //
3
+ // Two defects this replaces in supervisor.js:
4
+ // 1. Raw mode and the data listener were attached at the END of main(), after
5
+ // all the other start-up work. Until then the console is in cooked
6
+ // (line-buffered) mode, so keys typed while the shell was still starting
7
+ // were held in the console's line buffer and could be discarded when raw mode
8
+ // was switched on. The forwarder is now attached the moment the PTY exists.
9
+ // 2. `data.toString()` on each chunk corrupts a multi-byte UTF-8 character
10
+ // that is split across two chunks. A StringDecoder keeps the partial bytes
11
+ // until the rest arrive.
12
+ // Every chunk is written exactly once, in order. Nothing here reads or echoes
13
+ // input itself: echo is the shell's job, through the PTY.
14
+ const { StringDecoder } = require('string_decoder');
15
+
16
+ function attachStdinForwarder({ stdin, write }) {
17
+ const decoder = new StringDecoder('utf8');
18
+ const onData = (chunk) => {
19
+ const text = typeof chunk === 'string' ? chunk : decoder.write(chunk);
20
+ if (text) write(text);
21
+ };
22
+ if (stdin.isTTY && typeof stdin.setRawMode === 'function') stdin.setRawMode(true);
23
+ stdin.on('data', onData);
24
+ stdin.resume();
25
+
26
+ return function detach() {
27
+ stdin.removeListener('data', onData);
28
+ try { if (stdin.isTTY && typeof stdin.setRawMode === 'function') stdin.setRawMode(false); } catch { /* terminal already gone */ }
29
+ stdin.pause();
30
+ };
31
+ }
32
+
33
+ module.exports = { attachStdinForwarder };
package/src/supervisor.js CHANGED
@@ -33,22 +33,18 @@ const { Terminal: HeadlessTerminal } = require('@xterm/headless');
33
33
  const fs = require('fs');
34
34
  const path = require('path');
35
35
  const WebSocket = require('ws');
36
- const { exec, execFile } = require('child_process');
37
- const { promisify } = require('util');
38
- const execAsync = promisify(exec);
39
- // execFile (not exec) for anything that embeds a real filesystem path -
40
- // exec runs through cmd.exe, string-interpolating a path into a shell
41
- // command line is a real injection risk if that path ever contained
42
- // shell metacharacters (an unlikely but not impossible filename the CLI
43
- // itself created). execFile passes args as a real array, no shell
44
- // involved, no interpolation - the correct tool whenever a path is
45
- // data, not part of the command syntax itself.
46
- const execFileAsync = promisify(execFile);
36
+ const { exec } = require('child_process');
47
37
  const { getAdapter } = require('./cli-adapters');
38
+ const { getGitDiff } = require('./gitDiff');
48
39
  const setuCrypto = require('./crypto');
40
+ const { splitIntoParts, trimSnapshot, limitForProvider } = require('./transportSplit');
49
41
  const { createReconnectManager, WARN_AFTER_ATTEMPTS } = require('./reconnect');
50
42
  const { createDedupCache } = require('./dedup');
51
43
  const { attachProviderProtocol } = require('./providerProtocol');
44
+ const { createDiagnostics } = require('./diagnostics');
45
+ const { attachStdinForwarder } = require('./stdinForwarder');
46
+ const { adoptPhoneKey } = require('./sharedKey');
47
+ const { approvalFingerprint, createApprovalDeduper, relayWithRetry } = require('./approvalRelay');
52
48
 
53
49
  // Real bug found by testing: this script's own console.log/console.error
54
50
  // calls write to the SAME process.stdout the PTY's raw output is echoed
@@ -63,7 +59,7 @@ const { attachProviderProtocol } = require('./providerProtocol');
63
59
  // from that point on.
64
60
  const os = require('os');
65
61
  const crypto = require('crypto');
66
- const { readConfig, CONFIG_DIR } = require('./config');
62
+ const { readConfig, writeConfig, CONFIG_DIR } = require('./config');
67
63
 
68
64
  // Real gap in the proof-of-concept this replaces: every run required
69
65
  // typing <deviceName> <sessionId> as argv, and diagnostics went to a log
@@ -80,6 +76,31 @@ function log(...args) {
80
76
  fs.appendFileSync(LOG_FILE, line);
81
77
  }
82
78
 
79
+ // Once the PTY exists it owns the terminal: see diagnostics.js. Use diag.say()
80
+ // for every message that can fire after spawn; never console.log/error there.
81
+ // Declared up here, with its own flag rather than ptyProcess, because some
82
+ // callers run at module load, before ptyProcess is initialised.
83
+ let terminalOwned = false;
84
+ const diag = createDiagnostics({ log, isTerminalOwned: () => terminalOwned });
85
+
86
+ // No plaintext, ever: terminal content only leaves this computer encrypted. With no
87
+ // shared secret (this computer has no key for the phone yet) nothing is sent, and
88
+ // the user is told once, after the shell exits, what to do. The terminal on this
89
+ // laptop is unaffected.
90
+ // The only way terminal content is turned into a wire payload. It throws when
91
+ // there is no secret, so a missing key can never degrade into plaintext.
92
+ function encryptStrict(piece) {
93
+ if (!sharedSecret) throw new Error('refusing to send terminal content without an encryption key');
94
+ return setuCrypto.encrypt(sharedSecret, piece);
95
+ }
96
+ let warnedNoKey = false;
97
+ function noteNoEncryptionKey() {
98
+ log('[supervisor] No encryption key for the phone: terminal content is NOT being sent (plaintext is never used).');
99
+ if (warnedNoKey) return;
100
+ warnedNoKey = true;
101
+ diag.say('[cli-setu] Terminal output is NOT being sent to your phone: this computer has no encryption key for it yet, and plaintext is never used. Run `cli-setu pair` to pair this computer with your phone again. The terminal on this computer keeps working normally.', { error: true, showAtExit: true });
102
+ }
103
+
83
104
  // Real config, from pairing (src/pair.js, via the explicit `cli-setu pair`
84
105
  // command - see SETU-001: pairing and session creation are two distinct
85
106
  // steps now, bin/setu.js's `session` subcommand never pairs on its own
@@ -150,7 +171,7 @@ LOG_FILE = path.join(CONFIG_DIR, `supervisor.${DEVICE_NAME.replace(/[^a-zA-Z0-9-
150
171
 
151
172
  const adapter = getAdapter(CLI_NAME);
152
173
  console.log(`[supervisor] Using CLI adapter: ${adapter.displayName} (${adapter.id})`);
153
- log(`Using CLI adapter: ${adapter.displayName} (${adapter.id})`);
174
+ log(`cli-setu ${require("../package.json").version} (node ${process.version}, ${process.platform}) - using CLI adapter: ${adapter.displayName} (${adapter.id})`);
154
175
 
155
176
  // Real bug found by testing: when the spawned adapter is 'shell' (the
156
177
  // bare-`cli-setu` default - see cli-adapters/shell.js), the user is expected
@@ -194,7 +215,11 @@ let deviceToken = config.deviceToken;
194
215
  let deviceId = null;
195
216
  let ws = null;
196
217
  let azureReady = false;
218
+ // Which realtime provider this session actually connected through
219
+ // ('ably' | 'azure'); decides the per-message size limit (transportSplit.js).
220
+ let connectedProvider = null;
197
221
  const pendingPrompts = new Map();
222
+ const approvalDeduper = createApprovalDeduper({ isPending: (id) => pendingPrompts.has(id) });
198
223
 
199
224
  // Real gap found by investigation: both connectToAzure's own retry
200
225
  // paths (a failed /device/connect HTTP call, and the WebSocket's own
@@ -208,7 +233,7 @@ const pendingPrompts = new Map();
208
233
  const reconnectManager = createReconnectManager({
209
234
  onAttempt: () => connectToAzure(),
210
235
  onWarn: (attemptNumber) => {
211
- console.error(`\n[supervisor] Still unable to connect after ${attemptNumber} attempts - will keep retrying, but something is wrong (network, backend, or Azure). Check your connection; this is not a code bug if it eventually recovers.`);
236
+ diag.say(`[supervisor] Still unable to connect after ${attemptNumber} attempts - will keep retrying, but something is wrong (network, backend, or Azure). Check your connection; this is not a code bug if it eventually recovers.`, { error: true });
212
237
  log(`[supervisor] Reconnect warning threshold reached: ${attemptNumber} consecutive failures`);
213
238
  },
214
239
  log,
@@ -248,7 +273,7 @@ if (config.devicePrivateKey && config.phonePublicKey) {
248
273
  const privateKey = setuCrypto.privateKeyFromBase64(config.devicePrivateKey);
249
274
  sharedSecret = setuCrypto.deriveSharedSecret(privateKey, config.phonePublicKey);
250
275
  } catch (err) {
251
- console.error('[cli-setu] Could not derive E2E encryption key (falling back to unencrypted relay):', err.message);
276
+ diag.say(`[cli-setu] Could not derive E2E encryption key (falling back to unencrypted relay): ${err.message}`, { error: true, showAtExit: true });
252
277
  }
253
278
  }
254
279
 
@@ -314,7 +339,7 @@ async function pollFocus() {
314
339
  `${AUTH_SERVER}/terminal/is-focused?sessionId=${encodeURIComponent(SESSION_ID)}${deviceId ? `&deviceId=${encodeURIComponent(deviceId)}` : ''}${detectedParam}`
315
340
  );
316
341
  if (pollFocusFailureCount >= WARN_AFTER_ATTEMPTS) {
317
- console.log('[supervisor] Heartbeat to the backend recovered.');
342
+ diag.say('[supervisor] Heartbeat to the backend recovered.');
318
343
  log('[supervisor] pollFocus heartbeat recovered after failures');
319
344
  }
320
345
  pollFocusFailureCount = 0;
@@ -325,7 +350,7 @@ async function pollFocus() {
325
350
  // tick," same as before) - this fix is purely about visibility.
326
351
  pollFocusFailureCount += 1;
327
352
  if (pollFocusFailureCount === WARN_AFTER_ATTEMPTS) {
328
- console.error(`\n[supervisor] Heartbeat to the backend has failed ${pollFocusFailureCount} times in a row (${err.message}) - the backend may be down. Terminal output/input may not sync correctly until this recovers.`);
353
+ diag.say(`[supervisor] Heartbeat to the backend has failed ${pollFocusFailureCount} times in a row (${err.message}) - the backend may be down. Terminal output/input may not sync correctly until this recovers.`, { error: true });
329
354
  }
330
355
  log(`[supervisor] pollFocus failed (consecutive=${pollFocusFailureCount}): ${err.message}`);
331
356
  }
@@ -413,7 +438,7 @@ async function connectToAzure() {
413
438
  setTimeout(() => process.exit(1), 1500).unref();
414
439
  };
415
440
  if (res.status === 403) {
416
- console.error(`\n[supervisor] Connection rejected: ${err.error || 'the server declined this session.'}`);
441
+ diag.say(`[supervisor] Connection rejected: ${err.error || 'the server declined this session.'}`, { error: true, showAtExit: true });
417
442
  log(`[supervisor] /device/connect rejected (403): ${err.error || 'no reason given'}`);
418
443
  killAndExit();
419
444
  }
@@ -425,8 +450,8 @@ async function connectToAzure() {
425
450
  // wrong or what to do about it. Treated the same as 403 now: stop,
426
451
  // say so clearly, point at the real fix.
427
452
  if (res.status === 401) {
428
- console.error(`\n[supervisor] This device is no longer paired (it may have been unpaired from the app).`);
429
- console.error('[supervisor] Run `cli-setu pair` to pair it again.');
453
+ diag.say('[supervisor] This device is no longer paired (it may have been unpaired from the app).', { error: true, showAtExit: true });
454
+ diag.say('[supervisor] Run `cli-setu pair` to pair it again.', { error: true, showAtExit: true });
430
455
  log(`[supervisor] /device/connect rejected (401): ${err.error || 'no reason given'}`);
431
456
  killAndExit();
432
457
  }
@@ -436,6 +461,20 @@ async function connectToAzure() {
436
461
  }
437
462
  const conn = await res.json();
438
463
  deviceId = conn.deviceId;
464
+ // The backend holds the phone key this device is CURRENTLY registered with.
465
+ // Adopt it so a phone key that changed after pairing (reinstall, second
466
+ // phone, late sync) does not leave us encrypting to a stale key - see
467
+ // sharedKey.js. Private keys and secrets are never logged.
468
+ {
469
+ const adopted = adoptPhoneKey({ config, offeredKey: conn.phonePublicKey, currentSecret: sharedSecret });
470
+ if (adopted.error) log(`[supervisor] ${adopted.error}`);
471
+ if (adopted.secret) sharedSecret = adopted.secret;
472
+ if (adopted.changed) {
473
+ config.phonePublicKey = conn.phonePublicKey;
474
+ try { writeConfig(config); } catch (e) { log(`[supervisor] could not save the updated phone key: ${e.message}`); }
475
+ log('[supervisor] phone public key updated from the backend; encryption secret re-derived');
476
+ }
477
+ }
439
478
  // See this function's own call site (main()'s former focusTimer
440
479
  // comment) for why this starts HERE and not unconditionally at
441
480
  // startup - deviceId must be real before pollFocus's heartbeat is
@@ -449,7 +488,7 @@ async function connectToAzure() {
449
488
  // actually makes a session show up before its first approval prompt)
450
489
  // was even attempted and whether it succeeded, right here, instead of
451
490
  // needing server log access to find out.
452
- console.log(`[supervisor] session.started broadcast: ${conn.sessionBroadcast || '(not reported by this server version)'}`);
491
+ diag.say(`[supervisor] session.started broadcast: ${conn.sessionBroadcast || '(not reported by this server version)'}`);
453
492
 
454
493
  ws = new WebSocket(conn.wssUrl);
455
494
 
@@ -464,6 +503,7 @@ async function connectToAzure() {
464
503
  const providerConnection = attachProviderProtocol(ws, conn.wssUrl, `device:${deviceId}`, {
465
504
  onReady: () => {
466
505
  azureReady = true;
506
+ connectedProvider = providerConnection.provider;
467
507
  reconnectManager.reset();
468
508
  log(`[supervisor] Connected (${providerConnection.provider}). Ready to forward permission requests.`);
469
509
  },
@@ -490,18 +530,21 @@ async function connectToAzure() {
490
530
  // build talking to each other don't try to decrypt plaintext or
491
531
  // vice versa - see this file's own sharedSecret comment for why
492
532
  // that fallback has to be all-or-nothing, never silent guessing.
493
- let data = msg.data;
494
- if (msg.encrypted) {
495
- if (!sharedSecret) {
496
- log('[supervisor] Dropped an encrypted terminal.input - this device has no shared secret to decrypt it (re-pair to fix).');
497
- return;
498
- }
499
- try {
500
- data = setuCrypto.decrypt(sharedSecret, msg.data);
501
- } catch (err) {
502
- log('[supervisor] Failed to decrypt terminal.input, dropping:', err.message);
503
- return;
504
- }
533
+ // Plaintext input is refused: it must arrive encrypted and decrypt cleanly.
534
+ if (!msg.encrypted) {
535
+ log('[supervisor] Refused a plaintext terminal.input (plaintext is never accepted).');
536
+ return;
537
+ }
538
+ if (!sharedSecret) {
539
+ log('[supervisor] Dropped an encrypted terminal.input - this device has no shared secret to decrypt it (re-pair to fix).');
540
+ return;
541
+ }
542
+ let data;
543
+ try {
544
+ data = setuCrypto.decrypt(sharedSecret, msg.data);
545
+ } catch (err) {
546
+ log('[supervisor] Failed to decrypt terminal.input, dropping:', err.message);
547
+ return;
505
548
  }
506
549
  ptyProcess.write(data);
507
550
  }
@@ -536,7 +579,7 @@ async function connectToAzure() {
536
579
  // cleanup and actually exits, avoiding the node-pty Windows
537
580
  // async-teardown race already fixed elsewhere in this file.
538
581
  log(`[supervisor] Received session.close from the phone - shutting down.`);
539
- console.log('\n[supervisor] Session closed from the mobile app.');
582
+ diag.say('[supervisor] Session closed from the mobile app.', { showAtExit: true });
540
583
  process.exitCode = 0;
541
584
  if (ptyProcess) {
542
585
  ptyProcess.kill();
@@ -614,26 +657,19 @@ async function connectToAzure() {
614
657
  ws.on('error', (err) => log('[supervisor] Azure socket error:', err.message));
615
658
  }
616
659
 
617
- // Real bug found by code review, fixed before ever shipping: `scrollback`
618
- // is now genuinely unbounded in memory (SETU-009/015's own explicit "full
619
- // session, no cap" requirement) - but Azure Web PubSub (and Ably) both
620
- // have a REAL, documented hard ceiling of 1MB per message. A session
621
- // whose history grew past that would have its snapshot broadcast
622
- // rejected outright the next time a phone reconnects, leaving it with a
623
- // BLANK terminal instead of the promised full mirror - worse than a cap.
624
- // This does NOT touch `scrollback` itself (still fully unbounded, still
625
- // used for live streaming - see appendScrollback's own comment) - it only
626
- // trims what gets sent in this ONE-TIME reconnect snapshot, so a phone
627
- // attaching to a genuinely huge session still gets a recent, working
628
- // view instead of nothing at all. Margin left well under the real 1MB
629
- // limit for JSON framing + the pre-TUI history prefix + encryption
630
- // overhead (encryption inflates size - confirmed this session via a real
631
- // backend log showing a 1549-byte plaintext snapshot arrive as 2972
632
- // encrypted bytes, roughly 2x - 900KB plaintext stays safely under 1MB
633
- // even after that).
634
- const SNAPSHOT_MAX_SCROLLBACK_BYTES = 900_000;
660
+ // The realtime provider refuses any single message over its size limit
661
+ // (Ably Free/Standard: 64 KiB; Azure Web PubSub: 1 MB), and the old code sent
662
+ // the whole snapshot as ONE message, so a session with more than about 45 KB
663
+ // of history could reach the phone blank. The snapshot is now split into
664
+ // parts that each fit (see transportSplit.js) and the phone reassembles them.
665
+ // `scrollback` itself stays unbounded (SETU-009/015: full-session mirror).
666
+ // Only this one-time reconnect snapshot is capped, at a large size, and
667
+ // when it is capped the phone is TOLD (a visible notice plus a log line)
668
+ // instead of the history silently shrinking.
669
+ const SNAPSHOT_MAX_CHARS = 8_000_000;
635
670
 
636
671
  async function sendSnapshot() {
672
+ if (!sharedSecret) { noteNoEncryptionKey(); return; }
637
673
  try {
638
674
  // preservedHistoryText() (see its own comment) is plain text, from
639
675
  // BEFORE the current full-screen TUI took over - prepended ahead of
@@ -642,24 +678,50 @@ async function sendSnapshot() {
642
678
  // pre-TUI history too, not just whatever the current alt-screen
643
679
  // buffer still happens to show.
644
680
  const history = await preservedHistoryText();
645
- const scrollbackForSnapshot = scrollback.length > SNAPSHOT_MAX_SCROLLBACK_BYTES
646
- ? scrollback.slice(scrollback.length - SNAPSHOT_MAX_SCROLLBACK_BYTES)
647
- : scrollback;
648
- const plainScreen = history ? `${history}\n${scrollbackForSnapshot}` : scrollbackForSnapshot;
681
+ const combined = history ? `${history}\n${scrollback}` : scrollback;
682
+ const trimmed = trimSnapshot(combined, SNAPSHOT_MAX_CHARS);
683
+ if (trimmed.truncated) {
684
+ log(`[supervisor] Snapshot trimmed: ${trimmed.droppedChars} older characters are not sent (limit ${SNAPSHOT_MAX_CHARS}).`);
685
+ }
686
+ const plainScreen = trimmed.text;
687
+ const snapshotId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
688
+ const encryptIfNeeded = (piece) => encryptStrict(piece);
689
+ const parts = plainScreen
690
+ ? splitIntoParts(plainScreen, {
691
+ maxBytes: limitForProvider(connectedProvider),
692
+ measure: (piece) =>
693
+ Buffer.byteLength(
694
+ JSON.stringify({ sessionId: SESSION_ID, snapshotId, part: 99999, totalParts: 99999, screen: encryptIfNeeded(piece), encrypted: true, cols: PTY_COLS, rows: PTY_ROWS })
695
+ ),
696
+ })
697
+ : [''];
649
698
  // TEMPORARY diagnostic logging (2026-10-28) - remove once the
650
699
  // scrollback-not-refreshed-on-reload bug is confirmed/fixed.
651
- log(`[supervisor][diag] sendSnapshot: history=${history.length} scrollback=${scrollback.length} sent=${scrollbackForSnapshot.length} total=${plainScreen.length} bytes, AUTH_SERVER=${AUTH_SERVER}`);
652
- // Section 1 E2E: see terminal.input's own comment on why this is
653
- // all-or-nothing, never a silent per-message guess.
654
- const screen = sharedSecret ? setuCrypto.encrypt(sharedSecret, plainScreen) : plainScreen;
655
- await fetch(`${AUTH_SERVER}/relay/terminal-snapshot`, {
656
- method: 'POST',
657
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
658
- // cols/rows: the real PTY's actual geometry, so a phone attaching
659
- // can lock its terminal to match instead of guessing its own size -
660
- // see auth-server.js's matching comment for why this matters.
661
- body: JSON.stringify({ sessionId: SESSION_ID, screen, encrypted: !!sharedSecret, cols: PTY_COLS, rows: PTY_ROWS }),
662
- });
700
+ log(`[supervisor][diag] sendSnapshot: history=${history.length} scrollback=${scrollback.length} total=${plainScreen.length} parts=${parts.length}`);
701
+ for (let i = 0; i < parts.length; i++) {
702
+ // Section 1 E2E: see terminal.input's own comment on why this is
703
+ // all-or-nothing, never a silent per-message guess.
704
+ const res = await fetch(`${AUTH_SERVER}/relay/terminal-snapshot`, {
705
+ method: 'POST',
706
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
707
+ // cols/rows: the real PTY's actual geometry, so a phone attaching
708
+ // can lock its terminal to match instead of guessing its own size -
709
+ // see auth-server.js's matching comment for why this matters.
710
+ // A single-part snapshot keeps the exact original body shape.
711
+ body: JSON.stringify({
712
+ sessionId: SESSION_ID,
713
+ screen: encryptIfNeeded(parts[i]),
714
+ encrypted: true,
715
+ cols: PTY_COLS,
716
+ rows: PTY_ROWS,
717
+ ...(parts.length > 1 ? { snapshotId, part: i, totalParts: parts.length } : {}),
718
+ }),
719
+ });
720
+ if (!res.ok) {
721
+ log(`[supervisor] Snapshot part ${i + 1}/${parts.length} was refused by the backend (HTTP ${res.status}); stopping.`);
722
+ return;
723
+ }
724
+ }
663
725
  } catch (err) {
664
726
  log('[supervisor] Failed to send snapshot:', err.message);
665
727
  }
@@ -676,88 +738,16 @@ async function sendSnapshot() {
676
738
  // against each untracked file (Windows git still accepts the POSIX
677
739
  // /dev/null form here) gets a real unified diff for those too, rather
678
740
  // than just a bare filename with no content shown.
679
- const GIT_TIMEOUT_MS = 15_000;
680
- // Web PubSub has a real per-message size ceiling - a genuinely huge diff
681
- // (a big refactor, an accidentally-modified generated/vendored file)
682
- // could otherwise silently fail to relay at all. Capping per-file and
683
- // truncating with a visible marker is safer than an unbounded payload -
684
- // the phone still sees SOMETHING and knows it's incomplete, rather than
685
- // the whole request quietly failing.
686
- const MAX_DIFF_CHARS_PER_FILE = 20_000;
687
-
688
- function capDiff(diffText) {
689
- if (diffText.length <= MAX_DIFF_CHARS_PER_FILE) return { diff: diffText, truncated: false };
690
- return {
691
- diff: diffText.slice(0, MAX_DIFF_CHARS_PER_FILE) + '\n\n... (diff truncated - too large to send in full)',
692
- truncated: true,
693
- };
694
- }
695
-
696
- async function getGitDiff(cwd) {
697
- // Not a git repo at all - a real, common, non-error state (the
698
- // session's working directory might just never have been a repo) -
699
- // distinguished from a real git failure so the phone can show an
700
- // honest "not a git repository" message instead of a blank/broken pane.
701
- try {
702
- await execAsync('git rev-parse --is-inside-work-tree', { cwd, timeout: GIT_TIMEOUT_MS });
703
- } catch {
704
- return { isGitRepo: false, files: [] };
705
- }
706
-
707
- const files = [];
708
-
709
- // --name-only first, then one `git diff` PER FILE - not a single
710
- // combined `git diff` call. A combined diff mixes every modified
711
- // file's text into one blob, which would make capDiff's per-file
712
- // truncation (below) chop arbitrarily mid-file instead of cleanly
713
- // per-file, and would collapse the phone's ability to show "which
714
- // specific files changed" as a real list rather than one wall of text.
715
- const { stdout: nameOnlyOut } = await execAsync('git diff --name-only', { cwd, timeout: GIT_TIMEOUT_MS });
716
- const modifiedPaths = nameOnlyOut.split('\n').map((l) => l.trim()).filter(Boolean);
717
-
718
- for (const relPath of modifiedPaths) {
719
- try {
720
- const { stdout } = await execFileAsync('git', ['diff', '--', relPath], { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 10 * 1024 * 1024 });
721
- if (stdout) files.push({ status: 'modified', path: relPath, ...capDiff(stdout) });
722
- } catch (err) {
723
- log(`[supervisor] git diff failed for modified file "${relPath}":`, err.message);
724
- }
725
- }
726
-
727
- // --porcelain's stable, machine-parseable format - '??' is git's own
728
- // marker for untracked. Path may be quoted (e.g. contains a space) -
729
- // stripping surrounding quotes is enough for this app's own diff
730
- // request, not a full porcelain parser.
731
- const { stdout: statusOut } = await execAsync('git status --porcelain', { cwd, timeout: GIT_TIMEOUT_MS });
732
- const untrackedPaths = statusOut
733
- .split('\n')
734
- .filter((line) => line.startsWith('?? '))
735
- .map((line) => line.slice(3).trim().replace(/^"|"$/g, ''));
736
-
737
- for (const relPath of untrackedPaths) {
738
- try {
739
- // --no-index compares two paths outside git's own tracking - the
740
- // ONLY way to get a real content diff for a file git has never
741
- // seen before. Exits non-zero whenever the files differ (which is
742
- // always true here, comparing against nothing) - execFileAsync
743
- // treats that as a rejected promise even though stdout still has
744
- // the real diff text, so it's read off the caught error instead.
745
- // execFile, not exec - relPath is a real filesystem path (from git
746
- // status output, ultimately from whatever the CLI wrote to disk),
747
- // passed as a real argv entry with no shell involved, not
748
- // interpolated into a command string.
749
- await execFileAsync('git', ['diff', '--no-index', '--', '/dev/null', relPath], { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 5 * 1024 * 1024 });
750
- } catch (err) {
751
- if (err.stdout) files.push({ status: 'untracked', path: relPath, ...capDiff(err.stdout) });
752
- }
753
- }
754
-
755
- return { isGitRepo: true, files, hasChanges: modifiedPaths.length > 0 || untrackedPaths.length > 0 };
756
- }
741
+ // The git collection (changed files, staged/renamed/deleted/binary/conflict,
742
+ // size budget) lives in gitDiff.js and is tested against real repositories.
743
+ const GIT_DIFF_ENVELOPE_BYTES = 4000;
757
744
 
758
745
  async function sendGitDiff(requestId) {
759
746
  try {
760
- const result = await getGitDiff(WORKING_DIR);
747
+ const result = await getGitDiff(WORKING_DIR, {
748
+ maxBodyBytes: limitForProvider(connectedProvider) - GIT_DIFF_ENVELOPE_BYTES,
749
+ log,
750
+ });
761
751
  await fetch(`${AUTH_SERVER}/relay/git-diff-response`, {
762
752
  method: 'POST',
763
753
  headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
@@ -834,24 +824,51 @@ function flushOutputBuffer() {
834
824
  // immediately and broadcasts to Azure in the background, so this
835
825
  // fetch() itself should resolve quickly regardless of Azure's own cost.
836
826
  sendInFlight = sendInFlight.then(async () => {
837
- try {
838
- // Section 1 E2E: see terminal.input's own comment on why this is
839
- // all-or-nothing, never a silent per-message guess.
840
- const data = sharedSecret ? setuCrypto.encrypt(sharedSecret, batch) : batch;
841
- await fetch(`${AUTH_SERVER}/relay/terminal-output`, {
842
- method: 'POST',
843
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
844
- body: JSON.stringify({ sessionId: SESSION_ID, seq: ++outputSeq, data, encrypted: !!sharedSecret }),
845
- });
846
- } catch (err) {
847
- // A dropped terminal.output batch isn't fatal the way a dropped
848
- // confirmation would be - the next batch (or a fresh session.attach
849
- // snapshot) catches the view back up, so just log and move on.
850
- log('[supervisor] Failed to stream output batch:', err.message);
827
+ // A batch can be far bigger than BATCH_MAX_BYTES (one large chunk from
828
+ // the terminal), and the realtime provider refuses any single message
829
+ // over its limit (Ably Free/Standard: 64 KiB). Each piece gets its own
830
+ // consecutive seq, which the phone already reorders by.
831
+ if (!sharedSecret) { noteNoEncryptionKey(); return; }
832
+ for (const piece of splitBatchForTransport(batch)) {
833
+ try {
834
+ // Section 1 E2E: see terminal.input's own comment on why this is
835
+ // all-or-nothing, never a silent per-message guess.
836
+ const data = encryptStrict(piece);
837
+ const res = await fetch(`${AUTH_SERVER}/relay/terminal-output`, {
838
+ method: 'POST',
839
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
840
+ body: JSON.stringify({ sessionId: SESSION_ID, seq: ++outputSeq, data, encrypted: true }),
841
+ });
842
+ if (!res.ok) log(`[supervisor] Output piece seq=${outputSeq} was refused by the backend (HTTP ${res.status}, ${data.length} chars).`);
843
+ } catch (err) {
844
+ // A dropped terminal.output batch isn't fatal the way a dropped
845
+ // confirmation would be - the next batch (or a fresh session.attach
846
+ // snapshot) catches the view back up, so just log and move on.
847
+ log('[supervisor] Failed to stream output batch:', err.message);
848
+ }
851
849
  }
852
850
  });
853
851
  }
854
852
 
853
+ // Short batches cannot exceed the limit even if every byte JSON-escapes to
854
+ // six (6000 * 6 = 36 KB), so they skip the size measurement.
855
+ const SMALL_BATCH_CHARS = 6000;
856
+ function splitBatchForTransport(batch) {
857
+ if (batch.length <= SMALL_BATCH_CHARS) return [batch];
858
+ return splitIntoParts(batch, {
859
+ maxBytes: limitForProvider(connectedProvider),
860
+ measure: (piece) =>
861
+ Buffer.byteLength(
862
+ JSON.stringify({
863
+ sessionId: SESSION_ID,
864
+ seq: outputSeq + 1,
865
+ data: encryptStrict(piece),
866
+ encrypted: true,
867
+ })
868
+ ),
869
+ });
870
+ }
871
+
855
872
  // Real bug found by testing: writing several keystrokes (a plain
856
873
  // character plus \x1b[B escape sequences) to the PTY in ONE
857
874
  // ptyProcess.write() call only ever registered the FIRST one on a real
@@ -1168,6 +1185,7 @@ async function preservedHistoryText() {
1168
1185
 
1169
1186
  let processedLines = 0;
1170
1187
  let ptyProcess = null;
1188
+ let detachStdin = null;
1171
1189
  let pollTimer = null;
1172
1190
  let focusTimer = null;
1173
1191
  // No longer an interval (see the on-demand usage.refresh.request handler
@@ -1752,59 +1770,46 @@ async function relayApproval(event, options, text, questionIndex = 0, totalQuest
1752
1770
  // treats the second, genuinely different prompt as a duplicate of the
1753
1771
  // first and drops it, or conflates their responses. DEVICE_NAME makes
1754
1772
  // the id unique per-process even under a same-millisecond collision.
1773
+ // One logical approval = one card: a repeat of a still-pending request (same
1774
+ // session, tool, tool_use_id and input) is dropped. Step updates of a wizard
1775
+ // (reusePromptId) are not new approvals. See approvalRelay.js.
1776
+ const fingerprint = reusePromptId ? null : approvalFingerprint(event);
1777
+ if (fingerprint && approvalDeduper.isDuplicate(fingerprint)) {
1778
+ log('[supervisor] Ignored a repeat of an approval that is still pending (same session, tool and input).');
1779
+ return;
1780
+ }
1755
1781
  const promptId = reusePromptId || `p-${DEVICE_NAME}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1756
1782
  pendingPrompts.set(promptId, { ...event, options, questionIndex, totalQuestions, isMultiSelect: !!multiSelectOptions });
1783
+ if (fingerprint) approvalDeduper.remember(fingerprint, promptId);
1757
1784
 
1758
1785
  log(`[supervisor] Detected approval prompt: ${text}`);
1759
1786
  log(`[supervisor] Relaying to auth-server as promptId=${promptId}${reusePromptId ? ' (step update)' : ''}...`);
1760
1787
 
1761
- try {
1762
- const res = await fetch(`${AUTH_SERVER}/relay/confirmation-request`, {
1763
- method: 'POST',
1764
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
1765
- body: JSON.stringify({
1766
- sessionId: SESSION_ID,
1767
- promptId,
1768
- text,
1769
- options: multiSelectOptions ? [] : options.map(({ label, style }) => ({ label, style })),
1770
- ...(multiSelectOptions ? { isMultiSelect: true, multiSelectOptions } : {}),
1771
- ...(totalQuestions > 1 ? { stepIndex: questionIndex, totalSteps: totalQuestions } : {}),
1772
- }),
1773
- });
1774
- if (!res.ok) {
1775
- const err = await res.json().catch(() => ({}));
1776
- log('[supervisor] Relay failed:', err.error || res.status);
1777
- }
1778
- } catch (err) {
1779
- log('[supervisor] Failed to reach auth-server:', err.message);
1780
- }
1788
+ // Delivery is retried with backoff (same promptId, so it is idempotent) until
1789
+ // it is accepted, permanently refused, or the prompt is no longer pending.
1790
+ // Not awaited: a slow or failing backend must not hold up the next prompt in the queue.
1791
+ relayWithRetry({
1792
+ send: async () => {
1793
+ const res = await fetch(`${AUTH_SERVER}/relay/confirmation-request`, {
1794
+ method: 'POST',
1795
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
1796
+ body: JSON.stringify({
1797
+ sessionId: SESSION_ID,
1798
+ promptId,
1799
+ text,
1800
+ options: multiSelectOptions ? [] : options.map(({ label, style }) => ({ label, style })),
1801
+ ...(multiSelectOptions ? { isMultiSelect: true, multiSelectOptions } : {}),
1802
+ ...(totalQuestions > 1 ? { stepIndex: questionIndex, totalSteps: totalQuestions } : {}),
1803
+ }),
1804
+ });
1805
+ return { ok: res.ok, status: res.status };
1806
+ },
1807
+ isStillPending: () => pendingPrompts.has(promptId),
1808
+ log: (m) => log(`[supervisor] ${m} (promptId=${promptId})`),
1809
+ }).then((delivery) => {
1810
+ if (!delivery.delivered) log(`[supervisor] Approval ${promptId} was NOT delivered to the phone: ${delivery.reason} after ${delivery.attempts} attempt(s). It is still answerable at the laptop.`);
1811
+ });
1781
1812
 
1782
- // Real gap found by testing: an APPROVED Bash/Write/PowerShell prompt
1783
- // gets a PostToolUse event (resolveIfPending), but a REJECTED one
1784
- // doesn't - the tool never ran, so there's nothing to hook. Several
1785
- // attempts at matching Claude Code's own rejection wording proved
1786
- // unreliable (see cli-adapters/claude.js's isMenuStillOnScreen
1787
- // comment). This instead polls whether the SAME menu is still
1788
- // physically on screen - once it isn't, a decision happened (approved,
1789
- // rejected, or interrupted, doesn't matter which) and the prompt is
1790
- // resolved. Skipped for AskUserQuestion, which already resolves
1791
- // reliably and precisely via PostToolUse's exact question-text match -
1792
- // this cruder "is ANY proceed-style menu gone" check would be a
1793
- // downgrade for that tool_name, not an improvement.
1794
- //
1795
- // Real bug found by code review, fixed before ever shipping: this used
1796
- // to hardcode claudeAdapter.approvals.isMenuStillOnScreen/
1797
- // distinguishingTextFor regardless of which adapter actually produced
1798
- // the event - Codex's own approvals object defines neither (see
1799
- // codex.js - it has no on-screen-menu-text concept at all, just its own
1800
- // fingerprint-based dedup), so a Codex prompt was being watched against
1801
- // CLAUDE's "Do you want to proceed?" wording, which never matches real
1802
- // Codex menu text - the very first poll (500ms later) always saw "no
1803
- // menu" and wrongly resolved a still-genuinely-pending Codex approval
1804
- // as abandoned. Using the passed-in approvalsAdapter (defaults to
1805
- // claudeAdapter.approvals, correct for pollForRequestsOnce's own
1806
- // exclusively-Claude path) means this now correctly no-ops for Codex,
1807
- // which has no isMenuStillOnScreen to even check.
1808
1813
  if (approvalsAdapter.isMenuStillOnScreen && event.tool_name !== 'AskUserQuestion') {
1809
1814
  // Real bug found by testing (live capture): two back-to-back Read
1810
1815
  // prompts for the same session each got their own watcher, but
@@ -1886,6 +1891,12 @@ async function main() {
1886
1891
  throw new Error(`Could not start "${adapter.spawn.command}" in ${WORKING_DIR}: ${err.message}`);
1887
1892
  }
1888
1893
 
1894
+ // Attach the laptop keyboard IMMEDIATELY, before any other start-up work, so
1895
+ // the first keystroke is never typed into a console that is still in cooked
1896
+ // mode (see stdinForwarder.js).
1897
+ terminalOwned = true; // from here on the PTY owns stdout: see diag
1898
+ detachStdin = attachStdinForwarder({ stdin: process.stdin, write: (text) => ptyProcess.write(text) });
1899
+
1889
1900
  // SETU-014: keep the real PTY (and the headless buffer that mirrors it
1890
1901
  // for the phone, see headlessTerm's own comment) in sync with the
1891
1902
  // laptop's own terminal WINDOW size - see PTY_COLS/PTY_ROWS's own
@@ -2111,17 +2122,16 @@ async function main() {
2111
2122
  ptyProcess.onExit(({ exitCode }) => {
2112
2123
  if (finishedExiting) return;
2113
2124
  finishedExiting = true;
2125
+ try { if (detachStdin) detachStdin(); } catch {}
2126
+ terminalOwned = false; // the terminal is the user's again: diagnostics may print
2114
2127
  console.log(`\n[supervisor] ${adapter.displayName} exited with code ${exitCode}`);
2128
+ diag.flushAtExit();
2115
2129
  if (pollTimer) clearInterval(pollTimer);
2116
2130
  if (focusTimer) clearInterval(focusTimer);
2117
2131
  if (usageTimer) clearInterval(usageTimer);
2118
2132
  if (batteryTimer) clearInterval(batteryTimer);
2119
2133
  if (adapterDetectTimer) clearInterval(adapterDetectTimer);
2120
2134
  if (ws) ws.close();
2121
- try {
2122
- if (process.stdin.isTTY) process.stdin.setRawMode(false);
2123
- process.stdin.pause();
2124
- } catch {}
2125
2135
  removePidFile();
2126
2136
  // If a caller (connectToAzure's 403/401, or cleanupAndExit) already
2127
2137
  // set process.exitCode before calling .kill(), respect that instead
@@ -2176,10 +2186,6 @@ async function main() {
2176
2186
  adapterDetectTimer = setInterval(detectRunningAdapter, ADAPTER_DETECT_POLL_INTERVAL_MS);
2177
2187
  }
2178
2188
 
2179
- process.stdin.setRawMode(true);
2180
- process.stdin.resume();
2181
- process.stdin.on('data', (data) => ptyProcess.write(data.toString()));
2182
-
2183
2189
  // Real gap in the PoC this replaces: there was no way for `cli-setu status`
2184
2190
  // or `cli-setu stop` (both new - see src/status.js, src/stop.js) to know
2185
2191
  // whether a session watcher was even running, or on which PID, since
@@ -0,0 +1,72 @@
1
+ // Splits terminal text into pieces that each fit one realtime-provider message.
2
+ //
3
+ // Why: Ably's Free and Standard plans reject any single published message
4
+ // over 64 KiB (see Ably's published platform limits page). The CLI used
5
+ // to send each output batch and the whole reconnect snapshot as ONE message
6
+ // with no size limit, so a large chunk or a long history could be refused
7
+ // and never reach the phone. Encryption (about 1.33x for base64) and JSON
8
+ // escaping make the sent size differ from the text length, so sizes are
9
+ // MEASURED on the real message, not guessed.
10
+ 'use strict';
11
+
12
+ // Well under 64 KiB (65,536 bytes) to leave room for the backend and
13
+ // provider envelope around our fields.
14
+ const MAX_MESSAGE_BYTES = 48_000;
15
+ // Azure Web PubSub allows 1 MB per message; well under it. Keeping Azure at
16
+ // its larger size means a history that used to arrive whole still arrives
17
+ // whole, so apps that do not know about parts keep working on Azure.
18
+ const AZURE_MESSAGE_BYTES = 900_000;
19
+
20
+ // provider is what the CLI is actually connected through ('ably' | 'azure').
21
+ // Unknown means the small, safe limit.
22
+ function limitForProvider(provider) {
23
+ return provider === 'azure' ? AZURE_MESSAGE_BYTES : MAX_MESSAGE_BYTES;
24
+ }
25
+ const MIN_PIECE_CHARS = 512;
26
+
27
+ // Never cut between the two halves of a surrogate pair: each piece is
28
+ // encrypted and decoded on its own, and a lone surrogate turns into U+FFFD.
29
+ function safeEnd(text, start, end) {
30
+ if (end >= text.length) return text.length;
31
+ const code = text.charCodeAt(end - 1);
32
+ if (code >= 0xd800 && code <= 0xdbff && end - start > 1) return end - 1;
33
+ return end;
34
+ }
35
+
36
+ // measure(piece) must return the byte size of the FULL message that would
37
+ // carry that piece (after encryption and JSON.stringify of the body).
38
+ // The first attempt is the WHOLE text (so anything that fits stays one part);
39
+ // when it does not fit, the size shrinks in proportion to how far over it was
40
+ // and is re-measured until the real message fits.
41
+ function splitIntoParts(text, { measure, maxBytes = MAX_MESSAGE_BYTES, initialChars = Infinity, minChars = MIN_PIECE_CHARS }) {
42
+ const parts = [];
43
+ let i = 0;
44
+ let size = Math.min(initialChars, text.length) || 1;
45
+ while (i < text.length) {
46
+ const end = safeEnd(text, i, Math.min(text.length, i + size));
47
+ const piece = text.slice(i, end);
48
+ const bytes = measure(piece);
49
+ if (bytes > maxBytes && piece.length > minChars) {
50
+ size = Math.max(minChars, Math.floor(piece.length * (maxBytes / bytes) * 0.9));
51
+ continue;
52
+ }
53
+ parts.push(piece);
54
+ i = end;
55
+ }
56
+ return parts;
57
+ }
58
+
59
+ // Keeps the NEWEST output when a snapshot would be larger than maxChars.
60
+ // Cuts at a line boundary so the first kept line is whole, and says so with a
61
+ // visible notice instead of dropping history silently.
62
+ function trimSnapshot(text, maxChars) {
63
+ if (text.length <= maxChars) return { text, truncated: false, droppedChars: 0 };
64
+ let cut = text.length - maxChars;
65
+ const nl = text.indexOf('\n', cut);
66
+ if (nl !== -1 && nl < text.length - 1) cut = nl + 1;
67
+ const dropped = cut;
68
+ const notice = `\x1b[0m\r\n[cli-setu: ${dropped} characters of older output are not shown after a reconnect]\r\n`;
69
+ return { text: notice + text.slice(cut), truncated: true, droppedChars: dropped };
70
+ }
71
+
72
+ module.exports = { MAX_MESSAGE_BYTES, AZURE_MESSAGE_BYTES, limitForProvider, splitIntoParts, trimSnapshot };