@wonderwhy-er/desktop-commander 0.2.51 → 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.
@@ -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,6 +158,12 @@ 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;
119
169
  /** Notified when auth-js rotates the session; the device persists it. */
@@ -135,6 +185,8 @@ export class RemoteChannel {
135
185
  this.presenceTracked = false;
136
186
  /** Last capability value written (null = never), to avoid redundant writes. */
137
187
  this.transportCapableWritten = null;
188
+ /** Monotonic start of a Presence-only degradation while broadcast remains joined. */
189
+ this.presenceFailureStartedAt = null;
138
190
  /** Re-entrancy guard: on a wedged socket each track() buffers for the full
139
191
  * 10s push timeout, so 10s health ticks would stack pushes. */
140
192
  this.isTrackingPresence = false;
@@ -165,6 +217,7 @@ export class RemoteChannel {
165
217
  auth: { autoRefreshToken: false },
166
218
  global: { fetch: clockAwareFetch },
167
219
  realtime: {
220
+ reconnectAfterMs: realtimeReconnectDelayMs,
168
221
  // supabase-js's resolver ends in `?? supabaseKey`, so after SIGNED_OUT
169
222
  // the socket silently re-pins to the anon key and every private-channel
170
223
  // join is refused. Overriding under `realtime` (not the top-level
@@ -195,6 +248,14 @@ export class RemoteChannel {
195
248
  catch { /* no onHeartbeat on this client version: staleness check stays inert */ }
196
249
  }
197
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
+ }
198
259
  /**
199
260
  * Register a callback fired when auth-js rotates the session. auth-js
200
261
  * rotates the refresh token on every refresh and the previous one is spent,
@@ -420,15 +481,30 @@ export class RemoteChannel {
420
481
  console.debug('[DEBUG] Existing device found:', !!existingDevice);
421
482
  }
422
483
  if (existingDevice) {
423
- console.debug('[DEBUG] Updating device status to online');
424
- // transport_broadcast_v1 is NOT set here: the server treats it as
425
- // binding, so it is written only once presence is proven.
426
- await this.updateDevice(existingDevice.id, {
427
- 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',
428
495
  last_seen: new Date().toISOString(),
429
496
  capabilities: this.capabilitiesPayload(false),
430
497
  device_name: deviceName
431
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
+ }
432
508
  // Store parameters for channel recreation
433
509
  this.deviceId = existingDevice.id;
434
510
  this.deviceName = deviceName;
@@ -436,9 +512,13 @@ export class RemoteChannel {
436
512
  console.debug(`⏳ Subscribing to tool call channel...`);
437
513
  // Create and subscribe to the channel
438
514
  console.debug('[DEBUG] Calling createChannel()');
439
- await this.createChannel().catch((error) => {
440
- console.debug(`[DEBUG] Failed to create channel, will retry after socket reconnect: ${error?.message || error} — ${this.connState()}`);
441
- });
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();
442
522
  }
443
523
  else {
444
524
  console.error(` - ❌ Device not found: ${currentDeviceId}`);
@@ -463,6 +543,10 @@ export class RemoteChannel {
463
543
  }
464
544
  }
465
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;
466
550
  for (let attempt = 1; attempt <= attempts; attempt++) {
467
551
  if (!this.channel || this.channel.state !== 'joined')
468
552
  return;
@@ -479,25 +563,86 @@ export class RemoteChannel {
479
563
  status = `threw: ${trackErr?.message}`;
480
564
  }
481
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
+ }
482
602
  this.presenceTracked = true;
603
+ this.presenceFailureStartedAt = null;
483
604
  console.log(`👋 Presence tracked (device ${this.deviceId} visible as online)`);
484
605
  // Reconnect attempts preceding this join (0 on a first join).
485
606
  captureRemote('remote_channel_presence_tracked', { recoveredAfterAttempts: recovered }).catch(() => { });
486
- // Proven end-to-end (joined AND presence published) — only now
487
- // advertise the capability dispatch requires.
488
- 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
+ });
489
618
  return;
490
619
  }
491
620
  console.error(`❌ Presence track not acknowledged (${status}) — attempt ${attempt}/${attempts}`);
492
621
  if (attempt < attempts)
493
- await this.sleep(500 * attempt);
622
+ await this.sleep(presenceRetryDelayMs(attempt));
494
623
  }
495
624
  this.presenceTracked = false;
496
- console.error('❌ Presence track failed after retries — withdrawing broadcast capability');
497
625
  captureRemote('remote_channel_presence_track_error', { attempts }).catch(() => { });
498
- // Withdraw: the dashboard reads a flagged device with no presence as
499
- // offline. The faster heartbeat tier keeps the device's DB status
500
- // accurate 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');
501
646
  await this.setTransportCapable(false);
502
647
  }
503
648
  /**
@@ -517,9 +662,9 @@ export class RemoteChannel {
517
662
  */
518
663
  async setTransportCapable(capable) {
519
664
  if (!this.client || !this.deviceId)
520
- return;
665
+ return false;
521
666
  if (this.transportCapableWritten === capable)
522
- return; // no redundant writes
667
+ return true; // no redundant writes
523
668
  try {
524
669
  const capabilities = this.capabilitiesPayload(capable);
525
670
  const { error } = await this.client
@@ -528,7 +673,7 @@ export class RemoteChannel {
528
673
  .eq('id', this.deviceId);
529
674
  if (error) {
530
675
  console.error('[DEBUG] Failed to update transport capability:', error.message);
531
- return;
676
+ return false;
532
677
  }
533
678
  this.transportCapableWritten = capable;
534
679
  console.debug(`[DEBUG] Transport capability set to ${capable ? 'broadcast_v1' : 'withdrawn'}`);
@@ -543,7 +688,9 @@ export class RemoteChannel {
543
688
  }
544
689
  catch (error) {
545
690
  console.error('[DEBUG] Transport capability update threw:', error?.message);
691
+ return false;
546
692
  }
693
+ return true;
547
694
  }
548
695
  /** Create and subscribe the private channel (initial join and recreation). */
549
696
  createChannel() {
@@ -578,16 +725,21 @@ export class RemoteChannel {
578
725
  this.reconnectAttempt = 0;
579
726
  this.lastHeartbeatOkAt = performance.now(); // a fresh join is proof of life too
580
727
  console.log(`✅ Channel subscribed${recovered > 0 ? ` (recovered after ${recovered} attempt${recovered === 1 ? '' : 's'})` : ''}`);
581
- // Update device status on successful connection (queued, so
582
- // it can't be overtaken by a teardown's status write).
583
- this.queueStatusWrite('online');
584
- // The capability flag dispatch requires is written only
585
- // once presence lands, so resolve then — otherwise
586
- // registerDevice() reports "Device ready" while still
587
- // 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.
588
738
  this.trackPresenceWithRetry(recovered)
589
739
  .catch(() => { })
590
- .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')));
591
743
  }
592
744
  else if (status === 'CHANNEL_ERROR') {
593
745
  // CHANNEL_ERROR is the only status carrying a real error message.
@@ -597,24 +749,69 @@ export class RemoteChannel {
597
749
  // Fires on ordinary network faults too — filter on the
598
750
  // error text to isolate an 008 misconfiguration.
599
751
  captureRemote('remote_channel_subscription_error', { error: err?.message || 'Channel error' }).catch(() => { });
600
- 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'));
601
753
  }
602
754
  else if (status === 'TIMED_OUT') {
603
755
  console.error(`⏱️ Channel subscription timed out, Reconnecting... — ${this.connState()}`);
604
756
  this.syncReachabilityStatus();
605
757
  captureRemote('remote_channel_subscription_timeout', { attempt: this.reconnectAttempt }).catch(() => { });
606
- reject(new Error('Tool call channel subscription timed out'));
758
+ reject(new ChannelUnreachableError('tool call channel subscription timed out'));
607
759
  }
608
760
  else if (status === 'CLOSED') {
609
761
  // Settle the promise so an in-flight recreateChannel() can't await
610
762
  // forever (which would wedge the re-entrancy guard / watchdog).
611
763
  console.warn(`⚠️ Channel closed — ${this.connState()}`);
612
764
  this.syncReachabilityStatus();
613
- reject(new Error('Tool call channel closed during subscribe'));
765
+ reject(new ChannelUnreachableError('tool call channel closed during subscribe'));
614
766
  }
615
767
  });
616
768
  });
617
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
+ }
618
815
  /** Hand a call to device.ts, observing the rejection — the handler is async
619
816
  * and an unhandled rejection terminates the process. */
620
817
  dispatchToolCall(payload) {
@@ -662,6 +859,7 @@ export class RemoteChannel {
662
859
  .eq('id', callId)
663
860
  .eq('device_id', this.deviceId)
664
861
  .eq('status', 'pending')
862
+ .gt('timeout_at', new Date(Date.now()).toISOString())
665
863
  .select('*');
666
864
  if (!error) {
667
865
  row = data?.[0] ?? null;
@@ -696,8 +894,11 @@ export class RemoteChannel {
696
894
  await captureRemote('remote_channel_doorbell_fetch_error', { error });
697
895
  return;
698
896
  }
699
- if (current?.status === 'pending') {
700
- // No claim landed; device.ts claims it.
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.
701
902
  this.dispatchToolCall({ new: current });
702
903
  }
703
904
  else {
@@ -942,6 +1143,7 @@ export class RemoteChannel {
942
1143
  .update({ status: 'executing' })
943
1144
  .eq('id', callId)
944
1145
  .eq('status', 'pending')
1146
+ .gt('timeout_at', new Date(Date.now()).toISOString())
945
1147
  .select('id');
946
1148
  if (error) {
947
1149
  console.error('[DEBUG] Failed to mark call executing:', error.message);
@@ -1004,18 +1206,31 @@ export class RemoteChannel {
1004
1206
  console.debug('[DEBUG] Call result updated successfully:', callId);
1005
1207
  }
1006
1208
  }
1007
- /** 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
+ */
1008
1216
  isReachable() {
1009
- return this.channel?.state === 'joined';
1217
+ return this.channel?.state === 'joined'
1218
+ && this.presenceTracked
1219
+ && this.localExecutorProbe();
1010
1220
  }
1011
1221
  /**
1012
1222
  * Set `status` from actual reachability. `status` is transport-agnostic (the
1013
1223
  * server filters on it), so it must not follow one channel's health — the
1014
1224
  * private channel's error path re-fires on every rejoin and would oscillate
1015
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.
1016
1230
  */
1231
+ /** Resolves with whether the row actually took the write. */
1017
1232
  syncReachabilityStatus() {
1018
- this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1233
+ return this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1019
1234
  }
1020
1235
  /**
1021
1236
  * Serialize the channel-callback status writes. They fire from un-awaited
@@ -1030,13 +1245,18 @@ export class RemoteChannel {
1030
1245
  // After teardown begins, setOffline() owns the final status write.
1031
1246
  if (this.shuttingDown) {
1032
1247
  console.debug(`[DEBUG] Status write '${status}' suppressed — teardown in progress`);
1033
- return;
1248
+ return Promise.resolve(false);
1034
1249
  }
1035
- this.statusWriteChain = this.statusWriteChain
1036
- .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))
1037
1254
  .catch((e) => {
1038
1255
  console.error('[DEBUG] Status write failed:', e?.message);
1256
+ return false;
1039
1257
  });
1258
+ this.statusWriteChain = write.then(() => undefined);
1259
+ return write;
1040
1260
  }
1041
1261
  /**
1042
1262
  * Heartbeat cadence for the tier this device is CURRENTLY in. Follows the
@@ -1159,9 +1379,10 @@ export class RemoteChannel {
1159
1379
  }
1160
1380
  this.stopTokenRefresh();
1161
1381
  }
1382
+ /** @returns whether the row actually took the write. */
1162
1383
  async setOnlineStatus(deviceId, status) {
1163
1384
  if (!this.client)
1164
- return;
1385
+ return false;
1165
1386
  // Only log if status changed
1166
1387
  if (this.lastDeviceStatus !== status) {
1167
1388
  console.log(`🔌 Device marked as ${status}`);
@@ -1177,11 +1398,12 @@ export class RemoteChannel {
1177
1398
  console.error('Failed to update device status:', error.message);
1178
1399
  }
1179
1400
  await captureRemote('remote_channel_status_update_error', { error, status });
1180
- return;
1401
+ return false;
1181
1402
  }
1182
1403
  else {
1183
1404
  console.debug(`[DEBUG] Device status set to ${status}`);
1184
1405
  }
1406
+ return true;
1185
1407
  // console.log(status === 'online' ? `🔌 Device marked as ${status}` : `❌ Device marked as ${status}`);
1186
1408
  }
1187
1409
  async setOffline(deviceId) {