@wonderwhy-er/desktop-commander 0.2.51 → 0.3.0

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.
Files changed (121) hide show
  1. package/README.md +14 -24
  2. package/dist/command-manager.d.ts +7 -2
  3. package/dist/command-manager.js +16 -11
  4. package/dist/config-manager.d.ts +55 -3
  5. package/dist/config-manager.js +329 -87
  6. package/dist/config-recovery.d.ts +28 -0
  7. package/dist/config-recovery.js +81 -0
  8. package/dist/config.d.ts +1 -0
  9. package/dist/config.js +9 -0
  10. package/dist/handlers/filesystem-handlers.d.ts +1 -1
  11. package/dist/handlers/filesystem-handlers.js +26 -16
  12. package/dist/handlers/search-answers.d.ts +58 -0
  13. package/dist/handlers/search-answers.js +172 -0
  14. package/dist/handlers/search-handlers.js +4 -92
  15. package/dist/index.js +14 -7
  16. package/dist/npm-scripts/remote.js +47 -4
  17. package/dist/remote-device/desktop-commander-integration.d.ts +21 -0
  18. package/dist/remote-device/desktop-commander-integration.js +121 -40
  19. package/dist/remote-device/device-authenticator.d.ts +13 -1
  20. package/dist/remote-device/device-authenticator.js +87 -47
  21. package/dist/remote-device/device.d.ts +14 -0
  22. package/dist/remote-device/device.js +244 -51
  23. package/dist/remote-device/diagnostics/device-log.d.ts +63 -0
  24. package/dist/remote-device/diagnostics/device-log.js +219 -0
  25. package/dist/remote-device/diagnostics/redact.d.ts +1 -0
  26. package/dist/remote-device/diagnostics/redact.js +76 -0
  27. package/dist/remote-device/diagnostics/report.d.ts +118 -0
  28. package/dist/remote-device/diagnostics/report.js +748 -0
  29. package/dist/remote-device/diagnostics/upload.d.ts +11 -0
  30. package/dist/remote-device/diagnostics/upload.js +59 -0
  31. package/dist/remote-device/realtime-health-telemetry.d.ts +35 -0
  32. package/dist/remote-device/realtime-health-telemetry.js +110 -0
  33. package/dist/remote-device/remote-channel.d.ts +86 -5
  34. package/dist/remote-device/remote-channel.js +470 -68
  35. package/dist/remote-device/scripts/blocking-offline-update.js +108 -69
  36. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  37. package/dist/remote-device/transport-telemetry.js +48 -0
  38. package/dist/search-manager.d.ts +239 -27
  39. package/dist/search-manager.js +746 -312
  40. package/dist/server.js +157 -303
  41. package/dist/terminal-manager.d.ts +138 -21
  42. package/dist/terminal-manager.js +300 -215
  43. package/dist/tools/config.d.ts +1 -1
  44. package/dist/tools/config.js +21 -70
  45. package/dist/tools/edit.js +12 -4
  46. package/dist/tools/filesystem.d.ts +30 -6
  47. package/dist/tools/filesystem.js +246 -140
  48. package/dist/tools/improved-process-tools.d.ts +9 -3
  49. package/dist/tools/improved-process-tools.js +171 -68
  50. package/dist/tools/pdf/extract-images.d.ts +2 -0
  51. package/dist/tools/pdf/extract-images.js +4 -1
  52. package/dist/tools/pdf/index.d.ts +5 -3
  53. package/dist/tools/pdf/index.js +4 -3
  54. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  55. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  56. package/dist/tools/pdf/manipulations.d.ts +12 -1
  57. package/dist/tools/pdf/manipulations.js +17 -4
  58. package/dist/tools/pdf/markdown.d.ts +96 -0
  59. package/dist/tools/pdf/markdown.js +485 -20
  60. package/dist/tools/pdf/utils.d.ts +2 -2
  61. package/dist/tools/pdf/utils.js +4 -4
  62. package/dist/tools/process.js +8 -5
  63. package/dist/tools/schemas.d.ts +1 -11
  64. package/dist/tools/schemas.js +15 -14
  65. package/dist/types.d.ts +1 -1
  66. package/dist/ui/config-editor/config-editor-runtime.js +53 -53
  67. package/dist/ui/config-editor/src/app.js +2 -15
  68. package/dist/ui/file-preview/preview-runtime.js +190 -182
  69. package/dist/utils/ab-test.js +27 -9
  70. package/dist/utils/atomic-write.d.ts +14 -0
  71. package/dist/utils/atomic-write.js +80 -0
  72. package/dist/utils/capture.d.ts +17 -1
  73. package/dist/utils/capture.js +177 -68
  74. package/dist/utils/exit-process.d.ts +24 -0
  75. package/dist/utils/exit-process.js +31 -0
  76. package/dist/utils/feature-flags.js +2 -1
  77. package/dist/utils/files/base.d.ts +3 -1
  78. package/dist/utils/files/docx.d.ts +3 -0
  79. package/dist/utils/files/docx.js +24 -9
  80. package/dist/utils/files/excel.d.ts +10 -0
  81. package/dist/utils/files/excel.js +93 -33
  82. package/dist/utils/files/factory.d.ts +22 -1
  83. package/dist/utils/files/factory.js +59 -4
  84. package/dist/utils/files/image.d.ts +12 -4
  85. package/dist/utils/files/image.js +19 -8
  86. package/dist/utils/files/index.d.ts +5 -3
  87. package/dist/utils/files/index.js +4 -3
  88. package/dist/utils/files/pdf.js +18 -36
  89. package/dist/utils/files/text.d.ts +21 -5
  90. package/dist/utils/files/text.js +90 -86
  91. package/dist/utils/internal-facts.d.ts +3 -0
  92. package/dist/utils/internal-facts.js +23 -0
  93. package/dist/utils/lazy-package.d.ts +25 -0
  94. package/dist/utils/lazy-package.js +44 -0
  95. package/dist/utils/open-browser.js +2 -1
  96. package/dist/utils/process-detection.d.ts +24 -5
  97. package/dist/utils/process-detection.js +199 -89
  98. package/dist/utils/process-tree.d.ts +14 -0
  99. package/dist/utils/process-tree.js +223 -0
  100. package/dist/utils/rename.d.ts +9 -0
  101. package/dist/utils/rename.js +74 -0
  102. package/dist/utils/ripgrep-resolver.js +9 -14
  103. package/dist/utils/shell.d.ts +42 -0
  104. package/dist/utils/shell.js +187 -0
  105. package/dist/utils/system-info.d.ts +1 -0
  106. package/dist/utils/system-info.js +40 -25
  107. package/dist/utils/trackTools.js +2 -1
  108. package/dist/utils/usageTracker.d.ts +0 -39
  109. package/dist/utils/usageTracker.js +1 -161
  110. package/dist/version.d.ts +1 -1
  111. package/dist/version.js +1 -1
  112. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  113. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  114. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  115. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  116. package/package.json +32 -16
  117. package/vendor/telemetry-contract/README.md +56 -0
  118. package/vendor/telemetry-contract/package.json +32 -0
  119. package/vendor/telemetry-contract/transport.d.ts +38 -0
  120. package/vendor/telemetry-contract/transport.js +164 -0
  121. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -1,5 +1,7 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import { captureRemote } from '../utils/capture.js';
3
+ import { observeTransport } from './transport-telemetry.js';
4
+ import { RealtimeHealthTelemetry } from './realtime-health-telemetry.js';
3
5
  import { VERSION } from '../version.js';
4
6
  const NUL_CHAR = String.fromCharCode(0);
5
7
  const NUL_RE = new RegExp(NUL_CHAR, 'g');
@@ -28,14 +30,48 @@ export function stripNullBytes(value) {
28
30
  }
29
31
  return value;
30
32
  }
33
+ /**
34
+ * The device registered, but its realtime channel is not usable — the join
35
+ * failed, or presence was never acknowledged. Distinct from every other
36
+ * registration failure on purpose: this one the socket watchdog can repair, so
37
+ * the caller keeps the process alive, while a failed lookup or a missing row
38
+ * happens before the recreation parameters are stored and nothing can repair it.
39
+ */
40
+ export class ChannelUnreachableError extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = 'ChannelUnreachableError';
44
+ }
45
+ }
31
46
  // last_seen cadences. The server tiers its sweep on the transport_broadcast_v1
32
47
  // flag, so each must fit its tier's threshold in the server's constants.ts:
33
48
  // capable -> 15 min, unflagged -> 45s.
34
49
  const CAPABLE_HEARTBEAT_INTERVAL = 5 * 60 * 1000;
35
50
  const LEGACY_HEARTBEAT_INTERVAL = 15 * 1000;
51
+ // Fast recovery for short Wi-Fi blips, but never retry every 10 seconds forever.
52
+ // Prolonged provider incidents must not keep the entire device fleet joining.
53
+ // Independent jitter spreads retry work; full jitter applies at attempt >= 5.
54
+ const REALTIME_RECONNECT_BASE_MS = [1000, 2000, 5000, 10000, 20000, 40000, 80000, 120000];
55
+ const REALTIME_RECONNECT_FALLBACK_MS = 120000;
56
+ const WATCHDOG_RECREATE_MAX_BACKOFF_MS = 120000;
57
+ // Presence-only failures do not mean broadcast delivery is down: a joined
58
+ // channel can still receive doorbells while Presence's DB-backed work is
59
+ // degraded. Keep a previously-proven capability for one normal heartbeat
60
+ // interval before falling back to the 15s legacy tier, avoiding a 20x heartbeat
61
+ // write-rate jump during short provider incidents.
62
+ const PRESENCE_WITHDRAW_GRACE_MS = 5 * 60 * 1000;
36
63
  // 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).
64
+ // Must exceed createChannel()'s worst case (~32.25s of jittered presence retries).
38
65
  const RECREATE_TIMEOUT_MS = 45000;
66
+ // Upper bound on the persistent unready-join budget. Anything >= 8 already
67
+ // selects the 120s SDK tier; the cap only keeps the counter meaningful.
68
+ const MAX_UNREADY_JOIN_BUDGET = 16;
69
+ // A channel that has stayed joined this long, with a heartbeat confirmed after
70
+ // the join, is a working broadcast path even if Presence is still degraded.
71
+ // Its join no longer counts toward reconnect backoff (Presence keeps its own
72
+ // cooldown). Comfortably longer than the incident's join->error cycle (~10-30s)
73
+ // and covers at least four 25s heartbeats.
74
+ const STABLE_BROADCAST_RESET_MS = 120000;
39
75
  // Max continuous time in 'joining' before forcing a recreate — a half-open
40
76
  // socket parks the channel there forever, and a genuine join settles in ~10s.
41
77
  const JOINING_WEDGE_TIMEOUT_MS = 30000;
@@ -54,6 +90,11 @@ const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
54
90
  // Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
55
91
  // does not cover.
56
92
  const CAPABILITY_WRITE_TIMEOUT_MS = 5000;
93
+ // Cap on one write to this device's row (capability, status), after which it
94
+ // is aborted. A PATCH sent down a half-open connection is otherwise answered
95
+ // only by fetch's own 300 s headers timeout, and the write queue behind it,
96
+ // with the presence publish waiting on that queue, waits as long.
97
+ const DEVICE_ROW_WRITE_TIMEOUT_MS = 10000;
57
98
  // Cap on the shutdown session fetch, which races device.ts's 5s force-exit.
58
99
  const OFFLINE_SESSION_TIMEOUT_MS = 500;
59
100
  // realtime-js parks in 'disconnecting' for ~100ms after a disconnect and
@@ -62,6 +103,41 @@ const OFFLINE_SESSION_TIMEOUT_MS = 500;
62
103
  // already covers.
63
104
  const SOCKET_SETTLE_MAX_MS = 300;
64
105
  const SOCKET_SETTLE_POLL_MS = 20;
106
+ // Reconnect recovery is a safety net, not the primary transport. Bound each
107
+ // scan so a pathological backlog cannot turn one reconnect into an unbounded
108
+ // burst of REST claims/tool executions.
109
+ const PENDING_RECOVERY_BATCH_SIZE = 100;
110
+ function jitterAround(baseMs, random) {
111
+ const sample = Math.max(0, Math.min(1, random()));
112
+ return Math.max(1, Math.round(baseMs * (0.5 + sample)));
113
+ }
114
+ /** Exponential-ish SDK backoff. Attempts 1-4 preserve short recovery latency. */
115
+ export function realtimeReconnectDelayMs(tries, random = Math.random) {
116
+ const attempt = Math.max(1, Math.floor(tries || 1));
117
+ const baseMs = REALTIME_RECONNECT_BASE_MS[attempt - 1] ?? REALTIME_RECONNECT_FALLBACK_MS;
118
+ if (attempt <= 4)
119
+ return jitterAround(baseMs, random);
120
+ // Full jitter is deliberately independent per device; floor avoids an immediate tight retry.
121
+ return Math.max(1000, Math.round(baseMs * Math.max(0, Math.min(1, random()))));
122
+ }
123
+ /** Watchdog must not defeat the SDK's slower persistent-failure backoff. */
124
+ export function watchdogRecreateDelayMs(tries, random = Math.random) {
125
+ const attempt = Math.max(1, Math.floor(tries || 1));
126
+ const baseMs = Math.min(WATCHDOG_RECREATE_MAX_BACKOFF_MS, 1000 * 2 ** Math.min(attempt, 7));
127
+ return jitterAround(baseMs, random);
128
+ }
129
+ /** Preserve short in-batch Presence retries, independently jittered. */
130
+ export function presenceRetryDelayMs(failedAttempt, random = Math.random) {
131
+ const attempt = Math.max(1, Math.floor(failedAttempt || 1));
132
+ return jitterAround(500 * attempt, random);
133
+ }
134
+ /** Delay new Presence batches after repeated failed batches, even across SDK rejoins.
135
+ * This is intentionally independent of the Phoenix channel/socket reconnect timer. */
136
+ export function presenceRecoveryDelayMs(failures, random = Math.random) {
137
+ const attempt = Math.max(1, Math.floor(failures || 1));
138
+ const baseMs = Math.min(120000, 5000 * 2 ** Math.min(attempt - 1, 5));
139
+ return Math.max(1000, Math.round(baseMs * Math.max(0, Math.min(1, random()))));
140
+ }
65
141
  // auth-js compares token expiry against this device's own Date.now(), with no
66
142
  // clock-skew tolerance — a fast clock treats every fresh token as expired and
67
143
  // refreshes forever (confirmed in prod on one device, via at least 3 separate
@@ -114,6 +190,12 @@ export class RemoteChannel {
114
190
  this.heartbeatDeviceId = null;
115
191
  // Single-slot queue keeping concurrent `status` PATCHes in order.
116
192
  this.statusWriteChain = Promise.resolve();
193
+ /**
194
+ * Answers whether the local execution child is alive. Default yes, so a
195
+ * RemoteChannel used without a device (tests, other callers) behaves as
196
+ * before; MCPDevice installs the real probe.
197
+ */
198
+ this.localExecutorProbe = () => true;
117
199
  /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
118
200
  this.lastKnownSession = null;
119
201
  /** Notified when auth-js rotates the session; the device persists it. */
@@ -135,9 +217,26 @@ export class RemoteChannel {
135
217
  this.presenceTracked = false;
136
218
  /** Last capability value written (null = never), to avoid redundant writes. */
137
219
  this.transportCapableWritten = null;
220
+ /** Value of the last capability write still queued or in flight; null once the queue is idle. */
221
+ this.transportCapableQueued = null;
222
+ // Single-slot queue keeping capability writes in order (see setTransportCapable).
223
+ this.capabilityWriteChain = Promise.resolve();
224
+ /** Monotonic start of a Presence-only degradation while broadcast remains joined. */
225
+ this.presenceFailureStartedAt = null;
138
226
  /** Re-entrancy guard: on a wedged socket each track() buffers for the full
139
227
  * 10s push timeout, so 10s health ticks would stack pushes. */
140
228
  this.isTrackingPresence = false;
229
+ // The SDK resets its rejoin timer on *every* SUBSCRIBED, even if Presence
230
+ // immediately times out. Count such joins across SDK/channel recreation.
231
+ // Reset only after Presence AND durable readiness writes succeed.
232
+ this.consecutiveUnreadyJoins = 0;
233
+ this.consecutivePresenceFailures = 0;
234
+ this.nextPresenceAttemptAt = 0; // monotonic; independent of Date.now skew correction
235
+ /** performance.now() of the latest SUBSCRIBED; null while not joined. */
236
+ this.joinedAt = null;
237
+ this.realtimeHealth = new RealtimeHealthTelemetry((window) => {
238
+ captureRemote('remote_realtime_health_window', window).catch(() => { });
239
+ });
141
240
  // Track last device status to prevent duplicate log messages
142
241
  this.lastDeviceStatus = 'offline';
143
242
  // Track last channel state for debug logging
@@ -156,6 +255,11 @@ export class RemoteChannel {
156
255
  this.tokenRefreshInterval = null;
157
256
  this._user = null;
158
257
  }
258
+ /** SDK channel and socket timers share reconnectAfterMs. The persistent
259
+ * unready-join budget prevents a series of partial successes restarting at 1s. */
260
+ reconnectDelayMs(tries, random = Math.random) {
261
+ return realtimeReconnectDelayMs(Math.max(tries, this.consecutiveUnreadyJoins), random);
262
+ }
159
263
  get user() { return this._user; }
160
264
  initialize(url, key) {
161
265
  // autoRefreshToken:false — we drive refresh ourselves (startTokenRefresh(),
@@ -165,6 +269,7 @@ export class RemoteChannel {
165
269
  auth: { autoRefreshToken: false },
166
270
  global: { fetch: clockAwareFetch },
167
271
  realtime: {
272
+ reconnectAfterMs: (tries) => this.reconnectDelayMs(tries),
168
273
  // supabase-js's resolver ends in `?? supabaseKey`, so after SIGNED_OUT
169
274
  // the socket silently re-pins to the anon key and every private-channel
170
275
  // join is refused. Overriding under `realtime` (not the top-level
@@ -195,6 +300,14 @@ export class RemoteChannel {
195
300
  catch { /* no onHeartbeat on this client version: staleness check stays inert */ }
196
301
  }
197
302
  }
303
+ /**
304
+ * Teach the channel how to ask whether the local executor is alive.
305
+ * `status` is a claim that this device will run a tool call right now, and
306
+ * a joined channel alone cannot support that claim - issue #4.
307
+ */
308
+ setLocalExecutorProbe(probe) {
309
+ this.localExecutorProbe = probe;
310
+ }
198
311
  /**
199
312
  * Register a callback fired when auth-js rotates the session. auth-js
200
313
  * rotates the refresh token on every refresh and the previous one is spent,
@@ -420,25 +533,45 @@ export class RemoteChannel {
420
533
  console.debug('[DEBUG] Existing device found:', !!existingDevice);
421
534
  }
422
535
  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',
428
- last_seen: new Date().toISOString(),
536
+ console.debug('[DEBUG] Registering device as offline until the channel proves otherwise');
537
+ // Neither half of this row may claim reachability yet. transport_
538
+ // broadcast_v1 is NOT set here: the server treats it as binding, so
539
+ // it is written only once presence is proven. `status` is the same
540
+ // promise in the other notation — dispatch picks its target by it,
541
+ // then fails the call fast for the missing capability, so a row
542
+ // marked online before the channel is up hands every call in that
543
+ // window to a device with no delivery path. SUBSCRIBED writes
544
+ // 'online'; presence writes the capability.
545
+ const { error: registrationError } = await this.updateDevice(existingDevice.id, {
546
+ status: 'offline',
547
+ last_seen: 'now',
429
548
  capabilities: this.capabilitiesPayload(false),
430
549
  device_name: deviceName
431
550
  });
551
+ // updateDevice() logs and returns its error rather than throwing.
552
+ // Opening the channel anyway would leave a row that still says
553
+ // whatever the last run left there — including 'online' — while
554
+ // nothing here can correct it: the channel's own error path queues
555
+ // an offline write, and setOnlineStatus() only logs when that write
556
+ // fails too. Stop before the channel instead.
557
+ if (registrationError) {
558
+ throw new Error(`Failed to register device: ${registrationError.message}`);
559
+ }
432
560
  // Store parameters for channel recreation
433
561
  this.deviceId = existingDevice.id;
562
+ this.realtimeHealth.setDevice(existingDevice.id);
434
563
  this.deviceName = deviceName;
435
564
  this.onToolCall = onToolCall;
436
565
  console.debug(`⏳ Subscribing to tool call channel...`);
437
566
  // Create and subscribe to the channel
438
567
  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
- });
568
+ // Let a failed join reach the caller. createChannel() resolves only
569
+ // once the channel is joined AND presence is published — the two
570
+ // things dispatch needs — so swallowing its rejection here was what
571
+ // let device.ts print "Device ready" over a device that cannot
572
+ // receive a single command. The caller decides what to do with it;
573
+ // it is not fatal, the socket watchdog keeps retrying.
574
+ await this.createChannel();
442
575
  }
443
576
  else {
444
577
  console.error(` - ❌ Device not found: ${currentDeviceId}`);
@@ -454,6 +587,10 @@ export class RemoteChannel {
454
587
  async trackPresenceWithRetry(recovered, attempts = 3) {
455
588
  if (this.isTrackingPresence)
456
589
  return; // never stack pushes on a wedged socket
590
+ // SDK may deliver SUBSCRIBED again before Presence's separate cooldown
591
+ // expires. Do not let each successful join bypass that cooldown.
592
+ if (this.presenceInCooldown())
593
+ return;
457
594
  this.isTrackingPresence = true;
458
595
  try {
459
596
  await this.trackPresenceInner(recovered, attempts);
@@ -462,13 +599,42 @@ export class RemoteChannel {
462
599
  this.isTrackingPresence = false;
463
600
  }
464
601
  }
602
+ /** One failed Presence batch: grow the Presence-only cooldown. Deadlines are
603
+ * monotonic so a Date.now skew correction cannot shorten or extend them. */
604
+ recordPresenceBatchFailure() {
605
+ this.consecutivePresenceFailures++;
606
+ this.nextPresenceAttemptAt = performance.now() +
607
+ presenceRecoveryDelayMs(this.consecutivePresenceFailures);
608
+ }
609
+ /** Presence is withheld by its cooldown right now. */
610
+ presenceInCooldown() {
611
+ return performance.now() < this.nextPresenceAttemptAt;
612
+ }
465
613
  async trackPresenceInner(recovered, attempts) {
614
+ // A fresh attempt starts from "not proven", so a leftover true from an
615
+ // earlier join cannot keep the device counting as reachable while this
616
+ // one is still deciding.
617
+ this.presenceTracked = false;
618
+ // Every await below can outlive this channel (recreateChannel() swaps
619
+ // it). A late result must not touch retry state the newer channel owns.
620
+ const channel = this.channel;
621
+ let failedAttempts = 0;
466
622
  for (let attempt = 1; attempt <= attempts; attempt++) {
467
- if (!this.channel || this.channel.state !== 'joined')
623
+ if (this.channel !== channel)
468
624
  return;
625
+ if (!channel || channel.state !== 'joined') {
626
+ // Production sequence (2026-10-13): track() times out, then the
627
+ // channel errors before the next in-batch attempt. That batch
628
+ // failed too; without recording it the next SUBSCRIBED would
629
+ // publish again with no cooldown at all.
630
+ if (failedAttempts > 0)
631
+ this.recordPresenceBatchFailure();
632
+ return;
633
+ }
469
634
  let status;
635
+ this.realtimeHealth.record('presence_attempts');
470
636
  try {
471
- status = await this.channel.track({
637
+ status = await channel.track({
472
638
  device_id: this.deviceId,
473
639
  device_name: this.deviceName,
474
640
  app_version: VERSION,
@@ -478,26 +644,105 @@ export class RemoteChannel {
478
644
  catch (trackErr) {
479
645
  status = `threw: ${trackErr?.message}`;
480
646
  }
647
+ if (this.channel !== channel)
648
+ return; // stale ack/timeout from a replaced channel
481
649
  if (status === 'ok') {
650
+ this.realtimeHealth.record('presence_successes');
651
+ // `presenceTracked` is not "track() said ok" — isReachable()
652
+ // reads it as "this device receives commands", and the heartbeat
653
+ // consults isReachable() directly rather than waiting for the
654
+ // sequence below. Raising it here let a heartbeat firing while
655
+ // these writes were in flight assert `online` over a row with no
656
+ // capability recorded: the very state this is meant to remove.
657
+ // So it is raised last, when every claim it makes is already true.
658
+ //
659
+ // Both writes have to land. Supabase reports a refused write in
660
+ // the result rather than by throwing, and a device whose row
661
+ // records neither the capability nor `online` is exactly as
662
+ // undispatchable as one that never published presence. The
663
+ // health check retries presence while this stays false, which is
664
+ // the way back.
665
+ const capabilityWritten = await this.setTransportCapable(true);
666
+ // Strictly after, never alongside: `online` may be claimed only
667
+ // where the capability is already advertised, or the row lands
668
+ // back in the state this whole change is about.
669
+ // Not syncReachabilityStatus(): its predicate reads presenceTracked,
670
+ // and that flag is deliberately still false here - it is raised last,
671
+ // once these writes have landed, so a heartbeat cannot advertise the
672
+ // row mid-sequence. Both halves the predicate asks about are already
673
+ // known at this point: the channel is joined and presence was just
674
+ // acknowledged. The only open question is the local executor, so ask
675
+ // that directly - a joined, present device whose executor is dead must
676
+ // not be advertised either.
677
+ const statusWritten = capabilityWritten
678
+ ? await this.queueStatusWrite(this.localExecutorProbe() ? 'online' : 'offline')
679
+ : false;
680
+ if (!capabilityWritten || !statusWritten) {
681
+ console.error('❌ Presence published but the device row could not be updated — not ready');
682
+ this.realtimeHealth.record('readiness_write_failures');
683
+ captureRemote('remote_channel_readiness_write_failed', {
684
+ capabilityWritten, statusWritten
685
+ }).catch(() => { });
686
+ return;
687
+ }
688
+ // Writes can take up to DEVICE_ROW_WRITE_TIMEOUT_MS each; if the
689
+ // channel was replaced meanwhile, its own join decides readiness.
690
+ if (this.channel !== channel)
691
+ return;
482
692
  this.presenceTracked = true;
693
+ // A joined socket is only a partial recovery. Clear backoff
694
+ // after Presence and both readiness writes have succeeded.
695
+ this.consecutiveUnreadyJoins = 0;
696
+ this.consecutivePresenceFailures = 0;
697
+ this.nextPresenceAttemptAt = 0;
698
+ this.presenceFailureStartedAt = null;
483
699
  console.log(`👋 Presence tracked (device ${this.deviceId} visible as online)`);
484
700
  // Reconnect attempts preceding this join (0 on a first join).
485
701
  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);
702
+ // Broadcast is only a wake-up signal; mcp_remote_calls is the
703
+ // durable queue. A call inserted while this socket was briefly
704
+ // disconnected can miss its one new_call doorbell and otherwise
705
+ // stay pending until the server reaper times it out. Drain that
706
+ // durable backlog whenever the channel becomes genuinely usable.
707
+ // Fire-and-forget so readiness does not wait on backlog recovery;
708
+ // each row still goes through the atomic pending -> executing
709
+ // claim, so a late/duplicate doorbell can safely race this scan.
710
+ this.recoverPendingCalls().catch((error) => {
711
+ console.error('[DEBUG] Pending call recovery failed:', error?.message);
712
+ });
489
713
  return;
490
714
  }
715
+ failedAttempts++;
491
716
  console.error(`❌ Presence track not acknowledged (${status}) — attempt ${attempt}/${attempts}`);
717
+ this.realtimeHealth.record('presence_failures');
492
718
  if (attempt < attempts)
493
- await this.sleep(500 * attempt);
719
+ await this.sleep(presenceRetryDelayMs(attempt));
494
720
  }
721
+ if (this.channel !== channel)
722
+ return;
495
723
  this.presenceTracked = false;
496
- console.error('❌ Presence track failed after retries — withdrawing broadcast capability');
724
+ this.recordPresenceBatchFailure();
497
725
  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.
726
+ // Presence is an observer signal, not the delivery path. If this device
727
+ // already proved broadcast capability and the channel is still joined,
728
+ // keep that capability through a short provider-side Presence incident
729
+ // instead of immediately switching to the 15s legacy heartbeat tier.
730
+ // The 10s health check keeps retrying Presence; a success clears the
731
+ // timer. Genuine channel failure is handled separately by
732
+ // recreateChannel(), which still withdraws after 3 failed recreates.
733
+ if (this.transportCapableWritten === true && this.channel?.state === 'joined') {
734
+ const now = performance.now();
735
+ if (this.presenceFailureStartedAt === null)
736
+ this.presenceFailureStartedAt = now;
737
+ const degradedForMs = now - this.presenceFailureStartedAt;
738
+ if (degradedForMs < PRESENCE_WITHDRAW_GRACE_MS) {
739
+ console.warn(`⚠️ Presence unavailable for ${Math.round(degradedForMs / 1000)}s — ` +
740
+ `retaining broadcast capability during ${PRESENCE_WITHDRAW_GRACE_MS / 1000}s grace`);
741
+ return;
742
+ }
743
+ }
744
+ this.presenceFailureStartedAt = null;
745
+ console.error('❌ Presence track remained unavailable — withdrawing broadcast capability');
501
746
  await this.setTransportCapable(false);
502
747
  }
503
748
  /**
@@ -514,21 +759,45 @@ export class RemoteChannel {
514
759
  * Advertise (or withdraw) the broadcast capability. Only true while genuinely
515
760
  * reachable that way — the server fails dispatch fast without it and picks
516
761
  * the offline-sweep tier from it, so every change must re-arm the heartbeat.
762
+ *
763
+ * Writes are queued, like the status writes. A withdrawal the recreate stops
764
+ * waiting for still lands: compared with the last landed value, a re-publish
765
+ * in the meantime looked redundant and was skipped, and the withdrawal then
766
+ * left a device that claims to be online without the flag. Resolves with
767
+ * whether the row holds `capable` once this write is done.
517
768
  */
518
- async setTransportCapable(capable) {
769
+ setTransportCapable(capable) {
519
770
  if (!this.client || !this.deviceId)
520
- return;
521
- if (this.transportCapableWritten === capable)
522
- return; // no redundant writes
771
+ return Promise.resolve(false);
772
+ // What the row holds once the queue drains — no redundant writes.
773
+ if ((this.transportCapableQueued ?? this.transportCapableWritten) === capable) {
774
+ return this.capabilityWriteChain.then(() => this.transportCapableWritten === capable);
775
+ }
776
+ this.transportCapableQueued = capable;
777
+ const write = this.capabilityWriteChain.then(() => this.writeTransportCapable(capable));
778
+ this.capabilityWriteChain = write;
779
+ write.then(() => {
780
+ if (this.capabilityWriteChain === write)
781
+ this.transportCapableQueued = null;
782
+ });
783
+ return write;
784
+ }
785
+ async writeTransportCapable(capable) {
786
+ if (!this.client || !this.deviceId)
787
+ return false;
523
788
  try {
524
789
  const capabilities = this.capabilitiesPayload(capable);
525
790
  const { error } = await this.client
526
791
  .from('mcp_devices')
527
792
  .update({ capabilities })
528
- .eq('id', this.deviceId);
793
+ .eq('id', this.deviceId)
794
+ .abortSignal(this.deviceRowWriteSignal());
529
795
  if (error) {
530
796
  console.error('[DEBUG] Failed to update transport capability:', error.message);
531
- return;
797
+ // An aborted write may still land: what the row holds is
798
+ // unknown, so the next write of either value is not skipped.
799
+ this.transportCapableWritten = null;
800
+ return false;
532
801
  }
533
802
  this.transportCapableWritten = capable;
534
803
  console.debug(`[DEBUG] Transport capability set to ${capable ? 'broadcast_v1' : 'withdrawn'}`);
@@ -543,7 +812,14 @@ export class RemoteChannel {
543
812
  }
544
813
  catch (error) {
545
814
  console.error('[DEBUG] Transport capability update threw:', error?.message);
815
+ this.transportCapableWritten = null;
816
+ return false;
546
817
  }
818
+ return true;
819
+ }
820
+ /** Aborts one write to this device's row after DEVICE_ROW_WRITE_TIMEOUT_MS (a method, so tests can shorten it). */
821
+ deviceRowWriteSignal() {
822
+ return AbortSignal.timeout(DEVICE_ROW_WRITE_TIMEOUT_MS);
547
823
  }
548
824
  /** Create and subscribe the private channel (initial join and recreation). */
549
825
  createChannel() {
@@ -558,6 +834,7 @@ export class RemoteChannel {
558
834
  // Presence, keyed by device id.
559
835
  const channelName = `user:${this.user.id}`;
560
836
  console.debug(`[DEBUG] Creating channel: ${channelName}`);
837
+ this.realtimeHealth.newChannel();
561
838
  this.channel = this.client.channel(channelName, {
562
839
  config: {
563
840
  private: true,
@@ -566,6 +843,10 @@ export class RemoteChannel {
566
843
  }
567
844
  })
568
845
  .on('broadcast', { event: 'new_call' }, ({ payload }) => {
846
+ if (!this.shuttingDown) {
847
+ observeTransport({ stage: 'received', payload, deviceId: this.deviceId,
848
+ userId: this.user?.id, transport: 'broadcast' });
849
+ }
569
850
  this.onDoorbell(payload).catch((e) => {
570
851
  console.error('[DEBUG] Doorbell handling failed:', e?.message);
571
852
  });
@@ -574,47 +855,116 @@ export class RemoteChannel {
574
855
  // Debug: Log all subscription status events
575
856
  console.debug(`[DEBUG] Channel subscription status: ${status}${err ? ' (error: ' + (err?.message || err) + ')' : ''} — ${this.connState()}`);
576
857
  if (status === 'SUBSCRIBED') {
858
+ this.realtimeHealth.record('join_successes');
859
+ // The SDK resets its rejoinTimer here regardless of Presence.
860
+ // Carry failure budget across successful-but-unready joins.
861
+ // reconnectAttempt is different: it counts watchdog
862
+ // recreations (and gates capability withdrawal), and a
863
+ // join does end that particular failure mode.
864
+ this.consecutiveUnreadyJoins = Math.min(MAX_UNREADY_JOIN_BUDGET, this.consecutiveUnreadyJoins + 1);
577
865
  const recovered = this.reconnectAttempt;
578
- this.reconnectAttempt = 0;
579
- this.lastHeartbeatOkAt = performance.now(); // a fresh join is proof of life too
866
+ this.reconnectAttempt = 0; // watchdog attempts only, not recovery proof
867
+ const joinedAt = performance.now();
868
+ this.joinedAt = joinedAt;
869
+ this.lastHeartbeatOkAt = joinedAt; // a fresh join is proof of life too
580
870
  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.
871
+ // A join is only half of what dispatch needs. The other
872
+ // half is presence, which writes the capability the
873
+ // server checks — and when every track() is refused,
874
+ // trackPresenceInner() withdraws the capability and
875
+ // returns normally. Resolving here regardless left the
876
+ // row online with the capability withdrawn: the exact
877
+ // state the server refuses as not_broadcast_capable.
878
+ // `status` is written on the same event as the
879
+ // capability, in trackPresenceInner, so the two can
880
+ // never disagree.
881
+ //
882
+ // During a Presence cooldown no publish is attempted.
883
+ // The promise still rejects (the device is not ready),
884
+ // but the joined channel itself is left in place: the
885
+ // health check treats 'joined' as healthy and only
886
+ // retries Presence once the cooldown expires.
887
+ const deferred = this.presenceInCooldown();
588
888
  this.trackPresenceWithRetry(recovered)
589
889
  .catch(() => { })
590
- .finally(() => resolve());
890
+ .finally(() => this.presenceTracked
891
+ ? resolve()
892
+ : reject(new ChannelUnreachableError(deferred
893
+ ? 'channel joined; presence deferred by cooldown after repeated failures'
894
+ : 'channel joined but presence was never acknowledged, so no command can be delivered')));
591
895
  }
592
896
  else if (status === 'CHANNEL_ERROR') {
897
+ this.realtimeHealth.record('join_errors');
593
898
  // CHANNEL_ERROR is the only status carrying a real error message.
594
899
  console.error(`❌ Channel error: ${err?.message || 'unknown'} — ${this.connState()}`);
900
+ this.joinedAt = null;
595
901
  this.presenceTracked = false;
596
902
  this.syncReachabilityStatus();
597
903
  // Fires on ordinary network faults too — filter on the
598
904
  // error text to isolate an 008 misconfiguration.
599
905
  captureRemote('remote_channel_subscription_error', { error: err?.message || 'Channel error' }).catch(() => { });
600
- reject(err || new Error('Failed to initialize tool call channel subscription'));
906
+ reject(new ChannelUnreachableError(err?.message || 'failed to subscribe to the tool call channel'));
601
907
  }
602
908
  else if (status === 'TIMED_OUT') {
909
+ this.realtimeHealth.record('join_timeouts');
603
910
  console.error(`⏱️ Channel subscription timed out, Reconnecting... — ${this.connState()}`);
604
911
  this.syncReachabilityStatus();
605
912
  captureRemote('remote_channel_subscription_timeout', { attempt: this.reconnectAttempt }).catch(() => { });
606
- reject(new Error('Tool call channel subscription timed out'));
913
+ reject(new ChannelUnreachableError('tool call channel subscription timed out'));
607
914
  }
608
915
  else if (status === 'CLOSED') {
916
+ this.realtimeHealth.record('join_closures');
609
917
  // Settle the promise so an in-flight recreateChannel() can't await
610
918
  // forever (which would wedge the re-entrancy guard / watchdog).
611
919
  console.warn(`⚠️ Channel closed — ${this.connState()}`);
612
920
  this.syncReachabilityStatus();
613
- reject(new Error('Tool call channel closed during subscribe'));
921
+ reject(new ChannelUnreachableError('tool call channel closed during subscribe'));
614
922
  }
615
923
  });
616
924
  });
617
925
  }
926
+ /**
927
+ * Recover calls whose Realtime doorbell was missed while this device was
928
+ * disconnected. Broadcast provides the fast path; the DB row is the source
929
+ * of truth. Only still-live pending rows for this device are considered.
930
+ *
931
+ * The follow-up onDoorbell() call performs the existing conditional claim,
932
+ * which makes this safe against a doorbell arriving at the same time.
933
+ */
934
+ async recoverPendingCalls() {
935
+ if (!this.client || !this.deviceId || !this.isReachable())
936
+ return;
937
+ const { data: pending, error } = await this.client
938
+ .from('mcp_remote_calls')
939
+ .select('id,device_id')
940
+ .eq('device_id', this.deviceId)
941
+ .eq('status', 'pending')
942
+ .gt('timeout_at', 'now')
943
+ .order('created_at', { ascending: true })
944
+ .limit(PENDING_RECOVERY_BATCH_SIZE);
945
+ if (error) {
946
+ console.error('[DEBUG] Failed to query pending calls after reconnect:', error.message);
947
+ await captureRemote('remote_channel_pending_recovery_error', { error });
948
+ return;
949
+ }
950
+ if (!pending?.length)
951
+ return;
952
+ console.log(`♻️ Recovering ${pending.length} pending remote call${pending.length === 1 ? '' : 's'} after reconnect`);
953
+ captureRemote('remote_channel_pending_recovery', {
954
+ pending_count: pending.length,
955
+ batch_capped: pending.length === PENDING_RECOVERY_BATCH_SIZE,
956
+ }).catch(() => { });
957
+ // Claim quickly; dispatchToolCall() does not await tool execution, so
958
+ // this loop serializes only the small REST claim operations.
959
+ for (const row of pending) {
960
+ if (!this.isReachable())
961
+ break;
962
+ await this.onDoorbell({
963
+ call_id: row.id,
964
+ device_id: row.device_id,
965
+ });
966
+ }
967
+ }
618
968
  /** Hand a call to device.ts, observing the rejection — the handler is async
619
969
  * and an unhandled rejection terminates the process. */
620
970
  dispatchToolCall(payload) {
@@ -650,7 +1000,9 @@ export class RemoteChannel {
650
1000
  return;
651
1001
  // Retry on transient failures (a REST blip while the socket stays
652
1002
  // healthy). This claim is the only way we learn about a call,
653
- // so a hiccup must not cost a 5-minute timeout.
1003
+ // so a hiccup must not cost a timeout. PostgREST interprets the
1004
+ // special timestamptz input 'now' in PostgreSQL, not on the device;
1005
+ // this atomically excludes expired rows despite client clock skew.
654
1006
  let row = null;
655
1007
  let claimError = null;
656
1008
  for (const delayMs of [0, 500, 1500]) {
@@ -662,6 +1014,7 @@ export class RemoteChannel {
662
1014
  .eq('id', callId)
663
1015
  .eq('device_id', this.deviceId)
664
1016
  .eq('status', 'pending')
1017
+ .gt('timeout_at', 'now')
665
1018
  .select('*');
666
1019
  if (!error) {
667
1020
  row = data?.[0] ?? null;
@@ -690,6 +1043,7 @@ export class RemoteChannel {
690
1043
  .select('*')
691
1044
  .eq('id', callId)
692
1045
  .eq('device_id', this.deviceId)
1046
+ .gt('timeout_at', 'now')
693
1047
  .maybeSingle();
694
1048
  if (error) {
695
1049
  console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after claim errors:`, error.message);
@@ -697,7 +1051,8 @@ export class RemoteChannel {
697
1051
  return;
698
1052
  }
699
1053
  if (current?.status === 'pending') {
700
- // No claim landed; device.ts claims it.
1054
+ // No claim landed; device.ts claims it. Read-back already excludes
1055
+ // expired rows using PostgreSQL time; its own claim does likewise.
701
1056
  this.dispatchToolCall({ new: current });
702
1057
  }
703
1058
  else {
@@ -737,10 +1092,14 @@ export class RemoteChannel {
737
1092
  return;
738
1093
  }
739
1094
  const state = this.channel.state;
1095
+ this.realtimeHealth.observeSocketState(String(this.client?.realtime?.connectionState?.() ?? 'unknown'));
740
1096
  // Debug: Log current channel state (only if changed)
741
1097
  if (!this.lastChannelState || this.lastChannelState !== state) {
742
1098
  console.debug(`[DEBUG] channel state: ${state} — ${this.connState()}`);
743
1099
  this.lastChannelState = state;
1100
+ if (state !== 'joined' && state !== 'joining') {
1101
+ captureRemote('remote_channel_state_health', { state, attempt: this.reconnectAttempt }).catch(() => { });
1102
+ }
744
1103
  }
745
1104
  // 'joined' = healthy. Clear the joining-overstay timer.
746
1105
  if (state === 'joined') {
@@ -756,12 +1115,24 @@ export class RemoteChannel {
756
1115
  return;
757
1116
  }
758
1117
  }
1118
+ // Broadcast has outlived the incident's join->error cycle with a
1119
+ // heartbeat confirmed after the join: the socket/channel path is
1120
+ // working even if Presence is not. Stop charging this join to the
1121
+ // reconnect budget, so a later ordinary blip gets fast recovery.
1122
+ // Presence keeps its own cooldown; full readiness still needs it.
1123
+ if (this.consecutiveUnreadyJoins > 0 && this.joinedAt !== null &&
1124
+ this.lastHeartbeatOkAt !== null && this.lastHeartbeatOkAt > this.joinedAt &&
1125
+ performance.now() - this.joinedAt >= STABLE_BROADCAST_RESET_MS) {
1126
+ console.debug(`[DEBUG] Broadcast channel stable for ${Math.round((performance.now() - this.joinedAt) / 1000)}s — clearing reconnect backoff budget (presence ${this.presenceTracked ? 'ready' : 'still pending'})`);
1127
+ this.consecutiveUnreadyJoins = 0;
1128
+ }
759
1129
  // Self-heal a failed presence publish: the channel is up, so nothing
760
1130
  // else will ever retry (SUBSCRIBED won't fire again). Until it
761
1131
  // lands the dashboard shows this device offline, and if track()
762
1132
  // already failed its retries the capability is withdrawn too, so
763
1133
  // the server fails every dispatch to it fast.
764
- if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence) {
1134
+ if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence &&
1135
+ !this.presenceInCooldown()) {
765
1136
  console.debug('[DEBUG] Channel joined but presence not tracked — retrying track()');
766
1137
  this.trackPresenceWithRetry(0, 1).catch(() => { });
767
1138
  }
@@ -787,7 +1158,6 @@ export class RemoteChannel {
787
1158
  }
788
1159
  // Unhealthy: closed, errored, leaving — recreate
789
1160
  this.joiningSince = null;
790
- captureRemote('remote_channel_state_health', { state, attempt: this.reconnectAttempt });
791
1161
  console.debug(`[DEBUG] ⚠️ Channel in unhealthy state '${state}' - recreating... — ${this.connState()}`);
792
1162
  this.recreateChannel();
793
1163
  }
@@ -813,8 +1183,9 @@ export class RemoteChannel {
813
1183
  await this.sleep(SOCKET_SETTLE_MAX_MS);
814
1184
  return;
815
1185
  }
816
- const deadline = Date.now() + SOCKET_SETTLE_MAX_MS;
817
- while (realtime.isDisconnecting() && Date.now() < deadline) {
1186
+ // Monotonic: Date.now may be patched by the clock-skew correction.
1187
+ const deadline = performance.now() + SOCKET_SETTLE_MAX_MS;
1188
+ while (realtime.isDisconnecting() && performance.now() < deadline) {
818
1189
  await this.sleep(SOCKET_SETTLE_POLL_MS);
819
1190
  }
820
1191
  }
@@ -853,9 +1224,10 @@ export class RemoteChannel {
853
1224
  // Create fresh channel
854
1225
  console.log(`🔄 Recreating channel... (attempt ${this.reconnectAttempt}) — ${this.connState()}`);
855
1226
  try {
856
- // Jittered backoff so a fleet-wide event doesn't stampede every
857
- // device into reconnecting at once. ~1-3s rising to ~15-45s.
858
- const backoffMs = Math.min(30000, 1000 * 2 ** Math.min(this.reconnectAttempt, 5)) * (0.5 + Math.random());
1227
+ // Our force-recreate fallback shares the extended sustained-failure
1228
+ // budget with the SDK. A 10s watchdog tick cannot cancel this wait
1229
+ // because isRecreatingChannel guards its whole duration.
1230
+ const backoffMs = watchdogRecreateDelayMs(Math.max(this.reconnectAttempt, this.consecutiveUnreadyJoins));
859
1231
  console.debug(`[DEBUG] Reconnect backoff: ${Math.round(backoffMs)}ms`);
860
1232
  await this.sleep(backoffMs);
861
1233
  // realtime-js runs its own rejoin timer, and the backoff above gives
@@ -871,6 +1243,8 @@ export class RemoteChannel {
871
1243
  console.log(`✅ Channel self-healed during backoff — skipping recreate — ${this.connState()}`);
872
1244
  return; // finally-block below clears the re-entrancy guard
873
1245
  }
1246
+ // Count only watchdog recreations that continue past SDK self-heal.
1247
+ this.realtimeHealth.record('watchdog_recreates');
874
1248
  // Cap the whole recreate: a never-settling await (e.g. a subscribe that only
875
1249
  // ever emits CLOSED) must not pin isRecreatingChannel=true and silently disable
876
1250
  // the 10s watchdog. On timeout we reject -> catch -> finally clears the guard.
@@ -916,8 +1290,9 @@ export class RemoteChannel {
916
1290
  await this.withTimeout(() => this.setTransportCapable(false), CAPABILITY_WRITE_TIMEOUT_MS, 'withdrawTransportCapability');
917
1291
  }
918
1292
  catch (withdrawErr) {
919
- // The next failed recreate retries; the flag only advances
920
- // on a confirmed write, so nothing is lost.
1293
+ // The write stays queued, in order with any re-publish after
1294
+ // it, and ends within DEVICE_ROW_WRITE_TIMEOUT_MS; the flag
1295
+ // only advances on a confirmed write.
921
1296
  console.debug(`[DEBUG] Capability withdrawal did not complete: ${withdrawErr?.message}`);
922
1297
  }
923
1298
  }
@@ -930,8 +1305,9 @@ export class RemoteChannel {
930
1305
  * Claim a call. True only when THIS update flipped the row pending ->
931
1306
  * executing, which is what makes dual delivery safe across processes.
932
1307
  * .eq('status','pending') makes it conditional; .select('id') makes the
933
- * result observable. On a transient DB error it returns true (execute
934
- * anyway), matching prior behaviour — so device.ts's in-memory guard is what
1308
+ * result observable. Expiry is checked using Postgres time, not the
1309
+ * device clock. On a transient DB error it returns true (execute anyway),
1310
+ * matching prior behaviour — so device.ts's in-memory guard is what
935
1311
  * actually guarantees exactly-once within a process.
936
1312
  */
937
1313
  async markCallExecuting(callId) {
@@ -942,6 +1318,7 @@ export class RemoteChannel {
942
1318
  .update({ status: 'executing' })
943
1319
  .eq('id', callId)
944
1320
  .eq('status', 'pending')
1321
+ .gt('timeout_at', 'now')
945
1322
  .select('id');
946
1323
  if (error) {
947
1324
  console.error('[DEBUG] Failed to mark call executing:', error.message);
@@ -960,10 +1337,9 @@ export class RemoteChannel {
960
1337
  async updateCallResult(callId, status, result = null, errorMessage = null) {
961
1338
  if (!this.client)
962
1339
  throw new Error('Client not initialized');
963
- const updateData = {
964
- status: status,
965
- completed_at: new Date().toISOString()
966
- };
1340
+ // The DB terminal-status trigger stamps completed_at using PostgreSQL
1341
+ // time. Do not send a device-generated timestamp.
1342
+ const updateData = { status };
967
1343
  // Strip NUL (U+0000) before it reaches the jsonb `result` column.
968
1344
  // jsonb cannot store and rejects the whole write (Postgres 22P05),
969
1345
  // which otherwise leaves the call stuck 'executing' → the user waits out
@@ -1004,18 +1380,31 @@ export class RemoteChannel {
1004
1380
  console.debug('[DEBUG] Call result updated successfully:', callId);
1005
1381
  }
1006
1382
  }
1007
- /** Reachable means the private channel is joined. Gates the heartbeat and `status`. */
1383
+ /**
1384
+ * Reachable means all of it is true at once: the private channel is
1385
+ * joined, this device has published its presence, and the local executor
1386
+ * answers. The server needs the first two before it will dispatch, and a
1387
+ * healthy channel on a device whose executor is dead is the false-online
1388
+ * state issue #4 was opened for. Gates the heartbeat and `status`.
1389
+ */
1008
1390
  isReachable() {
1009
- return this.channel?.state === 'joined';
1391
+ return this.channel?.state === 'joined'
1392
+ && this.presenceTracked
1393
+ && this.localExecutorProbe();
1010
1394
  }
1011
1395
  /**
1012
1396
  * Set `status` from actual reachability. `status` is transport-agnostic (the
1013
1397
  * server filters on it), so it must not follow one channel's health — the
1014
1398
  * private channel's error path re-fires on every rejoin and would oscillate
1015
1399
  * the row against the heartbeat. Same predicate as the heartbeat gate.
1400
+ *
1401
+ * Every transition belongs here rather than calling setOnlineStatus(), which
1402
+ * is the write and not the decision. Public so the device can route its
1403
+ * recovery transition through the predicate too.
1016
1404
  */
1405
+ /** Resolves with whether the row actually took the write. */
1017
1406
  syncReachabilityStatus() {
1018
- this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1407
+ return this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1019
1408
  }
1020
1409
  /**
1021
1410
  * Serialize the channel-callback status writes. They fire from un-awaited
@@ -1030,13 +1419,18 @@ export class RemoteChannel {
1030
1419
  // After teardown begins, setOffline() owns the final status write.
1031
1420
  if (this.shuttingDown) {
1032
1421
  console.debug(`[DEBUG] Status write '${status}' suppressed — teardown in progress`);
1033
- return;
1422
+ return Promise.resolve(false);
1034
1423
  }
1035
- this.statusWriteChain = this.statusWriteChain
1036
- .then(() => (this.deviceId ? this.setOnlineStatus(this.deviceId, status) : undefined))
1424
+ // The chain only sequences the writes; whether one landed goes back
1425
+ // to whoever asked, so readiness can depend on it.
1426
+ const write = this.statusWriteChain
1427
+ .then(() => (this.deviceId ? this.setOnlineStatus(this.deviceId, status) : false))
1037
1428
  .catch((e) => {
1038
1429
  console.error('[DEBUG] Status write failed:', e?.message);
1430
+ return false;
1039
1431
  });
1432
+ this.statusWriteChain = write.then(() => undefined);
1433
+ return write;
1040
1434
  }
1041
1435
  /**
1042
1436
  * Heartbeat cadence for the tier this device is CURRENTLY in. Follows the
@@ -1072,7 +1466,7 @@ export class RemoteChannel {
1072
1466
  }
1073
1467
  const { error } = await this.client
1074
1468
  .from('mcp_devices')
1075
- .update({ last_seen: new Date().toISOString(), status: 'online' })
1469
+ .update({ last_seen: 'now', status: 'online' })
1076
1470
  .eq('id', deviceId);
1077
1471
  if (error) {
1078
1472
  console.error('[DEBUG] Heartbeat update failed:', error.message);
@@ -1090,6 +1484,8 @@ export class RemoteChannel {
1090
1484
  startHeartbeat(deviceId) {
1091
1485
  console.debug('[DEBUG] Starting heartbeat for device:', deviceId);
1092
1486
  this.heartbeatDeviceId = deviceId;
1487
+ this.realtimeHealth.setDevice(deviceId);
1488
+ this.realtimeHealth.start();
1093
1489
  this.connectionCheckInterval = setInterval(() => {
1094
1490
  this.checkConnectionHealth();
1095
1491
  }, 10000);
@@ -1159,9 +1555,10 @@ export class RemoteChannel {
1159
1555
  }
1160
1556
  this.stopTokenRefresh();
1161
1557
  }
1558
+ /** @returns whether the row actually took the write. */
1162
1559
  async setOnlineStatus(deviceId, status) {
1163
1560
  if (!this.client)
1164
- return;
1561
+ return false;
1165
1562
  // Only log if status changed
1166
1563
  if (this.lastDeviceStatus !== status) {
1167
1564
  console.log(`🔌 Device marked as ${status}`);
@@ -1169,19 +1566,21 @@ export class RemoteChannel {
1169
1566
  }
1170
1567
  const { error } = await this.client
1171
1568
  .from('mcp_devices')
1172
- .update({ status: status, last_seen: new Date().toISOString() })
1173
- .eq('id', deviceId);
1569
+ .update({ status: status, last_seen: 'now' })
1570
+ .eq('id', deviceId)
1571
+ .abortSignal(this.deviceRowWriteSignal());
1174
1572
  if (error) {
1175
1573
  console.error(`[DEBUG] Failed to set status ${status}:`, error.message);
1176
1574
  if (status == "online") {
1177
1575
  console.error('Failed to update device status:', error.message);
1178
1576
  }
1179
1577
  await captureRemote('remote_channel_status_update_error', { error, status });
1180
- return;
1578
+ return false;
1181
1579
  }
1182
1580
  else {
1183
1581
  console.debug(`[DEBUG] Device status set to ${status}`);
1184
1582
  }
1583
+ return true;
1185
1584
  // console.log(status === 'online' ? `🔌 Device marked as ${status}` : `❌ Device marked as ${status}`);
1186
1585
  }
1187
1586
  async setOffline(deviceId) {
@@ -1229,7 +1628,9 @@ export class RemoteChannel {
1229
1628
  const scriptPath = path.join(__dirname, 'scripts', 'blocking-offline-update.js');
1230
1629
  console.debug('[DEBUG] Spawning blocking update script:', scriptPath);
1231
1630
  console.debug('[DEBUG] Using node executable:', process.execPath);
1232
- const result = spawnSync('node', [
1631
+ // The node running this device, by its full path: a bare 'node' is
1632
+ // looked up in the working folder first on Windows
1633
+ const result = spawnSync(process.execPath, [
1233
1634
  scriptPath,
1234
1635
  deviceId,
1235
1636
  supabaseUrl,
@@ -1276,6 +1677,7 @@ export class RemoteChannel {
1276
1677
  }
1277
1678
  }
1278
1679
  async unsubscribe() {
1680
+ this.realtimeHealth.stop();
1279
1681
  // setOffline()'s durable write is the final word on `status` from here,
1280
1682
  // so stop the heartbeat and the channel callbacks from racing it. The
1281
1683
  // races that matter: a heartbeat tick firing as the signal arrives, and