@wonderwhy-er/desktop-commander 0.2.46 → 0.2.47

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.
@@ -1,34 +1,98 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import { captureRemote } from '../utils/capture.js';
3
- const HEARTBEAT_INTERVAL = 15000;
4
- // Cap a single channel recreate so a hung await can't pin the re-entrancy guard
5
- // true (which would silently disable the connection watchdog).
6
- const RECREATE_TIMEOUT_MS = 30000;
7
- // Max time the channel may sit CONTINUOUSLY in 'joining' before we force a recreate.
8
- // 'joining' is normally healthy (we let realtime-js's rejoin backoff converge), but on a
9
- // HALF-OPEN socket (readyState OPEN yet dead) realtime-js parks the channel in 'joining'
10
- // forever and never reconnects the socket — the device then wedges offline silently with
11
- // no recreate firing. realtime-js's join push times out in ~10s, so a genuine join
12
- // resolves/errors well within this window; 3 health ticks of unbroken 'joining' means the
13
- // state machine has stalled and only a fresh socket (via recreate) recovers it.
3
+ import { VERSION } from '../version.js';
4
+ const NUL_CHAR = String.fromCharCode(0);
5
+ const NUL_RE = new RegExp(NUL_CHAR, 'g');
6
+ /**
7
+ * Strip NUL characters (U+0000) from strings and object keys — Postgres rejects
8
+ * them in jsonb and text (22P05). Walks the structure rather than
9
+ * round-tripping JSON, which would also match escape text in legitimate content.
10
+ */
11
+ export function stripNullBytes(value) {
12
+ if (typeof value === 'string') {
13
+ return (value.includes(NUL_CHAR) ? value.replace(NUL_RE, '') : value);
14
+ }
15
+ if (Array.isArray(value)) {
16
+ return value.map((item) => stripNullBytes(item));
17
+ }
18
+ if (value && typeof value === 'object') {
19
+ // Plain objects only — leave Date/Buffer/etc. untouched.
20
+ const proto = Object.getPrototypeOf(value);
21
+ if (proto !== Object.prototype && proto !== null)
22
+ return value;
23
+ const out = {};
24
+ for (const [k, v] of Object.entries(value)) {
25
+ out[k.includes(NUL_CHAR) ? k.replace(NUL_RE, '') : k] = stripNullBytes(v);
26
+ }
27
+ return out;
28
+ }
29
+ return value;
30
+ }
31
+ // last_seen cadences. The server tiers its sweep on the transport_broadcast_v1
32
+ // flag, so each must fit its tier's threshold in the server's constants.ts:
33
+ // capable -> 15 min, unflagged -> 45s.
34
+ const CAPABLE_HEARTBEAT_INTERVAL = 5 * 60 * 1000;
35
+ const LEGACY_HEARTBEAT_INTERVAL = 15 * 1000;
36
+ // Cap on a recreate's rebuild step so a hung await can't disable the watchdog.
37
+ // Must exceed createChannel()'s worst case (~31.5s of presence retries).
38
+ const RECREATE_TIMEOUT_MS = 45000;
39
+ // Max continuous time in 'joining' before forcing a recreate — a half-open
40
+ // socket parks the channel there forever, and a genuine join settles in ~10s.
14
41
  const JOINING_WEDGE_TIMEOUT_MS = 30000;
42
+ // Failed recreates before withdrawing transport_broadcast_v1 — keeping it while
43
+ // unable to join makes the device undispatchable. Not lower than 3: ordinary
44
+ // half-open recovery legitimately costs 2.
45
+ const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
46
+ // Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
47
+ // does not cover.
48
+ const CAPABILITY_WRITE_TIMEOUT_MS = 5000;
49
+ // Cap on the shutdown session fetch, which races device.ts's 5s force-exit.
50
+ const OFFLINE_SESSION_TIMEOUT_MS = 500;
51
+ // realtime-js parks in 'disconnecting' for ~100ms after a disconnect and
52
+ // connect() early-returns for that whole window (see waitForSocketSettled).
53
+ // Bound generously — this only ever delays a recreate, which RECREATE_TIMEOUT_MS
54
+ // already covers.
55
+ const SOCKET_SETTLE_MAX_MS = 300;
56
+ const SOCKET_SETTLE_POLL_MS = 20;
15
57
  export class RemoteChannel {
16
58
  constructor() {
17
59
  this.client = null;
18
60
  this.channel = null;
61
+ /** Legacy listener, on its own public channel so a private-channel auth
62
+ * failure can't take both transports down. Removed at the flip (009). */
63
+ this.legacyChannel = null;
19
64
  this.heartbeatInterval = null;
20
65
  this.connectionCheckInterval = null;
66
+ /** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
67
+ this.heartbeatDeviceId = null;
68
+ // Single-slot queue keeping concurrent `status` PATCHes in order.
69
+ this.statusWriteChain = Promise.resolve();
70
+ /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
71
+ this.lastKnownSession = null;
72
+ /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
73
+ * land after setOffline()'s durable write. */
74
+ this.shuttingDown = false;
21
75
  // Store subscription parameters for channel recreation
22
76
  this.deviceId = null;
77
+ this.deviceName = null;
23
78
  this.onToolCall = null;
79
+ // Guard so setSession being called twice can't stack auth listeners.
80
+ this.authListenerRegistered = false;
81
+ /** False when presence publishing failed on an otherwise healthy channel;
82
+ * the health check retries, since SUBSCRIBED won't fire again. */
83
+ this.presenceTracked = false;
84
+ /** Last capability value written (null = never), to avoid redundant writes. */
85
+ this.transportCapableWritten = null;
86
+ /** Re-entrancy guard: on a wedged socket each track() buffers for the full
87
+ * 10s push timeout, so 10s health ticks would stack pushes. */
88
+ this.isTrackingPresence = false;
24
89
  // Track last device status to prevent duplicate log messages
25
90
  this.lastDeviceStatus = 'offline';
26
91
  // Track last channel state for debug logging
27
92
  this.lastChannelState = null;
28
- // Reconnect diagnostics + guard (see connState() / recreateChannel())
29
- this.reconnectAttempt = 0; // recreateChannel() attempts since last success
30
- this.isRecreatingChannel = false; // a recreate is in flight (re-entrancy guard)
31
- this.joiningSince = null; // ts the channel entered an unbroken 'joining' run; null when not joining
93
+ this.reconnectAttempt = 0; // recreates since the last success
94
+ this.isRecreatingChannel = false; // re-entrancy guard
95
+ this.joiningSince = null; // start of an unbroken 'joining' run
32
96
  this._user = null;
33
97
  }
34
98
  get user() { return this._user; }
@@ -63,6 +127,30 @@ export class RemoteChannel {
63
127
  }
64
128
  this._user = user;
65
129
  console.debug('[DEBUG] Session set successfully, user:', user.email);
130
+ // Push the CURRENT token, not the one we were handed: setSession()
131
+ // refreshes internally, and the stale parameter would overwrite it.
132
+ const { data: { session: currentSession } } = await this.client.auth.getSession();
133
+ const realtimeToken = currentSession?.access_token ?? session.access_token;
134
+ this.client.realtime.setAuth(realtimeToken);
135
+ // Cached for setOffline(), which can't afford to wait on getSession().
136
+ this.lastKnownSession = {
137
+ access_token: realtimeToken,
138
+ refresh_token: currentSession?.refresh_token ?? session.refresh_token ?? null,
139
+ };
140
+ console.debug('[DEBUG] Realtime socket authorized with current session JWT');
141
+ if (!this.authListenerRegistered) {
142
+ this.authListenerRegistered = true;
143
+ this.client.auth.onAuthStateChange((event, newSession) => {
144
+ if (event === 'TOKEN_REFRESHED' && newSession?.access_token && this.client) {
145
+ console.debug('[DEBUG] Token refreshed — re-authorizing realtime socket');
146
+ this.client.realtime.setAuth(newSession.access_token);
147
+ this.lastKnownSession = {
148
+ access_token: newSession.access_token,
149
+ refresh_token: newSession.refresh_token ?? this.lastKnownSession?.refresh_token ?? null,
150
+ };
151
+ }
152
+ });
153
+ }
66
154
  return { error };
67
155
  }
68
156
  async getSession() {
@@ -129,19 +217,23 @@ export class RemoteChannel {
129
217
  }
130
218
  if (existingDevice) {
131
219
  console.debug('[DEBUG] Updating device status to online');
220
+ // transport_broadcast_v1 is NOT set here: the server treats it as
221
+ // binding, so it is written only once presence is proven.
132
222
  await this.updateDevice(existingDevice.id, {
133
223
  status: 'online',
134
224
  last_seen: new Date().toISOString(),
135
- capabilities: {}, // TODO: Capabilities are not yet implemented; keep this empty object for schema compatibility until device capabilities are defined and stored.
225
+ capabilities: this.capabilitiesPayload(false),
136
226
  device_name: deviceName
137
227
  });
138
228
  // Store parameters for channel recreation
139
229
  this.deviceId = existingDevice.id;
230
+ this.deviceName = deviceName;
140
231
  this.onToolCall = onToolCall;
141
232
  console.debug(`⏳ Subscribing to tool call channel...`);
142
233
  // Create and subscribe to the channel
143
234
  console.debug('[DEBUG] Calling createChannel()');
144
- // ! Ignore silently in Initialization to reconnect after
235
+ // Independent safety net for the doorbell transport.
236
+ this.createLegacyChannel();
145
237
  await this.createChannel().catch((error) => {
146
238
  console.debug(`[DEBUG] Failed to create channel, will retry after socket reconnect: ${error?.message || error} — ${this.connState()}`);
147
239
  });
@@ -153,17 +245,114 @@ export class RemoteChannel {
153
245
  }
154
246
  }
155
247
  /**
156
- * Create and subscribe to the channel.
157
- * This is used for both initial subscription and recreation after socket reconnects.
248
+ * Publish presence, retrying a non-'ok' result — track() resolves with a
249
+ * status rather than rejecting, and absent presence reads as offline on the
250
+ * server. `presenceTracked` lets the health check retry later.
158
251
  */
159
- createChannel() {
160
- return new Promise((resolve, reject) => {
161
- if (!this.client || !this.user?.id || !this.onToolCall) {
162
- console.debug('[DEBUG] createChannel() failed - missing prerequisites');
163
- return reject(new Error('Client not initialized or missing subscription parameters'));
252
+ async trackPresenceWithRetry(recovered, attempts = 3) {
253
+ if (this.isTrackingPresence)
254
+ return; // never stack pushes on a wedged socket
255
+ this.isTrackingPresence = true;
256
+ try {
257
+ await this.trackPresenceInner(recovered, attempts);
258
+ }
259
+ finally {
260
+ this.isTrackingPresence = false;
261
+ }
262
+ }
263
+ async trackPresenceInner(recovered, attempts) {
264
+ for (let attempt = 1; attempt <= attempts; attempt++) {
265
+ if (!this.channel || this.channel.state !== 'joined')
266
+ return;
267
+ let status;
268
+ try {
269
+ status = await this.channel.track({
270
+ device_id: this.deviceId,
271
+ device_name: this.deviceName,
272
+ app_version: VERSION,
273
+ platform: process.platform
274
+ });
275
+ }
276
+ catch (trackErr) {
277
+ status = `threw: ${trackErr?.message}`;
278
+ }
279
+ if (status === 'ok') {
280
+ this.presenceTracked = true;
281
+ console.log(`👋 Presence tracked (device ${this.deviceId} visible as online)`);
282
+ // Reconnect attempts preceding this join (0 on a first join).
283
+ captureRemote('remote_channel_presence_tracked', { recoveredAfterAttempts: recovered }).catch(() => { });
284
+ // Proven end-to-end (joined AND presence published) — only now
285
+ // may the server treat our presence as authoritative.
286
+ await this.setTransportCapable(true);
287
+ return;
288
+ }
289
+ console.error(`❌ Presence track not acknowledged (${status}) — attempt ${attempt}/${attempts}`);
290
+ if (attempt < attempts)
291
+ await this.sleep(500 * attempt);
292
+ }
293
+ this.presenceTracked = false;
294
+ console.error('❌ Presence track failed after retries — reverting to the legacy transport tier');
295
+ captureRemote('remote_channel_presence_track_error', { attempts }).catch(() => { });
296
+ // Withdraw: a stale flag with no presence makes the server refuse to
297
+ // dispatch at all. The legacy tier keeps the device usable.
298
+ await this.setTransportCapable(false);
299
+ }
300
+ /**
301
+ * The complete `capabilities` JSONB value. One place only: every write
302
+ * replaces the whole column, so a second literal would silently drop keys.
303
+ */
304
+ capabilitiesPayload(broadcastCapable) {
305
+ return {
306
+ app_version: VERSION,
307
+ ...(broadcastCapable ? { transport_broadcast_v1: true } : {})
308
+ };
309
+ }
310
+ /**
311
+ * Advertise (or withdraw) the broadcast capability. Only true while genuinely
312
+ * reachable that way — the server uses it to pick a transport, to read absent
313
+ * presence as offline, and to choose the sweep tier, so every change must
314
+ * re-arm the heartbeat.
315
+ */
316
+ async setTransportCapable(capable) {
317
+ if (!this.client || !this.deviceId)
318
+ return;
319
+ if (this.transportCapableWritten === capable)
320
+ return; // no redundant writes
321
+ try {
322
+ const capabilities = this.capabilitiesPayload(capable);
323
+ const { error } = await this.client
324
+ .from('mcp_devices')
325
+ .update({ capabilities })
326
+ .eq('id', this.deviceId);
327
+ if (error) {
328
+ console.error('[DEBUG] Failed to update transport capability:', error.message);
329
+ return;
330
+ }
331
+ this.transportCapableWritten = capable;
332
+ console.debug(`[DEBUG] Transport capability set to ${capable ? 'broadcast_v1' : 'legacy'}`);
333
+ // Tier changed — move last_seen onto the cadence that tier's sweep
334
+ // threshold expects (no-op if the heartbeat hasn't started yet).
335
+ this.scheduleHeartbeat();
336
+ // last_seen may already be past the 45s threshold now judging us,
337
+ // so write once immediately rather than waiting out the interval.
338
+ if (!capable && this.heartbeatDeviceId) {
339
+ this.updateHeartbeat(this.heartbeatDeviceId).catch(() => { });
164
340
  }
165
- console.debug('[DEBUG] Creating channel: device_tool_call_queue');
166
- this.channel = this.client.channel('device_tool_call_queue')
341
+ }
342
+ catch (error) {
343
+ console.error('[DEBUG] Transport capability update threw:', error?.message);
344
+ }
345
+ }
346
+ /**
347
+ * Legacy postgres_changes listener on its own public channel. Best-effort:
348
+ * failures are logged, never thrown. Removed at the flip (009).
349
+ */
350
+ createLegacyChannel() {
351
+ if (!this.client || !this.user?.id)
352
+ return;
353
+ try {
354
+ this.legacyChannel = this.client
355
+ .channel('device_tool_call_queue')
167
356
  .on('postgres_changes', {
168
357
  event: 'INSERT',
169
358
  schema: 'public',
@@ -171,9 +360,53 @@ export class RemoteChannel {
171
360
  filter: `user_id=eq.${this.user.id}`
172
361
  }, (payload) => {
173
362
  console.debug('[DEBUG] Realtime event received, payload:', payload?.new?.id);
174
- if (this.onToolCall) {
175
- this.onToolCall(payload);
363
+ this.dispatchToolCall(payload);
364
+ })
365
+ .subscribe((status) => {
366
+ console.debug(`[DEBUG] Legacy channel status: ${status}`);
367
+ });
368
+ }
369
+ catch (error) {
370
+ console.debug('[DEBUG] Legacy channel subscribe failed (doorbell path unaffected):', error?.message);
371
+ }
372
+ }
373
+ /** Tear down the legacy channel (best effort). */
374
+ async removeLegacyChannel() {
375
+ if (!this.legacyChannel || !this.client)
376
+ return;
377
+ try {
378
+ await this.client.removeChannel(this.legacyChannel);
379
+ }
380
+ catch { /* best effort */ }
381
+ this.legacyChannel = null;
382
+ }
383
+ /** Create and subscribe the private channel (initial join and recreation). */
384
+ createChannel() {
385
+ return new Promise((resolve, reject) => {
386
+ if (!this.client || !this.user?.id || !this.onToolCall || !this.deviceId) {
387
+ // deviceId is the presence KEY; a null key gets a random one and
388
+ // the server's lookup by device id silently misses.
389
+ console.debug('[DEBUG] createChannel() failed - missing prerequisites');
390
+ return reject(new Error('Client not initialized or missing subscription parameters'));
391
+ }
392
+ // Private per-user channel: new_call doorbells + this device's
393
+ // Presence, keyed by device id.
394
+ const channelName = `user:${this.user.id}`;
395
+ console.debug(`[DEBUG] Creating channel: ${channelName}`);
396
+ this.channel = this.client.channel(channelName, {
397
+ // ack: true — without it send() resolves 'ok' once the frame hits
398
+ // the socket, making notifyResult's status check dead code.
399
+ config: {
400
+ private: true,
401
+ broadcast: { ack: true },
402
+ // Non-null: the guard above rejects when !deviceId.
403
+ presence: { key: this.deviceId, enabled: true }
176
404
  }
405
+ })
406
+ .on('broadcast', { event: 'new_call' }, ({ payload }) => {
407
+ this.onDoorbell(payload).catch((e) => {
408
+ console.error('[DEBUG] Doorbell handling failed:', e?.message);
409
+ });
177
410
  })
178
411
  .subscribe((status, err) => {
179
412
  // Debug: Log all subscription status events
@@ -182,38 +415,143 @@ export class RemoteChannel {
182
415
  const recovered = this.reconnectAttempt;
183
416
  this.reconnectAttempt = 0;
184
417
  console.log(`✅ Channel subscribed${recovered > 0 ? ` (recovered after ${recovered} attempt${recovered === 1 ? '' : 's'})` : ''}`);
185
- // Update device status on successful connection
186
- if (this.deviceId) {
187
- this.setOnlineStatus(this.deviceId, 'online').catch(e => {
188
- console.error('Failed to set online status:', e.message);
189
- });
190
- }
191
- resolve();
418
+ // Update device status on successful connection (queued, so
419
+ // it can't be overtaken by a teardown's status write).
420
+ this.queueStatusWrite('online');
421
+ // Presence is the live signal dispatch reads, so resolve
422
+ // only once it lands — otherwise registerDevice() reports
423
+ // "Device ready" while still undispatchable.
424
+ this.trackPresenceWithRetry(recovered)
425
+ .catch(() => { })
426
+ .finally(() => resolve());
192
427
  }
193
428
  else if (status === 'CHANNEL_ERROR') {
194
429
  // CHANNEL_ERROR is the only status carrying a real error message.
195
430
  console.error(`❌ Channel error: ${err?.message || 'unknown'} — ${this.connState()}`);
196
- this.setOnlineStatus(this.deviceId, 'offline');
431
+ this.presenceTracked = false;
432
+ this.syncReachabilityStatus();
433
+ // Fires on ordinary network faults too — filter on the
434
+ // error text to isolate an 008 misconfiguration.
197
435
  captureRemote('remote_channel_subscription_error', { error: err?.message || 'Channel error' }).catch(() => { });
198
436
  reject(err || new Error('Failed to initialize tool call channel subscription'));
199
437
  }
200
438
  else if (status === 'TIMED_OUT') {
201
439
  console.error(`⏱️ Channel subscription timed out, Reconnecting... — ${this.connState()}`);
202
- this.setOnlineStatus(this.deviceId, 'offline');
440
+ this.syncReachabilityStatus();
203
441
  captureRemote('remote_channel_subscription_timeout', { attempt: this.reconnectAttempt }).catch(() => { });
204
442
  reject(new Error('Tool call channel subscription timed out'));
205
443
  }
206
444
  else if (status === 'CLOSED') {
207
445
  // Settle the promise so an in-flight recreateChannel() can't await
208
- // forever (which would wedge the re-entrancy guard / watchdog), and
209
- // mark the device offline like the other degraded states.
446
+ // forever (which would wedge the re-entrancy guard / watchdog).
210
447
  console.warn(`⚠️ Channel closed — ${this.connState()}`);
211
- this.setOnlineStatus(this.deviceId, 'offline');
448
+ this.syncReachabilityStatus();
212
449
  reject(new Error('Tool call channel closed during subscribe'));
213
450
  }
214
451
  });
215
452
  });
216
453
  }
454
+ /** Hand a call to device.ts, observing the rejection — the handler is async
455
+ * and an unhandled rejection terminates the process. */
456
+ dispatchToolCall(payload) {
457
+ try {
458
+ const maybePromise = this.onToolCall?.(payload);
459
+ if (maybePromise instanceof Promise) {
460
+ maybePromise.catch((e) => {
461
+ console.error('[DEBUG] Tool call handler rejected:', e?.message);
462
+ });
463
+ }
464
+ }
465
+ catch (e) {
466
+ console.error('[DEBUG] Tool call handler threw:', e?.message);
467
+ }
468
+ }
469
+ /**
470
+ * Handle a 'new_call' doorbell. It carries ids only; the row is fetched by
471
+ * primary key and fed through the same handler as a postgres_changes
472
+ * payload, so device.ts stays transport-agnostic.
473
+ */
474
+ async onDoorbell(payload) {
475
+ const callId = payload?.call_id;
476
+ if (!callId)
477
+ return;
478
+ if (payload?.device_id && payload.device_id !== this.deviceId) {
479
+ console.debug('[DEBUG] Ignoring doorbell for different device');
480
+ return;
481
+ }
482
+ // Not a telemetry event on purpose: ~126k/day in prod. Transport usage
483
+ // is already segmentable server-side via metadata.transport.
484
+ console.debug('[DEBUG] Doorbell received for call:', callId);
485
+ if (!this.client)
486
+ return;
487
+ // Retry on transient failures (a REST blip while the socket stays
488
+ // healthy). Post-flip this fetch is the only way we learn about a call,
489
+ // so a hiccup must not cost a 5-minute timeout.
490
+ let row = null;
491
+ let lastError = null;
492
+ for (const delayMs of [0, 500, 1500]) {
493
+ if (delayMs > 0)
494
+ await this.sleep(delayMs);
495
+ const { data, error } = await this.client
496
+ .from('mcp_remote_calls')
497
+ .select('*')
498
+ .eq('id', callId)
499
+ .maybeSingle();
500
+ if (!error) {
501
+ row = data;
502
+ lastError = null;
503
+ break;
504
+ }
505
+ lastError = error;
506
+ console.debug(`[DEBUG] Doorbell row fetch attempt failed for ${callId}: ${error.message} — retrying`);
507
+ }
508
+ if (lastError) {
509
+ console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after retries:`, lastError.message);
510
+ await captureRemote('remote_channel_doorbell_fetch_error', { error: lastError });
511
+ return;
512
+ }
513
+ if (!row) {
514
+ // Already claimed and deleted, or cleanup raced delivery. Not
515
+ // retried: the row is always inserted before the doorbell is sent.
516
+ await captureRemote('remote_channel_doorbell_row_missing', { call_id: callId });
517
+ return;
518
+ }
519
+ // Optimization, not a guard — saves a hop when the legacy path already
520
+ // claimed this. Exactly-once lives in device.ts (seenCallIds + DB claim).
521
+ if (row.status !== 'pending') {
522
+ console.debug('[DEBUG] Doorbell call already claimed via legacy path:', callId);
523
+ return;
524
+ }
525
+ // Same payload shape as postgres_changes ({ new: row }).
526
+ this.dispatchToolCall({ new: row });
527
+ }
528
+ /**
529
+ * Tell the server a result row is written. Fire-and-forget: a failed send
530
+ * just falls back to the server's 10s recovery poll. MUST run only after
531
+ * updateCallResult() resolves, so the server's fetch-by-id sees a terminal row.
532
+ */
533
+ async notifyResult(callId) {
534
+ if (!this.channel || this.channel.state !== 'joined') {
535
+ console.debug('[DEBUG] Result doorbell skipped — channel not joined (recovery poll covers)');
536
+ return;
537
+ }
538
+ try {
539
+ // realtime-js send() RESOLVES with 'ok' | 'timed out' | 'error' —
540
+ // it does not reject, so check the status or failures are invisible.
541
+ const result = await this.channel.send({ type: 'broadcast', event: 'result', payload: { call_id: callId } });
542
+ if (result === 'ok') {
543
+ console.debug('[DEBUG] Result doorbell sent:', callId);
544
+ }
545
+ else {
546
+ console.debug(`[DEBUG] Result doorbell not acknowledged (${result}) — recovery poll covers:`, callId);
547
+ captureRemote('remote_channel_result_doorbell_send_failed', { result }).catch(() => { });
548
+ }
549
+ }
550
+ catch (error) {
551
+ console.debug('[DEBUG] Result doorbell send failed (recovery poll covers):', error?.message);
552
+ captureRemote('remote_channel_result_doorbell_send_failed', { error: error?.message }).catch(() => { });
553
+ }
554
+ }
217
555
  /**
218
556
  * Compact connection state for logs — e.g. "socket=open(1) ch=errored attempt=3".
219
557
  * readyState 1=OPEN (a 1 while joins keep failing = a half-open socket being reused),
@@ -244,15 +582,20 @@ export class RemoteChannel {
244
582
  // 'joined' = healthy. Clear the joining-overstay timer.
245
583
  if (state === 'joined') {
246
584
  this.joiningSince = null;
585
+ // Self-heal a failed presence publish: the channel is up, so nothing
586
+ // else will ever retry (SUBSCRIBED won't fire again), and without
587
+ // presence the server reports this healthy device as offline.
588
+ if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence) {
589
+ console.debug('[DEBUG] Channel joined but presence not tracked — retrying track()');
590
+ this.trackPresenceWithRetry(0, 1).catch(() => { });
591
+ }
247
592
  return;
248
593
  }
249
- // 'joining' = transitional — normally let realtime-js's own rejoin backoff converge
250
- // instead of tearing the channel down mid-join (recreating on every non-joined state
251
- // amputates that backoff). BUT bound it: on a half-open socket realtime-js can park
252
- // the channel in 'joining' indefinitely without ever reconnecting the socket, so the
253
- // recreate below would never fire and the device wedges offline silently. If 'joining'
254
- // overstays JOINING_WEDGE_TIMEOUT_MS unbroken, force a recreate — the only path that
255
- // disconnect()s the dead socket. (connState() in the log shows the half-open socket.)
594
+ // 'joining' is transitional — let realtime-js's rejoin backoff converge
595
+ // rather than tearing the channel down mid-join. But bound it: a
596
+ // half-open socket parks the channel here indefinitely, so past
597
+ // JOINING_WEDGE_TIMEOUT_MS force a recreate, the only path that
598
+ // disconnect()s the dead socket.
256
599
  if (state === 'joining') {
257
600
  const now = Date.now();
258
601
  if (this.joiningSince === null)
@@ -277,6 +620,28 @@ export class RemoteChannel {
277
620
  * can't leave isRecreatingChannel stuck true and disable the watchdog. Mirrors
278
621
  * closeWithTimeout() in desktop-commander-integration.ts.
279
622
  */
623
+ sleep(ms) {
624
+ return new Promise((resolve) => setTimeout(resolve, ms));
625
+ }
626
+ /**
627
+ * Block until realtime-js has left the 'disconnecting' state it enters on
628
+ * disconnect(), so the next subscribe() actually dials a socket instead of
629
+ * hitting connect()'s early return. Bounded either way — worst case we cost
630
+ * a recreate SOCKET_SETTLE_MAX_MS.
631
+ */
632
+ async waitForSocketSettled() {
633
+ const realtime = this.client?.realtime;
634
+ // No predicate to poll (older/newer client): wait out the internal
635
+ // fallback timer blind rather than guess at the state.
636
+ if (typeof realtime?.isDisconnecting !== 'function') {
637
+ await this.sleep(SOCKET_SETTLE_MAX_MS);
638
+ return;
639
+ }
640
+ const deadline = Date.now() + SOCKET_SETTLE_MAX_MS;
641
+ while (realtime.isDisconnecting() && Date.now() < deadline) {
642
+ await this.sleep(SOCKET_SETTLE_POLL_MS);
643
+ }
644
+ }
280
645
  async withTimeout(op, ms, name) {
281
646
  let timer;
282
647
  try {
@@ -312,18 +677,34 @@ export class RemoteChannel {
312
677
  // Create fresh channel
313
678
  console.log(`🔄 Recreating channel... (attempt ${this.reconnectAttempt}) — ${this.connState()}`);
314
679
  try {
680
+ // Jittered backoff so a fleet-wide event doesn't stampede every
681
+ // device into reconnecting at once. ~1-3s rising to ~15-45s.
682
+ const backoffMs = Math.min(30000, 1000 * 2 ** Math.min(this.reconnectAttempt, 5)) * (0.5 + Math.random());
683
+ console.debug(`[DEBUG] Reconnect backoff: ${Math.round(backoffMs)}ms`);
684
+ await this.sleep(backoffMs);
685
+ // realtime-js runs its own rejoin timer, and the backoff above gives
686
+ // it a window to win: the old channel can come back 'joined' while we
687
+ // slept. Destroying a healthy channel would cause a pointless outage
688
+ // cycle — bail out instead (observed live on staging, 2026-07-23).
689
+ if (this.channel?.state === 'joined') {
690
+ console.log(`✅ Channel self-healed during backoff — skipping recreate — ${this.connState()}`);
691
+ return; // finally-block below clears the re-entrancy guard
692
+ }
315
693
  // Cap the whole recreate: a never-settling await (e.g. a subscribe that only
316
694
  // ever emits CLOSED) must not pin isRecreatingChannel=true and silently disable
317
695
  // the 10s watchdog. On timeout we reject -> catch -> finally clears the guard.
318
696
  await this.withTimeout(async () => {
319
- // Destroy old channel — AWAIT it so the channel registry empties before we
320
- // rebuild. (The un-awaited version raced the synchronous new-channel push, so
321
- // realtime-js never tore the socket down and a half-open one got reused.)
697
+ // Await it so the channel registry empties before we rebuild —
698
+ // otherwise realtime-js never tears the socket down and a
699
+ // half-open one gets reused.
322
700
  if (this.channel) {
323
701
  console.debug('[DEBUG] Destroying old channel');
324
702
  await this.client.removeChannel(this.channel);
325
703
  this.channel = null;
326
704
  }
705
+ // Rebuild the legacy channel too: it shares the socket, so a
706
+ // socket-level wedge takes it down with the private channel.
707
+ await this.removeLegacyChannel();
327
708
  // FIX (core): force a brand-new WebSocket. After idle / wifi-loss the socket can
328
709
  // be HALF-OPEN (readyState OPEN but dead); reusing it made every join TIME_OUT
329
710
  // forever. disconnect() drops it so the next subscribe() dials a fresh one.
@@ -331,32 +712,80 @@ export class RemoteChannel {
331
712
  await this.client.realtime?.disconnect?.();
332
713
  }
333
714
  catch { /* best effort */ }
715
+ // ...but disconnect() is not synchronous from connect()'s point
716
+ // of view: it parks _connectionState in 'disconnecting' and
717
+ // _teardownConnection() nulls the conn.onclose that would clear
718
+ // it, so only an internal ~100ms fallback timer does. connect()
719
+ // early-returns for that whole window, so rebuilding here makes
720
+ // subscribe()'s socket.connect() a silent no-op and BOTH
721
+ // channels sit in 'joining' until the 10s join timeout — the
722
+ // wasted-first-recreate that left the device dark on the legacy
723
+ // channel too. Wait for the state to settle before rebuilding.
724
+ await this.waitForSocketSettled();
334
725
  console.debug('[DEBUG] Calling createChannel() for recreation');
726
+ // Rebuild the legacy safety net FIRST and unconditionally: if
727
+ // createChannel() throws or exceeds RECREATE_TIMEOUT_MS, anything
728
+ // after it is skipped, which used to leave the fallback dead for
729
+ // the entire duration of a private-channel outage — every
730
+ // subsequent health tick repeating the same teardown.
731
+ this.createLegacyChannel();
335
732
  await this.createChannel();
336
733
  }, RECREATE_TIMEOUT_MS, 'recreateChannel');
337
734
  }
338
735
  catch (err) {
339
736
  captureRemote('remote_channel_recreate_error', { errMsg: err?.message, attempt: this.reconnectAttempt });
340
737
  console.debug(`[DEBUG] Channel recreation failed: ${err?.message} — ${this.connState()}`);
738
+ // Sustained failure: stop promising a transport we can't deliver, or
739
+ // the server's presence overlay reports this device offline
740
+ // authoritatively and overrides `status`.
741
+ if (this.reconnectAttempt >= TRANSPORT_WITHDRAW_AFTER_ATTEMPTS) {
742
+ // Bounded, in its own try: this catch block is outside
743
+ // RECREATE_TIMEOUT_MS, so a hanging PATCH would pin
744
+ // isRecreatingChannel and disable the watchdog.
745
+ try {
746
+ await this.withTimeout(() => this.setTransportCapable(false), CAPABILITY_WRITE_TIMEOUT_MS, 'withdrawTransportCapability');
747
+ }
748
+ catch (withdrawErr) {
749
+ // The next failed recreate retries; the flag only advances
750
+ // on a confirmed write, so nothing is lost.
751
+ console.debug(`[DEBUG] Capability withdrawal did not complete: ${withdrawErr?.message}`);
752
+ }
753
+ }
341
754
  }
342
755
  finally {
343
756
  this.isRecreatingChannel = false;
344
757
  }
345
758
  }
759
+ /**
760
+ * Claim a call. True only when THIS update flipped the row pending ->
761
+ * executing, which is what makes dual delivery safe across processes.
762
+ * .eq('status','pending') makes it conditional; .select('id') makes the
763
+ * result observable. On a transient DB error it returns true (execute
764
+ * anyway), matching prior behaviour — so device.ts's in-memory guard is what
765
+ * actually guarantees exactly-once within a process.
766
+ */
346
767
  async markCallExecuting(callId) {
347
768
  if (!this.client)
348
769
  throw new Error('Client not initialized');
349
- const { error } = await this.client
770
+ const { data, error } = await this.client
350
771
  .from('mcp_remote_calls')
351
772
  .update({ status: 'executing' })
352
- .eq('id', callId);
773
+ .eq('id', callId)
774
+ .eq('status', 'pending')
775
+ .select('id');
353
776
  if (error) {
354
777
  console.error('[DEBUG] Failed to mark call executing:', error.message);
355
778
  await captureRemote('remote_channel_mark_call_executing_error', { error });
779
+ return true; // preserve legacy behavior: execution proceeds despite the write error
356
780
  }
357
- else {
781
+ const claimed = !!data && data.length > 0;
782
+ if (claimed) {
358
783
  console.debug('[DEBUG] Call marked executing:', callId);
359
784
  }
785
+ else {
786
+ console.debug('[DEBUG] Call already claimed (duplicate delivery), skipping:', callId);
787
+ }
788
+ return claimed;
360
789
  }
361
790
  async updateCallResult(callId, status, result = null, errorMessage = null) {
362
791
  if (!this.client)
@@ -365,36 +794,130 @@ export class RemoteChannel {
365
794
  status: status,
366
795
  completed_at: new Date().toISOString()
367
796
  };
797
+ // Strip NUL (U+0000) before it reaches the jsonb `result` column.
798
+ // jsonb cannot store and rejects the whole write (Postgres 22P05),
799
+ // which otherwise leaves the call stuck 'executing' → the user waits out
800
+ // a 5-minute timeout for a tool that actually ran. Common with binary
801
+ // file reads / process output. error_message is text, so it's exempt.
368
802
  if (result !== null)
369
- updateData.result = result;
803
+ updateData.result = stripNullBytes(result);
804
+ // Postgres `text` rejects NUL too (not just jsonb) — a NUL-bearing error
805
+ // message would fail this terminal write, and because result === null the
806
+ // fallback below wouldn't fire, stranding the call until the 5-min timeout.
370
807
  if (errorMessage !== null)
371
- updateData.error_message = errorMessage;
372
- console.debug('[DEBUG] Updating call result:', updateData);
373
- const { data, error } = await this.client
808
+ updateData.error_message = stripNullBytes(errorMessage);
809
+ // Gated: the size is only knowable by serializing, and results reach
810
+ // 13 MB — doing that eagerly for a log line would cost more than the
811
+ // rest of this function.
812
+ if (process.env.DEBUG_MODE === 'true') {
813
+ console.debug(`[DEBUG] Updating call result: ${callId} status=${status}` +
814
+ (result !== null ? ` resultBytes=~${JSON.stringify(updateData.result)?.length ?? 0}` : ''));
815
+ }
816
+ const { error } = await this.client
374
817
  .from('mcp_remote_calls')
375
818
  .update(updateData)
376
819
  .eq('id', callId);
377
820
  if (error) {
378
821
  console.error('[DEBUG] Failed to update call result:', error.message);
379
822
  await captureRemote('remote_channel_update_call_result_error', { error });
823
+ // Fail-fast fallback: if the RESULT write failed (sanitize should
824
+ // prevent the NUL case, but any unstorable payload lands here),
825
+ // record a terminal 'failed' with a text-only message so the user
826
+ // gets an immediate, honest error instead of a 5-minute phantom
827
+ // timeout. Guard against infinite recursion (only for result writes).
828
+ if (result !== null && status !== 'failed') {
829
+ await this.updateCallResult(callId, 'failed', null, `Result could not be stored (${error.message})`);
830
+ }
380
831
  }
381
832
  else {
382
- console.debug('[DEBUG] Call result updated successfully:', data);
833
+ // (an UPDATE without .select() returns no row data — log the id)
834
+ console.debug('[DEBUG] Call result updated successfully:', callId);
383
835
  }
384
836
  }
837
+ /**
838
+ * Reachable by SOME transport — the private channel or, during the
839
+ * transition, the independent legacy one. Gates the heartbeat and `status`:
840
+ * asking only about the private channel starves last_seen for a device whose
841
+ * legacy channel is fine, and the 45s sweep then blacks it out.
842
+ * Collapses to a single check at the flip (009).
843
+ */
844
+ isReachable() {
845
+ return this.channel?.state === 'joined' || this.legacyChannel?.state === 'joined';
846
+ }
847
+ /**
848
+ * Set `status` from actual reachability. `status` is transport-agnostic (the
849
+ * server filters on it), so it must not follow one channel's health — the
850
+ * private channel's error path re-fires on every rejoin and would oscillate
851
+ * the row against the heartbeat. Same predicate as the heartbeat gate.
852
+ */
853
+ syncReachabilityStatus() {
854
+ this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
855
+ }
856
+ /**
857
+ * Serialize the channel-callback status writes. They fire from un-awaited
858
+ * callbacks, and inside recreateChannel() a teardown's 'offline' and the
859
+ * fresh join's 'online' land ~100-300ms apart — unordered, 'offline' can win
860
+ * and leave a healthy device undispatchable until the next heartbeat.
861
+ *
862
+ * Not the single writer: updateHeartbeat, registerDevice and setOffline's
863
+ * subprocess write status directly, so this is not total ordering.
864
+ */
865
+ queueStatusWrite(status) {
866
+ // After teardown begins, setOffline() owns the final status write.
867
+ if (this.shuttingDown) {
868
+ console.debug(`[DEBUG] Status write '${status}' suppressed — teardown in progress`);
869
+ return;
870
+ }
871
+ this.statusWriteChain = this.statusWriteChain
872
+ .then(() => (this.deviceId ? this.setOnlineStatus(this.deviceId, status) : undefined))
873
+ .catch((e) => {
874
+ console.error('[DEBUG] Status write failed:', e?.message);
875
+ });
876
+ }
877
+ /**
878
+ * Heartbeat cadence for the tier this device is CURRENTLY in. Follows the
879
+ * capability flag (what the server actually tiers its sweep on), not the
880
+ * build — see LEGACY_HEARTBEAT_INTERVAL.
881
+ */
882
+ heartbeatIntervalMs() {
883
+ return this.transportCapableWritten === true
884
+ ? CAPABLE_HEARTBEAT_INTERVAL
885
+ : LEGACY_HEARTBEAT_INTERVAL;
886
+ }
385
887
  async updateHeartbeat(deviceId) {
386
888
  if (!this.client)
387
889
  return;
890
+ // This write asserts status:'online' too, so it MUST respect the
891
+ // shutdown gate — otherwise a heartbeat firing (or in flight) as SIGINT
892
+ // lands can be applied after setOffline()'s subprocess write and leave
893
+ // an exited process marked online with a fresh last_seen, which for a
894
+ // capable device the sweep then cannot age out for a full tier window.
895
+ if (this.shuttingDown) {
896
+ console.debug('[DEBUG] Skipping heartbeat write — shutting down');
897
+ return;
898
+ }
388
899
  try {
900
+ // Skip the write entirely when no transport is up. Bumping last_seen
901
+ // on a deaf device would keep its row perpetually young, so the
902
+ // server's staleness sweep could never age it out and correct a
903
+ // stale 'online' — and whenever presence is unavailable (kill
904
+ // switch, wedged socket) that stale row is exactly what dispatch
905
+ // falls back to. Staying silent lets the sweep do its job.
906
+ if (!this.isReachable()) {
907
+ console.debug('[DEBUG] Skipping heartbeat write — no transport joined; letting the row age out');
908
+ return;
909
+ }
389
910
  const { error } = await this.client
390
911
  .from('mcp_devices')
391
- .update({ last_seen: new Date().toISOString() })
912
+ .update({ last_seen: new Date().toISOString(), status: 'online' })
392
913
  .eq('id', deviceId);
393
914
  if (error) {
394
915
  console.error('[DEBUG] Heartbeat update failed:', error.message);
395
916
  await captureRemote('remote_channel_heartbeat_error', { error });
396
917
  }
397
- // console.log(`🔌 Heartbeat sent for device: ${deviceId}`);
918
+ else {
919
+ console.debug('[DEBUG] last_seen bookkeeping write ok:', deviceId);
920
+ }
398
921
  }
399
922
  catch (error) {
400
923
  console.error('Heartbeat failed:', error.message);
@@ -403,18 +926,36 @@ export class RemoteChannel {
403
926
  }
404
927
  startHeartbeat(deviceId) {
405
928
  console.debug('[DEBUG] Starting heartbeat for device:', deviceId);
929
+ this.heartbeatDeviceId = deviceId;
406
930
  this.connectionCheckInterval = setInterval(() => {
407
931
  this.checkConnectionHealth();
408
932
  }, 10000);
409
- // Update last_seen every 15 seconds
410
- this.heartbeatInterval = setInterval(async () => {
411
- await this.updateHeartbeat(deviceId);
412
- }, HEARTBEAT_INTERVAL);
413
- console.debug('[DEBUG] Heartbeat intervals set - connectionCheck: 10s, heartbeat: 15s');
933
+ // Bookkeeping last_seen write. Self-rescheduling rather than a fixed
934
+ // setInterval so the cadence can follow the tier: a device that
935
+ // withdraws the capability flag must fall back to the fast legacy
936
+ // cadence immediately, not 30 minutes later.
937
+ this.scheduleHeartbeat();
938
+ console.debug(`[DEBUG] Heartbeat started - connectionCheck: 10s, last_seen: ${this.heartbeatIntervalMs()}ms`);
939
+ }
940
+ /** Arm (or re-arm) the last_seen timer at the current tier's cadence. */
941
+ scheduleHeartbeat() {
942
+ if (this.heartbeatInterval) {
943
+ clearTimeout(this.heartbeatInterval);
944
+ this.heartbeatInterval = null;
945
+ }
946
+ if (!this.heartbeatDeviceId)
947
+ return;
948
+ this.heartbeatInterval = setTimeout(async () => {
949
+ if (this.heartbeatDeviceId) {
950
+ await this.updateHeartbeat(this.heartbeatDeviceId);
951
+ }
952
+ this.scheduleHeartbeat(); // re-read the tier every tick
953
+ }, this.heartbeatIntervalMs());
414
954
  }
415
955
  stopHeartbeat() {
956
+ this.heartbeatDeviceId = null;
416
957
  if (this.heartbeatInterval) {
417
- clearInterval(this.heartbeatInterval);
958
+ clearTimeout(this.heartbeatInterval);
418
959
  this.heartbeatInterval = null;
419
960
  }
420
961
  if (this.connectionCheckInterval) {
@@ -454,13 +995,26 @@ export class RemoteChannel {
454
995
  }
455
996
  console.debug('[DEBUG] setOffline() initiating blocking update for device:', deviceId);
456
997
  try {
457
- // Get current session for the subprocess
458
- const { data: sessionData } = await this.client.auth.getSession();
459
- if (!sessionData?.session?.access_token) {
998
+ // Session for the subprocess — bounded, with a cached fallback.
999
+ // getSession() is not a cheap read: it takes a lock (10s acquire
1000
+ // timeout) and refreshes when the token is within ~90s of expiry,
1001
+ // POSTing /token with its own ~30s retry budget. On a just-woken
1002
+ // machine that outlasts device.ts's 5s force-exit, and then spawnSync
1003
+ // never runs and the offline write is lost. The subprocess calls
1004
+ // setSession() itself, so a slightly stale access_token is fine.
1005
+ const live = await Promise.race([
1006
+ this.client.auth.getSession().then((r) => r.data?.session ?? null),
1007
+ this.sleep(OFFLINE_SESSION_TIMEOUT_MS).then(() => null),
1008
+ ]).catch(() => null);
1009
+ const session = live ?? this.lastKnownSession;
1010
+ if (!session?.access_token) {
460
1011
  console.error('❌ No valid session for offline update');
461
1012
  console.debug('[DEBUG] Session data missing or invalid');
462
1013
  return;
463
1014
  }
1015
+ if (!live) {
1016
+ console.debug('[DEBUG] getSession() slow/failed — using last known session tokens');
1017
+ }
464
1018
  // Get Supabase config from client
465
1019
  const supabaseUrl = this.client.supabaseUrl;
466
1020
  const supabaseKey = this.client.supabaseKey;
@@ -484,8 +1038,8 @@ export class RemoteChannel {
484
1038
  deviceId,
485
1039
  supabaseUrl,
486
1040
  supabaseKey,
487
- sessionData.session.access_token,
488
- sessionData.session.refresh_token || ''
1041
+ session.access_token,
1042
+ session.refresh_token || ''
489
1043
  ], {
490
1044
  timeout: 3000,
491
1045
  stdio: 'pipe', // Capture output to prevent blocking
@@ -524,8 +1078,36 @@ export class RemoteChannel {
524
1078
  }
525
1079
  }
526
1080
  async unsubscribe() {
1081
+ // setOffline()'s durable write is the final word on `status` from here,
1082
+ // so stop the heartbeat and the channel callbacks from racing it. The
1083
+ // races that matter: a heartbeat tick firing as the signal arrives, and
1084
+ // SIGINT during recreateChannel()'s backoff, where the later join's
1085
+ // SUBSCRIBED would queue 'online' after the durable write.
1086
+ this.shuttingDown = true;
1087
+ // Budget against device.ts's 5s force-exit, worst case:
1088
+ // 250 drain + 3x300 leave + 500 session + 3000 spawnSync = 4650ms.
1089
+ // In practice only the untrack bound binds — removeChannel/unsubscribe
1090
+ // set state='leaving' first, so their leave push resolves inline.
1091
+ const LEAVE_BOUND_MS = 300;
1092
+ // Drain queued channel-callback writes. Can't drain an in-flight
1093
+ // heartbeat PATCH (it doesn't use the chain), but the gate above stops
1094
+ // any new one and an in-flight one started earlier.
1095
+ await Promise.race([this.statusWriteChain, this.sleep(250)]);
1096
+ await Promise.race([this.removeLegacyChannel(), this.sleep(LEAVE_BOUND_MS)]);
527
1097
  if (this.channel) {
528
- await this.channel.unsubscribe();
1098
+ // Leave presence on the graceful path (socket close covers the abrupt
1099
+ // one). Bounded: a half-open socket still reports 'joined', so the
1100
+ // push just buffers and would settle via realtime-js's 10s timeout.
1101
+ try {
1102
+ await Promise.race([
1103
+ this.channel.untrack(),
1104
+ this.sleep(LEAVE_BOUND_MS),
1105
+ ]);
1106
+ console.debug('[DEBUG] Presence untrack attempted (bounded)');
1107
+ }
1108
+ catch { /* best effort */ }
1109
+ // Bounded as insurance; unsubscribe() resolves inline in practice.
1110
+ await Promise.race([this.channel.unsubscribe(), this.sleep(LEAVE_BOUND_MS)]);
529
1111
  this.channel = null;
530
1112
  console.log('✓ Unsubscribed from tool call channel');
531
1113
  }