@wonderwhy-er/desktop-commander 0.2.50 → 0.2.52

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.
@@ -28,13 +28,38 @@ export function stripNullBytes(value) {
28
28
  }
29
29
  return value;
30
30
  }
31
+ /**
32
+ * The device registered, but its realtime channel is not usable — the join
33
+ * failed, or presence was never acknowledged. Distinct from every other
34
+ * registration failure on purpose: this one the socket watchdog can repair, so
35
+ * the caller keeps the process alive, while a failed lookup or a missing row
36
+ * happens before the recreation parameters are stored and nothing can repair it.
37
+ */
38
+ export class ChannelUnreachableError extends Error {
39
+ constructor(message) {
40
+ super(message);
41
+ this.name = 'ChannelUnreachableError';
42
+ }
43
+ }
31
44
  // last_seen cadences. The server tiers its sweep on the transport_broadcast_v1
32
45
  // flag, so each must fit its tier's threshold in the server's constants.ts:
33
46
  // capable -> 15 min, unflagged -> 45s.
34
47
  const CAPABLE_HEARTBEAT_INTERVAL = 5 * 60 * 1000;
35
48
  const LEGACY_HEARTBEAT_INTERVAL = 15 * 1000;
49
+ // Keep Supabase's retry cadence, but jitter every device independently so one
50
+ // Realtime disconnect cannot synchronize the whole fleet onto 1s/2s/5s/10s
51
+ // reconnect waves. ±50% keeps recovery latency close to the SDK default while
52
+ // spreading load across the recovery window.
53
+ const REALTIME_RECONNECT_BASE_MS = [1000, 2000, 5000, 10000];
54
+ const REALTIME_RECONNECT_FALLBACK_MS = 10000;
55
+ // Presence-only failures do not mean broadcast delivery is down: a joined
56
+ // channel can still receive doorbells while Presence's DB-backed work is
57
+ // degraded. Keep a previously-proven capability for one normal heartbeat
58
+ // interval before falling back to the 15s legacy tier, avoiding a 20x heartbeat
59
+ // write-rate jump during short provider incidents.
60
+ const PRESENCE_WITHDRAW_GRACE_MS = 5 * 60 * 1000;
36
61
  // 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).
62
+ // Must exceed createChannel()'s worst case (~32.25s of jittered presence retries).
38
63
  const RECREATE_TIMEOUT_MS = 45000;
39
64
  // Max continuous time in 'joining' before forcing a recreate — a half-open
40
65
  // socket parks the channel there forever, and a genuine join settles in ~10s.
@@ -48,8 +73,8 @@ const TOKEN_REFRESH_INTERVAL_MS = 45 * 60 * 1000;
48
73
  // Below this, skew is noise — leave Date.now untouched. Above it, correct.
49
74
  const CLOCK_SKEW_CORRECTION_THRESHOLD_MS = 5 * 60 * 1000;
50
75
  // Failed recreates before withdrawing transport_broadcast_v1 — keeping it while
51
- // unable to join makes the device undispatchable. Not lower than 3: ordinary
52
- // half-open recovery legitimately costs 2.
76
+ // unable to join leaves the server dispatching calls this device can't
77
+ // receive. Not lower than 3: ordinary half-open recovery legitimately costs 2.
53
78
  const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
54
79
  // Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
55
80
  // does not cover.
@@ -62,6 +87,25 @@ const OFFLINE_SESSION_TIMEOUT_MS = 500;
62
87
  // already covers.
63
88
  const SOCKET_SETTLE_MAX_MS = 300;
64
89
  const SOCKET_SETTLE_POLL_MS = 20;
90
+ // Reconnect recovery is a safety net, not the primary transport. Bound each
91
+ // scan so a pathological backlog cannot turn one reconnect into an unbounded
92
+ // burst of REST claims/tool executions.
93
+ const PENDING_RECOVERY_BATCH_SIZE = 100;
94
+ function jitterAround(baseMs, random) {
95
+ const sample = Math.max(0, Math.min(1, random()));
96
+ return Math.max(1, Math.round(baseMs * (0.5 + sample)));
97
+ }
98
+ /** Jittered version of realtime-js's default 1s/2s/5s/10s stepped backoff. */
99
+ export function realtimeReconnectDelayMs(tries, random = Math.random) {
100
+ const attempt = Math.max(1, Math.floor(tries || 1));
101
+ const baseMs = REALTIME_RECONNECT_BASE_MS[attempt - 1] ?? REALTIME_RECONNECT_FALLBACK_MS;
102
+ return jitterAround(baseMs, random);
103
+ }
104
+ /** Preserve Presence's existing 500ms-per-attempt retry shape, but desynchronize it. */
105
+ export function presenceRetryDelayMs(failedAttempt, random = Math.random) {
106
+ const attempt = Math.max(1, Math.floor(failedAttempt || 1));
107
+ return jitterAround(500 * attempt, random);
108
+ }
65
109
  // auth-js compares token expiry against this device's own Date.now(), with no
66
110
  // clock-skew tolerance — a fast clock treats every fresh token as expired and
67
111
  // refreshes forever (confirmed in prod on one device, via at least 3 separate
@@ -114,8 +158,16 @@ export class RemoteChannel {
114
158
  this.heartbeatDeviceId = null;
115
159
  // Single-slot queue keeping concurrent `status` PATCHes in order.
116
160
  this.statusWriteChain = Promise.resolve();
161
+ /**
162
+ * Answers whether the local execution child is alive. Default yes, so a
163
+ * RemoteChannel used without a device (tests, other callers) behaves as
164
+ * before; MCPDevice installs the real probe.
165
+ */
166
+ this.localExecutorProbe = () => true;
117
167
  /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
118
168
  this.lastKnownSession = null;
169
+ /** Notified when auth-js rotates the session; the device persists it. */
170
+ this.sessionRefreshedHandler = null;
119
171
  /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
120
172
  * land after setOffline()'s durable write. */
121
173
  this.shuttingDown = false;
@@ -133,6 +185,8 @@ export class RemoteChannel {
133
185
  this.presenceTracked = false;
134
186
  /** Last capability value written (null = never), to avoid redundant writes. */
135
187
  this.transportCapableWritten = null;
188
+ /** Monotonic start of a Presence-only degradation while broadcast remains joined. */
189
+ this.presenceFailureStartedAt = null;
136
190
  /** Re-entrancy guard: on a wedged socket each track() buffers for the full
137
191
  * 10s push timeout, so 10s health ticks would stack pushes. */
138
192
  this.isTrackingPresence = false;
@@ -163,6 +217,7 @@ export class RemoteChannel {
163
217
  auth: { autoRefreshToken: false },
164
218
  global: { fetch: clockAwareFetch },
165
219
  realtime: {
220
+ reconnectAfterMs: realtimeReconnectDelayMs,
166
221
  // supabase-js's resolver ends in `?? supabaseKey`, so after SIGNED_OUT
167
222
  // the socket silently re-pins to the anon key and every private-channel
168
223
  // join is refused. Overriding under `realtime` (not the top-level
@@ -193,11 +248,29 @@ export class RemoteChannel {
193
248
  catch { /* no onHeartbeat on this client version: staleness check stays inert */ }
194
249
  }
195
250
  }
251
+ /**
252
+ * Teach the channel how to ask whether the local executor is alive.
253
+ * `status` is a claim that this device will run a tool call right now, and
254
+ * a joined channel alone cannot support that claim - issue #4.
255
+ */
256
+ setLocalExecutorProbe(probe) {
257
+ this.localExecutorProbe = probe;
258
+ }
259
+ /**
260
+ * Register a callback fired when auth-js rotates the session. auth-js
261
+ * rotates the refresh token on every refresh and the previous one is spent,
262
+ * so a config written once at startup replays a dead token on the next
263
+ * restart and the device demands browser authorization again.
264
+ */
265
+ onSessionRefreshed(handler) {
266
+ this.sessionRefreshedHandler = handler;
267
+ }
196
268
  async setSession(session) {
197
269
  if (!this.client)
198
270
  throw new Error('Client not initialized');
199
271
  console.debug('[DEBUG] RemoteChannel.setSession() called, has refresh_token:', !!session.refresh_token);
200
- const { error } = await this.client.auth.setSession({
272
+ // setSession() already fetches the user from GoTrue (or refreshes), so no getUser() after it.
273
+ const { data: { user }, error } = await this.client.auth.setSession({
201
274
  access_token: session.access_token,
202
275
  refresh_token: session.refresh_token || ''
203
276
  });
@@ -206,13 +279,6 @@ export class RemoteChannel {
206
279
  await captureRemote('remote_channel_set_session_error', { error });
207
280
  return { error };
208
281
  }
209
- // Get user info
210
- const { data: { user }, error: userError } = await this.client.auth.getUser();
211
- if (userError) {
212
- console.error('[DEBUG] Failed to get user:', userError.message);
213
- await captureRemote('remote_channel_get_user_error', { error: userError });
214
- throw userError;
215
- }
216
282
  if (!user) {
217
283
  const noUserError = new Error('No user returned after setSession');
218
284
  console.error('[DEBUG] No user returned:', noUserError.message);
@@ -242,6 +308,14 @@ export class RemoteChannel {
242
308
  access_token: newSession.access_token,
243
309
  refresh_token: newSession.refresh_token ?? this.lastKnownSession?.refresh_token ?? null,
244
310
  };
311
+ // Memory alone is not enough: the token we just replaced is
312
+ // spent, so whatever is on disk is now unusable.
313
+ // Hand over the session we were just given. A listener that
314
+ // re-read it could find a sign-out instead and persist that.
315
+ this.sessionRefreshedHandler?.({
316
+ access_token: newSession.access_token,
317
+ refresh_token: newSession.refresh_token ?? null,
318
+ });
245
319
  }
246
320
  else if (event === 'SIGNED_OUT') {
247
321
  void this.handleSignedOut();
@@ -407,15 +481,30 @@ export class RemoteChannel {
407
481
  console.debug('[DEBUG] Existing device found:', !!existingDevice);
408
482
  }
409
483
  if (existingDevice) {
410
- console.debug('[DEBUG] Updating device status to online');
411
- // transport_broadcast_v1 is NOT set here: the server treats it as
412
- // binding, so it is written only once presence is proven.
413
- await this.updateDevice(existingDevice.id, {
414
- status: 'online',
484
+ console.debug('[DEBUG] Registering device as offline until the channel proves otherwise');
485
+ // Neither half of this row may claim reachability yet. transport_
486
+ // broadcast_v1 is NOT set here: the server treats it as binding, so
487
+ // it is written only once presence is proven. `status` is the same
488
+ // promise in the other notation — dispatch picks its target by it,
489
+ // then fails the call fast for the missing capability, so a row
490
+ // marked online before the channel is up hands every call in that
491
+ // window to a device with no delivery path. SUBSCRIBED writes
492
+ // 'online'; presence writes the capability.
493
+ const { error: registrationError } = await this.updateDevice(existingDevice.id, {
494
+ status: 'offline',
415
495
  last_seen: new Date().toISOString(),
416
496
  capabilities: this.capabilitiesPayload(false),
417
497
  device_name: deviceName
418
498
  });
499
+ // updateDevice() logs and returns its error rather than throwing.
500
+ // Opening the channel anyway would leave a row that still says
501
+ // whatever the last run left there — including 'online' — while
502
+ // nothing here can correct it: the channel's own error path queues
503
+ // an offline write, and setOnlineStatus() only logs when that write
504
+ // fails too. Stop before the channel instead.
505
+ if (registrationError) {
506
+ throw new Error(`Failed to register device: ${registrationError.message}`);
507
+ }
419
508
  // Store parameters for channel recreation
420
509
  this.deviceId = existingDevice.id;
421
510
  this.deviceName = deviceName;
@@ -423,9 +512,13 @@ export class RemoteChannel {
423
512
  console.debug(`⏳ Subscribing to tool call channel...`);
424
513
  // Create and subscribe to the channel
425
514
  console.debug('[DEBUG] Calling createChannel()');
426
- await this.createChannel().catch((error) => {
427
- console.debug(`[DEBUG] Failed to create channel, will retry after socket reconnect: ${error?.message || error} — ${this.connState()}`);
428
- });
515
+ // Let a failed join reach the caller. createChannel() resolves only
516
+ // once the channel is joined AND presence is published — the two
517
+ // things dispatch needs — so swallowing its rejection here was what
518
+ // let device.ts print "Device ready" over a device that cannot
519
+ // receive a single command. The caller decides what to do with it;
520
+ // it is not fatal, the socket watchdog keeps retrying.
521
+ await this.createChannel();
429
522
  }
430
523
  else {
431
524
  console.error(` - ❌ Device not found: ${currentDeviceId}`);
@@ -436,7 +529,7 @@ export class RemoteChannel {
436
529
  /**
437
530
  * Publish presence, retrying a non-'ok' result — track() resolves with a
438
531
  * status rather than rejecting, and absent presence reads as offline on the
439
- * server. `presenceTracked` lets the health check retry later.
532
+ * dashboard. `presenceTracked` lets the health check retry later.
440
533
  */
441
534
  async trackPresenceWithRetry(recovered, attempts = 3) {
442
535
  if (this.isTrackingPresence)
@@ -450,6 +543,10 @@ export class RemoteChannel {
450
543
  }
451
544
  }
452
545
  async trackPresenceInner(recovered, attempts) {
546
+ // A fresh attempt starts from "not proven", so a leftover true from an
547
+ // earlier join cannot keep the device counting as reachable while this
548
+ // one is still deciding.
549
+ this.presenceTracked = false;
453
550
  for (let attempt = 1; attempt <= attempts; attempt++) {
454
551
  if (!this.channel || this.channel.state !== 'joined')
455
552
  return;
@@ -466,25 +563,86 @@ export class RemoteChannel {
466
563
  status = `threw: ${trackErr?.message}`;
467
564
  }
468
565
  if (status === 'ok') {
566
+ // `presenceTracked` is not "track() said ok" — isReachable()
567
+ // reads it as "this device receives commands", and the heartbeat
568
+ // consults isReachable() directly rather than waiting for the
569
+ // sequence below. Raising it here let a heartbeat firing while
570
+ // these writes were in flight assert `online` over a row with no
571
+ // capability recorded: the very state this is meant to remove.
572
+ // So it is raised last, when every claim it makes is already true.
573
+ //
574
+ // Both writes have to land. Supabase reports a refused write in
575
+ // the result rather than by throwing, and a device whose row
576
+ // records neither the capability nor `online` is exactly as
577
+ // undispatchable as one that never published presence. The
578
+ // health check retries presence while this stays false, which is
579
+ // the way back.
580
+ const capabilityWritten = await this.setTransportCapable(true);
581
+ // Strictly after, never alongside: `online` may be claimed only
582
+ // where the capability is already advertised, or the row lands
583
+ // back in the state this whole change is about.
584
+ // Not syncReachabilityStatus(): its predicate reads presenceTracked,
585
+ // and that flag is deliberately still false here - it is raised last,
586
+ // once these writes have landed, so a heartbeat cannot advertise the
587
+ // row mid-sequence. Both halves the predicate asks about are already
588
+ // known at this point: the channel is joined and presence was just
589
+ // acknowledged. The only open question is the local executor, so ask
590
+ // that directly - a joined, present device whose executor is dead must
591
+ // not be advertised either.
592
+ const statusWritten = capabilityWritten
593
+ ? await this.queueStatusWrite(this.localExecutorProbe() ? 'online' : 'offline')
594
+ : false;
595
+ if (!capabilityWritten || !statusWritten) {
596
+ console.error('❌ Presence published but the device row could not be updated — not ready');
597
+ captureRemote('remote_channel_readiness_write_failed', {
598
+ capabilityWritten, statusWritten
599
+ }).catch(() => { });
600
+ return;
601
+ }
469
602
  this.presenceTracked = true;
603
+ this.presenceFailureStartedAt = null;
470
604
  console.log(`👋 Presence tracked (device ${this.deviceId} visible as online)`);
471
605
  // Reconnect attempts preceding this join (0 on a first join).
472
606
  captureRemote('remote_channel_presence_tracked', { recoveredAfterAttempts: recovered }).catch(() => { });
473
- // Proven end-to-end (joined AND presence published) — only now
474
- // may the server treat our presence as authoritative.
475
- await this.setTransportCapable(true);
607
+ // Broadcast is only a wake-up signal; mcp_remote_calls is the
608
+ // durable queue. A call inserted while this socket was briefly
609
+ // disconnected can miss its one new_call doorbell and otherwise
610
+ // stay pending until the server reaper times it out. Drain that
611
+ // durable backlog whenever the channel becomes genuinely usable.
612
+ // Fire-and-forget so readiness does not wait on backlog recovery;
613
+ // each row still goes through the atomic pending -> executing
614
+ // claim, so a late/duplicate doorbell can safely race this scan.
615
+ this.recoverPendingCalls().catch((error) => {
616
+ console.error('[DEBUG] Pending call recovery failed:', error?.message);
617
+ });
476
618
  return;
477
619
  }
478
620
  console.error(`❌ Presence track not acknowledged (${status}) — attempt ${attempt}/${attempts}`);
479
621
  if (attempt < attempts)
480
- await this.sleep(500 * attempt);
622
+ await this.sleep(presenceRetryDelayMs(attempt));
481
623
  }
482
624
  this.presenceTracked = false;
483
- console.error('❌ Presence track failed after retries — withdrawing broadcast capability');
484
625
  captureRemote('remote_channel_presence_track_error', { attempts }).catch(() => { });
485
- // Withdraw: a stale flag with no presence makes the server refuse to
486
- // dispatch at all. The faster heartbeat tier keeps the device's status
487
- // accurate for the DB-status fallback while it recovers.
626
+ // Presence is an observer signal, not the delivery path. If this device
627
+ // already proved broadcast capability and the channel is still joined,
628
+ // keep that capability through a short provider-side Presence incident
629
+ // instead of immediately switching to the 15s legacy heartbeat tier.
630
+ // The 10s health check keeps retrying Presence; a success clears the
631
+ // timer. Genuine channel failure is handled separately by
632
+ // recreateChannel(), which still withdraws after 3 failed recreates.
633
+ if (this.transportCapableWritten === true && this.channel?.state === 'joined') {
634
+ const now = performance.now();
635
+ if (this.presenceFailureStartedAt === null)
636
+ this.presenceFailureStartedAt = now;
637
+ const degradedForMs = now - this.presenceFailureStartedAt;
638
+ if (degradedForMs < PRESENCE_WITHDRAW_GRACE_MS) {
639
+ console.warn(`⚠️ Presence unavailable for ${Math.round(degradedForMs / 1000)}s — ` +
640
+ `retaining broadcast capability during ${PRESENCE_WITHDRAW_GRACE_MS / 1000}s grace`);
641
+ return;
642
+ }
643
+ }
644
+ this.presenceFailureStartedAt = null;
645
+ console.error('❌ Presence track remained unavailable — withdrawing broadcast capability');
488
646
  await this.setTransportCapable(false);
489
647
  }
490
648
  /**
@@ -499,15 +657,14 @@ export class RemoteChannel {
499
657
  }
500
658
  /**
501
659
  * Advertise (or withdraw) the broadcast capability. Only true while genuinely
502
- * reachable that way — the server uses it to pick a transport, to read absent
503
- * presence as offline, and to choose the sweep tier, so every change must
504
- * re-arm the heartbeat.
660
+ * reachable that way — the server fails dispatch fast without it and picks
661
+ * the offline-sweep tier from it, so every change must re-arm the heartbeat.
505
662
  */
506
663
  async setTransportCapable(capable) {
507
664
  if (!this.client || !this.deviceId)
508
- return;
665
+ return false;
509
666
  if (this.transportCapableWritten === capable)
510
- return; // no redundant writes
667
+ return true; // no redundant writes
511
668
  try {
512
669
  const capabilities = this.capabilitiesPayload(capable);
513
670
  const { error } = await this.client
@@ -516,7 +673,7 @@ export class RemoteChannel {
516
673
  .eq('id', this.deviceId);
517
674
  if (error) {
518
675
  console.error('[DEBUG] Failed to update transport capability:', error.message);
519
- return;
676
+ return false;
520
677
  }
521
678
  this.transportCapableWritten = capable;
522
679
  console.debug(`[DEBUG] Transport capability set to ${capable ? 'broadcast_v1' : 'withdrawn'}`);
@@ -531,14 +688,16 @@ export class RemoteChannel {
531
688
  }
532
689
  catch (error) {
533
690
  console.error('[DEBUG] Transport capability update threw:', error?.message);
691
+ return false;
534
692
  }
693
+ return true;
535
694
  }
536
695
  /** Create and subscribe the private channel (initial join and recreation). */
537
696
  createChannel() {
538
697
  return new Promise((resolve, reject) => {
539
698
  if (!this.client || !this.user?.id || !this.onToolCall || !this.deviceId) {
540
699
  // deviceId is the presence KEY; a null key gets a random one and
541
- // the server's lookup by device id silently misses.
700
+ // the dashboard's lookup by device id silently misses.
542
701
  console.debug('[DEBUG] createChannel() failed - missing prerequisites');
543
702
  return reject(new Error('Client not initialized or missing subscription parameters'));
544
703
  }
@@ -547,11 +706,8 @@ export class RemoteChannel {
547
706
  const channelName = `user:${this.user.id}`;
548
707
  console.debug(`[DEBUG] Creating channel: ${channelName}`);
549
708
  this.channel = this.client.channel(channelName, {
550
- // ack: true — without it send() resolves 'ok' once the frame hits
551
- // the socket, making notifyResult's status check dead code.
552
709
  config: {
553
710
  private: true,
554
- broadcast: { ack: true },
555
711
  // Non-null: the guard above rejects when !deviceId.
556
712
  presence: { key: this.deviceId, enabled: true }
557
713
  }
@@ -569,15 +725,21 @@ export class RemoteChannel {
569
725
  this.reconnectAttempt = 0;
570
726
  this.lastHeartbeatOkAt = performance.now(); // a fresh join is proof of life too
571
727
  console.log(`✅ Channel subscribed${recovered > 0 ? ` (recovered after ${recovered} attempt${recovered === 1 ? '' : 's'})` : ''}`);
572
- // Update device status on successful connection (queued, so
573
- // it can't be overtaken by a teardown's status write).
574
- this.queueStatusWrite('online');
575
- // Presence is the live signal dispatch reads, so resolve
576
- // only once it lands — otherwise registerDevice() reports
577
- // "Device ready" while still undispatchable.
728
+ // A join is only half of what dispatch needs. The other
729
+ // half is presence, which writes the capability the
730
+ // server checks — and when every track() is refused,
731
+ // trackPresenceInner() withdraws the capability and
732
+ // returns normally. Resolving here regardless left the
733
+ // row online with the capability withdrawn: the exact
734
+ // state the server refuses as not_broadcast_capable.
735
+ // `status` is written on the same event as the
736
+ // capability, in trackPresenceInner, so the two can
737
+ // never disagree.
578
738
  this.trackPresenceWithRetry(recovered)
579
739
  .catch(() => { })
580
- .finally(() => resolve());
740
+ .finally(() => this.presenceTracked
741
+ ? resolve()
742
+ : reject(new ChannelUnreachableError('channel joined but presence was never acknowledged, so no command can be delivered')));
581
743
  }
582
744
  else if (status === 'CHANNEL_ERROR') {
583
745
  // CHANNEL_ERROR is the only status carrying a real error message.
@@ -587,24 +749,69 @@ export class RemoteChannel {
587
749
  // Fires on ordinary network faults too — filter on the
588
750
  // error text to isolate an 008 misconfiguration.
589
751
  captureRemote('remote_channel_subscription_error', { error: err?.message || 'Channel error' }).catch(() => { });
590
- reject(err || new Error('Failed to initialize tool call channel subscription'));
752
+ reject(new ChannelUnreachableError(err?.message || 'failed to subscribe to the tool call channel'));
591
753
  }
592
754
  else if (status === 'TIMED_OUT') {
593
755
  console.error(`⏱️ Channel subscription timed out, Reconnecting... — ${this.connState()}`);
594
756
  this.syncReachabilityStatus();
595
757
  captureRemote('remote_channel_subscription_timeout', { attempt: this.reconnectAttempt }).catch(() => { });
596
- reject(new Error('Tool call channel subscription timed out'));
758
+ reject(new ChannelUnreachableError('tool call channel subscription timed out'));
597
759
  }
598
760
  else if (status === 'CLOSED') {
599
761
  // Settle the promise so an in-flight recreateChannel() can't await
600
762
  // forever (which would wedge the re-entrancy guard / watchdog).
601
763
  console.warn(`⚠️ Channel closed — ${this.connState()}`);
602
764
  this.syncReachabilityStatus();
603
- reject(new Error('Tool call channel closed during subscribe'));
765
+ reject(new ChannelUnreachableError('tool call channel closed during subscribe'));
604
766
  }
605
767
  });
606
768
  });
607
769
  }
770
+ /**
771
+ * Recover calls whose Realtime doorbell was missed while this device was
772
+ * disconnected. Broadcast provides the fast path; the DB row is the source
773
+ * of truth. Only still-live pending rows for this device are considered.
774
+ *
775
+ * The follow-up onDoorbell() call performs the existing conditional claim,
776
+ * which makes this safe against a doorbell arriving at the same time.
777
+ */
778
+ async recoverPendingCalls() {
779
+ if (!this.client || !this.deviceId || !this.isReachable())
780
+ return;
781
+ // Date.now() is deliberately used here: this process may patch it from
782
+ // Supabase's Date header to correct a badly skewed device clock.
783
+ const now = new Date(Date.now()).toISOString();
784
+ const { data: pending, error } = await this.client
785
+ .from('mcp_remote_calls')
786
+ .select('id,device_id')
787
+ .eq('device_id', this.deviceId)
788
+ .eq('status', 'pending')
789
+ .gt('timeout_at', now)
790
+ .order('created_at', { ascending: true })
791
+ .limit(PENDING_RECOVERY_BATCH_SIZE);
792
+ if (error) {
793
+ console.error('[DEBUG] Failed to query pending calls after reconnect:', error.message);
794
+ await captureRemote('remote_channel_pending_recovery_error', { error });
795
+ return;
796
+ }
797
+ if (!pending?.length)
798
+ return;
799
+ console.log(`♻️ Recovering ${pending.length} pending remote call${pending.length === 1 ? '' : 's'} after reconnect`);
800
+ captureRemote('remote_channel_pending_recovery', {
801
+ pending_count: pending.length,
802
+ batch_capped: pending.length === PENDING_RECOVERY_BATCH_SIZE,
803
+ }).catch(() => { });
804
+ // Claim quickly; dispatchToolCall() does not await tool execution, so
805
+ // this loop serializes only the small REST claim operations.
806
+ for (const row of pending) {
807
+ if (!this.isReachable())
808
+ break;
809
+ await this.onDoorbell({
810
+ call_id: row.id,
811
+ device_id: row.device_id,
812
+ });
813
+ }
814
+ }
608
815
  /** Hand a call to device.ts, observing the rejection — the handler is async
609
816
  * and an unhandled rejection terminates the process. */
610
817
  dispatchToolCall(payload) {
@@ -621,15 +828,15 @@ export class RemoteChannel {
621
828
  }
622
829
  }
623
830
  /**
624
- * Handle a 'new_call' doorbell. It carries ids only; the row is fetched by
625
- * primary key and fed through the same handler as a postgres_changes
626
- * payload, so device.ts stays transport-agnostic.
831
+ * Handle a 'new_call' doorbell. It carries ids only; one conditional update
832
+ * claims the row (pending -> executing) and returns it, and it is handed to
833
+ * device.ts marked as claimed.
627
834
  */
628
835
  async onDoorbell(payload) {
629
836
  const callId = payload?.call_id;
630
837
  if (!callId)
631
838
  return;
632
- if (payload?.device_id && payload.device_id !== this.deviceId) {
839
+ if (payload?.device_id !== this.deviceId) {
633
840
  console.debug('[DEBUG] Ignoring doorbell for different device');
634
841
  return;
635
842
  }
@@ -639,70 +846,72 @@ export class RemoteChannel {
639
846
  if (!this.client)
640
847
  return;
641
848
  // Retry on transient failures (a REST blip while the socket stays
642
- // healthy). Post-flip this fetch is the only way we learn about a call,
849
+ // healthy). This claim is the only way we learn about a call,
643
850
  // so a hiccup must not cost a 5-minute timeout.
644
851
  let row = null;
645
- let lastError = null;
852
+ let claimError = null;
646
853
  for (const delayMs of [0, 500, 1500]) {
647
854
  if (delayMs > 0)
648
855
  await this.sleep(delayMs);
649
856
  const { data, error } = await this.client
650
857
  .from('mcp_remote_calls')
651
- .select('*')
858
+ .update({ status: 'executing' })
652
859
  .eq('id', callId)
653
- .maybeSingle();
860
+ .eq('device_id', this.deviceId)
861
+ .eq('status', 'pending')
862
+ .gt('timeout_at', new Date(Date.now()).toISOString())
863
+ .select('*');
654
864
  if (!error) {
655
- row = data;
656
- lastError = null;
865
+ row = data?.[0] ?? null;
657
866
  break;
658
867
  }
659
- lastError = error;
660
- console.debug(`[DEBUG] Doorbell row fetch attempt failed for ${callId}: ${error.message} — retrying`);
661
- }
662
- if (lastError) {
663
- console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after retries:`, lastError.message);
664
- await captureRemote('remote_channel_doorbell_fetch_error', { error: lastError });
665
- return;
868
+ // Left set on purpose: a later clean empty result may still mean our
869
+ // own attempt committed, so the read-back below must run.
870
+ claimError = error;
871
+ console.debug(`[DEBUG] Doorbell claim attempt failed for ${callId}: ${error.message} — retrying`);
666
872
  }
667
- if (!row) {
668
- // Already claimed and deleted, or cleanup raced delivery. Not
669
- // retried: the row is always inserted before the doorbell is sent.
670
- await captureRemote('remote_channel_doorbell_row_missing', { call_id: callId });
873
+ if (row) {
874
+ this.dispatchToolCall({ new: row, claimed: true });
671
875
  return;
672
876
  }
673
- // Optimization, not a guard — saves a hop on a duplicate doorbell
674
- // (retry, reconnect). Exactly-once lives in device.ts (seenCallIds + DB claim).
675
- if (row.status !== 'pending') {
676
- console.debug('[DEBUG] Doorbell call already claimed:', callId);
877
+ if (!claimError) {
878
+ // Claimed by a duplicate doorbell or another process, or cleaned up.
879
+ console.debug('[DEBUG] Doorbell call already claimed or gone:', callId);
880
+ await captureRemote('remote_channel_doorbell_claim_no_row', { call_id: callId });
677
881
  return;
678
882
  }
679
- this.dispatchToolCall({ new: row });
680
- }
681
- /**
682
- * Tell the server a result row is written. Fire-and-forget: a failed send
683
- * just falls back to the server's 10s recovery poll. MUST run only after
684
- * updateCallResult() resolves, so the server's fetch-by-id sees a terminal row.
685
- */
686
- async notifyResult(callId) {
687
- if (!this.channel || this.channel.state !== 'joined') {
688
- console.debug('[DEBUG] Result doorbell skipped — channel not joined (recovery poll covers)');
883
+ await captureRemote('remote_channel_mark_call_executing_error', { error: claimError });
884
+ // A failed claim may never have reached the database, so read the row
885
+ // back: still 'pending' means nobody holds it and it can be delivered.
886
+ const { data: current, error } = await this.client
887
+ .from('mcp_remote_calls')
888
+ .select('*')
889
+ .eq('id', callId)
890
+ .eq('device_id', this.deviceId)
891
+ .maybeSingle();
892
+ if (error) {
893
+ console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after claim errors:`, error.message);
894
+ await captureRemote('remote_channel_doorbell_fetch_error', { error });
689
895
  return;
690
896
  }
691
- try {
692
- // realtime-js send() RESOLVES with 'ok' | 'timed out' | 'error' —
693
- // it does not reject, so check the status or failures are invisible.
694
- const result = await this.channel.send({ type: 'broadcast', event: 'result', payload: { call_id: callId } });
695
- if (result === 'ok') {
696
- console.debug('[DEBUG] Result doorbell sent:', callId);
697
- }
698
- else {
699
- console.debug(`[DEBUG] Result doorbell not acknowledged (${result}) — recovery poll covers:`, callId);
700
- captureRemote('remote_channel_result_doorbell_send_failed', { result }).catch(() => { });
701
- }
897
+ if (current?.status === 'pending'
898
+ && current.timeout_at
899
+ && new Date(current.timeout_at).getTime() > Date.now()) {
900
+ // No claim landed; device.ts claims it. Do not hand an expired
901
+ // side-effecting call to the executor while it races the reaper.
902
+ this.dispatchToolCall({ new: current });
702
903
  }
703
- catch (error) {
704
- console.debug('[DEBUG] Result doorbell send failed (recovery poll covers):', error?.message);
705
- captureRemote('remote_channel_result_doorbell_send_failed', { error: error?.message }).catch(() => { });
904
+ else {
905
+ // 'executing' reads the same whether our own claim committed with its
906
+ // response lost or another process holding this device_id won it, and
907
+ // the row carries no claimant. Running it on that guess executes a
908
+ // side-effecting tool twice; skipping costs one call its timeout, which
909
+ // is what a failed doorbell read already cost before the claim path.
910
+ console.debug('[DEBUG] Doorbell call already claimed or gone:', callId);
911
+ await captureRemote('remote_channel_doorbell_claim_unresolved', {
912
+ call_id: callId,
913
+ status: current?.status ?? null,
914
+ });
706
915
  }
707
916
  }
708
917
  /**
@@ -749,8 +958,10 @@ export class RemoteChannel {
749
958
  }
750
959
  }
751
960
  // Self-heal a failed presence publish: the channel is up, so nothing
752
- // else will ever retry (SUBSCRIBED won't fire again), and without
753
- // presence the server reports this healthy device as offline.
961
+ // else will ever retry (SUBSCRIBED won't fire again). Until it
962
+ // lands the dashboard shows this device offline, and if track()
963
+ // already failed its retries the capability is withdrawn too, so
964
+ // the server fails every dispatch to it fast.
754
965
  if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence) {
755
966
  console.debug('[DEBUG] Channel joined but presence not tracked — retrying track()');
756
967
  this.trackPresenceWithRetry(0, 1).catch(() => { });
@@ -896,9 +1107,8 @@ export class RemoteChannel {
896
1107
  catch (err) {
897
1108
  captureRemote('remote_channel_recreate_error', { errMsg: err?.message, attempt: this.reconnectAttempt });
898
1109
  console.debug(`[DEBUG] Channel recreation failed: ${err?.message} — ${this.connState()}`);
899
- // Sustained failure: stop promising a transport we can't deliver, or
900
- // the server's presence overlay reports this device offline
901
- // authoritatively and overrides `status`.
1110
+ // Sustained failure: stop promising a transport we can't deliver, so
1111
+ // dispatch fails fast instead of every call waiting out the timeout.
902
1112
  if (this.reconnectAttempt >= TRANSPORT_WITHDRAW_AFTER_ATTEMPTS) {
903
1113
  // Bounded, in its own try: this catch block is outside
904
1114
  // RECREATE_TIMEOUT_MS, so a hanging PATCH would pin
@@ -933,6 +1143,7 @@ export class RemoteChannel {
933
1143
  .update({ status: 'executing' })
934
1144
  .eq('id', callId)
935
1145
  .eq('status', 'pending')
1146
+ .gt('timeout_at', new Date(Date.now()).toISOString())
936
1147
  .select('id');
937
1148
  if (error) {
938
1149
  console.error('[DEBUG] Failed to mark call executing:', error.message);
@@ -995,18 +1206,31 @@ export class RemoteChannel {
995
1206
  console.debug('[DEBUG] Call result updated successfully:', callId);
996
1207
  }
997
1208
  }
998
- /** Reachable means the private channel is joined. Gates the heartbeat and `status`. */
1209
+ /**
1210
+ * Reachable means all of it is true at once: the private channel is
1211
+ * joined, this device has published its presence, and the local executor
1212
+ * answers. The server needs the first two before it will dispatch, and a
1213
+ * healthy channel on a device whose executor is dead is the false-online
1214
+ * state issue #4 was opened for. Gates the heartbeat and `status`.
1215
+ */
999
1216
  isReachable() {
1000
- return this.channel?.state === 'joined';
1217
+ return this.channel?.state === 'joined'
1218
+ && this.presenceTracked
1219
+ && this.localExecutorProbe();
1001
1220
  }
1002
1221
  /**
1003
1222
  * Set `status` from actual reachability. `status` is transport-agnostic (the
1004
1223
  * server filters on it), so it must not follow one channel's health — the
1005
1224
  * private channel's error path re-fires on every rejoin and would oscillate
1006
1225
  * the row against the heartbeat. Same predicate as the heartbeat gate.
1226
+ *
1227
+ * Every transition belongs here rather than calling setOnlineStatus(), which
1228
+ * is the write and not the decision. Public so the device can route its
1229
+ * recovery transition through the predicate too.
1007
1230
  */
1231
+ /** Resolves with whether the row actually took the write. */
1008
1232
  syncReachabilityStatus() {
1009
- this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1233
+ return this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1010
1234
  }
1011
1235
  /**
1012
1236
  * Serialize the channel-callback status writes. They fire from un-awaited
@@ -1021,13 +1245,18 @@ export class RemoteChannel {
1021
1245
  // After teardown begins, setOffline() owns the final status write.
1022
1246
  if (this.shuttingDown) {
1023
1247
  console.debug(`[DEBUG] Status write '${status}' suppressed — teardown in progress`);
1024
- return;
1248
+ return Promise.resolve(false);
1025
1249
  }
1026
- this.statusWriteChain = this.statusWriteChain
1027
- .then(() => (this.deviceId ? this.setOnlineStatus(this.deviceId, status) : undefined))
1250
+ // The chain only sequences the writes; whether one landed goes back
1251
+ // to whoever asked, so readiness can depend on it.
1252
+ const write = this.statusWriteChain
1253
+ .then(() => (this.deviceId ? this.setOnlineStatus(this.deviceId, status) : false))
1028
1254
  .catch((e) => {
1029
1255
  console.error('[DEBUG] Status write failed:', e?.message);
1256
+ return false;
1030
1257
  });
1258
+ this.statusWriteChain = write.then(() => undefined);
1259
+ return write;
1031
1260
  }
1032
1261
  /**
1033
1262
  * Heartbeat cadence for the tier this device is CURRENTLY in. Follows the
@@ -1055,9 +1284,8 @@ export class RemoteChannel {
1055
1284
  // Skip the write entirely when no transport is up. Bumping last_seen
1056
1285
  // on a deaf device would keep its row perpetually young, so the
1057
1286
  // server's staleness sweep could never age it out and correct a
1058
- // stale 'online' — and whenever presence is unavailable (kill
1059
- // switch, wedged socket) that stale row is exactly what dispatch
1060
- // falls back to. Staying silent lets the sweep do its job.
1287
+ // stale 'online' — and that row is what dispatch reads. Staying
1288
+ // silent lets the sweep do its job.
1061
1289
  if (!this.isReachable()) {
1062
1290
  console.debug('[DEBUG] Skipping heartbeat write — no transport joined; letting the row age out');
1063
1291
  return;
@@ -1151,9 +1379,10 @@ export class RemoteChannel {
1151
1379
  }
1152
1380
  this.stopTokenRefresh();
1153
1381
  }
1382
+ /** @returns whether the row actually took the write. */
1154
1383
  async setOnlineStatus(deviceId, status) {
1155
1384
  if (!this.client)
1156
- return;
1385
+ return false;
1157
1386
  // Only log if status changed
1158
1387
  if (this.lastDeviceStatus !== status) {
1159
1388
  console.log(`🔌 Device marked as ${status}`);
@@ -1169,11 +1398,12 @@ export class RemoteChannel {
1169
1398
  console.error('Failed to update device status:', error.message);
1170
1399
  }
1171
1400
  await captureRemote('remote_channel_status_update_error', { error, status });
1172
- return;
1401
+ return false;
1173
1402
  }
1174
1403
  else {
1175
1404
  console.debug(`[DEBUG] Device status set to ${status}`);
1176
1405
  }
1406
+ return true;
1177
1407
  // console.log(status === 'online' ? `🔌 Device marked as ${status}` : `❌ Device marked as ${status}`);
1178
1408
  }
1179
1409
  async setOffline(deviceId) {
@@ -1188,8 +1418,8 @@ export class RemoteChannel {
1188
1418
  // timeout) and refreshes when the token is within ~90s of expiry,
1189
1419
  // POSTing /token with its own ~30s retry budget. On a just-woken
1190
1420
  // machine that outlasts device.ts's 5s force-exit, and then spawnSync
1191
- // never runs and the offline write is lost. The subprocess calls
1192
- // setSession() itself, so a slightly stale access_token is fine.
1421
+ // never runs and the offline write is lost. The subprocess refreshes
1422
+ // an expired access_token itself, so a stale one is fine.
1193
1423
  const live = await Promise.race([
1194
1424
  this.client.auth.getSession().then((r) => r.data?.session ?? null),
1195
1425
  this.sleep(OFFLINE_SESSION_TIMEOUT_MS).then(() => null),
@@ -1227,7 +1457,9 @@ export class RemoteChannel {
1227
1457
  supabaseUrl,
1228
1458
  supabaseKey,
1229
1459
  session.access_token,
1230
- session.refresh_token || ''
1460
+ // A lost session's refresh token already failed to refresh;
1461
+ // presenting it again can trip GoTrue's reuse detection.
1462
+ this.sessionLost ? '' : session.refresh_token || ''
1231
1463
  ], {
1232
1464
  timeout: 3000,
1233
1465
  stdio: 'pipe', // Capture output to prevent blocking