cli-setu 0.3.2 → 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/src/supervisor.js CHANGED
@@ -1,1369 +1,2234 @@
1
- // QR pairing (unchanged) PLUS Phase 6 full terminal mirroring:
2
- // - Device never paired before -> the QR both pairs it AND jumps the
3
- // phone straight to watching THIS session (scan.html + auth-server.js's
4
- // /device/pair/qr-confirm do both in one round trip).
5
- // - Device already paired -> same QR mechanism, but auth-server.js skips
6
- // re-pairing and the scan just means "watch this session on the phone."
7
- // - EVERY byte the PTY produces is streamed live to Azure whenever a
8
- // phone has terminal.html open and focused on this session (Section
9
- // 11f) - not just detected confirmation prompts. Unfocused, nothing
10
- // extra streams; the confirmation-request path is completely
11
- // unaffected either way.
12
- // - Remote input (typed on the phone) and remote resize both write
13
- // straight into this PTY, same as a local keystroke or a dragged
14
- // terminal window edge.
15
- //
16
- // Run with: node supervisor-qr.js <deviceName> <sessionId> [workingDir] [--cli <name>]
17
- // e.g. node supervisor-qr.js Laptop-1 session-A
18
- // node supervisor-qr.js Laptop-1 session-B ./session-b
19
- // node supervisor-qr.js Laptop-1 session-C ./proj --cli codex
20
- //
21
- // --cli defaults to 'claude' (this script's original, only-ever-supported
22
- // CLI). Any name not in cli-adapters/index.js's KNOWN_ADAPTERS still runs -
23
- // it just gets the generic PTY-only adapter (mirrored terminal, no
24
- // structured Confirmations card, no usage tracking) instead of refusing
25
- // to start. See cli-adapters/README.md for the adapter interface this
26
- // script now drives instead of hardcoding Claude Code's behavior directly.
27
-
28
- const pty = require('node-pty');
29
- const { Terminal: HeadlessTerminal } = require('@xterm/headless');
30
- const fs = require('fs');
31
- const path = require('path');
32
- const WebSocket = require('ws');
33
- const { exec, execFile } = require('child_process');
34
- const { promisify } = require('util');
35
- const execAsync = promisify(exec);
36
- // execFile (not exec) for anything that embeds a real filesystem path -
37
- // exec runs through cmd.exe, string-interpolating a path into a shell
38
- // command line is a real injection risk if that path ever contained
39
- // shell metacharacters (an unlikely but not impossible filename the CLI
40
- // itself created). execFile passes args as a real array, no shell
41
- // involved, no interpolation - the correct tool whenever a path is
42
- // data, not part of the command syntax itself.
43
- const execFileAsync = promisify(execFile);
44
- const { getAdapter } = require('./cli-adapters');
45
- const setuCrypto = require('./crypto');
46
-
47
- // Real bug found by testing: this script's own console.log/console.error
48
- // calls write to the SAME process.stdout the PTY's raw output is echoed
49
- // to (see ptyProcess.onData below). Claude Code's TUI does full-screen
50
- // ANSI cursor positioning and assumes exclusive control of the terminal's
51
- // screen buffer - any plain text interleaved into that stream mid-redraw
52
- // (e.g. the "Azure decision..." log firing while a menu is on screen)
53
- // corrupts its cursor-position math, visible as duplicated headers,
54
- // garbled/overlapping lines, and log text bleeding into the TUI's own
55
- // chrome. Once the PTY is running, ALL supervisor diagnostics go to a log
56
- // file instead - stdout is reserved exclusively for the PTY passthrough
57
- // from that point on.
58
- const os = require('os');
59
- const crypto = require('crypto');
60
- const { readConfig, CONFIG_DIR } = require('./config');
61
-
62
- // Real gap in the proof-of-concept this replaces: every run required
63
- // typing <deviceName> <sessionId> as argv, and diagnostics went to a log
64
- // file sitting in the install folder. A real global install (`npm install
65
- // -g cli-setu`) has no single "install folder" a user would think to look
66
- // in, and every session's log lived in ~/.cli-setu instead - one file per
67
- // PAIRED DEVICE is still right (see the original comment this replaces:
68
- // keeps a Claude Code session and a Codex session from interleaving into
69
- // one indistinguishable file), just relocated to a real per-user config
70
- // directory instead of wherever npm happened to install the package.
71
- let LOG_FILE = path.join(CONFIG_DIR, 'supervisor.log');
72
- function log(...args) {
73
- const line = `[${new Date().toISOString()}] ${args.join(' ')}\n`;
74
- fs.appendFileSync(LOG_FILE, line);
75
- }
76
-
77
- // Real config, from pairing (src/pair.js, either via bin/setu.js's own
78
- // bare-`cli-setu` pairing check or the explicit `cli-setu pair` command) -
79
- // not argv. bin/setu.js already guarantees this exists before requiring
80
- // this file for a normal `cli-setu` run; this is a defensive fallback for
81
- // anyone requiring supervisor.js directly, so a null deviceToken fails
82
- // with a clear message instead of a confusing crash deep in connectToAzure().
83
- const config = readConfig();
84
- if (!config || !config.deviceToken) {
85
- console.error('[cli-setu] This computer isn\'t paired yet. Run `cli-setu` again, or run `cli-setu pair` directly.');
86
- process.exit(1);
87
- }
88
- const DEVICE_NAME = config.deviceName;
89
-
90
- // TEMPORARY: defaults to the DEV server, not production - see bin/setu.js's
91
- // matching comment. Must switch back to https://api.clisetu.com before
92
- // treating this package as production-ready for real users.
93
- const AUTH_SERVER = process.env.CLI_SETU_SERVER || 'https://dev-api.clisetu.com';
94
-
95
- // --cli still supported, e.g. `cli-setu --cli codex`, for the same reason it
96
- // existed before: one paired device can run more than one kind of CLI
97
- // across different sessions/folders. Real product decision (confirmed
98
- // directly by the PM): bare `cli-setu` with no --cli flag bridges the user's
99
- // own plain terminal (see cli-adapters/shell.js), not Claude Code by
100
- // default - the user decides what to run once it's open, same as
101
- // getAdapter's own default (index.js) - kept in sync here rather than
102
- // letting this default silently drift from that one.
103
- const cliFlagIndex = process.argv.indexOf('--cli');
104
- const CLI_NAME = cliFlagIndex !== -1 ? process.argv[cliFlagIndex + 1] : 'shell';
105
-
106
- const WORKING_DIR = process.cwd();
107
- // Real gap in the PoC this replaces: sessionId was a hand-typed argv, a
108
- // real user shouldn't need to invent one. Derived from the device name
109
- // plus the real working directory (not just the folder's basename, which
110
- // collides the moment two different projects share a folder name like
111
- // "app" on the same machine) plus a short random suffix so re-running
112
- // `cli-setu` in the same folder twice at once (e.g. two terminal tabs) never
113
- // silently shares one session.
114
- const dirHash = crypto.createHash('sha1').update(WORKING_DIR).digest('hex').slice(0, 8);
115
- const SESSION_ID = `${os.hostname()}-${dirHash}-${crypto.randomBytes(3).toString('hex')}`;
116
-
117
- // Per-device log file (see LOG_FILE's declaration comment above) - keeps
118
- // two supervisors running under the same paired device (e.g. a Claude
119
- // Code session and a Codex session) from interleaving into one
120
- // indistinguishable file.
121
- LOG_FILE = path.join(CONFIG_DIR, `supervisor.${DEVICE_NAME.replace(/[^a-zA-Z0-9-]/g, '_')}.log`);
122
-
123
- const adapter = getAdapter(CLI_NAME);
124
- console.log(`[supervisor] Using CLI adapter: ${adapter.displayName} (${adapter.id})`);
125
- log(`Using CLI adapter: ${adapter.displayName} (${adapter.id})`);
126
-
127
- // Real bug found by testing: when the spawned adapter is 'shell' (the
128
- // bare-`cli-setu` default - see cli-adapters/shell.js), the user is expected
129
- // to freely run `claude` INSIDE that bridged shell whenever they want to.
130
- // Gating hook registration on "is the spawn-time adapter Claude" (as this
131
- // used to) meant Claude Code's hooks never got installed into
132
- // WORKING_DIR's .claude/settings.json at all in that case, so no
133
- // confirmation ever reached the phone once the user actually typed
134
- // `claude` - the hook-queue mechanism had nothing writing to it. Fixed by
135
- // always using Claude's own approvals object (queueFileFor,
136
- // describePrompt, parseLiveOptions, etc.) for the hook-queue path,
137
- // regardless of which adapter was spawned - the queue file is only ever
138
- // written by Claude Code's own hooks in the first place, so there's
139
- // nothing wrong with always registering them defensively. Harmless if the
140
- // user never runs `claude` in this session: the hook stays installed but
141
- // silent, since nothing ever calls it.
142
- const claudeAdapter = require('./cli-adapters/claude');
143
- const QUEUE_FILE = claudeAdapter.approvals.queueFileFor(CONFIG_DIR, WORKING_DIR);
144
- const PROCESSED_FILE = path.join(CONFIG_DIR, `processed-requests.${SESSION_ID}.json`);
145
- const POLL_INTERVAL_MS = 300;
146
-
147
- // Always registered now (see QUEUE_FILE's comment above) - covers both
148
- // `cli-setu --cli claude` (adapter itself is Claude) and bare `cli-setu` /
149
- // `cli-setu --cli shell` followed by the user manually running `claude`
150
- // inside the bridged shell.
151
- {
152
- const { ensureHooksRegistered } = require('./hooks');
153
- ensureHooksRegistered(WORKING_DIR);
154
- }
155
-
156
- // Real config, from `cli-setu pair` (src/config.js) - not a per-device-name
157
- // token file. Pairing is now a separate, one-time command (`cli-setu pair`)
158
- // that must already have succeeded before this ever runs (checked above,
159
- // where the process exits early if config.deviceToken is missing) - so
160
- // unlike the PoC's ensurePaired(), there is no QR-pairing fallback here at
161
- // all. A session watcher's job is to watch a session, not to also be the
162
- // pairing flow; keeping them separate is what makes `cli-setu` (bare) not
163
- // need a QR code/camera every single run.
164
- let deviceToken = config.deviceToken;
165
- let deviceId = null;
166
- let ws = null;
167
- let azureReady = false;
168
- const pendingPrompts = new Map();
169
-
170
- // Section 1 E2E: derived once at startup, same lifetime as this process.
171
- // Null whenever either half is missing - a device paired before this
172
- // feature existed has devicePrivateKey/phonePublicKey absent from its
173
- // config.json, and terminal.input/output/snapshot below deliberately
174
- // fall back to sending PLAINTEXT for exactly that case (see this
175
- // project's own decision: no forced re-pair, upgrade happens naturally
176
- // on the next real re-pair). Never silently "half encrypt" - either a
177
- // real secret is available and used for every payload this session, or
178
- // none is and nothing here pretends otherwise.
179
- let sharedSecret = null;
180
- if (config.devicePrivateKey && config.phonePublicKey) {
181
- try {
182
- const privateKey = setuCrypto.privateKeyFromBase64(config.devicePrivateKey);
183
- sharedSecret = setuCrypto.deriveSharedSecret(privateKey, config.phonePublicKey);
184
- } catch (err) {
185
- console.error('[cli-setu] Could not derive E2E encryption key (falling back to unencrypted relay):', err.message);
186
- }
187
- }
188
-
189
- // Phase 6, Section 7: a rolling raw-byte scrollback so a phone that opens
190
- // terminal.html AFTER the session has been running for a while gets caught
191
- // up instantly via session.snapshot, instead of an empty screen. Capped so
192
- // this can't grow unbounded on a long session.
193
- const SCROLLBACK_MAX_BYTES = 200_000;
194
- let scrollback = '';
195
- function appendScrollback(chunk) {
196
- scrollback += chunk;
197
- if (scrollback.length > SCROLLBACK_MAX_BYTES) {
198
- scrollback = scrollback.slice(scrollback.length - SCROLLBACK_MAX_BYTES);
199
- }
200
- }
201
-
202
- let outputSeq = 0;
203
-
204
- // Real gap found by testing: this used to also track isFocused, gating
205
- // whether ptyProcess.onData's bytes were actually streamed live - removed
206
- // (see that call site's own comment) since it could silently drop real
207
- // conversation history from what's supposed to be a complete mirror.
208
- // Still polled regardless, though: deviceId doubles as a lightweight
209
- // heartbeat (see auth-server.js's /terminal/is-focused) - this call
210
- // already happens every 3s, so it's the natural place for the Devices
211
- // tab's "is this laptop actually alive right now" signal, and for
212
- // /live-sessions' per-session online status, instead of adding a second
213
- // poller just for those.
214
- async function pollFocus() {
215
- try {
216
- await fetch(
217
- `${AUTH_SERVER}/terminal/is-focused?sessionId=${encodeURIComponent(SESSION_ID)}${deviceId ? `&deviceId=${encodeURIComponent(deviceId)}` : ''}`
218
- );
219
- } catch {
220
- // Network hiccup - next poll (3s later) tries again; no local state
221
- // depends on this succeeding anymore.
222
- }
223
- }
224
-
225
- async function connectToAzure() {
226
- // cliType lets Devices/Profile show which CLI this paired laptop is
227
- // actually running (see auth-server.js's /device/connect handler and
228
- // db.js's devices.cli_type column) - sent on every connect (not just
229
- // pairing) since the SAME device row can legitimately run a different
230
- // CLI across restarts (e.g. re-launched with --cli codex next time).
231
- const res = await fetch(`${AUTH_SERVER}/device/connect`, {
232
- method: 'POST',
233
- headers: { Authorization: `Bearer ${deviceToken}`, 'Content-Type': 'application/json' },
234
- // sessionId here is what lets auth-server.js broadcast session.started
235
- // immediately - see its own comment on why a session shouldn't have
236
- // to wait for its first approval prompt to become visible on the
237
- // phone. folderName (new) is the real product ask: the phone's own
238
- // session lists only ever showed the raw sessionId (a hostname+hash+
239
- // random string, meaningless to a real user) - just the WORKING_DIR's
240
- // own folder name (not the full path - shorter, and doesn't expose
241
- // this laptop's real directory structure to the phone/backend) lets
242
- // someone actually tell which real project a session belongs to.
243
- body: JSON.stringify({ cliType: adapter.id, sessionId: SESSION_ID, folderName: path.basename(WORKING_DIR) }),
244
- });
245
- if (!res.ok) {
246
- const err = await res.json().catch(() => ({}));
247
- // A 403 here means a real, durable plan-limit rejection (see
248
- // auth-server.js's live-session-limit check) - retrying every 3s
249
- // forever would just spam the same rejection, since nothing about
250
- // THIS session changes by waiting (the fix is stopping an existing
251
- // live session elsewhere, or upgrading, not a transient retry).
252
- // Every other failure (network hiccup, a momentarily-down server)
253
- // keeps the original retry behavior.
254
- if (res.status === 403) {
255
- console.error(`\n[supervisor] Connection rejected: ${err.error || 'the server declined this session.'}`);
256
- log(`[supervisor] /device/connect rejected (403): ${err.error || 'no reason given'}`);
257
- process.exit(1);
258
- }
259
- // Real bug found by testing: a 401 here means the server genuinely
260
- // doesn't recognize this device token anymore (e.g. unpaired from the
261
- // phone app) - this used to fall into the generic retry-every-3s path
262
- // below, silently looping forever on a token that will never become
263
- // valid again, with no indication to the user of what's actually
264
- // wrong or what to do about it. Treated the same as 403 now: stop,
265
- // say so clearly, point at the real fix.
266
- if (res.status === 401) {
267
- console.error(`\n[supervisor] This device is no longer paired (it may have been unpaired from the app).`);
268
- console.error('[supervisor] Run `cli-setu pair` to pair it again.');
269
- log(`[supervisor] /device/connect rejected (401): ${err.error || 'no reason given'}`);
270
- process.exit(1);
271
- }
272
- log(`[supervisor] /device/connect failed: ${err.error || res.status}`);
273
- setTimeout(connectToAzure, 3000);
274
- return;
275
- }
276
- const conn = await res.json();
277
- deviceId = conn.deviceId;
278
- // See this function's own call site (main()'s former focusTimer
279
- // comment) for why this starts HERE and not unconditionally at
280
- // startup - deviceId must be real before pollFocus's heartbeat is
281
- // worth sending at all. Guarded so a reconnect (connectToAzure called
282
- // again after a dropped WebSocket) never stacks a second timer.
283
- if (!focusTimer) focusTimer = setInterval(pollFocus, 2000);
284
- log(`[supervisor] Connecting to Azure as device:${deviceId} (owner: ${conn.userId})...`);
285
- // Diagnostic found by testing: a session not appearing in the phone's
286
- // Terminal tab had no visible cause from the laptop's own side - this
287
- // surfaces whether the backend's session.started broadcast (what
288
- // actually makes a session show up before its first approval prompt)
289
- // was even attempted and whether it succeeded, right here, instead of
290
- // needing server log access to find out.
291
- console.log(`[supervisor] session.started broadcast: ${conn.sessionBroadcast || '(not reported by this server version)'}`);
292
-
293
- ws = new WebSocket(conn.wssUrl);
294
-
295
- ws.on('open', () => {
296
- azureReady = true;
297
- log('[supervisor] Connected to Azure. Ready to forward permission requests.');
298
- });
299
-
300
- ws.on('message', (raw) => {
301
- let msg;
302
- try {
303
- msg = JSON.parse(raw.toString());
304
- } catch {
305
- return;
306
- }
307
- if (msg.type === 'confirmation.response') handleAzureDecision(msg);
308
- if (msg.type === 'terminal.input' && msg.sessionId === SESSION_ID) {
309
- // Section 11f Step 2: typed input from the phone, written to the PTY
310
- // exactly like a local keystroke - this is the "arbitrary remote
311
- // input" half of the DoD, not just approve/reject.
312
- //
313
- // Section 1 E2E: msg.data is ciphertext whenever sharedSecret exists
314
- // (the phone encrypts before sending - see TerminalScreen.js's own
315
- // sendInput). msg.encrypted distinguishes the two wire shapes so a
316
- // pre-upgrade phone build (no E2E yet) and a pre-upgrade laptop
317
- // build talking to each other don't try to decrypt plaintext or
318
- // vice versa - see this file's own sharedSecret comment for why
319
- // that fallback has to be all-or-nothing, never silent guessing.
320
- let data = msg.data;
321
- if (msg.encrypted) {
322
- if (!sharedSecret) {
323
- log('[supervisor] Dropped an encrypted terminal.input - this device has no shared secret to decrypt it (re-pair to fix).');
324
- return;
325
- }
326
- try {
327
- data = setuCrypto.decrypt(sharedSecret, msg.data);
328
- } catch (err) {
329
- log('[supervisor] Failed to decrypt terminal.input, dropping:', err.message);
330
- return;
331
- }
332
- }
333
- ptyProcess.write(data);
334
- }
335
- if (msg.type === 'terminal.resize' && msg.sessionId === SESSION_ID) {
336
- // Real bug found by testing: this used to call ptyProcess.resize()
337
- // with the PHONE's dimensions, reflowing the one real, SHARED PTY to
338
- // whatever narrow width the phone's screen happened to be - since a
339
- // PTY has exactly one size, that visibly shrank and re-wrapped the
340
- // laptop's own terminal the moment a phone connected/attached,
341
- // corrupting the laptop-side view too, not just a phone-side
342
- // cosmetic issue. Ignoring the phone's resize entirely is the
343
- // correct fix: the laptop's real terminal keeps whatever size the
344
- // person actually sitting at it set, and the phone's own
345
- // xterm.js/WebView is responsible for wrapping/scrolling whatever
346
- // width of output it receives to fit its own screen - the same
347
- // model every real remote-terminal viewer (Termius, Blink) uses.
348
- log(`[supervisor] Ignoring phone resize request (${msg.cols}x${msg.rows}) - the real PTY keeps its own size.`);
349
- }
350
- if (msg.type === 'session.attach' && msg.sessionId === SESSION_ID) {
351
- // Section 7: a phone just opened/reopened the terminal view - hand it
352
- // the scrollback immediately instead of leaving it blank until the
353
- // next byte happens to be written.
354
- sendSnapshot();
355
- }
356
- if (msg.type === 'git.diff.request' && msg.sessionId === SESSION_ID) {
357
- // Roadmap #14 - git diff pane. Entirely independent of the running
358
- // CLI adapter (Claude Code, Codex, generic) - this is a plain git
359
- // operation against WORKING_DIR, not something any adapter needs to
360
- // declare. Fire-and-forget from this handler's point of view; the
361
- // real response goes back over its own relay endpoint (see
362
- // sendGitDiff below), same pattern as sendSnapshot above.
363
- sendGitDiff(msg.requestId);
364
- }
365
- if (msg.type === 'cross_session.inject' && msg.toSessionId === SESSION_ID) {
366
- // Roadmap #3 - cross-session messaging. Note the field checked is
367
- // toSessionId, not sessionId - this message genuinely has two
368
- // different sessions in it (where it came FROM, where it's going
369
- // TO), unlike every other message type in this file which only
370
- // ever concerns THIS session.
371
- //
372
- // auth-server.js has ALREADY decided this is safe to inject
373
- // (either nobody was watching, or the watching phone explicitly
374
- // tapped Inject on the pending card) - this handler's only job is
375
- // writing it in with a visible trace, never silently. A bracketed
376
- // system-style line in the scrollback (not literally typed as if
377
- // from the keyboard) is what makes an injected message
378
- // distinguishable after the fact from something typed locally,
379
- // even hours later when nobody remembers a message arrived.
380
- const marker = `\r\n\x1b[38;2;155;185;235m[message from ${msg.fromDeviceName || 'another session'} / ${msg.fromSessionId}]\x1b[0m\r\n`;
381
- ptyProcess.write(marker + msg.text + '\r');
382
- log(`[supervisor] Injected cross-session message ${msg.messageId} from ${msg.fromSessionId}`);
383
- }
384
- if (msg.type === 'usage.refresh.request' && msg.sessionId === SESSION_ID) {
385
- // Real feedback: the old 5-minute auto-timer (below, now removed)
386
- // ran /cost in the user's own terminal on a schedule regardless of
387
- // whether anyone was even looking at their phone - genuinely
388
- // disruptive if someone's actively working locally and /cost's
389
- // full-screen usage report suddenly takes over their session. This
390
- // is the on-demand replacement: same triggerKeystrokes mechanism
391
- // (still a real, visible command - that constraint hasn't changed,
392
- // see cli-adapters/claude.js), but only ever fired when a phone
393
- // explicitly asks for a fresh number, not on a timer nobody
394
- // requested.
395
- if (adapter.usage?.triggerKeystrokes && ptyProcess) {
396
- ptyProcess.write(adapter.usage.triggerKeystrokes);
397
- usageListenUntil = Date.now() + USAGE_LISTEN_WINDOW_MS;
398
- log(`[supervisor] On-demand usage refresh requested for ${SESSION_ID}`);
399
- }
400
- }
401
- });
402
-
403
- ws.on('close', () => {
404
- azureReady = false;
405
- log('[supervisor] Azure connection closed. Reconnecting in 2s...');
406
- setTimeout(connectToAzure, 2000);
407
- });
408
-
409
- ws.on('error', (err) => log('[supervisor] Azure socket error:', err.message));
410
- }
411
-
412
- async function sendSnapshot() {
413
- try {
414
- // preservedHistoryText() (see its own comment) is plain text, from
415
- // BEFORE the current full-screen TUI took over - prepended ahead of
416
- // the real, live raw-byte scrollback (still replayed as actual ANSI,
417
- // unchanged), so a phone scrolling up sees the real startup banner/
418
- // pre-TUI history too, not just whatever the current alt-screen
419
- // buffer still happens to show.
420
- const history = await preservedHistoryText();
421
- const plainScreen = history ? `${history}\n${scrollback}` : scrollback;
422
- // Section 1 E2E: see terminal.input's own comment on why this is
423
- // all-or-nothing, never a silent per-message guess.
424
- const screen = sharedSecret ? setuCrypto.encrypt(sharedSecret, plainScreen) : plainScreen;
425
- await fetch(`${AUTH_SERVER}/relay/terminal-snapshot`, {
426
- method: 'POST',
427
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
428
- // cols/rows: the real PTY's actual geometry, so a phone attaching
429
- // can lock its terminal to match instead of guessing its own size -
430
- // see auth-server.js's matching comment for why this matters.
431
- body: JSON.stringify({ sessionId: SESSION_ID, screen, encrypted: !!sharedSecret, cols: PTY_COLS, rows: PTY_ROWS }),
432
- });
433
- } catch (err) {
434
- log('[supervisor] Failed to send snapshot:', err.message);
435
- }
436
- }
437
-
438
- // Roadmap #14 - git diff pane. Entirely CLI-agnostic: this runs plain git
439
- // commands against WORKING_DIR regardless of which adapter (Claude Code,
440
- // Codex, generic) is driving the PTY - no adapter interface changes
441
- // needed, unlike the command palette (#6) which is genuinely adapter-
442
- // specific. `git diff` alone only shows changes to ALREADY-TRACKED files -
443
- // a brand-new file Claude/Codex just created shows up in `git status`
444
- // but produces no `git diff` output at all, which is exactly the case
445
- // most worth seeing remotely. `git diff --no-index /dev/null <file>`
446
- // against each untracked file (Windows git still accepts the POSIX
447
- // /dev/null form here) gets a real unified diff for those too, rather
448
- // than just a bare filename with no content shown.
449
- const GIT_TIMEOUT_MS = 15_000;
450
- // Web PubSub has a real per-message size ceiling - a genuinely huge diff
451
- // (a big refactor, an accidentally-modified generated/vendored file)
452
- // could otherwise silently fail to relay at all. Capping per-file and
453
- // truncating with a visible marker is safer than an unbounded payload -
454
- // the phone still sees SOMETHING and knows it's incomplete, rather than
455
- // the whole request quietly failing.
456
- const MAX_DIFF_CHARS_PER_FILE = 20_000;
457
-
458
- function capDiff(diffText) {
459
- if (diffText.length <= MAX_DIFF_CHARS_PER_FILE) return { diff: diffText, truncated: false };
460
- return {
461
- diff: diffText.slice(0, MAX_DIFF_CHARS_PER_FILE) + '\n\n... (diff truncated - too large to send in full)',
462
- truncated: true,
463
- };
464
- }
465
-
466
- async function getGitDiff(cwd) {
467
- // Not a git repo at all - a real, common, non-error state (the
468
- // session's working directory might just never have been a repo) -
469
- // distinguished from a real git failure so the phone can show an
470
- // honest "not a git repository" message instead of a blank/broken pane.
471
- try {
472
- await execAsync('git rev-parse --is-inside-work-tree', { cwd, timeout: GIT_TIMEOUT_MS });
473
- } catch {
474
- return { isGitRepo: false, files: [] };
475
- }
476
-
477
- const files = [];
478
-
479
- // --name-only first, then one `git diff` PER FILE - not a single
480
- // combined `git diff` call. A combined diff mixes every modified
481
- // file's text into one blob, which would make capDiff's per-file
482
- // truncation (below) chop arbitrarily mid-file instead of cleanly
483
- // per-file, and would collapse the phone's ability to show "which
484
- // specific files changed" as a real list rather than one wall of text.
485
- const { stdout: nameOnlyOut } = await execAsync('git diff --name-only', { cwd, timeout: GIT_TIMEOUT_MS });
486
- const modifiedPaths = nameOnlyOut.split('\n').map((l) => l.trim()).filter(Boolean);
487
-
488
- for (const relPath of modifiedPaths) {
489
- try {
490
- const { stdout } = await execFileAsync('git', ['diff', '--', relPath], { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 10 * 1024 * 1024 });
491
- if (stdout) files.push({ status: 'modified', path: relPath, ...capDiff(stdout) });
492
- } catch (err) {
493
- log(`[supervisor] git diff failed for modified file "${relPath}":`, err.message);
494
- }
495
- }
496
-
497
- // --porcelain's stable, machine-parseable format - '??' is git's own
498
- // marker for untracked. Path may be quoted (e.g. contains a space) -
499
- // stripping surrounding quotes is enough for this app's own diff
500
- // request, not a full porcelain parser.
501
- const { stdout: statusOut } = await execAsync('git status --porcelain', { cwd, timeout: GIT_TIMEOUT_MS });
502
- const untrackedPaths = statusOut
503
- .split('\n')
504
- .filter((line) => line.startsWith('?? '))
505
- .map((line) => line.slice(3).trim().replace(/^"|"$/g, ''));
506
-
507
- for (const relPath of untrackedPaths) {
508
- try {
509
- // --no-index compares two paths outside git's own tracking - the
510
- // ONLY way to get a real content diff for a file git has never
511
- // seen before. Exits non-zero whenever the files differ (which is
512
- // always true here, comparing against nothing) - execFileAsync
513
- // treats that as a rejected promise even though stdout still has
514
- // the real diff text, so it's read off the caught error instead.
515
- // execFile, not exec - relPath is a real filesystem path (from git
516
- // status output, ultimately from whatever the CLI wrote to disk),
517
- // passed as a real argv entry with no shell involved, not
518
- // interpolated into a command string.
519
- await execFileAsync('git', ['diff', '--no-index', '--', '/dev/null', relPath], { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 5 * 1024 * 1024 });
520
- } catch (err) {
521
- if (err.stdout) files.push({ status: 'untracked', path: relPath, ...capDiff(err.stdout) });
522
- }
523
- }
524
-
525
- return { isGitRepo: true, files, hasChanges: modifiedPaths.length > 0 || untrackedPaths.length > 0 };
526
- }
527
-
528
- async function sendGitDiff(requestId) {
529
- try {
530
- const result = await getGitDiff(WORKING_DIR);
531
- await fetch(`${AUTH_SERVER}/relay/git-diff-response`, {
532
- method: 'POST',
533
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
534
- body: JSON.stringify({ sessionId: SESSION_ID, requestId, ...result }),
535
- });
536
- } catch (err) {
537
- log('[supervisor] Failed to compute/send git diff:', err.message);
538
- // Best-effort error reporting to the phone - without this, a failed
539
- // diff (e.g. git not on PATH) would leave the phone's request hanging
540
- // forever with no explanation, rather than a clear error state.
541
- fetch(`${AUTH_SERVER}/relay/git-diff-response`, {
542
- method: 'POST',
543
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
544
- body: JSON.stringify({ sessionId: SESSION_ID, requestId, error: err.message }),
545
- }).catch(() => {});
546
- }
547
- }
548
-
549
- // Real bug #1, found by testing: ptyProcess.onData fires rapidly and
550
- // synchronously for every PTY chunk, but each streamOutput() call did its
551
- // own independent, un-awaited fetch(). Nothing guaranteed those HTTP
552
- // requests RESOLVED in the order they were SENT - a later chunk's request
553
- // could finish first under normal network jitter, and terminal.html just
554
- // wrote whatever arrived with no reordering. Symptom: words/lines rendered
555
- // interleaved, e.g. "Listingserver.js," instead of two separate lines.
556
- //
557
- // First fix was one fetch() per chunk, strictly serialized - correct
558
- // order, but real bug #2: a single Claude Code response can produce MANY
559
- // small PTY chunks, and awaiting a full HTTP round trip before sending the
560
- // next one turned a live stream into a slow drip - observed as a ~2
561
- // minute lag before anything appeared, for output that should stream in
562
- // under a second.
563
- //
564
- // Actual fix: batch. Chunks accumulate in a buffer; a short timer (or the
565
- // buffer growing large) triggers ONE combined send instead of one send
566
- // per chunk - still exactly one in-flight request at a time (order
567
- // preserved by construction, same as before), but far fewer round trips.
568
- let outputBuffer = '';
569
- let flushTimer = null;
570
- let sendInFlight = Promise.resolve();
571
- const BATCH_WINDOW_MS = 40;
572
- const BATCH_MAX_BYTES = 8000; // flush early if a burst gets large, rather than waiting the full window
573
-
574
- function streamOutput(chunk) {
575
- outputBuffer += chunk;
576
- if (outputBuffer.length >= BATCH_MAX_BYTES) {
577
- scheduleFlush(0);
578
- } else if (!flushTimer) {
579
- scheduleFlush(BATCH_WINDOW_MS);
580
- }
581
- }
582
-
583
- function scheduleFlush(delayMs) {
584
- clearTimeout(flushTimer);
585
- flushTimer = setTimeout(flushOutputBuffer, delayMs);
586
- }
587
-
588
- function flushOutputBuffer() {
589
- flushTimer = null;
590
- if (!outputBuffer) return;
591
-
592
- const batch = outputBuffer;
593
- outputBuffer = '';
594
-
595
- // Still serialized against any send already in flight, so batches
596
- // themselves can never arrive out of order relative to each other.
597
- // Real bug found by testing: the Backend used to AWAIT Azure's own
598
- // sendToAll broadcast (~190-200ms per call, confirmed inherent to
599
- // Azure Web PubSub's broadcast API, not fixable from our side) before
600
- // responding here - since this chain won't send its next batch until
601
- // this fetch() resolves, every Azure call directly delayed the next
602
- // batch too, compounding into real, visible lag during a burst of PTY
603
- // output. auth-server.js's /relay/terminal-output now responds
604
- // immediately and broadcasts to Azure in the background, so this
605
- // fetch() itself should resolve quickly regardless of Azure's own cost.
606
- sendInFlight = sendInFlight.then(async () => {
607
- try {
608
- // Section 1 E2E: see terminal.input's own comment on why this is
609
- // all-or-nothing, never a silent per-message guess.
610
- const data = sharedSecret ? setuCrypto.encrypt(sharedSecret, batch) : batch;
611
- await fetch(`${AUTH_SERVER}/relay/terminal-output`, {
612
- method: 'POST',
613
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
614
- body: JSON.stringify({ sessionId: SESSION_ID, seq: ++outputSeq, data, encrypted: !!sharedSecret }),
615
- });
616
- } catch (err) {
617
- // A dropped terminal.output batch isn't fatal the way a dropped
618
- // confirmation would be - the next batch (or a fresh session.attach
619
- // snapshot) catches the view back up, so just log and move on.
620
- log('[supervisor] Failed to stream output batch:', err.message);
621
- }
622
- });
623
- }
624
-
625
- function handleAzureDecision(msg) {
626
- const pending = pendingPrompts.get(msg.promptId);
627
- if (!pending) {
628
- log(`[supervisor] Got a decision for unknown promptId ${msg.promptId} - already handled or unrecognized, ignoring.`);
629
- return;
630
- }
631
-
632
- const chosen = pending.options?.[msg.optionIndex];
633
- const keystroke = chosen ? chosen.keystroke : '\x1b';
634
-
635
- // Real bug found by testing: "Type something" (the phone's own
636
- // keepPending path - see ConfirmationsScreen.js) only opens Claude
637
- // Code's freeform input, it isn't a real decision - but this used to
638
- // unconditionally delete the promptId from pendingPrompts regardless of
639
- // WHICH option was chosen. That meant tapping a REAL option (e.g.
640
- // "Empty file") on the same still-visible card right after "Type
641
- // something" found nothing left to act on - the keystroke silently
642
- // never reached the terminal. Only delete when the actual decision was
643
- // a real one, so the same card can still be resolved for real
644
- // afterward.
645
- if (chosen?.label !== 'Type something') {
646
- pendingPrompts.delete(msg.promptId);
647
- }
648
-
649
- log(`[supervisor] Azure decision for ${msg.promptId}: "${chosen ? chosen.label : 'unknown'}". Injecting keystroke "${keystroke}"...`);
650
- // Real bug found by testing: Claude Code's inline permission menu
651
- // (1/2/3, or a bare Esc to reject) selects AND confirms on the single
652
- // keypress alone - it's a hotkey menu, not a typed line. Appending '\r'
653
- // unconditionally sent a second, separate Enter right after the
654
- // selection, which landed in whatever input the UI advanced to next
655
- // (the freeform chat box) - visible as a stray "1" typed into chat,
656
- // sometimes racing with the terminal's own answer if you'd already
657
- // resolved the same prompt locally before the phone's decision arrived.
658
- ptyProcess.write(keystroke);
659
- fs.appendFileSync(
660
- PROCESSED_FILE,
661
- JSON.stringify({ ...pending, chosenLabel: chosen?.label, injectedAt: new Date().toISOString() }) + '\n'
662
- );
663
- }
664
-
665
- // Real bug found by testing: these used to be hardcoded to 120x30
666
- // regardless of the user's REAL terminal window size - on any window
667
- // bigger than that (the normal case for a maximized/large terminal),
668
- // the PTY was spawned SMALLER than the window showing it, leaving real,
669
- // visible blank space in the laptop's own terminal below and to the
670
- // right of the actual PTY content - not a phone-side rendering bug at
671
- // all, a genuine laptop-side geometry mismatch. process.stdout.columns/
672
- // rows reflect the REAL terminal's actual current size at the moment
673
- // `cli-setu` starts (falling back to the old 120x30 only if those aren't
674
- // available - e.g. output piped to a file, not a real TTY). Still a
675
- // FIXED size after this point, same reasoning as before (not read back
676
- // off ptyProcess after spawn, never resized again - see the
677
- // terminal.resize handler above for why phone-side resize requests are
678
- // still correctly ignored): just a better, size-aware fixed size instead
679
- // of an arbitrary guessed one.
680
- const PTY_COLS = process.stdout.columns || 120;
681
- const PTY_ROWS = process.stdout.rows || 30;
682
-
683
- // Real gap found by testing: Claude Code's full-screen TUI does its own
684
- // absolute-cursor-positioning redraws, which means the raw scrollback
685
- // STRING above (appendScrollback) is not a reliable transcript - earlier
686
- // bytes get visually overwritten by later ones at the byte level (the
687
- // same reason Claude Code's own startup banner disappeared from the
688
- // phone's scrollback once real conversation started: the banner's bytes
689
- // were still THERE in the string, but replaying them through a FRESH
690
- // xterm instance just re-runs the same overwrites, landing on the same
691
- // final picture). The real fix: @xterm/headless is xterm.js's own
692
- // official Node.js package - running a real terminal emulator here,
693
- // fed the IDENTICAL bytes the real PTY produces, maintains an actual,
694
- // always-correct RENDERED buffer, not just a raw byte log. Critically,
695
- // it tracks the NORMAL and ALTERNATE screen buffers separately (see
696
- // node_modules/@xterm/headless/typings - IBuffer.type) - a full-screen
697
- // TUI like Claude Code switches to the alternate buffer when it starts
698
- // (standard terminal behavior every full-screen app relies on), which
699
- // means whatever was in the NORMAL buffer before that (the real startup
700
- // banner, or any plain shell output before Claude Code launched) is
701
- // preserved completely untouched underneath, not overwritten - it's
702
- // just hidden while the alt buffer is active. Reading the normal buffer
703
- // independently (see preservedHistoryText below) means no "detect the
704
- // redraw" logic is needed at all.
705
- // allowProposedApi: true - buffer.normal/buffer.alternate are marked
706
- // EXPERIMENTAL in xterm.js's own typings and throw at runtime without
707
- // this explicit opt-in (confirmed directly: "You must set the
708
- // allowProposedApi option to true to use proposed API").
709
- const headlessTerm = new HeadlessTerminal({ cols: PTY_COLS, rows: PTY_ROWS, scrollback: SCROLLBACK_MAX_BYTES, allowProposedApi: true });
710
-
711
- // Real bug found by testing: term.write() is ASYNCHRONOUS - reading the
712
- // buffer immediately after calling it (no callback, no await) reads
713
- // STALE/EMPTY content, confirmed directly against a real minimal
714
- // reproduction. ptyProcess.onData can fire many times per second, so
715
- // awaiting every single write here would be wasteful - instead, chain
716
- // each write's completion onto the previous one (same pattern this file
717
- // already uses for sendInFlight's own output batching), and have
718
- // anything that needs to READ the buffer (preservedHistoryText, called
719
- // from sendSnapshot) await this chain first, so it's guaranteed caught
720
- // up by the time anyone actually reads it - without slowing down the hot
721
- // onData path at all.
722
- let headlessWriteChain = Promise.resolve();
723
- function writeToHeadlessTerm(data) {
724
- headlessWriteChain = headlessWriteChain.then(
725
- () => new Promise((resolve) => headlessTerm.write(data, resolve))
726
- );
727
- }
728
- async function awaitHeadlessTermCaughtUp() {
729
- await headlessWriteChain;
730
- }
731
-
732
- // Renders a buffer's lines back to plain text - translateToString(true)
733
- // trims trailing whitespace per line, same as how a real terminal looks
734
- // when you select and copy its text.
735
- function bufferToText(buffer) {
736
- const lines = [];
737
- for (let y = 0; y < buffer.length; y++) {
738
- const line = buffer.getLine(y);
739
- if (line) lines.push(line.translateToString(true));
740
- }
741
- return lines.join('\n');
742
- }
743
-
744
- // Real product ask: scrolling up on the phone should show EVERYTHING,
745
- // including content from before the current alt-screen TUI took over.
746
- // Deliberately only ever returns the PRESERVED NORMAL buffer (the
747
- // banner/pre-TUI history) as plain text, to be PREPENDED before the
748
- // existing raw-byte scrollback (see sendSnapshot) - never a replacement
749
- // for it. The live/current content still replays as real ANSI bytes
750
- // through the existing mechanism (term.write() of the raw scrollback
751
- // string), which correctly handles Claude Code's own absolute cursor
752
- // positioning; converting that part to plain text too would lose
753
- // coloring and risk misaligning the cursor position live streaming
754
- // continues from afterward. When the CLI is still on the plain normal
755
- // buffer (hasn't switched to an alt screen at all - e.g. a plain shell
756
- // with no full-screen TUI running), buffer.normal IS buffer.active, so
757
- // this would just duplicate the live scrollback - returns '' in that
758
- // case since there's nothing EXTRA to prepend.
759
- async function preservedHistoryText() {
760
- // Must wait for every queued write to actually apply first - see
761
- // writeToHeadlessTerm's own comment on why reading right after a raw
762
- // write would see stale/empty content.
763
- await awaitHeadlessTermCaughtUp();
764
- if (headlessTerm.buffer.active.type === 'normal') return '';
765
- return bufferToText(headlessTerm.buffer.normal);
766
- }
767
-
768
- let processedLines = 0;
769
- let ptyProcess = null;
770
- let pollTimer = null;
771
- let focusTimer = null;
772
- // No longer an interval (see the on-demand usage.refresh.request handler
773
- // below) - kept as a variable only so ptyProcess.onExit's cleanup has
774
- // something harmless to clearInterval() on, in case a future change ever
775
- // reintroduces a real timer here.
776
- let usageTimer = null;
777
- // Only actually parse PTY output for usage data while this is in the
778
- // future - set a few seconds out each time triggerKeystrokes is sent
779
- // (see below), cleared back to 0 the moment a match is found or the
780
- // window lapses. See the onData handler's usage-polling comment for why
781
- // this window exists at all instead of parsing every chunk forever.
782
- let usageListenUntil = 0;
783
- const USAGE_LISTEN_WINDOW_MS = 10_000;
784
- // Codex-shape usage de-dup (no trigger keystrokes, and no reliable
785
- // persistent status line to gate a check on - see cli-adapters/codex.js
786
- // and the onData handler's comment on why every chunk gets checked) -
787
- // only reports to the Backend when the parsed percentage actually
788
- // CHANGES, not on every chunk that happens to still show the same
789
- // still-rendered text.
790
- let lastReportedCodexContextPct = null;
791
- // Which onboarding gate (by `reason`) was last auto-answered - null once
792
- // no gate is currently on-screen. Identity-based, not time-based (see the
793
- // onData handler's comment for why a timer cooldown re-fired incorrectly
794
- // in testing) - re-answers only when a DIFFERENT gate appears, or the
795
- // same one reappears after genuinely clearing.
796
- let lastOnboardingAnswered = null;
797
- // De-dupes a Codex approval prompt that's still on-screen (and therefore
798
- // still matching detectApproval) across many chunks, vs. a genuinely NEW
799
- // prompt appearing - see cli-adapters/codex.js's detectApproval comment.
800
- let lastApprovalFingerprint = null;
801
-
802
- // Best-effort - a dropped usage report just means Profile/Devices show a
803
- // slightly stale number until the next successful poll, same "core
804
- // function survives an enhancement failing" principle used everywhere
805
- // else in this app (push notifications, profile fetch, etc.).
806
- async function reportUsage(parsed) {
807
- if (!deviceId) return;
808
- try {
809
- await fetch(`${AUTH_SERVER}/device/usage`, {
810
- method: 'POST',
811
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
812
- body: JSON.stringify({
813
- cliType: adapter.id,
814
- totalTokens: parsed.totalTokens,
815
- inputTokens: parsed.inputTokens,
816
- outputTokens: parsed.outputTokens,
817
- costUsd: parsed.costUsd,
818
- contextUsedPct: parsed.sessionContextUsedPct,
819
- weekUsedPct: parsed.weekUsedPct,
820
- sessionResetsAt: parsed.sessionResetsAt,
821
- weekResetsAt: parsed.weekResetsAt,
822
- }),
823
- });
824
- log(`[supervisor] Reported usage: ${JSON.stringify(parsed)}`);
825
- } catch (err) {
826
- log('[supervisor] Failed to report usage:', err.message);
827
- }
828
- }
829
-
830
- // Laptop battery-low warning - reads Windows' own Win32_Battery WMI
831
- // class via a PowerShell one-liner (verified live: returns a real
832
- // EstimatedChargeRemaining percentage on a real laptop; returns NOTHING
833
- // at all on a desktop with no battery, which is exactly the "just skip
834
- // this feature there" behavior wanted - no separate desktop-detection
835
- // logic needed). Not a Node package - node's own APIs have no battery
836
- // reading at all, and this needs zero new dependencies.
837
- const BATTERY_LOW_THRESHOLD_PCT = 20;
838
- const BATTERY_POLL_INTERVAL_MS = 5 * 60_000;
839
- let batteryTimer = null;
840
- // Tracks whether the LAST reading was already below the threshold, so
841
- // the alert fires once per crossing (unplugged and draining past 20%)
842
- // rather than every single 5-minute poll for as long as the battery
843
- // stays low - repeating the same "your laptop is low" push every 5
844
- // minutes while someone's already aware and mid-charge (or just hasn't
845
- // gotten to a charger yet) would be pure noise, not a useful alert.
846
- let wasBatteryLow = false;
847
-
848
- function checkBatteryOnce() {
849
- exec(
850
- 'powershell -NoProfile -Command "Get-CimInstance -ClassName Win32_Battery | Select-Object -ExpandProperty EstimatedChargeRemaining"',
851
- { timeout: 10_000 },
852
- (err, stdout) => {
853
- if (err) return; // no battery (desktop), PowerShell unavailable, etc. - silently skip, not an error worth logging every 5 minutes
854
- const pct = Number(String(stdout).trim());
855
- if (!Number.isFinite(pct)) return;
856
-
857
- const isLow = pct < BATTERY_LOW_THRESHOLD_PCT;
858
- if (isLow && !wasBatteryLow) {
859
- log(`[supervisor] Battery low: ${pct}% - sending alert`);
860
- if (deviceId) {
861
- fetch(`${AUTH_SERVER}/device/battery-alert`, {
862
- method: 'POST',
863
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
864
- body: JSON.stringify({ batteryPct: pct }),
865
- }).catch((fetchErr) => log('[supervisor] Failed to send battery alert:', fetchErr.message));
866
- }
867
- }
868
- wasBatteryLow = isLow;
869
- }
870
- );
871
- }
872
-
873
- async function pollForRequests() {
874
- // No queue file for this adapter (approvals: null - generic CLI or
875
- // Codex's plain-PTY mode) means there is nothing to poll: this CLI has
876
- // no known mechanism to report a prompt before it happens, so the human
877
- // just answers it directly in the mirrored terminal, with no
878
- // structured Confirmations card ever generated for it.
879
- if (!azureReady || !QUEUE_FILE) return;
880
-
881
- let raw;
882
- try {
883
- raw = fs.readFileSync(QUEUE_FILE, 'utf8');
884
- } catch {
885
- return;
886
- }
887
-
888
- const lines = raw.split('\n').filter(Boolean);
889
- if (lines.length <= processedLines) return;
890
-
891
- const newLines = lines.slice(processedLines);
892
- processedLines = lines.length;
893
-
894
- for (const line of newLines) {
895
- let event;
896
- try {
897
- event = JSON.parse(line);
898
- } catch {
899
- continue;
900
- }
901
-
902
- if (event.hook_event_name === 'PostToolUse') {
903
- resolveIfPending(event);
904
- continue;
905
- }
906
-
907
- const options = await resolveRealOptions(event);
908
- const text = claudeAdapter.approvals.describePrompt(event);
909
- await relayApproval(event, options, text);
910
- }
911
- }
912
-
913
- // Real bug found by testing: getDialogOptions' Write/Bash/PowerShell
914
- // option sets are a hardcoded guess (the hook payload never carries the
915
- // real menu for those tool types) - it drifted the moment Claude Code
916
- // added a 4th choice ("switch to auto mode") to its own menu, showing the
917
- // phone 3 buttons for a real 4-option prompt. adapter.approvals.
918
- // parseLiveOptions reads the ACTUAL rendered menu from the terminal
919
- // instead, but PermissionRequest fires BEFORE the prompt is drawn on
920
- // screen (see this file's own top comment) - so a short retry loop here
921
- // gives the PTY time to actually render it before ever falling back to
922
- // the static guess. Skipped entirely for AskUserQuestion, whose real
923
- // options DO come through the hook payload already (getDialogOptions
924
- // reads tool_input.questions[0].options directly) - no need to wait on
925
- // a screen render for a case that's already exact.
926
- async function resolveRealOptions(event) {
927
- if (!claudeAdapter.approvals.parseLiveOptions || event.tool_name === 'AskUserQuestion') {
928
- return claudeAdapter.approvals.getDialogOptions(event);
929
- }
930
- for (let attempt = 0; attempt < 8; attempt++) {
931
- const live = claudeAdapter.approvals.parseLiveOptions(scrollback.slice(-3000));
932
- if (live) return live;
933
- await new Promise((r) => setTimeout(r, 150));
934
- }
935
- log('[supervisor] Live menu did not render in time - falling back to the static guess for this prompt.');
936
- return claudeAdapter.approvals.getDialogOptions(event);
937
- }
938
-
939
- // Real gap found by testing: a prompt answered directly at the laptop's
940
- // own keyboard (never via the phone) left its card stuck "pending"
941
- // forever on the phone, since nothing ever told the Backend the tool
942
- // actually ran. PostToolUse only fires once a tool call actually
943
- // executes - which can only happen after ITS permission prompt was
944
- // answered somehow, locally or remotely - so a PostToolUse for the same
945
- // tool_name + session_id we're still holding pending is real proof that
946
- // prompt got resolved. Matched on tool_name + session_id rather than
947
- // exact tool_input equality - Claude Code's PostToolUse payload doesn't
948
- // echo back tool_input in a byte-identical shape to PermissionRequest's,
949
- // and two DIFFERENT pending prompts for the exact same tool_name in the
950
- // exact same session (e.g. two Bash calls in a row) resolve in the order
951
- // they were opened either way, so ambiguity here is harmless.
952
- function reportResolvedLocally(promptId, reason) {
953
- log(`[supervisor] ${promptId} resolved locally (${reason}) - notifying Backend.`);
954
- fetch(`${AUTH_SERVER}/relay/confirmation-resolved-locally`, {
955
- method: 'POST',
956
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
957
- body: JSON.stringify({ sessionId: SESSION_ID, promptId }),
958
- }).catch((err) => log('[supervisor] Failed to report local resolution:', err.message));
959
- }
960
-
961
- // Extracts a real identity for one AskUserQuestion prompt - its actual
962
- // question text, not just "this session asked SOMETHING". Undefined for
963
- // every other tool_name, which is fine: those never fire two pending
964
- // prompts back-to-back for the same session the way AskUserQuestion can
965
- // (see resolveIfPending's own comment).
966
- function askUserQuestionKey(event) {
967
- return event.tool_input?.questions?.[0]?.question;
968
- }
969
-
970
- function resolveIfPending(postToolUseEvent) {
971
- // Real bug found by testing: matching on tool_name + session_id alone
972
- // resolved whichever pending prompt happened to be found FIRST in the
973
- // Map, not necessarily the one that actually just got answered.
974
- // AskUserQuestion specifically can have two genuinely different
975
- // pending questions in flight for the SAME session at once - rejecting
976
- // one often makes Claude Code immediately ask a related follow-up
977
- // question before the first prompt's PostToolUse even fires - so this
978
- // ambiguity isn't a rare edge case for it, it's a real, observed
979
- // sequence. Matching on the actual question text (when available)
980
- // instead of just tool_name+session_id resolves the CORRECT one even
981
- // when two are pending at once; falls back to the old less-precise
982
- // match for every other tool_name, where this ambiguity doesn't arise.
983
- const postKey = askUserQuestionKey(postToolUseEvent);
984
- for (const [promptId, pending] of pendingPrompts.entries()) {
985
- if (pending.session_id !== postToolUseEvent.session_id) continue;
986
- if (pending.tool_name !== postToolUseEvent.tool_name) continue;
987
- if (postKey && askUserQuestionKey(pending) && askUserQuestionKey(pending) !== postKey) continue;
988
- pendingPrompts.delete(promptId);
989
- reportResolvedLocally(promptId, `PostToolUse for ${postToolUseEvent.tool_name}`);
990
- return;
991
- }
992
- }
993
-
994
- // Real gap found by testing: an APPROVED prompt gets a PostToolUse event
995
- // (resolveIfPending above catches it), but a REJECTED/interrupted one
996
- // never does - the tool call never ran, so there's no "it ran" signal to
997
- // observe at all. The one thing that IS still true: Claude Code only ever
998
- // has ONE open prompt per session at a time, so a genuinely NEW
999
- // PermissionRequest arriving for a session is real proof any OLDER
1000
- // pending prompt in that same session is no longer live - it was
1001
- // rejected, interrupted, or otherwise handled, by definition, since
1002
- // Claude Code moved on. Called right before relaying the new prompt.
1003
- function resolveStaleForSession(sessionId, reason = 'a newer prompt arrived for the same session') {
1004
- for (const [promptId, pending] of pendingPrompts.entries()) {
1005
- if (pending.session_id === sessionId) {
1006
- pendingPrompts.delete(promptId);
1007
- reportResolvedLocally(promptId, reason);
1008
- }
1009
- }
1010
- }
1011
-
1012
- // Shared by both approval-detection mechanisms (Claude Code's hook-queue
1013
- // polling above, and Codex's PTY-scrape detection below) - same
1014
- // pendingPrompts bookkeeping and /relay/confirmation-request call either
1015
- // way, since from the phone's perspective a confirmation card looks
1016
- // identical regardless of which CLI/detection method produced it.
1017
- async function relayApproval(event, options, text) {
1018
- // See resolveStaleForSession's own comment - a new prompt for this
1019
- // session means any older one we're still holding pending is stale.
1020
- resolveStaleForSession(event.session_id);
1021
-
1022
- // Real bug found by testing: Date.now() alone collides when two
1023
- // separate supervisor processes (different laptops/sessions) detect a
1024
- // prompt in the same millisecond - the phone's seenPromptIds dedup then
1025
- // treats the second, genuinely different prompt as a duplicate of the
1026
- // first and drops it, or conflates their responses. DEVICE_NAME makes
1027
- // the id unique per-process even under a same-millisecond collision.
1028
- const promptId = `p-${DEVICE_NAME}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1029
- pendingPrompts.set(promptId, { ...event, options });
1030
-
1031
- log(`[supervisor] Detected approval prompt: ${text}`);
1032
- log(`[supervisor] Relaying to auth-server as promptId=${promptId}...`);
1033
-
1034
- try {
1035
- const res = await fetch(`${AUTH_SERVER}/relay/confirmation-request`, {
1036
- method: 'POST',
1037
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
1038
- body: JSON.stringify({
1039
- sessionId: SESSION_ID,
1040
- promptId,
1041
- text,
1042
- options: options.map(({ label, style }) => ({ label, style })),
1043
- }),
1044
- });
1045
- if (!res.ok) {
1046
- const err = await res.json().catch(() => ({}));
1047
- log('[supervisor] Relay failed:', err.error || res.status);
1048
- }
1049
- } catch (err) {
1050
- log('[supervisor] Failed to reach auth-server:', err.message);
1051
- }
1052
-
1053
- // Real gap found by testing: an APPROVED Bash/Write/PowerShell prompt
1054
- // gets a PostToolUse event (resolveIfPending), but a REJECTED one
1055
- // doesn't - the tool never ran, so there's nothing to hook. Several
1056
- // attempts at matching Claude Code's own rejection wording proved
1057
- // unreliable (see cli-adapters/claude.js's isMenuStillOnScreen
1058
- // comment). This instead polls whether the SAME menu is still
1059
- // physically on screen - once it isn't, a decision happened (approved,
1060
- // rejected, or interrupted, doesn't matter which) and the prompt is
1061
- // resolved. Skipped for AskUserQuestion, which already resolves
1062
- // reliably and precisely via PostToolUse's exact question-text match -
1063
- // this cruder "is ANY proceed-style menu gone" check would be a
1064
- // downgrade for that tool_name, not an improvement.
1065
- if (claudeAdapter.approvals.isMenuStillOnScreen && event.tool_name !== 'AskUserQuestion') {
1066
- watchForMenuDisappearance(promptId);
1067
- }
1068
- }
1069
-
1070
- // Polls every 500ms for up to 5 minutes (a real user can genuinely take
1071
- // that long to decide) - stops early the moment isMenuStillOnScreen
1072
- // returns false, or the moment this promptId is no longer pending at all
1073
- // (already resolved through the phone, PostToolUse, or a newer prompt -
1074
- // no point continuing to poll something that's already been handled).
1075
- async function watchForMenuDisappearance(promptId) {
1076
- const deadline = Date.now() + 5 * 60_000;
1077
- while (Date.now() < deadline) {
1078
- await new Promise((r) => setTimeout(r, 500));
1079
- if (!pendingPrompts.has(promptId)) return; // already resolved some other way
1080
- if (!claudeAdapter.approvals.isMenuStillOnScreen(scrollback.slice(-3000))) {
1081
- pendingPrompts.delete(promptId);
1082
- reportResolvedLocally(promptId, 'the on-screen menu is gone - resolved locally (approved, rejected, or interrupted)');
1083
- return;
1084
- }
1085
- }
1086
- }
1087
-
1088
- // Codex-specific entry point (cli-adapters/codex.js's sourceMode:
1089
- // 'pty-scrape') - called from the onData handler once detectApproval
1090
- // finds a NEW (not-yet-seen) prompt in the scrollback window.
1091
- function handleDetectedApproval(detected) {
1092
- const options = adapter.approvals.getDialogOptions(detected);
1093
- const text = adapter.approvals.describePrompt(detected);
1094
- relayApproval(detected, options, text);
1095
- }
1096
-
1097
- // Real gap found by testing: a laptop-side warning used to fire here any
1098
- // time another setu was already running for the same folder - built
1099
- // before the real enforcement below existed, to catch accidental
1100
- // duplicates. Removed: running a 2nd session in the same folder is
1101
- // explicitly an ALLOWED product rule (2 live sessions per device - see
1102
- // auth-server.js's PLAN_LIMITS.maxLiveSessions, now scoped per-device),
1103
- // so warning about it read alarmingly for something that's actually
1104
- // fine, and the real safety net now exists at the backend: /device/
1105
- // connect itself rejects a 3rd session for this device with a clear
1106
- // error message, before it ever gets a usable connection - a stronger,
1107
- // more reliable guarantee than a laptop-side warning a user could miss
1108
- // or click past anyway.
1109
- async function main() {
1110
- if (QUEUE_FILE) fs.writeFileSync(QUEUE_FILE, '');
1111
- fs.writeFileSync(PROCESSED_FILE, '');
1112
-
1113
- console.log(`\n[supervisor] Spawning ${adapter.displayName} in a PTY (device=${DEVICE_NAME}, session=${SESSION_ID}, cwd=${WORKING_DIR})...`);
1114
-
1115
- try {
1116
- ptyProcess = pty.spawn(adapter.spawn.command, adapter.spawn.args(WORKING_DIR), {
1117
- name: 'xterm-color',
1118
- cols: PTY_COLS,
1119
- rows: PTY_ROWS,
1120
- cwd: WORKING_DIR,
1121
- env: process.env,
1122
- });
1123
- } catch (err) {
1124
- // Real bug found by testing (PM report, multiple real macOS users):
1125
- // node-pty's spawn() can still throw an opaque native error (e.g.
1126
- // "posix_spawnp failed") for reasons shell.js's own path validation
1127
- // doesn't cover - a CLI adapter (claude/codex) genuinely not
1128
- // installed/on PATH, a cwd the OS won't let this process enter, a
1129
- // sandboxed/restricted environment. Previously this propagated all
1130
- // the way up to main().catch's generic "[supervisor] fatal: <msg>"
1131
- // with zero context about WHAT was being spawned or WHERE - telling
1132
- // the user only that something failed, never why. Re-throwing with
1133
- // the actual command and cwd attached turns that into an actionable
1134
- // message instead of a dead end.
1135
- throw new Error(`Could not start "${adapter.spawn.command}" in ${WORKING_DIR}: ${err.message}`);
1136
- }
1137
-
1138
- ptyProcess.onData((data) => {
1139
- process.stdout.write(data);
1140
-
1141
- // Section 4c call ① -> the scrollback (Section 7) is kept regardless
1142
- // of whether anyone's watching, so a phone attaching later still gets
1143
- // real history, not just whatever arrives after it connects.
1144
- appendScrollback(data);
1145
- // Fed the IDENTICAL bytes as the real PTY, in the same order - see
1146
- // headlessTerm's own declaration comment for why this (not the raw
1147
- // scrollback string above) is what makes a genuinely complete
1148
- // transcript possible. writeToHeadlessTerm (not a direct .write()
1149
- // call) queues this safely - see its own comment on why reading the
1150
- // buffer right after a raw write would see stale/empty content.
1151
- writeToHeadlessTerm(data);
1152
-
1153
- // Real gap found by testing: gating live streaming on isFocused (only
1154
- // spend a request if a phone is CURRENTLY looking at this session)
1155
- // meant anything that happened while the user was on a different tab,
1156
- // or had the app backgrounded, was never streamed live - only
1157
- // recoverable later via the one-time scrollback snapshot on next
1158
- // attach, which truncates past SCROLLBACK_MAX_BYTES and in practice
1159
- // left real conversation history missing from what should be a
1160
- // complete mirror. The whole point of this feature is "the phone's
1161
- // terminal shows the exact same thing scrolling up as the real
1162
- // laptop terminal does" - a cost optimization that can silently drop
1163
- // real content contradicts that, so this now always streams
1164
- // regardless of isFocused (kept only for the Devices tab's online
1165
- // heartbeat - see pollFocus's own comment).
1166
- streamOutput(data);
1167
-
1168
- // Usage polling (see cli-adapters/claude.js) - only ever active for
1169
- // an adapter that defines usage.parseFromOutput; every other adapter
1170
- // leaves usageState untouched and Devices/Profile just show nothing
1171
- // for token usage, same "optional richness" pattern as approvals.
1172
- //
1173
- // Real bug found by testing: parsing each raw `data` chunk in
1174
- // isolation silently failed most of the time - a PTY streams output
1175
- // in small, arbitrarily-split pieces (this is exactly why
1176
- // TerminalScreen.js's own out-of-order chunk sequencing exists), and
1177
- // `/cost`'s multi-line render (the "58% used" text, the "Resets ..."
1178
- // line right after it) is not guaranteed to land in one chunk. A
1179
- // regex against a single chunk that happens to end mid-render just
1180
- // never matches, with no error - it looked like "auto-refresh isn't
1181
- // working" from the phone side when the real gap was here. Matching
1182
- // against a trailing window of the already-accumulated scrollback
1183
- // instead guarantees the full rendered output is visible regardless
1184
- // of how the PTY happened to chunk it.
1185
- //
1186
- // Gated to a short window after triggerKeystrokes was actually sent
1187
- // (usageListenUntil) rather than running on every chunk for the
1188
- // entire session - re-running 6 regexes against a 4KB window on
1189
- // every single byte the CLI ever prints (a long response streams
1190
- // MANY chunks) would be pure waste outside the brief moment right
1191
- // after we actually asked for a fresh reading.
1192
- if (adapter.usage?.parseFromOutput) {
1193
- if (adapter.usage.triggerKeystrokes) {
1194
- // Claude Code shape: only worth checking right after we actually
1195
- // asked for a fresh reading (see usageListenUntil above).
1196
- if (Date.now() < usageListenUntil) {
1197
- const recentWindow = scrollback.slice(-4000);
1198
- const parsed = adapter.usage.parseFromOutput(recentWindow);
1199
- if (parsed) {
1200
- reportUsage(parsed);
1201
- usageListenUntil = 0; // got it - stop checking until the next trigger
1202
- // Real feedback: /cost's full-screen usage report otherwise
1203
- // sits visible in the person's own terminal after an
1204
- // on-demand refresh, showing exactly what just happened
1205
- // behind the scenes - not something a remote refresh should
1206
- // leave lying around for whoever's physically at the laptop
1207
- // to wonder about. Esc is the standard way Claude Code's own
1208
- // full-screen views (Usage/Config/Status) are dismissed
1209
- // elsewhere in this CLI - NOT independently re-verified
1210
- // against this exact /cost screen in this session, so treat
1211
- // this as the first real test of that assumption, not a
1212
- // confirmed fact. Same mechanism as the approval
1213
- // auto-injection above (ptyProcess.write with a real
1214
- // keystroke), nothing new.
1215
- ptyProcess.write('\x1b');
1216
- }
1217
- }
1218
- } else {
1219
- // Codex shape (cli-adapters/codex.js) - real bug found by live
1220
- // testing: "% context left" is NOT a persistent, always-visible
1221
- // status line the way the first version of this comment assumed.
1222
- // It only renders for a brief moment right after a turn finishes,
1223
- // while the input box is idle-focused ("tab to queue message ...
1224
- // NN% context left") - gone again as soon as the next prompt is
1225
- // typed or another turn starts. A 5-minute throttle (copied from
1226
- // Claude Code's shape, where /cost is manually triggered and its
1227
- // output persists on screen) missed this window almost every
1228
- // time in testing - across several real approved turns, usage
1229
- // was never once recorded, because the 5-minute cooldown was
1230
- // still active during the one brief moment the text existed.
1231
- // There's no reliable trigger to key a narrower check off (see
1232
- // README.md), so the only option that actually works is checking
1233
- // EVERY chunk - affordable here since this is one small regex,
1234
- // not Claude Code's six-regex /cost parse.
1235
- const recentWindow = scrollback.slice(-4000);
1236
- const parsed = adapter.usage.parseFromOutput(recentWindow);
1237
- // De-duped by the actual percentage, not a timer - the same
1238
- // "100% context left" render can appear across several
1239
- // consecutive chunks before Codex's next redraw changes it,
1240
- // and reporting on every one of those would spam
1241
- // /device/usage with identical, redundant POSTs.
1242
- if (parsed && parsed.sessionContextUsedPct !== lastReportedCodexContextPct) {
1243
- lastReportedCodexContextPct = parsed.sessionContextUsedPct;
1244
- reportUsage(parsed);
1245
- }
1246
- }
1247
- }
1248
-
1249
- // Approval detection for an adapter using PTY-text scraping instead
1250
- // of a hook queue (see cli-adapters/codex.js's sourceMode) - Claude
1251
- // Code's approvals flow through pollForRequests/QUEUE_FILE instead;
1252
- // this branch is a no-op for any adapter without approvals.sourceMode
1253
- // === 'pty-scrape' (Claude Code, generic, or an adapter with
1254
- // approvals: null entirely).
1255
- if (adapter.approvals?.sourceMode === 'pty-scrape' && azureReady) {
1256
- const recentWindow = scrollback.slice(-4000);
1257
-
1258
- const onboarding = adapter.approvals.autoAnswerOnboarding(recentWindow);
1259
- if (onboarding && onboarding.reason !== lastOnboardingAnswered) {
1260
- // Real bug found by testing: a time-based cooldown (originally
1261
- // 2s) re-fired repeatedly on the SAME still-on-screen gate,
1262
- // sometimes minutes apart - the screen can stay rendered in the
1263
- // scrollback window far longer than any short cooldown, since
1264
- // it's real elapsed wall-clock time until Codex actually
1265
- // processes the keystroke and redraws, not a fixed delay.
1266
- // Tracking WHICH gate (by reason) was last answered instead of a
1267
- // timer means it's answered exactly once and never re-sent until
1268
- // a genuinely DIFFERENT gate (or none) appears - each extra
1269
- // stray keypress risked landing on the real chat input once the
1270
- // gate actually cleared.
1271
- lastOnboardingAnswered = onboarding.reason;
1272
- log(`[supervisor] Auto-answering Codex onboarding gate: ${onboarding.reason}`);
1273
- ptyProcess.write(onboarding.keystrokes);
1274
- } else if (!onboarding) {
1275
- lastOnboardingAnswered = null; // gate cleared - a future recurrence should be answered again
1276
- const detected = adapter.approvals.detectApproval(recentWindow);
1277
- if (detected && detected.fingerprint !== lastApprovalFingerprint) {
1278
- lastApprovalFingerprint = detected.fingerprint;
1279
- handleDetectedApproval(detected);
1280
- }
1281
- }
1282
- }
1283
-
1284
- // Real gap found by testing: an APPROVED prompt gets a real
1285
- // PostToolUse hook event to key off of (resolveIfPending above), but
1286
- // a REJECTED/interrupted one produces no hook event at all - the tool
1287
- // call never ran. A PTY-text-scan for Claude Code's own "Interrupted..."
1288
- // wording was tried here and removed again - real captured terminal
1289
- // output across several live rejection tests never actually contained
1290
- // that literal text in a form the regex could reliably match (Claude
1291
- // Code doesn't render it consistently enough to key off of). Left as
1292
- // the reliable fallback instead: a rejected prompt clears once ANOTHER
1293
- // prompt arrives for the same session (resolveStaleForSession, called
1294
- // from relayApproval below) - not instant, but proven correct across
1295
- // testing, unlike the PTY-scan attempt.
1296
- });
1297
-
1298
- ptyProcess.onExit(({ exitCode }) => {
1299
- console.log(`\n[supervisor] ${adapter.displayName} exited with code ${exitCode}`);
1300
- if (pollTimer) clearInterval(pollTimer);
1301
- if (focusTimer) clearInterval(focusTimer);
1302
- if (usageTimer) clearInterval(usageTimer);
1303
- if (batteryTimer) clearInterval(batteryTimer);
1304
- if (ws) ws.close();
1305
- process.exit(exitCode || 0);
1306
- });
1307
-
1308
- // Real feedback: an automatic timer used to run here (every 5 minutes,
1309
- // unconditionally) asking the session for a fresh /cost reading -
1310
- // removed after live testing showed it genuinely disrupting someone
1311
- // actively working at the laptop, taking over their visible terminal
1312
- // with a full-screen usage report on a schedule nobody asked for. Usage
1313
- // now only ever refreshes on an explicit request from the phone (see
1314
- // this file's 'usage.refresh.request' handler above) - the SAME
1315
- // triggerKeystrokes mechanism, just fired on demand instead of blind
1316
- // polling. usageTimer is kept defined (see its own comment above) so
1317
- // ptyProcess.onExit's cleanup still has a valid, harmless no-op target.
1318
-
1319
- pollTimer = setInterval(pollForRequests, POLL_INTERVAL_MS);
1320
- // Real bug found by testing (PM report: "device shows offline after
1321
- // connecting"): focusTimer used to start HERE, unconditionally, before
1322
- // connectToAzure() (called at the bottom of this function, unawaited)
1323
- // had any chance to resolve its /device/connect call and set the real
1324
- // deviceId below. pollFocus's own deviceId-aware URL building silently
1325
- // omits the heartbeat whenever deviceId is still null - harmless for a
1326
- // couple of ticks on a normal fast connect, but genuinely persistent
1327
- // (heartbeat omitted for the ENTIRE outage) whenever /device/connect is
1328
- // stuck in its own 3s retry loop (network hiccup, backend restart) -
1329
- // every tick silently did nothing, with no visible error, for as long
1330
- // as that retry loop ran. Moved to start right where deviceId itself
1331
- // gets set, inside connectToAzure() (see its own comment there) -
1332
- // "Offline" on the phone now correctly means "genuinely not
1333
- // connected," never "connected, but the heartbeat hasn't started yet."
1334
- // CLI-agnostic - runs for every adapter (Claude Code, Codex, generic),
1335
- // since battery is a property of the LAPTOP, not of whatever CLI it
1336
- // happens to be running.
1337
- checkBatteryOnce(); // one immediate reading at startup, not just 5 min later
1338
- batteryTimer = setInterval(checkBatteryOnce, BATTERY_POLL_INTERVAL_MS);
1339
-
1340
- process.stdin.setRawMode(true);
1341
- process.stdin.resume();
1342
- process.stdin.on('data', (data) => ptyProcess.write(data.toString()));
1343
-
1344
- // Real gap in the PoC this replaces: there was no way for `cli-setu status`
1345
- // or `cli-setu stop` (both new - see src/status.js, src/stop.js) to know
1346
- // whether a session watcher was even running, or on which PID, since
1347
- // supervisor-qr.js was always started and killed by hand in a visible
1348
- // terminal. One small PID file per running session (keyed by
1349
- // SESSION_ID, since one paired device can run several sessions at
1350
- // once) - written here at startup, removed on every real exit path.
1351
- const pidFile = path.join(CONFIG_DIR, `session.${SESSION_ID}.pid`);
1352
- fs.writeFileSync(pidFile, JSON.stringify({ pid: process.pid, deviceName: DEVICE_NAME, sessionId: SESSION_ID, cwd: WORKING_DIR, startedAt: new Date().toISOString() }, null, 2));
1353
- const removePidFile = () => { try { fs.unlinkSync(pidFile); } catch {} };
1354
-
1355
- process.on('SIGINT', () => {
1356
- ptyProcess.kill();
1357
- if (ws) ws.close();
1358
- removePidFile();
1359
- process.exit(0);
1360
- });
1361
- process.on('exit', removePidFile);
1362
-
1363
- connectToAzure();
1364
- }
1365
-
1366
- main().catch((err) => {
1367
- console.error('[supervisor] fatal:', err.message);
1368
- process.exit(1);
1369
- });
1
+ // QR pairing (unchanged) PLUS Phase 6 full terminal mirroring:
2
+ // - Device never paired before -> the QR both pairs it AND jumps the
3
+ // phone straight to watching THIS session (scan.html + auth-server.js's
4
+ // /device/pair/qr-confirm do both in one round trip).
5
+ // - Device already paired -> same QR mechanism, but auth-server.js skips
6
+ // re-pairing and the scan just means "watch this session on the phone."
7
+ // - EVERY byte the PTY produces is streamed live to Azure whenever a
8
+ // phone has terminal.html open and focused on this session (Section
9
+ // 11f) - not just detected confirmation prompts. Unfocused, nothing
10
+ // extra streams; the confirmation-request path is completely
11
+ // unaffected either way.
12
+ // - Remote input (typed on the phone) and remote resize both write
13
+ // straight into this PTY, same as a local keystroke or a dragged
14
+ // terminal window edge.
15
+ //
16
+ // Run via the real CLI entry point (bin/setu.js), never directly:
17
+ // cli-setu session bridges a plain shell in this folder
18
+ // cli-setu session --cli claude bridges Claude Code in this folder
19
+ // cli-setu session --cli codex bridges Codex CLI in this folder
20
+ // Requires this device to already be paired (`cli-setu pair` first - see
21
+ // SETU-001) - this file's own top-of-file guard exits with a clear message
22
+ // otherwise, rather than ever starting a session on an unpaired device.
23
+ //
24
+ // --cli defaults to 'shell' (a plain bridged terminal, not any specific
25
+ // CLI - see CLI_NAME's own declaration below). Any name not in
26
+ // cli-adapters/index.js's KNOWN_ADAPTERS still runs - it just gets the
27
+ // generic PTY-only adapter (mirrored terminal, no structured Confirmations
28
+ // card, no usage tracking) instead of refusing to start. See
29
+ // cli-adapters/README.md for the adapter interface this script drives.
30
+
31
+ const pty = require('node-pty');
32
+ const { Terminal: HeadlessTerminal } = require('@xterm/headless');
33
+ const fs = require('fs');
34
+ const path = require('path');
35
+ const WebSocket = require('ws');
36
+ const { exec } = require('child_process');
37
+ const { getAdapter } = require('./cli-adapters');
38
+ const { getGitDiff } = require('./gitDiff');
39
+ const setuCrypto = require('./crypto');
40
+ const { splitIntoParts, trimSnapshot, limitForProvider } = require('./transportSplit');
41
+ const { createReconnectManager, WARN_AFTER_ATTEMPTS } = require('./reconnect');
42
+ const { createDedupCache } = require('./dedup');
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');
48
+
49
+ // Real bug found by testing: this script's own console.log/console.error
50
+ // calls write to the SAME process.stdout the PTY's raw output is echoed
51
+ // to (see ptyProcess.onData below). Claude Code's TUI does full-screen
52
+ // ANSI cursor positioning and assumes exclusive control of the terminal's
53
+ // screen buffer - any plain text interleaved into that stream mid-redraw
54
+ // (e.g. the "Azure decision..." log firing while a menu is on screen)
55
+ // corrupts its cursor-position math, visible as duplicated headers,
56
+ // garbled/overlapping lines, and log text bleeding into the TUI's own
57
+ // chrome. Once the PTY is running, ALL supervisor diagnostics go to a log
58
+ // file instead - stdout is reserved exclusively for the PTY passthrough
59
+ // from that point on.
60
+ const os = require('os');
61
+ const crypto = require('crypto');
62
+ const { readConfig, writeConfig, CONFIG_DIR } = require('./config');
63
+
64
+ // Real gap in the proof-of-concept this replaces: every run required
65
+ // typing <deviceName> <sessionId> as argv, and diagnostics went to a log
66
+ // file sitting in the install folder. A real global install (`npm install
67
+ // -g cli-setu`) has no single "install folder" a user would think to look
68
+ // in, and every session's log lived in ~/.cli-setu instead - one file per
69
+ // PAIRED DEVICE is still right (see the original comment this replaces:
70
+ // keeps a Claude Code session and a Codex session from interleaving into
71
+ // one indistinguishable file), just relocated to a real per-user config
72
+ // directory instead of wherever npm happened to install the package.
73
+ let LOG_FILE = path.join(CONFIG_DIR, 'supervisor.log');
74
+ function log(...args) {
75
+ const line = `[${new Date().toISOString()}] ${args.join(' ')}\n`;
76
+ fs.appendFileSync(LOG_FILE, line);
77
+ }
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
+
104
+ // Real config, from pairing (src/pair.js, via the explicit `cli-setu pair`
105
+ // command - see SETU-001: pairing and session creation are two distinct
106
+ // steps now, bin/setu.js's `session` subcommand never pairs on its own
107
+ // behalf). This is the guard that makes SETU-001's "session without
108
+ // pairing must NOT create an unauthorized session" requirement real: a
109
+ // null deviceToken fails here, before any PTY/session registration ever
110
+ // happens, with a clear message instead of a confusing crash deep in
111
+ // connectToAzure().
112
+ const config = readConfig();
113
+ if (!config || !config.deviceToken) {
114
+ console.error('[cli-setu] This computer isn\'t paired yet. Run `cli-setu pair` first, then `cli-setu session`.');
115
+ process.exit(1);
116
+ }
117
+ const DEVICE_NAME = config.deviceName;
118
+
119
+ // TEMPORARY: defaults to the DEV server, not production - see bin/setu.js's
120
+ // matching comment. Must switch back to https://api.clisetu.com before
121
+ // treating this package as production-ready for real users.
122
+ const AUTH_SERVER = process.env.CLI_SETU_SERVER || 'https://dev-api.clisetu.com';
123
+
124
+ // --cli still supported, e.g. `cli-setu session --cli codex` (SETU-001/
125
+ //018: now a flag on the `session` subcommand, not the bare command
126
+ // itself - this file is only ever require()'d from bin/setu.js's own
127
+ // `session` case, so process.argv here is still the FULL original
128
+ // invocation and --cli is found exactly the same way regardless), for the
129
+ // same reason it existed before: one paired device can run more than one
130
+ // kind of CLI across different sessions/folders. Real product decision
131
+ // (confirmed directly by the PM): `cli-setu session` with no --cli flag
132
+ // bridges the user's own plain terminal (see cli-adapters/shell.js), not
133
+ // Claude Code by default - the user decides what to run once it's open,
134
+ // same as getAdapter's own default (index.js) - kept in sync here rather
135
+ // than letting this default silently drift from that one.
136
+ const cliFlagIndex = process.argv.indexOf('--cli');
137
+ const CLI_NAME = cliFlagIndex !== -1 ? process.argv[cliFlagIndex + 1] : 'shell';
138
+
139
+ const WORKING_DIR = process.cwd();
140
+ // Real gap in the PoC this replaces: sessionId was a hand-typed argv, a
141
+ // real user shouldn't need to invent one. Derived from the device name
142
+ // plus the real working directory (not just the folder's basename, which
143
+ // collides the moment two different projects share a folder name like
144
+ // "app" on the same machine) plus a short random suffix so re-running
145
+ // `cli-setu` in the same folder twice at once (e.g. two terminal tabs) never
146
+ // silently shares one session.
147
+ const dirHash = crypto.createHash('sha1').update(WORKING_DIR).digest('hex').slice(0, 8);
148
+ const SESSION_ID = `${os.hostname()}-${dirHash}-${crypto.randomBytes(3).toString('hex')}`;
149
+
150
+ // SETU-005: the real identity a duplicate-session check needs - resolves
151
+ // symlinks (fs.realpathSync) so two different-looking paths to the SAME
152
+ // real folder are recognized as identical, and lowercased on Windows
153
+ // (whose filesystem is case-insensitive, unlike Linux/macOS) so
154
+ // "D:\Proj" and "d:\proj" aren't treated as two different folders.
155
+ // realpathSync can throw if WORKING_DIR was deleted out from under this
156
+ // process between startup and here - falls back to the raw WORKING_DIR
157
+ // rather than crashing the whole session over a cosmetic dedup check.
158
+ let CANONICAL_WORKING_DIR;
159
+ try {
160
+ CANONICAL_WORKING_DIR = fs.realpathSync(WORKING_DIR);
161
+ } catch {
162
+ CANONICAL_WORKING_DIR = WORKING_DIR;
163
+ }
164
+ if (process.platform === 'win32') CANONICAL_WORKING_DIR = CANONICAL_WORKING_DIR.toLowerCase();
165
+
166
+ // Per-device log file (see LOG_FILE's declaration comment above) - keeps
167
+ // two supervisors running under the same paired device (e.g. a Claude
168
+ // Code session and a Codex session) from interleaving into one
169
+ // indistinguishable file.
170
+ LOG_FILE = path.join(CONFIG_DIR, `supervisor.${DEVICE_NAME.replace(/[^a-zA-Z0-9-]/g, '_')}.log`);
171
+
172
+ const adapter = getAdapter(CLI_NAME);
173
+ console.log(`[supervisor] 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})`);
175
+
176
+ // Real bug found by testing: when the spawned adapter is 'shell' (the
177
+ // bare-`cli-setu` default - see cli-adapters/shell.js), the user is expected
178
+ // to freely run `claude` INSIDE that bridged shell whenever they want to.
179
+ // Gating hook registration on "is the spawn-time adapter Claude" (as this
180
+ // used to) meant Claude Code's hooks never got installed into
181
+ // WORKING_DIR's .claude/settings.json at all in that case, so no
182
+ // confirmation ever reached the phone once the user actually typed
183
+ // `claude` - the hook-queue mechanism had nothing writing to it. Fixed by
184
+ // always using Claude's own approvals object (queueFileFor,
185
+ // describePrompt, parseLiveOptions, etc.) for the hook-queue path,
186
+ // regardless of which adapter was spawned - the queue file is only ever
187
+ // written by Claude Code's own hooks in the first place, so there's
188
+ // nothing wrong with always registering them defensively. Harmless if the
189
+ // user never runs `claude` in this session: the hook stays installed but
190
+ // silent, since nothing ever calls it.
191
+ const claudeAdapter = require('./cli-adapters/claude');
192
+ const codexAdapter = require('./cli-adapters/codex');
193
+ const QUEUE_FILE = claudeAdapter.approvals.queueFileFor(CONFIG_DIR, WORKING_DIR);
194
+ const PROCESSED_FILE = path.join(CONFIG_DIR, `processed-requests.${SESSION_ID}.json`);
195
+ const POLL_INTERVAL_MS = 300;
196
+
197
+ // Always registered now (see QUEUE_FILE's comment above) - covers both
198
+ // `cli-setu session --cli claude` (adapter itself is Claude) and bare
199
+ // `cli-setu session` / `cli-setu session --cli shell` followed by the
200
+ // user manually running `claude` inside the bridged shell.
201
+ {
202
+ const { ensureHooksRegistered } = require('./hooks');
203
+ ensureHooksRegistered(WORKING_DIR);
204
+ }
205
+
206
+ // Real config, from `cli-setu pair` (src/config.js) - not a per-device-name
207
+ // token file. Pairing is now a separate, one-time command (`cli-setu pair`)
208
+ // that must already have succeeded before this ever runs (checked above,
209
+ // where the process exits early if config.deviceToken is missing) - so
210
+ // unlike the PoC's ensurePaired(), there is no QR-pairing fallback here at
211
+ // all. A session watcher's job is to watch a session, not to also be the
212
+ // pairing flow; keeping them separate is what makes `cli-setu` (bare) not
213
+ // need a QR code/camera every single run.
214
+ let deviceToken = config.deviceToken;
215
+ let deviceId = null;
216
+ let ws = null;
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;
221
+ const pendingPrompts = new Map();
222
+ const approvalDeduper = createApprovalDeduper({ isPending: (id) => pendingPrompts.has(id) });
223
+
224
+ // Real gap found by investigation: both connectToAzure's own retry
225
+ // paths (a failed /device/connect HTTP call, and the WebSocket's own
226
+ // onclose handler) used a FIXED-interval retry forever, with no
227
+ // counter, no backoff, and no visible "still down" signal - see
228
+ // reconnect.js's own comment for exactly why this matters. One shared
229
+ // manager for both, since a /device/connect failure and a dropped
230
+ // WebSocket are the same underlying "not connected right now"
231
+ // condition from this process's perspective - reset() is called the
232
+ // moment a connection actually succeeds (see ws.on('open') below).
233
+ const reconnectManager = createReconnectManager({
234
+ onAttempt: () => connectToAzure(),
235
+ onWarn: (attemptNumber) => {
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 });
237
+ log(`[supervisor] Reconnect warning threshold reached: ${attemptNumber} consecutive failures`);
238
+ },
239
+ log,
240
+ });
241
+
242
+ // Real gap found by investigation: "a terminal command must never
243
+ // execute twice" was an explicit product requirement, but
244
+ // ptyProcess.write(data) in the terminal.input handler below had ZERO
245
+ // deduplication - any redelivery of the same message (Azure's own SDK
246
+ // retry behavior, a future phone-side retry) would type the same
247
+ // keystrokes into the PTY a second time with no way to tell it apart
248
+ // from a genuine second batch. Bounded by COUNT, not just a TTL - a
249
+ // pure time-based cache risks unbounded growth under a burst of
250
+ // distinct messages within one window; capping the actual entry count
251
+ // is the harder guarantee. FIFO eviction (insertion order, which a
252
+ // plain Map already preserves) is the right policy here: a message
253
+ // genuinely re-delivered after the window has passed is already long
254
+ // gone from any receiver's retry buffer anyway, so losing the OLDEST
255
+ // entries first costs nothing real.
256
+ const dedupCache = createDedupCache({ maxSize: 200 });
257
+ function isDuplicateMessage(messageId) {
258
+ return dedupCache.isDuplicate(messageId);
259
+ }
260
+
261
+ // Section 1 E2E: derived once at startup, same lifetime as this process.
262
+ // Null whenever either half is missing - a device paired before this
263
+ // feature existed has devicePrivateKey/phonePublicKey absent from its
264
+ // config.json, and terminal.input/output/snapshot below deliberately
265
+ // fall back to sending PLAINTEXT for exactly that case (see this
266
+ // project's own decision: no forced re-pair, upgrade happens naturally
267
+ // on the next real re-pair). Never silently "half encrypt" - either a
268
+ // real secret is available and used for every payload this session, or
269
+ // none is and nothing here pretends otherwise.
270
+ let sharedSecret = null;
271
+ if (config.devicePrivateKey && config.phonePublicKey) {
272
+ try {
273
+ const privateKey = setuCrypto.privateKeyFromBase64(config.devicePrivateKey);
274
+ sharedSecret = setuCrypto.deriveSharedSecret(privateKey, config.phonePublicKey);
275
+ } catch (err) {
276
+ diag.say(`[cli-setu] Could not derive E2E encryption key (falling back to unencrypted relay): ${err.message}`, { error: true, showAtExit: true });
277
+ }
278
+ }
279
+
280
+ // Phase 6, Section 7: a rolling raw-byte scrollback so a phone that opens
281
+ // terminal.html AFTER the session has been running for a while gets caught
282
+ // up instantly via session.snapshot, instead of an empty screen.
283
+ //
284
+ // SETU-009/015 real, explicit product requirement (confirmed live by the
285
+ // user, 2026-10-27/28, after two earlier attempts at a smaller cap with a
286
+ // truncation marker - 200KB, then 2MB - were both found to still cut off
287
+ // real conversation history the user wanted visible): this is a
288
+ // cli-setu-is-a-full-terminal-mirror product - EVERY line of output from
289
+ // session start to end must stay visible, same as scrolling back through
290
+ // a real terminal emulator's own unbounded scrollback. No cap, no
291
+ // truncation marker - the user explicitly chose this over a safety
292
+ // ceiling, accepting that a very long, output-heavy session will grow
293
+ // this string's memory usage for as long as the session runs (this
294
+ // scrollback is per-session, in-memory only - it's discarded when the
295
+ // session ends, not written to disk).
296
+ let scrollback = '';
297
+ function appendScrollback(chunk) {
298
+ scrollback += chunk;
299
+ }
300
+
301
+ let outputSeq = 0;
302
+
303
+ // Real gap found by testing: this used to also track isFocused, gating
304
+ // whether ptyProcess.onData's bytes were actually streamed live - removed
305
+ // (see that call site's own comment) since it could silently drop real
306
+ // conversation history from what's supposed to be a complete mirror.
307
+ // Still polled regardless, though: deviceId doubles as a lightweight
308
+ // heartbeat (see auth-server.js's /terminal/is-focused) - this call
309
+ // already happens every 3s, so it's the natural place for the Devices
310
+ // tab's "is this laptop actually alive right now" signal, and for
311
+ // /live-sessions' per-session online status, instead of adding a second
312
+ // poller just for those.
313
+ // Real gap found by testing (direct verification, 2026-10-22): killing
314
+ // the backend process while a session was live did NOT trigger the
315
+ // WebSocket reconnect logic at all (that connection goes straight to
316
+ // Azure, independent of our own backend being up) - but it silently
317
+ // broke THIS heartbeat completely, forever, with zero visible signal.
318
+ // pollFocus's own bare `catch {}` swallowed every single failure with
319
+ // no counter, no log, no escalation - a backend outage during an active
320
+ // session was completely invisible from the CLI's own output, exactly
321
+ // the same class of silent-forever problem reconnect.js's own
322
+ // WARN_AFTER_ATTEMPTS fixes for the WebSocket path. Same threshold
323
+ // reused here for consistency (one unified "how patient are we before
324
+ // saying something" policy, not two different numbers to reason about).
325
+ let pollFocusFailureCount = 0;
326
+ async function pollFocus() {
327
+ try {
328
+ // detectedCliType (see detectRunningAdapter's own comment, further
329
+ // down this file) piggybacks on this same already-running poll so
330
+ // the Usage button can reflect whatever CLI is ACTUALLY running
331
+ // right now, not just whichever --cli flag this session started
332
+ // with. Omitted entirely until the very first detection pass
333
+ // completes (lastDetectedCliType starts null) - sending 'shell'
334
+ // prematurely, before detectRunningAdapter has run even once, would
335
+ // incorrectly downgrade a session that started with `--cli claude`
336
+ // before this poll even has real data to report.
337
+ const detectedParam = lastDetectedCliType ? `&detectedCliType=${encodeURIComponent(lastDetectedCliType)}` : '';
338
+ await fetch(
339
+ `${AUTH_SERVER}/terminal/is-focused?sessionId=${encodeURIComponent(SESSION_ID)}${deviceId ? `&deviceId=${encodeURIComponent(deviceId)}` : ''}${detectedParam}`
340
+ );
341
+ if (pollFocusFailureCount >= WARN_AFTER_ATTEMPTS) {
342
+ diag.say('[supervisor] Heartbeat to the backend recovered.');
343
+ log('[supervisor] pollFocus heartbeat recovered after failures');
344
+ }
345
+ pollFocusFailureCount = 0;
346
+ } catch (err) {
347
+ // Network hiccup - next poll (2s later) tries again; no local state
348
+ // depends on any single poll succeeding. Only the SIGNAL changes
349
+ // here, never the retry behavior itself (still just "try again next
350
+ // tick," same as before) - this fix is purely about visibility.
351
+ pollFocusFailureCount += 1;
352
+ if (pollFocusFailureCount === WARN_AFTER_ATTEMPTS) {
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 });
354
+ }
355
+ log(`[supervisor] pollFocus failed (consecutive=${pollFocusFailureCount}): ${err.message}`);
356
+ }
357
+ }
358
+
359
+ async function connectToAzure() {
360
+ // cliType lets Devices/Profile show which CLI this paired laptop is
361
+ // actually running (see auth-server.js's /device/connect handler and
362
+ // db.js's devices.cli_type column) - sent on every connect (not just
363
+ // pairing) since the SAME device row can legitimately run a different
364
+ // CLI across restarts (e.g. re-launched with --cli codex next time).
365
+ const res = await fetch(`${AUTH_SERVER}/device/connect`, {
366
+ method: 'POST',
367
+ headers: { Authorization: `Bearer ${deviceToken}`, 'Content-Type': 'application/json' },
368
+ // sessionId here is what lets auth-server.js broadcast session.started
369
+ // immediately - see its own comment on why a session shouldn't have
370
+ // to wait for its first approval prompt to become visible on the
371
+ // phone. folderName is the real product ask: the phone's own session
372
+ // lists only ever showed the raw sessionId (a hostname+hash+random
373
+ // string, meaningless to a real user) - just the WORKING_DIR's own
374
+ // folder name (not the full path - shorter, and doesn't expose this
375
+ // laptop's real directory structure to the phone) lets someone
376
+ // actually tell which real project a session belongs to.
377
+ //
378
+ // folderPath (SETU-005) is the SEPARATE, full CANONICAL_WORKING_DIR -
379
+ // server-side only, used purely to detect a genuine duplicate session
380
+ // in the same folder on the same device (see auth-server.js's
381
+ // duplicate-session check in this same handler). Deliberately never
382
+ // forwarded into the session.started broadcast the phone receives -
383
+ // the phone only ever needs folderName, same privacy posture as
384
+ // before this field existed.
385
+ body: JSON.stringify({
386
+ cliType: adapter.id,
387
+ sessionId: SESSION_ID,
388
+ folderName: path.basename(WORKING_DIR),
389
+ folderPath: CANONICAL_WORKING_DIR,
390
+ }),
391
+ });
392
+ if (!res.ok) {
393
+ const err = await res.json().catch(() => ({}));
394
+ // A 403 here means a real, durable plan-limit rejection (see
395
+ // auth-server.js's live-session-limit check) - retrying every 3s
396
+ // forever would just spam the same rejection, since nothing about
397
+ // THIS session changes by waiting (the fix is stopping an existing
398
+ // live session elsewhere, or upgrading, not a transient retry).
399
+ // Every other failure (network hiccup, a momentarily-down server)
400
+ // keeps the original retry behavior.
401
+ // Shared cleanup for the 403/401 fatal-rejection branches below.
402
+ // Real bug found by testing, THREE rounds deep (direct verification
403
+ // 2026-10-22, then twice more live on 2026-10-25 after two incomplete
404
+ // fixes - a stale `ws` theory, then a stdin-raw-mode theory, neither
405
+ // of which actually stopped the crash): the real cause, confirmed via
406
+ // node-pty's own GitHub issues (microsoft/node-pty#584, #423, #375,
407
+ // #495), is that `ptyProcess.kill()` on Windows (ConPTY) does NOT
408
+ // synchronously tear down its native pipe/ConPTY handles - it
409
+ // schedules an ASYNC close. Calling `process.exit()` immediately
410
+ // after `.kill()` races that async teardown: libuv hits a handle
411
+ // that's already mid-close and fires `UV_HANDLE_CLOSING`.
412
+ //
413
+ // Compounding this: ptyProcess.onExit(...) (registered in main(),
414
+ // BEFORE connectToAzure() ever runs) already fires on ANY pty exit -
415
+ // including one caused by our own .kill() here - and that handler
416
+ // already does the real cleanup (clears every timer, closes ws, then
417
+ // process.exit()). Calling process.exit() AGAIN right here, from a
418
+ // second code path, is exactly the "kill+exit called from two races
419
+ // against each other" shape node-pty's own issue threads warn about.
420
+ //
421
+ // Fix: don't exit here at all. Set process.exitCode so the eventual
422
+ // exit (via onExit, once the pty's real async teardown completes)
423
+ // reports failure, then just call .kill() and let onExit do the one
424
+ // real cleanup+exit. A short timeout is a safety net only, in case
425
+ // onExit never fires (a few node-pty issue threads note this can
426
+ // happen if ConPTY's handle is already in a bad state) - unref'd so
427
+ // it never itself keeps the process alive if the clean path wins.
428
+ const killAndExit = () => {
429
+ process.exitCode = 1;
430
+ if (ptyProcess) {
431
+ ptyProcess.kill();
432
+ } else {
433
+ // No PTY ever spawned (shouldn't happen on this path today, but
434
+ // don't hang forever waiting for an onExit that will never fire).
435
+ process.exit(1);
436
+ return;
437
+ }
438
+ setTimeout(() => process.exit(1), 1500).unref();
439
+ };
440
+ if (res.status === 403) {
441
+ diag.say(`[supervisor] Connection rejected: ${err.error || 'the server declined this session.'}`, { error: true, showAtExit: true });
442
+ log(`[supervisor] /device/connect rejected (403): ${err.error || 'no reason given'}`);
443
+ killAndExit();
444
+ }
445
+ // Real bug found by testing: a 401 here means the server genuinely
446
+ // doesn't recognize this device token anymore (e.g. unpaired from the
447
+ // phone app) - this used to fall into the generic retry-every-3s path
448
+ // below, silently looping forever on a token that will never become
449
+ // valid again, with no indication to the user of what's actually
450
+ // wrong or what to do about it. Treated the same as 403 now: stop,
451
+ // say so clearly, point at the real fix.
452
+ if (res.status === 401) {
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 });
455
+ log(`[supervisor] /device/connect rejected (401): ${err.error || 'no reason given'}`);
456
+ killAndExit();
457
+ }
458
+ log(`[supervisor] /device/connect failed: ${err.error || res.status}`);
459
+ reconnectManager.scheduleRetry();
460
+ return;
461
+ }
462
+ const conn = await res.json();
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
+ }
478
+ // See this function's own call site (main()'s former focusTimer
479
+ // comment) for why this starts HERE and not unconditionally at
480
+ // startup - deviceId must be real before pollFocus's heartbeat is
481
+ // worth sending at all. Guarded so a reconnect (connectToAzure called
482
+ // again after a dropped WebSocket) never stacks a second timer.
483
+ if (!focusTimer) focusTimer = setInterval(pollFocus, 2000);
484
+ log(`[supervisor] Connecting to Azure as device:${deviceId} (owner: ${conn.userId})...`);
485
+ // Diagnostic found by testing: a session not appearing in the phone's
486
+ // Terminal tab had no visible cause from the laptop's own side - this
487
+ // surfaces whether the backend's session.started broadcast (what
488
+ // actually makes a session show up before its first approval prompt)
489
+ // was even attempted and whether it succeeded, right here, instead of
490
+ // needing server log access to find out.
491
+ diag.say(`[supervisor] session.started broadcast: ${conn.sessionBroadcast || '(not reported by this server version)'}`);
492
+
493
+ ws = new WebSocket(conn.wssUrl);
494
+
495
+ // attachProviderProtocol (see providerProtocol.js's own header
496
+ // comment) detects which real-time provider conn.wssUrl actually
497
+ // belongs to and, for Ably, handles its required ATTACH/ATTACHED
498
+ // handshake before onReady fires - for Azure (today's only real
499
+ // provider in production), onReady fires immediately on 'open' and
500
+ // onMessage receives the exact same raw-parsed JSON this handler
501
+ // always received, so everything below this point is 100% unchanged
502
+ // Azure behavior.
503
+ const providerConnection = attachProviderProtocol(ws, conn.wssUrl, `device:${deviceId}`, {
504
+ onReady: () => {
505
+ azureReady = true;
506
+ connectedProvider = providerConnection.provider;
507
+ reconnectManager.reset();
508
+ log(`[supervisor] Connected (${providerConnection.provider}). Ready to forward permission requests.`);
509
+ },
510
+ onMessage: (msg) => {
511
+ if (msg.type === 'confirmation.response') handleAzureDecision(msg).catch((err) => log('[supervisor] Failed to inject decision keystrokes:', err.message));
512
+ if (msg.type === 'terminal.input' && msg.sessionId === SESSION_ID) {
513
+ // Section 11f Step 2: typed input from the phone, written to the PTY
514
+ // exactly like a local keystroke - this is the "arbitrary remote
515
+ // input" half of the DoD, not just approve/reject.
516
+ //
517
+ // Dedup check FIRST, before any decryption work - a genuine
518
+ // redelivery should be dropped as cheaply as possible, not
519
+ // decrypted twice before being noticed. See isDuplicateMessage's
520
+ // own comment for why this exists at all.
521
+ if (isDuplicateMessage(msg.messageId)) {
522
+ log(`[supervisor] Dropped duplicate terminal.input (messageId=${msg.messageId}) - already executed this exact message.`);
523
+ return;
524
+ }
525
+ //
526
+ // Section 1 E2E: msg.data is ciphertext whenever sharedSecret exists
527
+ // (the phone encrypts before sending - see TerminalScreen.js's own
528
+ // sendInput). msg.encrypted distinguishes the two wire shapes so a
529
+ // pre-upgrade phone build (no E2E yet) and a pre-upgrade laptop
530
+ // build talking to each other don't try to decrypt plaintext or
531
+ // vice versa - see this file's own sharedSecret comment for why
532
+ // that fallback has to be all-or-nothing, never silent guessing.
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;
548
+ }
549
+ ptyProcess.write(data);
550
+ }
551
+ if (msg.type === 'terminal.resize' && msg.sessionId === SESSION_ID) {
552
+ // Real bug found by testing: this used to call ptyProcess.resize()
553
+ // with the PHONE's dimensions, reflowing the one real, SHARED PTY to
554
+ // whatever narrow width the phone's screen happened to be - since a
555
+ // PTY has exactly one size, that visibly shrank and re-wrapped the
556
+ // laptop's own terminal the moment a phone connected/attached,
557
+ // corrupting the laptop-side view too, not just a phone-side
558
+ // cosmetic issue. Ignoring the phone's resize entirely is the
559
+ // correct fix: the laptop's real terminal keeps whatever size the
560
+ // person actually sitting at it set, and the phone's own
561
+ // xterm.js/WebView is responsible for wrapping/scrolling whatever
562
+ // width of output it receives to fit its own screen - the same
563
+ // model every real remote-terminal viewer (Termius, Blink) uses.
564
+ log(`[supervisor] Ignoring phone resize request (${msg.cols}x${msg.rows}) - the real PTY keeps its own size.`);
565
+ }
566
+ if (msg.type === 'session.close' && msg.sessionId === SESSION_ID) {
567
+ // SETU-011: close a live session directly from the mobile app.
568
+ // Exits the WHOLE cli-setu process (confirmed as the right behavior -
569
+ // same as a local Ctrl+C), not just the inner shell/CLI - matches
570
+ // the brief's own wording ("stop/disconnect the laptop's CLI-Setu
571
+ // session"). Same three-line shape as main()'s own cleanupAndExit
572
+ // (SIGINT/SIGTERM/SIGHUP) rather than calling that function directly -
573
+ // it's a local const inside main(), not reachable from this module-
574
+ // level onMessage closure, and duplicating these exact three lines
575
+ // is simpler and safer than restructuring scope for it. See
576
+ // cleanupAndExit's own comment for why this never calls
577
+ // process.exit() directly: the ONE ptyProcess.onExit handler (set up
578
+ // in main(), before this message could ever arrive) does the real
579
+ // cleanup and actually exits, avoiding the node-pty Windows
580
+ // async-teardown race already fixed elsewhere in this file.
581
+ log(`[supervisor] Received session.close from the phone - shutting down.`);
582
+ diag.say('[supervisor] Session closed from the mobile app.', { showAtExit: true });
583
+ process.exitCode = 0;
584
+ if (ptyProcess) {
585
+ ptyProcess.kill();
586
+ setTimeout(() => process.exit(0), 1500).unref();
587
+ } else {
588
+ process.exit(0);
589
+ }
590
+ }
591
+ if (msg.type === 'session.attach') {
592
+ // TEMPORARY diagnostic logging (2026-10-28) - remove once the
593
+ // scrollback-not-refreshed-on-reload bug is confirmed/fixed.
594
+ log(`[supervisor][diag] session.attach received: msg.sessionId=${msg.sessionId} SESSION_ID=${SESSION_ID} match=${msg.sessionId === SESSION_ID}`);
595
+ }
596
+ if (msg.type === 'session.attach' && msg.sessionId === SESSION_ID) {
597
+ // Section 7: a phone just opened/reopened the terminal view - hand it
598
+ // the scrollback immediately instead of leaving it blank until the
599
+ // next byte happens to be written.
600
+ sendSnapshot();
601
+ }
602
+ if (msg.type === 'git.diff.request' && msg.sessionId === SESSION_ID) {
603
+ // Roadmap #14 - git diff pane. Entirely independent of the running
604
+ // CLI adapter (Claude Code, Codex, generic) - this is a plain git
605
+ // operation against WORKING_DIR, not something any adapter needs to
606
+ // declare. Fire-and-forget from this handler's point of view; the
607
+ // real response goes back over its own relay endpoint (see
608
+ // sendGitDiff below), same pattern as sendSnapshot above.
609
+ sendGitDiff(msg.requestId);
610
+ }
611
+ if (msg.type === 'cross_session.inject' && msg.toSessionId === SESSION_ID) {
612
+ // Roadmap #3 - cross-session messaging. Note the field checked is
613
+ // toSessionId, not sessionId - this message genuinely has two
614
+ // different sessions in it (where it came FROM, where it's going
615
+ // TO), unlike every other message type in this file which only
616
+ // ever concerns THIS session.
617
+ //
618
+ // auth-server.js has ALREADY decided this is safe to inject
619
+ // (either nobody was watching, or the watching phone explicitly
620
+ // tapped Inject on the pending card) - this handler's only job is
621
+ // writing it in with a visible trace, never silently. A bracketed
622
+ // system-style line in the scrollback (not literally typed as if
623
+ // from the keyboard) is what makes an injected message
624
+ // distinguishable after the fact from something typed locally,
625
+ // even hours later when nobody remembers a message arrived.
626
+ const marker = `\r\n\x1b[38;2;155;185;235m[message from ${msg.fromDeviceName || 'another session'} / ${msg.fromSessionId}]\x1b[0m\r\n`;
627
+ ptyProcess.write(marker + msg.text + '\r');
628
+ log(`[supervisor] Injected cross-session message ${msg.messageId} from ${msg.fromSessionId}`);
629
+ }
630
+ if (msg.type === 'usage.refresh.request' && msg.sessionId === SESSION_ID) {
631
+ // Real feedback: the old 5-minute auto-timer (below, now removed)
632
+ // ran /cost in the user's own terminal on a schedule regardless of
633
+ // whether anyone was even looking at their phone - genuinely
634
+ // disruptive if someone's actively working locally and /cost's
635
+ // full-screen usage report suddenly takes over their session. This
636
+ // is the on-demand replacement: same triggerKeystrokes mechanism
637
+ // (still a real, visible command - that constraint hasn't changed,
638
+ // see cli-adapters/claude.js), but only ever fired when a phone
639
+ // explicitly asks for a fresh number, not on a timer nobody
640
+ // requested.
641
+ const usageAdapter = getActiveUsageAdapter();
642
+ if (usageAdapter?.triggerKeystrokes && ptyProcess) {
643
+ ptyProcess.write(usageAdapter.triggerKeystrokes);
644
+ usageListenUntil = Date.now() + USAGE_LISTEN_WINDOW_MS;
645
+ log(`[supervisor] On-demand usage refresh requested for ${SESSION_ID}`);
646
+ }
647
+ }
648
+ },
649
+ log,
650
+ });
651
+
652
+ ws.on('close', () => {
653
+ azureReady = false;
654
+ reconnectManager.scheduleRetry();
655
+ });
656
+
657
+ ws.on('error', (err) => log('[supervisor] Azure socket error:', err.message));
658
+ }
659
+
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;
670
+
671
+ async function sendSnapshot() {
672
+ if (!sharedSecret) { noteNoEncryptionKey(); return; }
673
+ try {
674
+ // preservedHistoryText() (see its own comment) is plain text, from
675
+ // BEFORE the current full-screen TUI took over - prepended ahead of
676
+ // the real, live raw-byte scrollback (still replayed as actual ANSI,
677
+ // unchanged), so a phone scrolling up sees the real startup banner/
678
+ // pre-TUI history too, not just whatever the current alt-screen
679
+ // buffer still happens to show.
680
+ const history = await preservedHistoryText();
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
+ : [''];
698
+ // TEMPORARY diagnostic logging (2026-10-28) - remove once the
699
+ // scrollback-not-refreshed-on-reload bug is confirmed/fixed.
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
+ }
725
+ } catch (err) {
726
+ log('[supervisor] Failed to send snapshot:', err.message);
727
+ }
728
+ }
729
+
730
+ // Roadmap #14 - git diff pane. Entirely CLI-agnostic: this runs plain git
731
+ // commands against WORKING_DIR regardless of which adapter (Claude Code,
732
+ // Codex, generic) is driving the PTY - no adapter interface changes
733
+ // needed, unlike the command palette (#6) which is genuinely adapter-
734
+ // specific. `git diff` alone only shows changes to ALREADY-TRACKED files -
735
+ // a brand-new file Claude/Codex just created shows up in `git status`
736
+ // but produces no `git diff` output at all, which is exactly the case
737
+ // most worth seeing remotely. `git diff --no-index /dev/null <file>`
738
+ // against each untracked file (Windows git still accepts the POSIX
739
+ // /dev/null form here) gets a real unified diff for those too, rather
740
+ // than just a bare filename with no content shown.
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;
744
+
745
+ async function sendGitDiff(requestId) {
746
+ try {
747
+ const result = await getGitDiff(WORKING_DIR, {
748
+ maxBodyBytes: limitForProvider(connectedProvider) - GIT_DIFF_ENVELOPE_BYTES,
749
+ log,
750
+ });
751
+ await fetch(`${AUTH_SERVER}/relay/git-diff-response`, {
752
+ method: 'POST',
753
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
754
+ body: JSON.stringify({ sessionId: SESSION_ID, requestId, ...result }),
755
+ });
756
+ } catch (err) {
757
+ log('[supervisor] Failed to compute/send git diff:', err.message);
758
+ // Best-effort error reporting to the phone - without this, a failed
759
+ // diff (e.g. git not on PATH) would leave the phone's request hanging
760
+ // forever with no explanation, rather than a clear error state.
761
+ fetch(`${AUTH_SERVER}/relay/git-diff-response`, {
762
+ method: 'POST',
763
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
764
+ body: JSON.stringify({ sessionId: SESSION_ID, requestId, error: err.message }),
765
+ }).catch(() => {});
766
+ }
767
+ }
768
+
769
+ // Real bug #1, found by testing: ptyProcess.onData fires rapidly and
770
+ // synchronously for every PTY chunk, but each streamOutput() call did its
771
+ // own independent, un-awaited fetch(). Nothing guaranteed those HTTP
772
+ // requests RESOLVED in the order they were SENT - a later chunk's request
773
+ // could finish first under normal network jitter, and terminal.html just
774
+ // wrote whatever arrived with no reordering. Symptom: words/lines rendered
775
+ // interleaved, e.g. "Listingserver.js," instead of two separate lines.
776
+ //
777
+ // First fix was one fetch() per chunk, strictly serialized - correct
778
+ // order, but real bug #2: a single Claude Code response can produce MANY
779
+ // small PTY chunks, and awaiting a full HTTP round trip before sending the
780
+ // next one turned a live stream into a slow drip - observed as a ~2
781
+ // minute lag before anything appeared, for output that should stream in
782
+ // under a second.
783
+ //
784
+ // Actual fix: batch. Chunks accumulate in a buffer; a short timer (or the
785
+ // buffer growing large) triggers ONE combined send instead of one send
786
+ // per chunk - still exactly one in-flight request at a time (order
787
+ // preserved by construction, same as before), but far fewer round trips.
788
+ let outputBuffer = '';
789
+ let flushTimer = null;
790
+ let sendInFlight = Promise.resolve();
791
+ const BATCH_WINDOW_MS = 40;
792
+ const BATCH_MAX_BYTES = 8000; // flush early if a burst gets large, rather than waiting the full window
793
+
794
+ function streamOutput(chunk) {
795
+ outputBuffer += chunk;
796
+ if (outputBuffer.length >= BATCH_MAX_BYTES) {
797
+ scheduleFlush(0);
798
+ } else if (!flushTimer) {
799
+ scheduleFlush(BATCH_WINDOW_MS);
800
+ }
801
+ }
802
+
803
+ function scheduleFlush(delayMs) {
804
+ clearTimeout(flushTimer);
805
+ flushTimer = setTimeout(flushOutputBuffer, delayMs);
806
+ }
807
+
808
+ function flushOutputBuffer() {
809
+ flushTimer = null;
810
+ if (!outputBuffer) return;
811
+
812
+ const batch = outputBuffer;
813
+ outputBuffer = '';
814
+
815
+ // Still serialized against any send already in flight, so batches
816
+ // themselves can never arrive out of order relative to each other.
817
+ // Real bug found by testing: the Backend used to AWAIT Azure's own
818
+ // sendToAll broadcast (~190-200ms per call, confirmed inherent to
819
+ // Azure Web PubSub's broadcast API, not fixable from our side) before
820
+ // responding here - since this chain won't send its next batch until
821
+ // this fetch() resolves, every Azure call directly delayed the next
822
+ // batch too, compounding into real, visible lag during a burst of PTY
823
+ // output. auth-server.js's /relay/terminal-output now responds
824
+ // immediately and broadcasts to Azure in the background, so this
825
+ // fetch() itself should resolve quickly regardless of Azure's own cost.
826
+ sendInFlight = sendInFlight.then(async () => {
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
+ }
849
+ }
850
+ });
851
+ }
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
+
872
+ // Real bug found by testing: writing several keystrokes (a plain
873
+ // character plus \x1b[B escape sequences) to the PTY in ONE
874
+ // ptyProcess.write() call only ever registered the FIRST one on a real
875
+ // multiSelect screen - Claude Code's own input handling silently dropped
876
+ // everything after when it all arrived in the same burst with no real
877
+ // gap between keypresses, same class of issue as a paste outrunning a
878
+ // TUI's input loop. Writing each token separately with a short delay
879
+ // mimics real typing speed and is what actually made every checkbox
880
+ // register correctly in live testing.
881
+ async function injectKeystrokeSequence(tokens, delayMs = 60) {
882
+ for (const token of tokens) {
883
+ ptyProcess.write(token);
884
+ await new Promise((r) => setTimeout(r, delayMs));
885
+ }
886
+ }
887
+
888
+ async function handleAzureDecision(msg) {
889
+ const pending = pendingPrompts.get(msg.promptId);
890
+ if (!pending) {
891
+ log(`[supervisor] Got a decision for unknown promptId ${msg.promptId} - already handled or unrecognized, ignoring.`);
892
+ return;
893
+ }
894
+
895
+ // Real key mapping, confirmed live against a real multiSelect
896
+ // AskUserQuestion screen - see claude.js's buildMultiSelectKeystrokes.
897
+ // A multiSelect step has no single "chosen option" the way every other
898
+ // prompt here does (the phone sends WHICH indices got checked, any
899
+ // count from 0 to all of them), so it builds its own keystroke
900
+ // TOKEN ARRAY instead of looking one up in pending.options (which is
901
+ // empty for this case - see relayApproval's own comment).
902
+ const isMultiSelect = !!pending.isMultiSelect;
903
+ const chosen = isMultiSelect ? null : pending.options?.[msg.optionIndex];
904
+ const keystrokeTokens = isMultiSelect
905
+ ? claudeAdapter.approvals.buildMultiSelectKeystrokes(pending.tool_input.questions[pending.questionIndex].options.length, msg.optionIndices || [])
906
+ : [chosen ? chosen.keystroke : '\x1b'];
907
+ const chosenLabel = isMultiSelect
908
+ ? `Submitted (${(msg.optionIndices || []).length} selected)`
909
+ : chosen?.label;
910
+
911
+ // Real gap found by testing: a multi-question AskUserQuestion wizard
912
+ // (pending.totalQuestions > 1 - see relayApproval's own comment) isn't
913
+ // actually DONE once this step's keystroke is injected - Claude Code
914
+ // just advances to its NEXT question in the same wizard. Only delete
915
+ // from pendingPrompts (fully resolved) once the LAST step's decision is
916
+ // injected; an earlier step hands off to advanceAskUserQuestion below
917
+ // instead, which keeps this promptId alive and relays the next step as
918
+ // an update to the SAME card.
919
+ //
920
+ // Real gap found by testing (live capture): after the LAST real
921
+ // question is answered, Claude Code shows one more screen - "Review
922
+ // your answers" + a Submit/Cancel choice - that is NOT a new hook
923
+ // event and carries NO JSON payload at all (confirmed: the original
924
+ // PermissionRequest's tool_input.questions only ever has the real
925
+ // questions, this screen is purely Claude Code's own terminal-side
926
+ // redraw once the wizard's inputs are complete). pending.isFinalConfirm
927
+ // marks the SYNTHETIC extra step advanceAskUserQuestion sends for
928
+ // exactly this screen - only an answer to THAT step is truly final.
929
+ const isWizardStep = (pending.totalQuestions || 1) > 1;
930
+ const isLastRealStep = pending.questionIndex + 1 >= pending.totalQuestions;
931
+ const isLastStep = !isWizardStep || (isLastRealStep && (pending.isFinalConfirm || false));
932
+
933
+ // Real bug found by testing: "Type something" (the phone's own
934
+ // keepPending path - see ConfirmationsScreen.js) only opens Claude
935
+ // Code's freeform input, it isn't a real decision - but this used to
936
+ // unconditionally delete the promptId from pendingPrompts regardless of
937
+ // WHICH option was chosen. That meant tapping a REAL option (e.g.
938
+ // "Empty file") on the same still-visible card right after "Type
939
+ // something" found nothing left to act on - the keystroke silently
940
+ // never reached the terminal. Only delete when the actual decision was
941
+ // a real one, so the same card can still be resolved for real
942
+ // afterward.
943
+ if (chosenLabel !== 'Type something' && isLastStep) {
944
+ pendingPrompts.delete(msg.promptId);
945
+ }
946
+
947
+ log(`[supervisor] Azure decision for ${msg.promptId}: "${chosenLabel || 'unknown'}". Injecting ${keystrokeTokens.length} keystroke(s)...`);
948
+ // Real bug found by testing: Claude Code's inline permission menu
949
+ // (1/2/3, or a bare Esc to reject) selects AND confirms on the single
950
+ // keypress alone - it's a hotkey menu, not a typed line. Appending '\r'
951
+ // unconditionally sent a second, separate Enter right after the
952
+ // selection, which landed in whatever input the UI advanced to next
953
+ // (the freeform chat box) - visible as a stray "1" typed into chat,
954
+ // sometimes racing with the terminal's own answer if you'd already
955
+ // resolved the same prompt locally before the phone's decision arrived.
956
+ // (a single-choice decision is always exactly one token - see above -
957
+ // so injectKeystrokeSequence's per-token delay is a no-op loop of 1 for
958
+ // that case, same end behavior as the old direct write.)
959
+ await injectKeystrokeSequence(keystrokeTokens);
960
+ fs.appendFileSync(
961
+ PROCESSED_FILE,
962
+ JSON.stringify({ ...pending, chosenLabel, injectedAt: new Date().toISOString() }) + '\n'
963
+ );
964
+
965
+ if (isWizardStep && !isLastStep && chosenLabel !== 'Type something') {
966
+ // Real bug found by code review, fixed before ever shipping: this was
967
+ // a bare fire-and-forget call - handleAzureDecision's OWN call site
968
+ // (onMessage's handler) does have a `.catch(...)`, but that only ever
969
+ // covers handleAzureDecision's own returned promise, which already
970
+ // resolved by the time this un-awaited inner call's promise settles.
971
+ // With no process-level unhandledRejection handler anywhere in this
972
+ // file, a real rejection here (e.g. an unexpected tool_input shape
973
+ // mid-wizard) would crash the entire cli-setu session process instead
974
+ // of just failing this one step. Logged, not thrown.
975
+ advanceAskUserQuestion(msg.promptId, pending).catch((err) => log('[supervisor] Failed to advance AskUserQuestion wizard:', err.message));
976
+ }
977
+ }
978
+
979
+ // Real gap found by testing: see relayApproval's and handleAzureDecision's
980
+ // own comments - a multi-question AskUserQuestion wizard needs its NEXT
981
+ // question relayed as an UPDATE to the same card, not a new one, once the
982
+ // current step's keystroke has actually been injected and Claude Code has
983
+ // had a moment to redraw. A multiSelect step (checkboxes + Submit) is
984
+ // relayed too, using its own {label, description} shape rather than
985
+ // `options` - see claude.js's buildMultiSelectKeystrokes for the real,
986
+ // confirmed key mapping this builds on.
987
+ //
988
+ // Real gap found by testing (live capture): once every REAL question has
989
+ // been answered, Claude Code shows one more "Review your answers" +
990
+ // Submit/Cancel screen that is NOT part of tool_input.questions and has
991
+ // no JSON payload at all (see handleAzureDecision's own comment). This
992
+ // relays a SYNTHETIC extra step for exactly that screen (questionIndex ==
993
+ // totalQuestions, one past the real array, marked isFinalConfirm) so the
994
+ // phone still gets a card to finish the wizard, even though there's
995
+ // nothing from the hook payload to describe it with.
996
+ async function advanceAskUserQuestion(promptId, pending) {
997
+ const nextIndex = pending.questionIndex + 1;
998
+ const nextQuestion = pending.tool_input?.questions?.[nextIndex];
999
+
1000
+ // Give Claude Code's TUI a moment to actually redraw before reading/
1001
+ // relaying the next screen - PermissionRequest/the hook queue already
1002
+ // handed us the full questions array up front, so there's nothing new
1003
+ // to wait ON from the hook's side, just the terminal's own render lag.
1004
+ await new Promise((r) => setTimeout(r, 150));
1005
+
1006
+ if (!nextQuestion) {
1007
+ if (pending.isFinalConfirm) return; // already sent - nothing further to advance into
1008
+ const options = [
1009
+ { label: 'Submit answers', keystroke: '\r', style: 'approve' },
1010
+ { label: 'Cancel', keystroke: '\x1b', style: 'reject' },
1011
+ ];
1012
+ await relayApproval(
1013
+ { ...pending, isFinalConfirm: true },
1014
+ options,
1015
+ 'Submit your answers?',
1016
+ nextIndex,
1017
+ pending.totalQuestions + 1,
1018
+ promptId
1019
+ );
1020
+ return;
1021
+ }
1022
+
1023
+ const text = claudeAdapter.approvals.describePrompt(pending, nextIndex);
1024
+
1025
+ if (nextQuestion.multiSelect) {
1026
+ const multiSelectOptions = (nextQuestion.options || []).map((o) => ({ label: o.label, description: o.description || null }));
1027
+ await relayApproval(pending, [], text, nextIndex, pending.totalQuestions, promptId, multiSelectOptions);
1028
+ return;
1029
+ }
1030
+
1031
+ const options = await resolveRealOptions(pending, nextIndex);
1032
+ await relayApproval(pending, options, text, nextIndex, pending.totalQuestions, promptId);
1033
+ }
1034
+
1035
+ // Real bug found by testing: these used to be hardcoded to 120x30
1036
+ // regardless of the user's REAL terminal window size - on any window
1037
+ // bigger than that (the normal case for a maximized/large terminal),
1038
+ // the PTY was spawned SMALLER than the window showing it, leaving real,
1039
+ // visible blank space in the laptop's own terminal below and to the
1040
+ // right of the actual PTY content - not a phone-side rendering bug at
1041
+ // all, a genuine laptop-side geometry mismatch. process.stdout.columns/
1042
+ // rows reflect the REAL terminal's actual current size at the moment
1043
+ // `cli-setu` starts (falling back to the old 120x30 only if those aren't
1044
+ // available - e.g. output piped to a file, not a real TTY). Still a
1045
+ // FIXED size after this point, same reasoning as before (not read back
1046
+ // off ptyProcess after spawn, never resized again - see the
1047
+ // terminal.resize handler above for why phone-side resize requests are
1048
+ // still correctly ignored): just a better, size-aware fixed size instead
1049
+ // of an arbitrary guessed one.
1050
+ // SETU-014: let (not const) - see the real resize handler added in main()
1051
+ // below, right after ptyProcess is spawned. This was "never resized
1052
+ // again" by deliberate design UNTIL now (see this comment's own history
1053
+ // just above) for one specific, still-valid reason: a shared PTY has
1054
+ // exactly one size, and the PHONE's resize requests are correctly ignored
1055
+ // because satisfying the phone's screen size would corrupt the laptop's
1056
+ // own real terminal (see terminal.resize's own handler). Resizing when
1057
+ // the LAPTOP's own terminal WINDOW changes size is a different, genuinely
1058
+ // unaddressed case - matches SETU-014's exact reported symptoms ("text
1059
+ // overlaps, characters overwrite other text") far better than anything
1060
+ // already fixed in this file: the PTY and the laptop's real window going
1061
+ // out of sync (e.g. the user resizes their terminal mid-session) means
1062
+ // every subsequent redraw is computed for the WRONG width, corrupting
1063
+ // cursor-positioned output exactly the way Claude Code's full-screen TUI
1064
+ // (see headlessTerm's own comment) depends on getting right.
1065
+ let PTY_COLS = process.stdout.columns || 120;
1066
+ let PTY_ROWS = process.stdout.rows || 30;
1067
+
1068
+ // Real gap found by testing: Claude Code's full-screen TUI does its own
1069
+ // absolute-cursor-positioning redraws, which means the raw scrollback
1070
+ // STRING above (appendScrollback) is not a reliable transcript - earlier
1071
+ // bytes get visually overwritten by later ones at the byte level (the
1072
+ // same reason Claude Code's own startup banner disappeared from the
1073
+ // phone's scrollback once real conversation started: the banner's bytes
1074
+ // were still THERE in the string, but replaying them through a FRESH
1075
+ // xterm instance just re-runs the same overwrites, landing on the same
1076
+ // final picture). The real fix: @xterm/headless is xterm.js's own
1077
+ // official Node.js package - running a real terminal emulator here,
1078
+ // fed the IDENTICAL bytes the real PTY produces, maintains an actual,
1079
+ // always-correct RENDERED buffer, not just a raw byte log. Critically,
1080
+ // it tracks the NORMAL and ALTERNATE screen buffers separately (see
1081
+ // node_modules/@xterm/headless/typings - IBuffer.type) - a full-screen
1082
+ // TUI like Claude Code switches to the alternate buffer when it starts
1083
+ // (standard terminal behavior every full-screen app relies on), which
1084
+ // means whatever was in the NORMAL buffer before that (the real startup
1085
+ // banner, or any plain shell output before Claude Code launched) is
1086
+ // preserved completely untouched underneath, not overwritten - it's
1087
+ // just hidden while the alt buffer is active. Reading the normal buffer
1088
+ // independently (see preservedHistoryText below) means no "detect the
1089
+ // redraw" logic is needed at all.
1090
+ // allowProposedApi: true - buffer.normal/buffer.alternate are marked
1091
+ // EXPERIMENTAL in xterm.js's own typings and throw at runtime without
1092
+ // this explicit opt-in (confirmed directly: "You must set the
1093
+ // allowProposedApi option to true to use proposed API").
1094
+ // SETU-013: real unit mismatch found by investigation - this used to pass
1095
+ // SCROLLBACK_MAX_BYTES (200_000) directly as `scrollback`, but xterm.js's
1096
+ // own documented API defines that option as a LINE count, not a byte
1097
+ // count (confirmed against xterm.js's own Terminal options docs) - 200,000
1098
+ // LINES is a dramatically larger retained buffer than the ~200KB-of-raw-
1099
+ // bytes cap appendScrollback enforces elsewhere in this same file,
1100
+ // potentially hundreds of MB of real memory on a long-running session.
1101
+ // HEADLESS_SCROLLBACK_LINES is a separate, explicitly-named constant in
1102
+ // the correct unit, sized generously (a real terminal's default is
1103
+ // usually 1000-10000) without reusing a byte-oriented number that never
1104
+ // meant "lines" in the first place.
1105
+ const HEADLESS_SCROLLBACK_LINES = 10_000;
1106
+ const headlessTerm = new HeadlessTerminal({ cols: PTY_COLS, rows: PTY_ROWS, scrollback: HEADLESS_SCROLLBACK_LINES, allowProposedApi: true });
1107
+
1108
+ // Real bug found by testing: term.write() is ASYNCHRONOUS - reading the
1109
+ // buffer immediately after calling it (no callback, no await) reads
1110
+ // STALE/EMPTY content, confirmed directly against a real minimal
1111
+ // reproduction. ptyProcess.onData can fire many times per second, so
1112
+ // awaiting every single write here would be wasteful - instead, chain
1113
+ // each write's completion onto the previous one (same pattern this file
1114
+ // already uses for sendInFlight's own output batching), and have
1115
+ // anything that needs to READ the buffer (preservedHistoryText, called
1116
+ // from sendSnapshot) await this chain first, so it's guaranteed caught
1117
+ // up by the time anyone actually reads it - without slowing down the hot
1118
+ // onData path at all.
1119
+ let headlessWriteChain = Promise.resolve();
1120
+ function writeToHeadlessTerm(data) {
1121
+ headlessWriteChain = headlessWriteChain.then(
1122
+ () => new Promise((resolve) => headlessTerm.write(data, resolve))
1123
+ );
1124
+ }
1125
+ async function awaitHeadlessTermCaughtUp() {
1126
+ await headlessWriteChain;
1127
+ }
1128
+
1129
+ // Renders a buffer's lines back to plain text - translateToString(true)
1130
+ // trims trailing whitespace per line, same as how a real terminal looks
1131
+ // when you select and copy its text.
1132
+ function bufferToText(buffer) {
1133
+ const lines = [];
1134
+ for (let y = 0; y < buffer.length; y++) {
1135
+ const line = buffer.getLine(y);
1136
+ if (line) lines.push(line.translateToString(true));
1137
+ }
1138
+ return lines.join('\n');
1139
+ }
1140
+
1141
+ // Real product ask: scrolling up on the phone should show EVERYTHING,
1142
+ // including content from before the current alt-screen TUI took over.
1143
+ // Deliberately only ever returns the PRESERVED NORMAL buffer (the
1144
+ // banner/pre-TUI history) as plain text, to be PREPENDED before the
1145
+ // existing raw-byte scrollback (see sendSnapshot) - never a replacement
1146
+ // for it. The live/current content still replays as real ANSI bytes
1147
+ // through the existing mechanism (term.write() of the raw scrollback
1148
+ // string), which correctly handles Claude Code's own absolute cursor
1149
+ // positioning; converting that part to plain text too would lose
1150
+ // coloring and risk misaligning the cursor position live streaming
1151
+ // continues from afterward. When the CLI is still on the plain normal
1152
+ // buffer (hasn't switched to an alt screen at all - e.g. a plain shell
1153
+ // with no full-screen TUI running), buffer.normal IS buffer.active, so
1154
+ // this would just duplicate the live scrollback - returns '' in that
1155
+ // case since there's nothing EXTRA to prepend.
1156
+ async function preservedHistoryText() {
1157
+ // Must wait for every queued write to actually apply first - see
1158
+ // writeToHeadlessTerm's own comment on why reading right after a raw
1159
+ // write would see stale/empty content.
1160
+ await awaitHeadlessTermCaughtUp();
1161
+ if (headlessTerm.buffer.active.type === 'normal') return '';
1162
+ return bufferToText(headlessTerm.buffer.normal);
1163
+ }
1164
+
1165
+ // SETU-009/015 real product ask (confirmed live by the user, 2026-10-27/
1166
+ // 28): cli-setu is a full terminal mirror - the phone must show the
1167
+ // ENTIRE session from start to end, same as a real terminal emulator's
1168
+ // own unbounded scrollback, not just a capped recent window.
1169
+ //
1170
+ // Real finding from live testing (confirmed via a real captured log, NOT
1171
+ // assumed - two more complex approaches were tried and ruled out before
1172
+ // landing on this): Claude Code's own interactive chat UI does NOT clear/
1173
+ // redraw the screen between normal turns at all - a live session showed
1174
+ // exactly ONE erase-display sequence for its entire lifetime (its own
1175
+ // startup banner), then genuinely just APPENDED new text as the
1176
+ // conversation grew, same as a plain scrolling terminal. (It also never
1177
+ // switches to the terminal's alternate screen buffer - buffer.active.type
1178
+ // stayed "normal" throughout - ruling out that angle too.) This means
1179
+ // there was never anything to recover/archive from a clear - the real
1180
+ // limit the user hit was simply `scrollback`'s own byte cap (first 200KB,
1181
+ // then 2MB), which has since been removed entirely (see `scrollback`'s
1182
+ // own declaration comment) per the user's own explicit choice to accept
1183
+ // unbounded memory growth over any cap that could still cut off real
1184
+ // history.
1185
+
1186
+ let processedLines = 0;
1187
+ let ptyProcess = null;
1188
+ let detachStdin = null;
1189
+ let pollTimer = null;
1190
+ let focusTimer = null;
1191
+ // No longer an interval (see the on-demand usage.refresh.request handler
1192
+ // below) - kept as a variable only so ptyProcess.onExit's cleanup has
1193
+ // something harmless to clearInterval() on, in case a future change ever
1194
+ // reintroduces a real timer here.
1195
+ let usageTimer = null;
1196
+ // Only actually parse PTY output for usage data while this is in the
1197
+ // future - set a few seconds out each time triggerKeystrokes is sent
1198
+ // (see below), cleared back to 0 the moment a match is found or the
1199
+ // window lapses. See the onData handler's usage-polling comment for why
1200
+ // this window exists at all instead of parsing every chunk forever.
1201
+ let usageListenUntil = 0;
1202
+ const USAGE_LISTEN_WINDOW_MS = 10_000;
1203
+ // Codex-shape usage de-dup (no trigger keystrokes, and no reliable
1204
+ // persistent status line to gate a check on - see cli-adapters/codex.js
1205
+ // and the onData handler's comment on why every chunk gets checked) -
1206
+ // only reports to the Backend when the parsed percentage actually
1207
+ // CHANGES, not on every chunk that happens to still show the same
1208
+ // still-rendered text.
1209
+ let lastReportedCodexContextPct = null;
1210
+ // Which onboarding gate (by `reason`) was last auto-answered - null once
1211
+ // no gate is currently on-screen. Identity-based, not time-based (see the
1212
+ // onData handler's comment for why a timer cooldown re-fired incorrectly
1213
+ // in testing) - re-answers only when a DIFFERENT gate appears, or the
1214
+ // same one reappears after genuinely clearing.
1215
+ let lastOnboardingAnswered = null;
1216
+ // De-dupes a Codex approval prompt that's still on-screen (and therefore
1217
+ // still matching detectApproval) across many chunks, vs. a genuinely NEW
1218
+ // prompt appearing - see cli-adapters/codex.js's detectApproval comment.
1219
+ let lastApprovalFingerprint = null;
1220
+
1221
+ // Best-effort - a dropped usage report just means Profile/Devices show a
1222
+ // slightly stale number until the next successful poll, same "core
1223
+ // function survives an enhancement failing" principle used everywhere
1224
+ // else in this app (push notifications, profile fetch, etc.).
1225
+ async function reportUsage(parsed) {
1226
+ if (!deviceId) return;
1227
+ try {
1228
+ await fetch(`${AUTH_SERVER}/device/usage`, {
1229
+ method: 'POST',
1230
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
1231
+ body: JSON.stringify({
1232
+ cliType: adapter.id,
1233
+ totalTokens: parsed.totalTokens,
1234
+ inputTokens: parsed.inputTokens,
1235
+ outputTokens: parsed.outputTokens,
1236
+ costUsd: parsed.costUsd,
1237
+ contextUsedPct: parsed.sessionContextUsedPct,
1238
+ weekUsedPct: parsed.weekUsedPct,
1239
+ sessionResetsAt: parsed.sessionResetsAt,
1240
+ weekResetsAt: parsed.weekResetsAt,
1241
+ }),
1242
+ });
1243
+ log(`[supervisor] Reported usage: ${JSON.stringify(parsed)}`);
1244
+ } catch (err) {
1245
+ log('[supervisor] Failed to report usage:', err.message);
1246
+ }
1247
+ }
1248
+
1249
+ // Laptop battery-low warning - reads Windows' own Win32_Battery WMI
1250
+ // class via a PowerShell one-liner (verified live: returns a real
1251
+ // EstimatedChargeRemaining percentage on a real laptop; returns NOTHING
1252
+ // at all on a desktop with no battery, which is exactly the "just skip
1253
+ // this feature there" behavior wanted - no separate desktop-detection
1254
+ // logic needed). Not a Node package - node's own APIs have no battery
1255
+ // reading at all, and this needs zero new dependencies.
1256
+ const BATTERY_LOW_THRESHOLD_PCT = 20;
1257
+ const BATTERY_POLL_INTERVAL_MS = 5 * 60_000;
1258
+ let batteryTimer = null;
1259
+ // Tracks whether the LAST reading was already below the threshold, so
1260
+ // the alert fires once per crossing (unplugged and draining past 20%)
1261
+ // rather than every single 5-minute poll for as long as the battery
1262
+ // stays low - repeating the same "your laptop is low" push every 5
1263
+ // minutes while someone's already aware and mid-charge (or just hasn't
1264
+ // gotten to a charger yet) would be pure noise, not a useful alert.
1265
+ let wasBatteryLow = false;
1266
+
1267
+ function checkBatteryOnce() {
1268
+ exec(
1269
+ 'powershell -NoProfile -Command "Get-CimInstance -ClassName Win32_Battery | Select-Object -ExpandProperty EstimatedChargeRemaining"',
1270
+ { timeout: 10_000 },
1271
+ (err, stdout) => {
1272
+ if (err) return; // no battery (desktop), PowerShell unavailable, etc. - silently skip, not an error worth logging every 5 minutes
1273
+ const pct = Number(String(stdout).trim());
1274
+ if (!Number.isFinite(pct)) return;
1275
+
1276
+ const isLow = pct < BATTERY_LOW_THRESHOLD_PCT;
1277
+ if (isLow && !wasBatteryLow) {
1278
+ log(`[supervisor] Battery low: ${pct}% - sending alert`);
1279
+ if (deviceId) {
1280
+ fetch(`${AUTH_SERVER}/device/battery-alert`, {
1281
+ method: 'POST',
1282
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
1283
+ body: JSON.stringify({ batteryPct: pct }),
1284
+ }).catch((fetchErr) => log('[supervisor] Failed to send battery alert:', fetchErr.message));
1285
+ }
1286
+ }
1287
+ wasBatteryLow = isLow;
1288
+ }
1289
+ );
1290
+ }
1291
+
1292
+ // Real product gap found by testing (direct user feedback, 2026-10-25):
1293
+ // the phone's Usage button only ever appeared for a session LAUNCHED
1294
+ // with `--cli claude`/`--cli codex` - someone who started a plain shell
1295
+ // session (adapter.id === 'shell') and then typed `claude` by hand into
1296
+ // it never saw the button, even though Claude Code was genuinely
1297
+ // running, because cliType is reported once at connect time and never
1298
+ // re-checked. This periodically walks the PTY's own child-process tree
1299
+ // and reports back whatever CLI is ACTUALLY running right now, so the
1300
+ // button (and Devices tab's own CLI label) reflects reality instead of
1301
+ // whichever --cli flag the session happened to start with.
1302
+ //
1303
+ // Windows-only for now (ptyProcess.pid here is PowerShell/cmd.exe, and
1304
+ // claude.cmd/codex.cmd (see cli-adapters/resolveWindowsBin.js) spawn
1305
+ // through an intermediate cmd.exe layer into a bare `node.exe` process -
1306
+ // the literal process NAME is useless for telling claude/codex/our own
1307
+ // supervisor apart, so this matches on CommandLine instead, which
1308
+ // Win32_Process exposes and `tasklist`/Unix `ps` equivalents don't in a
1309
+ // portable way). macOS/Linux detection (via `pgrep -f` walking `ps
1310
+ // --ppid`) is real follow-up work, not done here - this project's own
1311
+ // resolveWindowsBin.js gap (a hardcoded dev-machine path that broke for
1312
+ // every other Windows user) is exactly the kind of untested-elsewhere
1313
+ // mistake this narrower Windows-first scope is deliberately avoiding.
1314
+ const ADAPTER_DETECT_POLL_INTERVAL_MS = 10_000;
1315
+ let adapterDetectTimer = null;
1316
+ let lastDetectedCliType = null;
1317
+
1318
+ // One PowerShell call walks the WHOLE descendant tree from ptyProcess.pid
1319
+ // in a single round trip (building the parent->children map client-side
1320
+ // here would mean one Win32_Process query per depth level - this is the
1321
+ // same data, fetched once).
1322
+ //
1323
+ // Matching rule confirmed by reading the REAL installed shims, not
1324
+ // guessed:
1325
+ // - `claude.cmd` spawns `claude.exe` DIRECTLY (a real native PE32+
1326
+ // binary, not a node.exe wrapper) - its own CommandLine contains
1327
+ // `claude-code\bin\claude.exe` (the real install path component,
1328
+ // checked instead of a bare `claude.exe` since that alone could
1329
+ // collide with some unrelated program of the same name).
1330
+ // - `codex.cmd` spawns `node.exe "...\@openai\codex\bin\codex.js" ...` -
1331
+ // the process NAME here is just `node.exe` (useless alone - every
1332
+ // Node process, including this very supervisor, matches that), so
1333
+ // codex is matched on CommandLine containing `@openai\codex` instead.
1334
+ // Used by the Windows branch (detectRunningAdapterWindows) - the Unix
1335
+ // branch (detectRunningAdapterUnix) does its own equivalent matching
1336
+ // directly via two separate `pgrep -f` calls instead of calling this
1337
+ // function, since pgrep itself does the pattern-matching server-side
1338
+ // rather than this process inspecting a returned command-line blob - see
1339
+ // its own comment for why. Matching rule confirmed by reading the REAL
1340
+ // installed Windows shims (see detectRunningAdapterWindows's own
1341
+ // comment); the macOS/Linux side is NOT independently live-verified (no
1342
+ // Mac/Linux machine available this session - see SETU-006's own
1343
+ // progress-doc note), reasoned from how both CLIs are actually published
1344
+ // on npm instead: both ship as SCOPED packages whose real native binary
1345
+ // is spawned from inside that scope (@anthropic-ai/claude-code,
1346
+ // @openai/codex - confirmed via npm/socket.dev package metadata, not
1347
+ // guessed) - the scope+package-name substring should appear in the real
1348
+ // process command line on any platform/install method (Homebrew Node,
1349
+ // nvm, system Node, native installer), unlike a full file path, which
1350
+ // varies by all of those.
1351
+ function matchCommandLineToCliType(lowerCaseLines) {
1352
+ if (lowerCaseLines.includes('claude-code\\bin\\claude.exe') || lowerCaseLines.includes('claude-code/bin/claude')) return 'claude';
1353
+ if (lowerCaseLines.includes('@openai\\codex') || lowerCaseLines.includes('@openai/codex')) return 'codex';
1354
+ return 'shell';
1355
+ }
1356
+
1357
+ function applyDetectedAdapter(detected) {
1358
+ if (detected !== lastDetectedCliType) {
1359
+ lastDetectedCliType = detected;
1360
+ log(`[supervisor] Detected running CLI changed to: ${detected}`);
1361
+ }
1362
+ }
1363
+
1364
+ function detectRunningAdapter() {
1365
+ if (!ptyProcess) return;
1366
+ if (process.platform === 'win32') {
1367
+ detectRunningAdapterWindows();
1368
+ } else if (process.platform === 'darwin' || process.platform === 'linux') {
1369
+ detectRunningAdapterUnix();
1370
+ }
1371
+ // Any other process.platform (e.g. a BSD variant Node also reports)
1372
+ // silently skips detection entirely, same posture as this function's
1373
+ // own pre-existing Windows-only early return did before this change -
1374
+ // a session.id's cliType stays whatever it was reported at connect
1375
+ // time, never worse than before this feature existed at all.
1376
+ }
1377
+
1378
+ function detectRunningAdapterWindows() {
1379
+ const rootPid = ptyProcess.pid;
1380
+ exec(
1381
+ `powershell -NoProfile -Command "` +
1382
+ `$all = Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine; ` +
1383
+ `$ids = @(${rootPid}); ` +
1384
+ `$frontier = @(${rootPid}); ` +
1385
+ `while ($frontier.Count -gt 0) { ` +
1386
+ `$children = $all | Where-Object { $frontier -contains $_.ParentProcessId } | Select-Object -ExpandProperty ProcessId; ` +
1387
+ `$frontier = $children | Where-Object { $ids -notcontains $_ }; ` +
1388
+ `$ids += $frontier ` +
1389
+ `}; ` +
1390
+ `$all | Where-Object { $ids -contains $_.ProcessId } | Select-Object -ExpandProperty CommandLine" `,
1391
+ { timeout: 10_000 },
1392
+ (err, stdout) => {
1393
+ if (err) return; // PowerShell unavailable, WMI disabled, etc. - silently skip, same posture as checkBatteryOnce
1394
+ applyDetectedAdapter(matchCommandLineToCliType(String(stdout).toLowerCase()));
1395
+ }
1396
+ );
1397
+ }
1398
+
1399
+ // NOT independently live-verified this session (no real Mac/Linux machine
1400
+ // available - see SETU-006's own progress-doc note for exactly what to
1401
+ // check first on a real device before trusting this). Reasoned instead
1402
+ // from: (1) macOS's BSD `ps` does NOT support GNU's `--ppid` selector
1403
+ // (confirmed via web search, not assumed) - `pgrep -P <pid>` (find direct
1404
+ // children of a PID) is the one process-tree primitive genuinely portable
1405
+ // across both macOS and Linux's default toolchains, so the same
1406
+ // breadth-first walk the Windows branch does client-side via one
1407
+ // Win32_Process query is done here via repeated `pgrep -P` calls instead,
1408
+ // since there's no single-call portable equivalent of the Windows query.
1409
+ // Comma-separated -P list (`-P a,b,c`, NOT repeated `-P a -P b` flags) is
1410
+ // confirmed via BSD/NetBSD/OpenBSD/Solaris/macOS man pages as the
1411
+ // universally documented multi-parent form.
1412
+ // (2) Getting full command lines for an explicit PID list was ALSO
1413
+ // considered via `ps -o command= -p <pid-list>`, but a real comma-
1414
+ // separated `-p` list is only confirmed documented for Linux's ps, NOT
1415
+ // for macOS's own BSD ps (no source found confirming it there) - unlike
1416
+ // `-P` on pgrep, which IS confirmed across both. Using `pgrep -f
1417
+ // <pattern>` instead (confirmed portable: matches the full command line
1418
+ // against a pattern, system-wide) sidesteps this entirely - it finds every
1419
+ // PID anywhere on the system matching claude's/codex's own real install
1420
+ // path pattern, and the result is intersected against this walk's own
1421
+ // descendant-PID set (ids) in plain JS, rather than asking ps to filter
1422
+ // by PID list itself. A failure anywhere in this chain (pgrep missing,
1423
+ // PATH not inherited into node-pty's spawned environment, a permissions
1424
+ // issue) is caught and silently skipped, same posture as the Windows
1425
+ // branch's own `if (err) return`.
1426
+ function detectRunningAdapterUnix() {
1427
+ const rootPid = ptyProcess.pid;
1428
+ let ids = [rootPid];
1429
+ let frontier = [rootPid];
1430
+
1431
+ const stepOrFinish = () => {
1432
+ if (frontier.length === 0) {
1433
+ if (ids.length === 0) return;
1434
+ // pgrep -f with a plain substring pattern (no regex anchors needed -
1435
+ // pgrep's own -f does a substring/regex match against the full
1436
+ // command line already) for each known CLI path fragment, checked
1437
+ // against THIS walk's own descendant-PID set - a match found
1438
+ // system-wide that ISN'T one of our own descendants doesn't count
1439
+ // (e.g. an unrelated claude-code process the user has open in a
1440
+ // completely different terminal window).
1441
+ exec(`pgrep -f 'claude-code/bin/claude'`, { timeout: 5_000 }, (claudeErr, claudeOut) => {
1442
+ const claudeIds = claudeErr ? [] : String(claudeOut).split('\n').map((s) => Number(s.trim())).filter((n) => Number.isInteger(n) && n > 0);
1443
+ if (claudeIds.some((pid) => ids.includes(pid))) return applyDetectedAdapter('claude');
1444
+ exec(`pgrep -f '@openai/codex'`, { timeout: 5_000 }, (codexErr, codexOut) => {
1445
+ const codexIds = codexErr ? [] : String(codexOut).split('\n').map((s) => Number(s.trim())).filter((n) => Number.isInteger(n) && n > 0);
1446
+ applyDetectedAdapter(codexIds.some((pid) => ids.includes(pid)) ? 'codex' : 'shell');
1447
+ });
1448
+ });
1449
+ return;
1450
+ }
1451
+ exec(`pgrep -P ${frontier.join(',')}`, { timeout: 5_000 }, (err, stdout) => {
1452
+ // A real, expected outcome, not an error: pgrep exits non-zero
1453
+ // when a frontier PID has no children left to find - this is just
1454
+ // "no more descendants down this branch", not a failure of the
1455
+ // whole walk. Treated as "empty frontier" rather than aborting.
1456
+ const found = err ? [] : String(stdout).split('\n').map((s) => Number(s.trim())).filter((n) => Number.isInteger(n) && n > 0);
1457
+ const newIds = found.filter((pid) => !ids.includes(pid));
1458
+ ids = ids.concat(newIds);
1459
+ frontier = newIds;
1460
+ stepOrFinish();
1461
+ });
1462
+ };
1463
+ stepOrFinish();
1464
+ }
1465
+
1466
+ // Real bug found by testing (direct user feedback, 2026-10-25): the
1467
+ // Usage button now correctly APPEARS for a plain-shell session once
1468
+ // Claude Code is detected running inside it (see detectRunningAdapter
1469
+ // above + auth-server.js's detectedCliType), but tapping it still did
1470
+ // nothing - usage.refresh.request's handler and the /cost-output parser
1471
+ // both read `adapter.usage`, and `adapter` here is the module-level
1472
+ // object chosen ONCE at session launch (getAdapter(CLI_NAME) - see its
1473
+ // own declaration) - for a session that started as plain shell, that's
1474
+ // permanently shell.js's `usage: null`, no matter what
1475
+ // detectRunningAdapter later reports to the backend for UI purposes
1476
+ // alone. Reassigning the whole `adapter` variable was considered and
1477
+ // rejected: adapter.approvals (PTY-scrape detection, used by Codex) and
1478
+ // adapter.spawn (already executed once at PTY-spawn time, see main())
1479
+ // would behave unpredictably if swapped mid-session for a process that
1480
+ // was never actually spawned via that adapter's own spawn.command. Usage
1481
+ // parsing has no such coupling - claudeAdapter/codexAdapter's own
1482
+ // `usage` objects are pure functions over PTY text, safe to use for ANY
1483
+ // session once that real CLI is confirmed actually running inside it,
1484
+ // regardless of how the session itself was launched.
1485
+ function getActiveUsageAdapter() {
1486
+ if (adapter.usage) return adapter.usage; // session launched with --cli claude/codex - unchanged, exact original behavior
1487
+ if (lastDetectedCliType === 'claude') return claudeAdapter.usage;
1488
+ if (lastDetectedCliType === 'codex') return codexAdapter.usage;
1489
+ return null;
1490
+ }
1491
+
1492
+ // SETU-006 hardening: the SAME gap getActiveUsageAdapter fixes, for
1493
+ // Codex's PTY-scrape approval detection specifically. Claude Code's own
1494
+ // hook-queue approvals (pollForRequests/QUEUE_FILE) already work
1495
+ // regardless of launch-time adapter (see QUEUE_FILE's own declaration
1496
+ // comment - hooks are registered defensively for every session) - this
1497
+ // gap is narrower than first suspected: it's Codex-only, since Codex has
1498
+ // no hook mechanism to fall back on, only PTY-scraping, which the PTY-
1499
+ // scrape gate below used to key off the LAUNCH-TIME adapter alone.
1500
+ // codexAdapter.approvals' detectApproval/getDialogOptions/describePrompt/
1501
+ // autoAnswerOnboarding are all pure functions over PTY text (same
1502
+ // category as usage.parseFromOutput above) - safe to use for a session
1503
+ // that started as plain shell and had Codex launched inside it manually,
1504
+ // once detectRunningAdapter actually confirms Codex is running.
1505
+ function getActiveApprovalsAdapter() {
1506
+ if (adapter.approvals?.sourceMode === 'pty-scrape') return adapter.approvals; // session launched with --cli codex - unchanged, exact original behavior
1507
+ if (lastDetectedCliType === 'codex') return codexAdapter.approvals;
1508
+ return null;
1509
+ }
1510
+
1511
+ // SETU-010: real re-entrancy bug found by investigation (matches the PM
1512
+ // brief's own "duplicate approval prompts" symptom). setInterval fires
1513
+ // this every POLL_INTERVAL_MS (300ms) regardless of whether a PREVIOUS
1514
+ // call is still awaiting inside resolveRealOptions (which can take up to
1515
+ // 8*150ms=1200ms waiting for Claude Code's live menu to render). If a
1516
+ // second, genuinely new PermissionRequest lands in the queue file while
1517
+ // the first is still being resolved, a second overlapping call to this
1518
+ // function processes it concurrently - both end up calling relayApproval,
1519
+ // and relayApproval's own resolveStaleForSession (correctly assuming only
1520
+ // ONE prompt is ever open per session) then resolves whichever one
1521
+ // finishes first as "stale" the moment the other relays - the phone
1522
+ // briefly sees BOTH cards before the stale one flips to "Resolved at the
1523
+ // laptop" a moment later. Guarding re-entrancy here closes the race
1524
+ // without touching resolveRealOptions' own timing at all: the NEXT poll
1525
+ // tick after this one finishes will pick up the second event cleanly,
1526
+ // one at a time, the same way the normal (non-overlapping) case already
1527
+ // works correctly today.
1528
+ let pollForRequestsInFlight = false;
1529
+ async function pollForRequests() {
1530
+ // No queue file for this adapter (approvals: null - generic CLI or
1531
+ // Codex's plain-PTY mode) means there is nothing to poll: this CLI has
1532
+ // no known mechanism to report a prompt before it happens, so the human
1533
+ // just answers it directly in the mirrored terminal, with no
1534
+ // structured Confirmations card ever generated for it.
1535
+ if (!azureReady || !QUEUE_FILE) return;
1536
+ if (pollForRequestsInFlight) return;
1537
+ pollForRequestsInFlight = true;
1538
+ try {
1539
+ await pollForRequestsOnce();
1540
+ } finally {
1541
+ pollForRequestsInFlight = false;
1542
+ }
1543
+ }
1544
+
1545
+ async function pollForRequestsOnce() {
1546
+ let raw;
1547
+ try {
1548
+ raw = fs.readFileSync(QUEUE_FILE, 'utf8');
1549
+ } catch {
1550
+ return;
1551
+ }
1552
+
1553
+ const lines = raw.split('\n').filter(Boolean);
1554
+ if (lines.length <= processedLines) return;
1555
+
1556
+ const newLines = lines.slice(processedLines);
1557
+ processedLines = lines.length;
1558
+
1559
+ for (const line of newLines) {
1560
+ let event;
1561
+ try {
1562
+ event = JSON.parse(line);
1563
+ } catch {
1564
+ continue;
1565
+ }
1566
+
1567
+ if (event.hook_event_name === 'PostToolUse') {
1568
+ resolveIfPending(event);
1569
+ continue;
1570
+ }
1571
+
1572
+ // Real gap found by testing: tool_input.questions can hold MULTIPLE
1573
+ // questions for one single AskUserQuestion call (a real captured
1574
+ // payload had 3 - "Next task" -> "Approach" -> "Scope") - only ever
1575
+ // relay step 0 here; advanceAskUserQuestion (called from
1576
+ // handleAzureDecision once this step's answer is injected) relays
1577
+ // the rest, one at a time, as updates to the same promptId.
1578
+ const totalQuestions = event.tool_name === 'AskUserQuestion' ? (event.tool_input?.questions?.length || 1) : 1;
1579
+ const text = claudeAdapter.approvals.describePrompt(event, 0);
1580
+ // Real bug found by code review, fixed before ever shipping: step 0
1581
+ // was always treated as single-choice here, even when
1582
+ // tool_input.questions[0].multiSelect is true (getDialogOptions
1583
+ // correctly returns null for that case - see its own comment - but
1584
+ // nothing downstream of THIS call site ever checked for it, unlike
1585
+ // advanceAskUserQuestion, which already has the matching guard for
1586
+ // every step AFTER 0). relayApproval's own `options.map(...)` then
1587
+ // threw on null, caught by the generic try/catch and misleadingly
1588
+ // logged as "Failed to reach auth-server" - the prompt was never
1589
+ // relayed at all, so the phone never got a card and the session
1590
+ // looked hung. Mirrors advanceAskUserQuestion's exact shape so step 0
1591
+ // is no longer a special, unguarded case.
1592
+ const firstQuestion = event.tool_name === 'AskUserQuestion' ? event.tool_input?.questions?.[0] : null;
1593
+ if (firstQuestion?.multiSelect) {
1594
+ const multiSelectOptions = (firstQuestion.options || []).map((o) => ({ label: o.label, description: o.description || null }));
1595
+ await relayApproval(event, [], text, 0, totalQuestions, null, multiSelectOptions);
1596
+ } else {
1597
+ const options = await resolveRealOptions(event, 0);
1598
+ await relayApproval(event, options, text, 0, totalQuestions);
1599
+ }
1600
+ }
1601
+ }
1602
+
1603
+ // Real bug found by testing: getDialogOptions' Write/Bash/PowerShell
1604
+ // option sets are a hardcoded guess (the hook payload never carries the
1605
+ // real menu for those tool types) - it drifted the moment Claude Code
1606
+ // added a 4th choice ("switch to auto mode") to its own menu, showing the
1607
+ // phone 3 buttons for a real 4-option prompt. adapter.approvals.
1608
+ // parseLiveOptions reads the ACTUAL rendered menu from the terminal
1609
+ // instead, but PermissionRequest fires BEFORE the prompt is drawn on
1610
+ // screen (see this file's own top comment) - so a short retry loop here
1611
+ // gives the PTY time to actually render it before ever falling back to
1612
+ // the static guess. Skipped entirely for AskUserQuestion, whose real
1613
+ // options DO come through the hook payload already (getDialogOptions
1614
+ // reads tool_input.questions[0].options directly) - no need to wait on
1615
+ // a screen render for a case that's already exact.
1616
+ async function resolveRealOptions(event, questionIndex = 0) {
1617
+ if (!claudeAdapter.approvals.parseLiveOptions || event.tool_name === 'AskUserQuestion') {
1618
+ return claudeAdapter.approvals.getDialogOptions(event, questionIndex);
1619
+ }
1620
+ for (let attempt = 0; attempt < 8; attempt++) {
1621
+ const live = claudeAdapter.approvals.parseLiveOptions(scrollback.slice(-3000));
1622
+ if (live) return live;
1623
+ await new Promise((r) => setTimeout(r, 150));
1624
+ }
1625
+ log('[supervisor] Live menu did not render in time - falling back to the static guess for this prompt.');
1626
+ return claudeAdapter.approvals.getDialogOptions(event, questionIndex);
1627
+ }
1628
+
1629
+ // Real gap found by testing: a prompt answered directly at the laptop's
1630
+ // own keyboard (never via the phone) left its card stuck "pending"
1631
+ // forever on the phone, since nothing ever told the Backend the tool
1632
+ // actually ran. PostToolUse only fires once a tool call actually
1633
+ // executes - which can only happen after ITS permission prompt was
1634
+ // answered somehow, locally or remotely - so a PostToolUse for the same
1635
+ // tool_name + session_id we're still holding pending is real proof that
1636
+ // prompt got resolved. Matched on tool_name + session_id rather than
1637
+ // exact tool_input equality - Claude Code's PostToolUse payload doesn't
1638
+ // echo back tool_input in a byte-identical shape to PermissionRequest's,
1639
+ // and two DIFFERENT pending prompts for the exact same tool_name in the
1640
+ // exact same session (e.g. two Bash calls in a row) resolve in the order
1641
+ // they were opened either way, so ambiguity here is harmless.
1642
+ function reportResolvedLocally(promptId, reason) {
1643
+ log(`[supervisor] ${promptId} resolved locally (${reason}) - notifying Backend.`);
1644
+ fetch(`${AUTH_SERVER}/relay/confirmation-resolved-locally`, {
1645
+ method: 'POST',
1646
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
1647
+ body: JSON.stringify({ sessionId: SESSION_ID, promptId }),
1648
+ }).catch((err) => log('[supervisor] Failed to report local resolution:', err.message));
1649
+ }
1650
+
1651
+ // Extracts a real identity for one AskUserQuestion prompt - its actual
1652
+ // question text, not just "this session asked SOMETHING". Undefined for
1653
+ // every other tool_name, which is fine: those never fire two pending
1654
+ // prompts back-to-back for the same session the way AskUserQuestion can
1655
+ // (see resolveIfPending's own comment).
1656
+ function askUserQuestionKey(event) {
1657
+ return event.tool_input?.questions?.[0]?.question;
1658
+ }
1659
+
1660
+ function resolveIfPending(postToolUseEvent) {
1661
+ // Real bug found by testing: matching on tool_name + session_id alone
1662
+ // resolved whichever pending prompt happened to be found FIRST in the
1663
+ // Map, not necessarily the one that actually just got answered.
1664
+ // AskUserQuestion specifically can have two genuinely different
1665
+ // pending questions in flight for the SAME session at once - rejecting
1666
+ // one often makes Claude Code immediately ask a related follow-up
1667
+ // question before the first prompt's PostToolUse even fires - so this
1668
+ // ambiguity isn't a rare edge case for it, it's a real, observed
1669
+ // sequence. Matching on the actual question text (when available)
1670
+ // instead of just tool_name+session_id resolves the CORRECT one even
1671
+ // when two are pending at once; falls back to the old less-precise
1672
+ // match for every other tool_name, where this ambiguity doesn't arise.
1673
+ const postKey = askUserQuestionKey(postToolUseEvent);
1674
+ for (const [promptId, pending] of pendingPrompts.entries()) {
1675
+ if (pending.session_id !== postToolUseEvent.session_id) continue;
1676
+ if (pending.tool_name !== postToolUseEvent.tool_name) continue;
1677
+ if (postKey && askUserQuestionKey(pending) && askUserQuestionKey(pending) !== postKey) continue;
1678
+ pendingPrompts.delete(promptId);
1679
+ reportResolvedLocally(promptId, `PostToolUse for ${postToolUseEvent.tool_name}`);
1680
+ return;
1681
+ }
1682
+ }
1683
+
1684
+ // Real gap found by testing: an APPROVED prompt gets a PostToolUse event
1685
+ // (resolveIfPending above catches it), but a REJECTED/interrupted one
1686
+ // never does - the tool call never ran, so there's no "it ran" signal to
1687
+ // observe at all. The one thing that IS still true: Claude Code only ever
1688
+ // has ONE open prompt per session at a time, so a genuinely NEW
1689
+ // PermissionRequest arriving for a session is real proof any OLDER
1690
+ // pending prompt in that same session is no longer live - it was
1691
+ // rejected, interrupted, or otherwise handled, by definition, since
1692
+ // Claude Code moved on. Called right before relaying the new prompt.
1693
+ function resolveStaleForSession(sessionId, reason = 'a newer prompt arrived for the same session') {
1694
+ for (const [promptId, pending] of pendingPrompts.entries()) {
1695
+ if (pending.session_id === sessionId) {
1696
+ pendingPrompts.delete(promptId);
1697
+ reportResolvedLocally(promptId, reason);
1698
+ }
1699
+ }
1700
+ }
1701
+
1702
+ // Shared by both approval-detection mechanisms (Claude Code's hook-queue
1703
+ // polling above, and Codex's PTY-scrape detection below) - same
1704
+ // pendingPrompts bookkeeping and /relay/confirmation-request call either
1705
+ // way, since from the phone's perspective a confirmation card looks
1706
+ // identical regardless of which CLI/detection method produced it.
1707
+ //
1708
+ // questionIndex/totalQuestions (real gap found by testing - see
1709
+ // describePrompt's own comment on AskUserQuestion's multi-question
1710
+ // payloads): when set, this call is relaying ONE STEP of a multi-step
1711
+ // AskUserQuestion wizard, not a standalone prompt. reusePromptId (set by
1712
+ // advanceAskUserQuestion for steps 2+) keeps the SAME promptId across
1713
+ // every step of one wizard, so the phone updates its existing card in
1714
+ // place instead of getting a new one per step - see ConfirmationsScreen.
1715
+ // js's confirmation.request handler, which now treats an already-known
1716
+ // promptId as "replace this card's contents", not "add a new card".
1717
+ // multiSelectOptions (real key mapping confirmed live - see claude.js's
1718
+ // buildMultiSelectKeystrokes): a multiSelect AskUserQuestion step
1719
+ // (checkboxes + Submit) has no 1:1 "pick option N -> send keystroke N"
1720
+ // shape the way every other prompt here does, so it's relayed with its
1721
+ // raw {label, description} list instead of `options`, and the phone
1722
+ // sends back WHICH indices were checked (not a single optionIndex) - see
1723
+ // handleAzureDecision's own isMultiSelect branch.
1724
+ // approvalsAdapter (real bug found by code review, fixed before ever
1725
+ // shipping): this used to hardcode `claudeAdapter.approvals` below for
1726
+ // BOTH the resolveStaleForSession gate and isMenuStillOnScreen, even when
1727
+ // relaying a Codex-detected prompt (handleDetectedApproval, sourceMode:
1728
+ // 'pty-scrape') - Codex's own detected event has no tool_name/session_id
1729
+ // at all (confirmed in codex.js's detectApproval - its real shape is
1730
+ // {fingerprint, isCommandPrompt, description, destination, raw}), so (1)
1731
+ // `event.tool_name === 'AskUserQuestion'` was always false for Codex,
1732
+ // silently skipping resolveStaleForSession's cleanup for every Codex
1733
+ // prompt, and (2) `event.tool_name !== 'AskUserQuestion'` was always TRUE
1734
+ // for Codex, so watchForMenuDisappearance ran anyway - but polling
1735
+ // CLAUDE's own PROCEED_RE wording against a real Codex menu, which never
1736
+ // matches it, meaning the very first poll (500ms later) always saw "no
1737
+ // menu" and wrongly resolved a still-genuinely-pending Codex approval as
1738
+ // abandoned. Passed in explicitly now (defaults to claudeAdapter, correct
1739
+ // for pollForRequestsOnce's own exclusively-Claude hook-queue path) so
1740
+ // each call site uses the adapter that actually produced the event -
1741
+ // Codex's own approvals object has no isMenuStillOnScreen at all, so it
1742
+ // correctly gets skipped below rather than borrowing Claude's.
1743
+ async function relayApproval(event, options, text, questionIndex = 0, totalQuestions = 1, reusePromptId = null, multiSelectOptions = null, approvalsAdapter = claudeAdapter.approvals) {
1744
+ // Real bug found by testing (live capture): Claude Code can genuinely
1745
+ // have MORE THAN ONE PermissionRequest queued for the same session at
1746
+ // once - e.g. two Read calls issued together each fire their own event
1747
+ // only ~400ms apart, but only the FIRST one's menu is actually on
1748
+ // screen; the second is real and still truly pending behind it, not
1749
+ // stale. resolveStaleForSession used to run for EVERY new prompt,
1750
+ // which wrongly evicted prompt #1 the instant prompt #2 arrived - the
1751
+ // phone's later tap on prompt #1's card then hit "unknown promptId,
1752
+ // ignoring" since it had already been marked "resolved at the laptop"
1753
+ // for a decision that was never actually made. Scoped to ONLY a brand
1754
+ // new AskUserQuestion wizard starting (questionIndex 0 AND this
1755
+ // tool_name) - that's the one case with no other safety net
1756
+ // (watchForMenuDisappearance below explicitly skips AskUserQuestion,
1757
+ // see its own comment) and where "Claude moved on" is still a safe
1758
+ // read. Every other tool_name relies on watchForMenuDisappearance's
1759
+ // real on-screen check instead, which doesn't have this false-positive
1760
+ // problem - it only resolves a prompt once its OWN menu is confirmed
1761
+ // gone, never because a different prompt merely showed up. Codex events
1762
+ // never match 'AskUserQuestion' (they have no tool_name at all), so
1763
+ // this never fires for Codex - correct, since Codex has no multi-
1764
+ // question wizard concept to begin with.
1765
+ if (questionIndex === 0 && event.tool_name === 'AskUserQuestion') resolveStaleForSession(event.session_id);
1766
+
1767
+ // Real bug found by testing: Date.now() alone collides when two
1768
+ // separate supervisor processes (different laptops/sessions) detect a
1769
+ // prompt in the same millisecond - the phone's seenPromptIds dedup then
1770
+ // treats the second, genuinely different prompt as a duplicate of the
1771
+ // first and drops it, or conflates their responses. DEVICE_NAME makes
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
+ }
1781
+ const promptId = reusePromptId || `p-${DEVICE_NAME}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1782
+ pendingPrompts.set(promptId, { ...event, options, questionIndex, totalQuestions, isMultiSelect: !!multiSelectOptions });
1783
+ if (fingerprint) approvalDeduper.remember(fingerprint, promptId);
1784
+
1785
+ log(`[supervisor] Detected approval prompt: ${text}`);
1786
+ log(`[supervisor] Relaying to auth-server as promptId=${promptId}${reusePromptId ? ' (step update)' : ''}...`);
1787
+
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
+ });
1812
+
1813
+ if (approvalsAdapter.isMenuStillOnScreen && event.tool_name !== 'AskUserQuestion') {
1814
+ // Real bug found by testing (live capture): two back-to-back Read
1815
+ // prompts for the same session each got their own watcher, but
1816
+ // isMenuStillOnScreen's generic check couldn't tell them apart - see
1817
+ // its own comment and distinguishingTextFor's. Passing the real file
1818
+ // path/command this SPECIFIC prompt is about means a different
1819
+ // prompt's identical-looking menu is never mistaken for this one's.
1820
+ const distinguishingText = approvalsAdapter.distinguishingTextFor?.(event) || null;
1821
+ watchForMenuDisappearance(promptId, distinguishingText, approvalsAdapter);
1822
+ }
1823
+ }
1824
+
1825
+ // Polls every 500ms for up to 5 minutes (a real user can genuinely take
1826
+ // that long to decide) - stops early the moment isMenuStillOnScreen
1827
+ // returns false, or the moment this promptId is no longer pending at all
1828
+ // (already resolved through the phone, PostToolUse, or a newer prompt -
1829
+ // no point continuing to poll something that's already been handled).
1830
+ async function watchForMenuDisappearance(promptId, distinguishingText = null, approvalsAdapter = claudeAdapter.approvals) {
1831
+ const deadline = Date.now() + 5 * 60_000;
1832
+ while (Date.now() < deadline) {
1833
+ await new Promise((r) => setTimeout(r, 500));
1834
+ if (!pendingPrompts.has(promptId)) return; // already resolved some other way
1835
+ if (!approvalsAdapter.isMenuStillOnScreen(scrollback.slice(-3000), distinguishingText)) {
1836
+ pendingPrompts.delete(promptId);
1837
+ reportResolvedLocally(promptId, 'the on-screen menu is gone - resolved locally (approved, rejected, or interrupted)');
1838
+ return;
1839
+ }
1840
+ }
1841
+ }
1842
+
1843
+ // Codex-specific entry point (cli-adapters/codex.js's sourceMode:
1844
+ // 'pty-scrape') - called from the onData handler once detectApproval
1845
+ // finds a NEW (not-yet-seen) prompt in the scrollback window.
1846
+ function handleDetectedApproval(detected) {
1847
+ const activeApprovals = getActiveApprovalsAdapter();
1848
+ const options = activeApprovals.getDialogOptions(detected);
1849
+ const text = activeApprovals.describePrompt(detected);
1850
+ relayApproval(detected, options, text, 0, 1, null, null, activeApprovals);
1851
+ }
1852
+
1853
+ // Real gap found by testing: a laptop-side warning used to fire here any
1854
+ // time another setu was already running for the same folder - built
1855
+ // before the real enforcement below existed, to catch accidental
1856
+ // duplicates. Removed: running a 2nd session in the same folder is
1857
+ // explicitly an ALLOWED product rule (2 live sessions per device - see
1858
+ // auth-server.js's PLAN_LIMITS.maxLiveSessions, now scoped per-device),
1859
+ // so warning about it read alarmingly for something that's actually
1860
+ // fine, and the real safety net now exists at the backend: /device/
1861
+ // connect itself rejects a 3rd session for this device with a clear
1862
+ // error message, before it ever gets a usable connection - a stronger,
1863
+ // more reliable guarantee than a laptop-side warning a user could miss
1864
+ // or click past anyway.
1865
+ async function main() {
1866
+ if (QUEUE_FILE) fs.writeFileSync(QUEUE_FILE, '');
1867
+ fs.writeFileSync(PROCESSED_FILE, '');
1868
+
1869
+ console.log(`\n[supervisor] Spawning ${adapter.displayName} in a PTY (device=${DEVICE_NAME}, session=${SESSION_ID}, cwd=${WORKING_DIR})...`);
1870
+
1871
+ try {
1872
+ ptyProcess = pty.spawn(adapter.spawn.command, adapter.spawn.args(WORKING_DIR), {
1873
+ name: 'xterm-color',
1874
+ cols: PTY_COLS,
1875
+ rows: PTY_ROWS,
1876
+ cwd: WORKING_DIR,
1877
+ env: process.env,
1878
+ });
1879
+ } catch (err) {
1880
+ // Real bug found by testing (PM report, multiple real macOS users):
1881
+ // node-pty's spawn() can still throw an opaque native error (e.g.
1882
+ // "posix_spawnp failed") for reasons shell.js's own path validation
1883
+ // doesn't cover - a CLI adapter (claude/codex) genuinely not
1884
+ // installed/on PATH, a cwd the OS won't let this process enter, a
1885
+ // sandboxed/restricted environment. Previously this propagated all
1886
+ // the way up to main().catch's generic "[supervisor] fatal: <msg>"
1887
+ // with zero context about WHAT was being spawned or WHERE - telling
1888
+ // the user only that something failed, never why. Re-throwing with
1889
+ // the actual command and cwd attached turns that into an actionable
1890
+ // message instead of a dead end.
1891
+ throw new Error(`Could not start "${adapter.spawn.command}" in ${WORKING_DIR}: ${err.message}`);
1892
+ }
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
+
1900
+ // SETU-014: keep the real PTY (and the headless buffer that mirrors it
1901
+ // for the phone, see headlessTerm's own comment) in sync with the
1902
+ // laptop's own terminal WINDOW size - see PTY_COLS/PTY_ROWS's own
1903
+ // declaration comment for why this is a different, previously-
1904
+ // unaddressed case from the phone-resize-is-ignored decision right next
1905
+ // to it. 'resize' only fires on a real TTY (process.stdout.columns/rows
1906
+ // being defined at all already implies one - see this file's own
1907
+ // process.stdout.columns || 120 fallback), so this is a safe no-op for
1908
+ // piped/non-TTY output, same posture as the rest of this file's TTY-
1909
+ // dependent code. Debounced (150ms) per @xterm/headless's own
1910
+ // documented "best practice to debounce calls to resize" (a user
1911
+ // dragging a terminal window's edge can fire many native resize events
1912
+ // per second - resizing the PTY/headless buffer on every single one
1913
+ // would be wasteful redraw churn at best).
1914
+ let resizeDebounceTimer = null;
1915
+ process.stdout.on('resize', () => {
1916
+ clearTimeout(resizeDebounceTimer);
1917
+ resizeDebounceTimer = setTimeout(() => {
1918
+ const cols = process.stdout.columns || PTY_COLS;
1919
+ const rows = process.stdout.rows || PTY_ROWS;
1920
+ if (cols === PTY_COLS && rows === PTY_ROWS) return;
1921
+ PTY_COLS = cols;
1922
+ PTY_ROWS = rows;
1923
+ try {
1924
+ ptyProcess.resize(PTY_COLS, PTY_ROWS);
1925
+ headlessTerm.resize(PTY_COLS, PTY_ROWS);
1926
+ log(`[supervisor] Laptop terminal resized to ${PTY_COLS}x${PTY_ROWS} - PTY and headless buffer resized to match.`);
1927
+ } catch (err) {
1928
+ // node-pty's resize() can throw if the PTY is already mid-exit (a
1929
+ // narrow race with the process ending right as a resize event
1930
+ // fires) - logged, not fatal, same posture as every other best-
1931
+ // effort operation in this file once a session is already winding
1932
+ // down.
1933
+ log('[supervisor] Failed to resize PTY/headless buffer:', err.message);
1934
+ }
1935
+ }, 150);
1936
+ });
1937
+
1938
+ ptyProcess.onData((data) => {
1939
+ process.stdout.write(data);
1940
+
1941
+ // Section 4c call ① -> the scrollback (Section 7) is kept regardless
1942
+ // of whether anyone's watching, so a phone attaching later still gets
1943
+ // real history, not just whatever arrives after it connects.
1944
+ appendScrollback(data);
1945
+ // Fed the IDENTICAL bytes as the real PTY, in the same order - see
1946
+ // headlessTerm's own declaration comment for why this (not the raw
1947
+ // scrollback string above) is what makes a genuinely complete
1948
+ // transcript possible. writeToHeadlessTerm (not a direct .write()
1949
+ // call) queues this safely - see its own comment on why reading the
1950
+ // buffer right after a raw write would see stale/empty content.
1951
+ writeToHeadlessTerm(data);
1952
+
1953
+ // Real gap found by testing: gating live streaming on isFocused (only
1954
+ // spend a request if a phone is CURRENTLY looking at this session)
1955
+ // meant anything that happened while the user was on a different tab,
1956
+ // or had the app backgrounded, was never streamed live - only
1957
+ // recoverable later via the one-time scrollback snapshot on next
1958
+ // attach, which (now uncapped - see `scrollback`'s own comment) always
1959
+ // covers the full session either way. The whole point of this feature
1960
+ // is "the phone's terminal shows the exact same thing scrolling up as
1961
+ // the real laptop terminal does" - a cost optimization that can
1962
+ // silently drop real content contradicts that, so this now always
1963
+ // streams regardless of isFocused (kept only for the Devices tab's
1964
+ // online heartbeat - see pollFocus's own comment).
1965
+ streamOutput(data);
1966
+
1967
+ // Usage polling (see cli-adapters/claude.js) - only ever active for
1968
+ // an adapter that defines usage.parseFromOutput; every other adapter
1969
+ // leaves usageState untouched and Devices/Profile just show nothing
1970
+ // for token usage, same "optional richness" pattern as approvals.
1971
+ //
1972
+ // Real bug found by testing: parsing each raw `data` chunk in
1973
+ // isolation silently failed most of the time - a PTY streams output
1974
+ // in small, arbitrarily-split pieces (this is exactly why
1975
+ // TerminalScreen.js's own out-of-order chunk sequencing exists), and
1976
+ // `/cost`'s multi-line render (the "58% used" text, the "Resets ..."
1977
+ // line right after it) is not guaranteed to land in one chunk. A
1978
+ // regex against a single chunk that happens to end mid-render just
1979
+ // never matches, with no error - it looked like "auto-refresh isn't
1980
+ // working" from the phone side when the real gap was here. Matching
1981
+ // against a trailing window of the already-accumulated scrollback
1982
+ // instead guarantees the full rendered output is visible regardless
1983
+ // of how the PTY happened to chunk it.
1984
+ //
1985
+ // Gated to a short window after triggerKeystrokes was actually sent
1986
+ // (usageListenUntil) rather than running on every chunk for the
1987
+ // entire session - re-running 6 regexes against a 4KB window on
1988
+ // every single byte the CLI ever prints (a long response streams
1989
+ // MANY chunks) would be pure waste outside the brief moment right
1990
+ // after we actually asked for a fresh reading.
1991
+ const usageAdapterForParsing = getActiveUsageAdapter();
1992
+ if (usageAdapterForParsing?.parseFromOutput) {
1993
+ if (usageAdapterForParsing.triggerKeystrokes) {
1994
+ // Claude Code shape: only worth checking right after we actually
1995
+ // asked for a fresh reading (see usageListenUntil above).
1996
+ if (Date.now() < usageListenUntil) {
1997
+ const recentWindow = scrollback.slice(-4000);
1998
+ const parsed = usageAdapterForParsing.parseFromOutput(recentWindow);
1999
+ if (parsed) {
2000
+ reportUsage(parsed);
2001
+ usageListenUntil = 0; // got it - stop checking until the next trigger
2002
+ // Real feedback: /cost's full-screen usage report otherwise
2003
+ // sits visible in the person's own terminal after an
2004
+ // on-demand refresh, showing exactly what just happened
2005
+ // behind the scenes - not something a remote refresh should
2006
+ // leave lying around for whoever's physically at the laptop
2007
+ // to wonder about. Esc is the standard way Claude Code's own
2008
+ // full-screen views (Usage/Config/Status) are dismissed
2009
+ // elsewhere in this CLI - NOT independently re-verified
2010
+ // against this exact /cost screen in this session, so treat
2011
+ // this as the first real test of that assumption, not a
2012
+ // confirmed fact. Same mechanism as the approval
2013
+ // auto-injection above (ptyProcess.write with a real
2014
+ // keystroke), nothing new.
2015
+ ptyProcess.write('\x1b');
2016
+ }
2017
+ }
2018
+ } else {
2019
+ // Codex shape (cli-adapters/codex.js) - real bug found by live
2020
+ // testing: "% context left" is NOT a persistent, always-visible
2021
+ // status line the way the first version of this comment assumed.
2022
+ // It only renders for a brief moment right after a turn finishes,
2023
+ // while the input box is idle-focused ("tab to queue message ...
2024
+ // NN% context left") - gone again as soon as the next prompt is
2025
+ // typed or another turn starts. A 5-minute throttle (copied from
2026
+ // Claude Code's shape, where /cost is manually triggered and its
2027
+ // output persists on screen) missed this window almost every
2028
+ // time in testing - across several real approved turns, usage
2029
+ // was never once recorded, because the 5-minute cooldown was
2030
+ // still active during the one brief moment the text existed.
2031
+ // There's no reliable trigger to key a narrower check off (see
2032
+ // README.md), so the only option that actually works is checking
2033
+ // EVERY chunk - affordable here since this is one small regex,
2034
+ // not Claude Code's six-regex /cost parse.
2035
+ const recentWindow = scrollback.slice(-4000);
2036
+ const parsed = usageAdapterForParsing.parseFromOutput(recentWindow);
2037
+ // De-duped by the actual percentage, not a timer - the same
2038
+ // "100% context left" render can appear across several
2039
+ // consecutive chunks before Codex's next redraw changes it,
2040
+ // and reporting on every one of those would spam
2041
+ // /device/usage with identical, redundant POSTs.
2042
+ if (parsed && parsed.sessionContextUsedPct !== lastReportedCodexContextPct) {
2043
+ lastReportedCodexContextPct = parsed.sessionContextUsedPct;
2044
+ reportUsage(parsed);
2045
+ }
2046
+ }
2047
+ }
2048
+
2049
+ // Approval detection for an adapter using PTY-text scraping instead
2050
+ // of a hook queue (see cli-adapters/codex.js's sourceMode) - Claude
2051
+ // Code's approvals flow through pollForRequests/QUEUE_FILE instead;
2052
+ // this branch is a no-op when getActiveApprovalsAdapter() returns null
2053
+ // (Claude Code, generic, or no Codex detected at all - see its own
2054
+ // header comment for the SETU-006 gap this now also covers: a session
2055
+ // launched as plain shell with Codex started inside it manually).
2056
+ const activeApprovals = getActiveApprovalsAdapter();
2057
+ if (activeApprovals && azureReady) {
2058
+ const recentWindow = scrollback.slice(-4000);
2059
+
2060
+ const onboarding = activeApprovals.autoAnswerOnboarding(recentWindow);
2061
+ if (onboarding && onboarding.reason !== lastOnboardingAnswered) {
2062
+ // Real bug found by testing: a time-based cooldown (originally
2063
+ // 2s) re-fired repeatedly on the SAME still-on-screen gate,
2064
+ // sometimes minutes apart - the screen can stay rendered in the
2065
+ // scrollback window far longer than any short cooldown, since
2066
+ // it's real elapsed wall-clock time until Codex actually
2067
+ // processes the keystroke and redraws, not a fixed delay.
2068
+ // Tracking WHICH gate (by reason) was last answered instead of a
2069
+ // timer means it's answered exactly once and never re-sent until
2070
+ // a genuinely DIFFERENT gate (or none) appears - each extra
2071
+ // stray keypress risked landing on the real chat input once the
2072
+ // gate actually cleared.
2073
+ lastOnboardingAnswered = onboarding.reason;
2074
+ log(`[supervisor] Auto-answering Codex onboarding gate: ${onboarding.reason}`);
2075
+ ptyProcess.write(onboarding.keystrokes);
2076
+ } else if (!onboarding) {
2077
+ lastOnboardingAnswered = null; // gate cleared - a future recurrence should be answered again
2078
+ const detected = activeApprovals.detectApproval(recentWindow);
2079
+ if (detected && detected.fingerprint !== lastApprovalFingerprint) {
2080
+ lastApprovalFingerprint = detected.fingerprint;
2081
+ handleDetectedApproval(detected);
2082
+ }
2083
+ }
2084
+ }
2085
+
2086
+ // Real gap found by testing: an APPROVED prompt gets a real
2087
+ // PostToolUse hook event to key off of (resolveIfPending above), but
2088
+ // a REJECTED/interrupted one produces no hook event at all - the tool
2089
+ // call never ran. A PTY-text-scan for Claude Code's own "Interrupted..."
2090
+ // wording was tried here and removed again - real captured terminal
2091
+ // output across several live rejection tests never actually contained
2092
+ // that literal text in a form the regex could reliably match (Claude
2093
+ // Code doesn't render it consistently enough to key off of). Left as
2094
+ // the reliable fallback instead: a rejected prompt clears once ANOTHER
2095
+ // prompt arrives for the same session (resolveStaleForSession, called
2096
+ // from relayApproval below) - not instant, but proven correct across
2097
+ // testing, unlike the PTY-scan attempt.
2098
+ });
2099
+
2100
+ // Single real exit path for this whole process, on Windows. Real bug
2101
+ // found by testing, three rounds deep (2026-10-22, then twice more
2102
+ // live on 2026-10-25 after two incomplete fixes): node-pty's
2103
+ // `ptyProcess.kill()` on Windows (ConPTY) does NOT synchronously tear
2104
+ // down its native handles - it schedules an ASYNC close (confirmed via
2105
+ // node-pty's own GitHub issues: microsoft/node-pty#584, #423, #375,
2106
+ // #495). Calling `process.exit()` immediately after `.kill()`, from
2107
+ // more than one place in this file, raced that async teardown and/or
2108
+ // raced each OTHER - libuv hit a handle already mid-close and crashed
2109
+ // with `Assertion failed: !(handle->flags & UV_HANDLE_CLOSING)`.
2110
+ //
2111
+ // Fix: every call site that wants to end the process (the 403/401
2112
+ // rejection in connectToAzure, and cleanupAndExit's SIGINT/SIGTERM/
2113
+ // SIGHUP handler below) now ONLY sets process.exitCode and calls
2114
+ // ptyProcess.kill() - neither calls process.exit() itself anymore.
2115
+ // This one handler is the SINGLE place that actually exits, once
2116
+ // node-pty's real async teardown completes and this fires - whether
2117
+ // the pty died on its own (user typed `exit`) or we killed it on
2118
+ // purpose. finishedExiting guards against this firing more than once
2119
+ // (node-pty's issue threads also warn kill()/exit() called twice can
2120
+ // itself retrigger the same assertion).
2121
+ let finishedExiting = false;
2122
+ ptyProcess.onExit(({ exitCode }) => {
2123
+ if (finishedExiting) return;
2124
+ finishedExiting = true;
2125
+ try { if (detachStdin) detachStdin(); } catch {}
2126
+ terminalOwned = false; // the terminal is the user's again: diagnostics may print
2127
+ console.log(`\n[supervisor] ${adapter.displayName} exited with code ${exitCode}`);
2128
+ diag.flushAtExit();
2129
+ if (pollTimer) clearInterval(pollTimer);
2130
+ if (focusTimer) clearInterval(focusTimer);
2131
+ if (usageTimer) clearInterval(usageTimer);
2132
+ if (batteryTimer) clearInterval(batteryTimer);
2133
+ if (adapterDetectTimer) clearInterval(adapterDetectTimer);
2134
+ if (ws) ws.close();
2135
+ removePidFile();
2136
+ // If a caller (connectToAzure's 403/401, or cleanupAndExit) already
2137
+ // set process.exitCode before calling .kill(), respect that instead
2138
+ // of the PTY's own exit code - a plan-limit rejection should exit
2139
+ // non-zero even though PowerShell itself was killed cleanly
2140
+ // (exitCode 0 from its own perspective).
2141
+ process.exit(process.exitCode ?? exitCode ?? 0);
2142
+ });
2143
+
2144
+ // Real feedback: an automatic timer used to run here (every 5 minutes,
2145
+ // unconditionally) asking the session for a fresh /cost reading -
2146
+ // removed after live testing showed it genuinely disrupting someone
2147
+ // actively working at the laptop, taking over their visible terminal
2148
+ // with a full-screen usage report on a schedule nobody asked for. Usage
2149
+ // now only ever refreshes on an explicit request from the phone (see
2150
+ // this file's 'usage.refresh.request' handler above) - the SAME
2151
+ // triggerKeystrokes mechanism, just fired on demand instead of blind
2152
+ // polling. usageTimer is kept defined (see its own comment above) so
2153
+ // ptyProcess.onExit's cleanup still has a valid, harmless no-op target.
2154
+
2155
+ pollTimer = setInterval(pollForRequests, POLL_INTERVAL_MS);
2156
+ // Real bug found by testing (PM report: "device shows offline after
2157
+ // connecting"): focusTimer used to start HERE, unconditionally, before
2158
+ // connectToAzure() (called at the bottom of this function, unawaited)
2159
+ // had any chance to resolve its /device/connect call and set the real
2160
+ // deviceId below. pollFocus's own deviceId-aware URL building silently
2161
+ // omits the heartbeat whenever deviceId is still null - harmless for a
2162
+ // couple of ticks on a normal fast connect, but genuinely persistent
2163
+ // (heartbeat omitted for the ENTIRE outage) whenever /device/connect is
2164
+ // stuck in its own 3s retry loop (network hiccup, backend restart) -
2165
+ // every tick silently did nothing, with no visible error, for as long
2166
+ // as that retry loop ran. Moved to start right where deviceId itself
2167
+ // gets set, inside connectToAzure() (see its own comment there) -
2168
+ // "Offline" on the phone now correctly means "genuinely not
2169
+ // connected," never "connected, but the heartbeat hasn't started yet."
2170
+ // CLI-agnostic - runs for every adapter (Claude Code, Codex, generic),
2171
+ // since battery is a property of the LAPTOP, not of whatever CLI it
2172
+ // happens to be running.
2173
+ checkBatteryOnce(); // one immediate reading at startup, not just 5 min later
2174
+ batteryTimer = setInterval(checkBatteryOnce, BATTERY_POLL_INTERVAL_MS);
2175
+
2176
+ // detectRunningAdapter (see its own comment) - only worth running at
2177
+ // all for a session that DIDN'T already start with a specific --cli
2178
+ // flag, since a session launched with `--cli claude` already reports
2179
+ // the right thing from the very first connect and doesn't need
2180
+ // reconfirming every 10s. adapter.id here is the ORIGINAL CLI choice
2181
+ // this session started with (never reassigned afterward), which is
2182
+ // exactly the "what did --cli actually say" check needed - comparing
2183
+ // against lastDetectedCliType (which DOES change live) would be wrong.
2184
+ if (adapter.id === 'shell') {
2185
+ detectRunningAdapter();
2186
+ adapterDetectTimer = setInterval(detectRunningAdapter, ADAPTER_DETECT_POLL_INTERVAL_MS);
2187
+ }
2188
+
2189
+ // Real gap in the PoC this replaces: there was no way for `cli-setu status`
2190
+ // or `cli-setu stop` (both new - see src/status.js, src/stop.js) to know
2191
+ // whether a session watcher was even running, or on which PID, since
2192
+ // supervisor-qr.js was always started and killed by hand in a visible
2193
+ // terminal. One small PID file per running session (keyed by
2194
+ // SESSION_ID, since one paired device can run several sessions at
2195
+ // once) - written here at startup, removed on every real exit path.
2196
+ const pidFile = path.join(CONFIG_DIR, `session.${SESSION_ID}.pid`);
2197
+ fs.writeFileSync(pidFile, JSON.stringify({ pid: process.pid, deviceName: DEVICE_NAME, sessionId: SESSION_ID, cwd: WORKING_DIR, startedAt: new Date().toISOString() }, null, 2));
2198
+ const removePidFile = () => { try { fs.unlinkSync(pidFile); } catch {} };
2199
+
2200
+ // Real bug found by testing (PM report): closing the terminal window
2201
+ // itself (not Ctrl+C) sends SIGHUP, and on some setups the process is
2202
+ // just killed directly without any signal process.on('exit') can act
2203
+ // on - confirmed via direct testing that an unhandled SIGTERM/SIGHUP
2204
+ // does NOT fire a Node 'exit' event. SIGINT was the only path that
2205
+ // ever actually removed the pidfile or told the backend the session
2206
+ // ended, so closing the window left both behind indefinitely -
2207
+ // re-running `cli-setu pair` on a fresh terminal shortly after found
2208
+ // the still-registered-live old session and refused to start a new
2209
+ // one. Same cleanup now runs for every real exit path.
2210
+ //
2211
+ // Only sets exitCode + kills the pty here - see ptyProcess.onExit's own
2212
+ // comment (above, in this same main()) for why: that single handler is
2213
+ // now the only place that actually closes ws, restores stdin, removes
2214
+ // the pidfile, and calls process.exit() - calling any of those a
2215
+ // second time from here raced node-pty's own async Windows teardown
2216
+ // and crashed with a real libuv assertion (confirmed live, three
2217
+ // rounds of testing, 2026-10-22 through 2026-10-25).
2218
+ const cleanupAndExit = () => {
2219
+ process.exitCode = 0;
2220
+ ptyProcess.kill();
2221
+ setTimeout(() => process.exit(0), 1500).unref(); // safety net - see onExit's own comment
2222
+ };
2223
+ process.on('SIGINT', cleanupAndExit);
2224
+ process.on('SIGTERM', cleanupAndExit);
2225
+ process.on('SIGHUP', cleanupAndExit);
2226
+ process.on('exit', removePidFile);
2227
+
2228
+ connectToAzure();
2229
+ }
2230
+
2231
+ main().catch((err) => {
2232
+ console.error('[supervisor] fatal:', err.message);
2233
+ process.exit(1);
2234
+ });