cli-setu 0.3.2 → 0.3.3

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