@wonderwhy-er/desktop-commander 0.3.1-alpha.2 → 0.3.1

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 (80) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +1152 -1152
  3. package/dist/bootstrap.js +0 -0
  4. package/dist/command-manager.js +0 -0
  5. package/dist/config-field-definitions.js +0 -0
  6. package/dist/config-manager.js +0 -0
  7. package/dist/config-recovery.js +0 -0
  8. package/dist/config.js +0 -0
  9. package/dist/custom-stdio.js +0 -0
  10. package/dist/data/onboarding-prompts.json +70 -70
  11. package/dist/error-handlers.js +0 -0
  12. package/dist/handlers/filesystem-handlers.js +2 -2
  13. package/dist/index.js +0 -0
  14. package/dist/npm-scripts/remote.js +25 -23
  15. package/dist/remote-device/desktop-commander-integration.d.ts +1 -0
  16. package/dist/remote-device/device.js +14 -2
  17. package/dist/remote-device/realtime-health-telemetry.d.ts +35 -0
  18. package/dist/remote-device/realtime-health-telemetry.js +110 -0
  19. package/dist/remote-device/remote-channel.d.ts +66 -55
  20. package/dist/remote-device/remote-channel.js +336 -389
  21. package/dist/remote-device/rollouts.d.ts +48 -0
  22. package/dist/remote-device/rollouts.js +105 -0
  23. package/dist/remote-device/scripts/blocking-offline-update.js +135 -133
  24. package/dist/search-manager.js +0 -0
  25. package/dist/server.js +581 -712
  26. package/dist/setup-claude-server.js +942 -942
  27. package/dist/terminal-manager.js +0 -0
  28. package/dist/tools/edit.js +2 -2
  29. package/dist/tools/fuzzySearch.js +9 -9
  30. package/dist/tools/improved-process-tools.js +10 -10
  31. package/dist/tools/pdf/extract-images.js +2 -6
  32. package/dist/tools/pdf/lib/pdf2md.js +28 -33
  33. package/dist/tools/pdf/utils.d.ts +10 -0
  34. package/dist/tools/pdf/utils.js +11 -0
  35. package/dist/tools/prompts.js +1 -1
  36. package/dist/tools/schemas.d.ts +0 -10
  37. package/dist/tools/schemas.js +0 -8
  38. package/dist/track-installation.js +387 -387
  39. package/dist/types.js +0 -0
  40. package/dist/ui/config-editor/config-editor-runtime.js +53 -53
  41. package/dist/ui/config-editor/index.html +13 -13
  42. package/dist/ui/config-editor/src/app.js +30 -30
  43. package/dist/ui/config-editor/src/array-modal.js +32 -32
  44. package/dist/ui/config-editor/styles.css +586 -586
  45. package/dist/ui/contracts.d.ts +27 -0
  46. package/dist/ui/contracts.js +36 -0
  47. package/dist/ui/file-preview/index.html +16 -16
  48. package/dist/ui/file-preview/preview-runtime.js +190 -182
  49. package/dist/ui/file-preview/src/app.js +8 -8
  50. package/dist/ui/file-preview/src/components/html-renderer.js +4 -2
  51. package/dist/ui/file-preview/src/document-layout.js +31 -31
  52. package/dist/ui/file-preview/src/document-outline.js +8 -8
  53. package/dist/ui/file-preview/src/markdown/conflict-dialog.js +33 -33
  54. package/dist/ui/file-preview/src/markdown/controller.js +9 -9
  55. package/dist/ui/file-preview/src/markdown/editor.js +31 -31
  56. package/dist/ui/file-preview/styles.css +1630 -1630
  57. package/dist/ui/resources.js +11 -4
  58. package/dist/uninstall-claude-server.js +745 -745
  59. package/dist/utils/files/binary.js +4 -4
  60. package/dist/utils/files/excel.js +3 -3
  61. package/dist/utils/files/text.d.ts +7 -0
  62. package/dist/utils/files/text.js +40 -21
  63. package/dist/utils/system-info.d.ts +1 -0
  64. package/dist/utils/system-info.js +110 -97
  65. package/dist/utils/terminal-timestamps.d.ts +2 -0
  66. package/dist/utils/terminal-timestamps.js +18 -0
  67. package/dist/utils/usageTracker.d.ts +0 -39
  68. package/dist/utils/usageTracker.js +16 -176
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -56
  72. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -32
  73. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -38
  74. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -164
  75. package/package.json +6 -10
  76. package/vendor/telemetry-contract/README.md +56 -56
  77. package/vendor/telemetry-contract/package.json +32 -32
  78. package/vendor/telemetry-contract/transport.d.ts +38 -38
  79. package/vendor/telemetry-contract/transport.js +164 -164
  80. package/vendor/telemetry-contract/transport.test.js +39 -39
@@ -1,6 +1,8 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import { captureRemote } from '../utils/capture.js';
3
3
  import { observeTransport } from './transport-telemetry.js';
4
+ import { RealtimeHealthTelemetry } from './realtime-health-telemetry.js';
5
+ import { rolloutManager } from './rollouts.js';
4
6
  import { VERSION } from '../version.js';
5
7
  const NUL_CHAR = String.fromCharCode(0);
6
8
  const NUL_RE = new RegExp(NUL_CHAR, 'g');
@@ -31,7 +33,7 @@ export function stripNullBytes(value) {
31
33
  }
32
34
  /**
33
35
  * The device registered, but its realtime channel is not usable — the join
34
- * failed, or presence was never acknowledged. Distinct from every other
36
+ * failed, or the device row could not be marked ready. Distinct from every other
35
37
  * registration failure on purpose: this one the socket watchdog can repair, so
36
38
  * the caller keeps the process alive, while a failed lookup or a missing row
37
39
  * happens before the recreation parameters are stored and nothing can repair it.
@@ -42,26 +44,34 @@ export class ChannelUnreachableError extends Error {
42
44
  this.name = 'ChannelUnreachableError';
43
45
  }
44
46
  }
45
- // last_seen cadences. The server tiers its sweep on the transport_broadcast_v1
46
- // flag, so each must fit its tier's threshold in the server's constants.ts:
47
- // capable -> 15 min, unflagged -> 45s.
48
- const CAPABLE_HEARTBEAT_INTERVAL = 5 * 60 * 1000;
49
- const LEGACY_HEARTBEAT_INTERVAL = 15 * 1000;
50
- // Keep Supabase's retry cadence, but jitter every device independently so one
51
- // Realtime disconnect cannot synchronize the whole fleet onto 1s/2s/5s/10s
52
- // reconnect waves. ±50% keeps recovery latency close to the SDK default while
53
- // spreading load across the recovery window.
54
- const REALTIME_RECONNECT_BASE_MS = [1000, 2000, 5000, 10000];
55
- const REALTIME_RECONNECT_FALLBACK_MS = 10000;
56
- // Presence-only failures do not mean broadcast delivery is down: a joined
57
- // channel can still receive doorbells while Presence's DB-backed work is
58
- // degraded. Keep a previously-proven capability for one normal heartbeat
59
- // interval before falling back to the 15s legacy tier, avoiding a 20x heartbeat
60
- // write-rate jump during short provider incidents.
61
- const PRESENCE_WITHDRAW_GRACE_MS = 5 * 60 * 1000;
47
+ // last_seen cadence. Must stay under the server's 15 min offline sweep and the
48
+ // dashboard's ~7 min freshness window for the online dot.
49
+ export const HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000;
50
+ // Fast recovery for short Wi-Fi blips, but never retry every 10 seconds forever.
51
+ // Prolonged provider incidents must not keep the entire device fleet joining.
52
+ // Independent jitter spreads retry work; full jitter applies at attempt >= 5.
53
+ const REALTIME_RECONNECT_BASE_MS = [1000, 2000, 5000, 10000, 20000, 40000, 80000, 120000];
54
+ const REALTIME_RECONNECT_FALLBACK_MS = 120000;
55
+ const WATCHDOG_RECREATE_MAX_BACKOFF_MS = 120000;
56
+ // Presence is best effort (dashboard only): a failed track() waits this long,
57
+ // doubling, before the next one, since a track() timeout can end the channel.
58
+ const PRESENCE_RETRY_BASE_MS = 5 * 60 * 1000;
59
+ const PRESENCE_RETRY_MAX_MS = 60 * 60 * 1000;
60
+ // Failed readiness writes are retried sooner: dispatch waits on them.
61
+ const READINESS_RETRY_BASE_MS = 5000;
62
+ const READINESS_RETRY_MAX_MS = 60000;
62
63
  // Cap on a recreate's rebuild step so a hung await can't disable the watchdog.
63
- // Must exceed createChannel()'s worst case (~32.25s of jittered presence retries).
64
+ // Must exceed createChannel()'s worst case: the join plus its status write,
65
+ // queued behind the teardown's 'offline' (~30s).
64
66
  const RECREATE_TIMEOUT_MS = 45000;
67
+ // Upper bound on the persistent unready-join budget. Anything >= 8 already
68
+ // selects the 120s SDK tier; the cap only keeps the counter meaningful.
69
+ const MAX_UNREADY_JOIN_BUDGET = 16;
70
+ // A channel that has stayed joined this long, with a heartbeat confirmed after
71
+ // the join, is a working broadcast path even if readiness is still pending.
72
+ // Its join no longer counts toward reconnect backoff. Comfortably longer than
73
+ // a join->error cycle (~10-30s) and covers at least four 25s heartbeats.
74
+ const STABLE_BROADCAST_RESET_MS = 120000;
65
75
  // Max continuous time in 'joining' before forcing a recreate — a half-open
66
76
  // socket parks the channel there forever, and a genuine join settles in ~10s.
67
77
  const JOINING_WEDGE_TIMEOUT_MS = 30000;
@@ -73,17 +83,10 @@ const HEARTBEAT_STALE_TIMEOUT_MS = 75000;
73
83
  const TOKEN_REFRESH_INTERVAL_MS = 45 * 60 * 1000;
74
84
  // Below this, skew is noise — leave Date.now untouched. Above it, correct.
75
85
  const CLOCK_SKEW_CORRECTION_THRESHOLD_MS = 5 * 60 * 1000;
76
- // Failed recreates before withdrawing transport_broadcast_v1 — keeping it while
77
- // unable to join leaves the server dispatching calls this device can't
78
- // receive. Not lower than 3: ordinary half-open recovery legitimately costs 2.
79
- const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
80
- // Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
81
- // does not cover.
82
- const CAPABILITY_WRITE_TIMEOUT_MS = 5000;
83
- // Cap on one write to this device's row (capability, status), after which it
84
- // is aborted. A PATCH sent down a half-open connection is otherwise answered
85
- // only by fetch's own 300 s headers timeout, and the write queue behind it,
86
- // with the presence publish waiting on that queue, waits as long.
86
+ // Cap on one status write to this device's row, after which it is aborted. A
87
+ // PATCH sent down a half-open connection is otherwise answered only by fetch's
88
+ // own 300 s headers timeout, and the write queue behind it, readiness
89
+ // included, waits as long.
87
90
  const DEVICE_ROW_WRITE_TIMEOUT_MS = 10000;
88
91
  // Cap on the shutdown session fetch, which races device.ts's 5s force-exit.
89
92
  const OFFLINE_SESSION_TIMEOUT_MS = 500;
@@ -101,16 +104,38 @@ function jitterAround(baseMs, random) {
101
104
  const sample = Math.max(0, Math.min(1, random()));
102
105
  return Math.max(1, Math.round(baseMs * (0.5 + sample)));
103
106
  }
104
- /** Jittered version of realtime-js's default 1s/2s/5s/10s stepped backoff. */
107
+ /** Exponential-ish SDK backoff. Attempts 1-4 preserve short recovery latency. */
105
108
  export function realtimeReconnectDelayMs(tries, random = Math.random) {
106
109
  const attempt = Math.max(1, Math.floor(tries || 1));
107
110
  const baseMs = REALTIME_RECONNECT_BASE_MS[attempt - 1] ?? REALTIME_RECONNECT_FALLBACK_MS;
111
+ if (attempt <= 4)
112
+ return jitterAround(baseMs, random);
113
+ // Full jitter is deliberately independent per device; floor avoids an immediate tight retry.
114
+ return Math.max(1000, Math.round(baseMs * Math.max(0, Math.min(1, random()))));
115
+ }
116
+ /** Watchdog must not defeat the SDK's slower persistent-failure backoff. */
117
+ export function watchdogRecreateDelayMs(tries, random = Math.random) {
118
+ const attempt = Math.max(1, Math.floor(tries || 1));
119
+ const baseMs = Math.min(WATCHDOG_RECREATE_MAX_BACKOFF_MS, 1000 * 2 ** Math.min(attempt, 7));
108
120
  return jitterAround(baseMs, random);
109
121
  }
110
- /** Preserve Presence's existing 500ms-per-attempt retry shape, but desynchronize it. */
111
- export function presenceRetryDelayMs(failedAttempt, random = Math.random) {
112
- const attempt = Math.max(1, Math.floor(failedAttempt || 1));
113
- return jitterAround(500 * attempt, random);
122
+ /** Doubling step after `failures` consecutive failures, capped at `maxMs`. */
123
+ function backoffStepMs(failures, baseMs, maxMs) {
124
+ const attempt = Math.max(1, Math.floor(failures || 1));
125
+ return Math.min(maxMs, baseMs * 2 ** Math.min(attempt - 1, 10));
126
+ }
127
+ /**
128
+ * Wait before the next track() after failed ones, across SDK rejoins and
129
+ * recreates. Never shorter than the step; up to 50% extra spreads the fleet.
130
+ */
131
+ export function presenceRecoveryDelayMs(failures, random = Math.random) {
132
+ const stepMs = backoffStepMs(failures, PRESENCE_RETRY_BASE_MS, PRESENCE_RETRY_MAX_MS);
133
+ return Math.round(stepMs * (1 + 0.5 * Math.max(0, Math.min(1, random()))));
134
+ }
135
+ /** Full-jitter wait before retrying the readiness write after failed ones. */
136
+ function readinessRetryDelayMs(failures, random = Math.random) {
137
+ const stepMs = backoffStepMs(failures, READINESS_RETRY_BASE_MS, READINESS_RETRY_MAX_MS);
138
+ return Math.max(1000, Math.round(stepMs * Math.max(0, Math.min(1, random()))));
114
139
  }
115
140
  // auth-js compares token expiry against this device's own Date.now(), with no
116
141
  // clock-skew tolerance — a fast clock treats every fresh token as expired and
@@ -160,8 +185,6 @@ export class RemoteChannel {
160
185
  this.channel = null;
161
186
  this.heartbeatInterval = null;
162
187
  this.connectionCheckInterval = null;
163
- /** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
164
- this.heartbeatDeviceId = null;
165
188
  // Single-slot queue keeping concurrent `status` PATCHes in order.
166
189
  this.statusWriteChain = Promise.resolve();
167
190
  /**
@@ -186,20 +209,29 @@ export class RemoteChannel {
186
209
  this.onToolCall = null;
187
210
  // Guard so setSession being called twice can't stack auth listeners.
188
211
  this.authListenerRegistered = false;
189
- /** False when presence publishing failed on an otherwise healthy channel;
190
- * the health check retries, since SUBSCRIBED won't fire again. */
212
+ /** The current join's status write landed: dispatchable. Gates the
213
+ * heartbeat, so only that write first marks the row online. */
214
+ this.channelReady = false;
215
+ /** Readiness write in flight. Cleared on every join, so each join writes its own. */
216
+ this.readinessInFlight = null;
217
+ this.consecutiveReadinessFailures = 0;
218
+ this.nextReadinessAttemptAt = 0; // monotonic
219
+ /** Presence published on the current join. Dashboard only; never gates dispatch. */
191
220
  this.presenceTracked = false;
192
- /** Last capability value written (null = never), to avoid redundant writes. */
193
- this.transportCapableWritten = null;
194
- /** Value of the last capability write still queued or in flight; null once the queue is idle. */
195
- this.transportCapableQueued = null;
196
- // Single-slot queue keeping capability writes in order (see setTransportCapable).
197
- this.capabilityWriteChain = Promise.resolve();
198
- /** Monotonic start of a Presence-only degradation while broadcast remains joined. */
199
- this.presenceFailureStartedAt = null;
200
221
  /** Re-entrancy guard: on a wedged socket each track() buffers for the full
201
222
  * 10s push timeout, so 10s health ticks would stack pushes. */
202
223
  this.isTrackingPresence = false;
224
+ // The SDK resets its rejoin timer on *every* SUBSCRIBED, even if the join
225
+ // dies before it is ready. Count such joins across SDK/channel recreation.
226
+ // Reset once the readiness write succeeds.
227
+ this.consecutiveUnreadyJoins = 0;
228
+ this.consecutivePresenceFailures = 0;
229
+ this.nextPresenceAttemptAt = 0; // monotonic; independent of Date.now skew correction
230
+ /** performance.now() of the latest SUBSCRIBED; null while not joined. */
231
+ this.joinedAt = null;
232
+ this.realtimeHealth = new RealtimeHealthTelemetry((window) => {
233
+ captureRemote('remote_realtime_health_window', window).catch(() => { });
234
+ });
203
235
  // Track last device status to prevent duplicate log messages
204
236
  this.lastDeviceStatus = 'offline';
205
237
  // Track last channel state for debug logging
@@ -218,6 +250,11 @@ export class RemoteChannel {
218
250
  this.tokenRefreshInterval = null;
219
251
  this._user = null;
220
252
  }
253
+ /** SDK channel and socket timers share reconnectAfterMs. The persistent
254
+ * unready-join budget prevents a series of partial successes restarting at 1s. */
255
+ reconnectDelayMs(tries, random = Math.random) {
256
+ return realtimeReconnectDelayMs(Math.max(tries, this.consecutiveUnreadyJoins), random);
257
+ }
221
258
  get user() { return this._user; }
222
259
  initialize(url, key) {
223
260
  // autoRefreshToken:false — we drive refresh ourselves (startTokenRefresh(),
@@ -227,24 +264,12 @@ export class RemoteChannel {
227
264
  auth: { autoRefreshToken: false },
228
265
  global: { fetch: clockAwareFetch },
229
266
  realtime: {
230
- reconnectAfterMs: realtimeReconnectDelayMs,
267
+ reconnectAfterMs: (tries) => this.reconnectDelayMs(tries),
231
268
  // supabase-js's resolver ends in `?? supabaseKey`, so after SIGNED_OUT
232
269
  // the socket silently re-pins to the anon key and every private-channel
233
270
  // join is refused. Overriding under `realtime` (not the top-level
234
271
  // `accessToken`, which turns client.auth into a throwing Proxy).
235
- // getSession() may refresh on-demand when the token reads expired —
236
- // that check is clock-skew-safe now (see clockAwareFetch above).
237
- accessToken: async () => {
238
- try {
239
- const { data } = await this.client.auth.getSession();
240
- if (data.session?.access_token)
241
- return data.session.access_token;
242
- }
243
- catch {
244
- /* fall through to the cached token */
245
- }
246
- return this.lastKnownSession?.access_token ?? null;
247
- },
272
+ accessToken: () => this.getAccessToken(),
248
273
  },
249
274
  });
250
275
  if (!this.heartbeatListenerRegistered) {
@@ -395,6 +420,8 @@ export class RemoteChannel {
395
420
  hadRefreshToken: !!cached?.refresh_token,
396
421
  });
397
422
  this.stopHeartbeat();
423
+ // Without a session the 30-minute rollouts request can only be refused
424
+ rolloutManager.stopRefresh();
398
425
  // Tear realtime down entirely, same as recreateChannel() does: sessionLost
399
426
  // only gates OUR health loop, while realtime-js keeps its own per-channel
400
427
  // rejoin timer (~10s cap) firing expired-JWT joins on the errored channel
@@ -433,6 +460,24 @@ export class RemoteChannel {
433
460
  throw new Error('Client not initialized');
434
461
  return await this.client.auth.getSession();
435
462
  }
463
+ /**
464
+ * The session's current access token, for the realtime socket and the
465
+ * device's own requests. getSession() may refresh on-demand when the token
466
+ * reads expired — that check is clock-skew-safe now (see clockAwareFetch
467
+ * above). Without a session it falls back to the last token known, and
468
+ * without that it is null, never the anon key.
469
+ */
470
+ async getAccessToken() {
471
+ try {
472
+ const { data } = await this.client.auth.getSession();
473
+ if (data.session?.access_token)
474
+ return data.session.access_token;
475
+ }
476
+ catch {
477
+ /* fall through to the cached token */
478
+ }
479
+ return this.lastKnownSession?.access_token ?? null;
480
+ }
436
481
  async findDevice(deviceId) {
437
482
  if (!this.client)
438
483
  throw new Error('Client not initialized');
@@ -492,18 +537,14 @@ export class RemoteChannel {
492
537
  }
493
538
  if (existingDevice) {
494
539
  console.debug('[DEBUG] Registering device as offline until the channel proves otherwise');
495
- // Neither half of this row may claim reachability yet. transport_
496
- // broadcast_v1 is NOT set here: the server treats it as binding, so
497
- // it is written only once presence is proven. `status` is the same
498
- // promise in the other notation — dispatch picks its target by it,
499
- // then fails the call fast for the missing capability, so a row
500
- // marked online before the channel is up hands every call in that
501
- // window to a device with no delivery path. SUBSCRIBED writes
502
- // 'online'; presence writes the capability.
540
+ // The row may not claim reachability yet: dispatch picks its target
541
+ // by `status`, so a row marked online before the channel is up hands
542
+ // every call in that window to a device with no delivery path.
543
+ // SUBSCRIBED writes 'online'.
503
544
  const { error: registrationError } = await this.updateDevice(existingDevice.id, {
504
545
  status: 'offline',
505
- last_seen: new Date().toISOString(),
506
- capabilities: this.capabilitiesPayload(false),
546
+ last_seen: 'now',
547
+ capabilities: this.capabilitiesPayload(),
507
548
  device_name: deviceName
508
549
  });
509
550
  // updateDevice() logs and returns its error rather than throwing.
@@ -517,13 +558,14 @@ export class RemoteChannel {
517
558
  }
518
559
  // Store parameters for channel recreation
519
560
  this.deviceId = existingDevice.id;
561
+ this.realtimeHealth.setDevice(existingDevice.id);
520
562
  this.deviceName = deviceName;
521
563
  this.onToolCall = onToolCall;
522
564
  console.debug(`⏳ Subscribing to tool call channel...`);
523
565
  // Create and subscribe to the channel
524
566
  console.debug('[DEBUG] Calling createChannel()');
525
567
  // Let a failed join reach the caller. createChannel() resolves only
526
- // once the channel is joined AND presence is published — the two
568
+ // once the channel is joined AND the device row says so — the two
527
569
  // things dispatch needs — so swallowing its rejection here was what
528
570
  // let device.ts print "Device ready" over a device that cannot
529
571
  // receive a single command. The caller decides what to do with it;
@@ -537,195 +579,124 @@ export class RemoteChannel {
537
579
  }
538
580
  }
539
581
  /**
540
- * Publish presence, retrying a non-'ok' result — track() resolves with a
541
- * status rather than rejecting, and absent presence reads as offline on the
542
- * dashboard. `presenceTracked` lets the health check retry later.
582
+ * Mark this join dispatchable by writing `status`. The write has to land —
583
+ * Supabase reports a refused write in the result rather than by throwing.
584
+ * The health check retries on its own cooldown.
585
+ */
586
+ markChannelReady() {
587
+ if (this.readinessInFlight)
588
+ return this.readinessInFlight;
589
+ const result = this.markChannelReadyInner().finally(() => {
590
+ if (this.readinessInFlight === result)
591
+ this.readinessInFlight = null;
592
+ });
593
+ this.readinessInFlight = result;
594
+ return result;
595
+ }
596
+ async markChannelReadyInner() {
597
+ const channel = this.channel;
598
+ if (!channel || channel.state !== 'joined')
599
+ return false;
600
+ // Queued while the channel is joined, so a drop's 'offline' queues
601
+ // behind it and lands last. A dead local executor is written as
602
+ // offline even on a healthy channel.
603
+ const statusWritten = await this.queueStatusWrite(this.localExecutorProbe() ? 'online' : 'offline');
604
+ // A replaced channel, or one that dropped meanwhile, decides for itself;
605
+ // the drop's 'offline' and the rejoin's own write are queued behind this one.
606
+ if (this.channel !== channel || channel.state !== 'joined')
607
+ return false;
608
+ if (!statusWritten) {
609
+ console.error('❌ Channel joined but the device row could not be updated — not ready');
610
+ // Status writes land in order, so this result is newer than any
611
+ // earlier join's success: the row may say offline now.
612
+ this.channelReady = false;
613
+ this.realtimeHealth.record('readiness_write_failures');
614
+ this.consecutiveReadinessFailures++;
615
+ this.nextReadinessAttemptAt = performance.now() +
616
+ readinessRetryDelayMs(this.consecutiveReadinessFailures);
617
+ captureRemote('remote_channel_readiness_write_failed', {}).catch(() => { });
618
+ return false;
619
+ }
620
+ this.channelReady = true;
621
+ this.consecutiveUnreadyJoins = 0;
622
+ this.consecutiveReadinessFailures = 0;
623
+ this.nextReadinessAttemptAt = 0;
624
+ console.log(`✅ Device ready (device ${this.deviceId})`);
625
+ // Broadcast is only a wake-up signal; mcp_remote_calls is the durable
626
+ // queue. Drain calls whose doorbell was missed while disconnected. Each
627
+ // row still goes through the atomic pending -> executing claim.
628
+ this.recoverPendingCalls().catch((error) => {
629
+ console.error('[DEBUG] Pending call recovery failed:', error?.message);
630
+ });
631
+ return true;
632
+ }
633
+ /**
634
+ * Publish presence for the dashboard. Best effort: one track() per call,
635
+ * no effect on readiness, and a growing cooldown after each failure — a
636
+ * track() timeout on the server can end the whole channel, and every
637
+ * rejoin would otherwise publish again.
543
638
  */
544
- async trackPresenceWithRetry(recovered, attempts = 3) {
545
- if (this.isTrackingPresence)
546
- return; // never stack pushes on a wedged socket
639
+ async trackPresence(recovered) {
640
+ if (this.isTrackingPresence || this.presenceInCooldown())
641
+ return;
642
+ const channel = this.channel;
643
+ if (!channel || channel.state !== 'joined')
644
+ return;
547
645
  this.isTrackingPresence = true;
646
+ this.realtimeHealth.record('presence_attempts');
647
+ let status;
548
648
  try {
549
- await this.trackPresenceInner(recovered, attempts);
649
+ status = await channel.track({
650
+ device_id: this.deviceId,
651
+ device_name: this.deviceName,
652
+ app_version: VERSION,
653
+ platform: process.platform
654
+ });
655
+ }
656
+ catch (trackErr) {
657
+ status = `threw: ${trackErr?.message}`;
550
658
  }
551
659
  finally {
552
660
  this.isTrackingPresence = false;
553
661
  }
554
- }
555
- async trackPresenceInner(recovered, attempts) {
556
- // A fresh attempt starts from "not proven", so a leftover true from an
557
- // earlier join cannot keep the device counting as reachable while this
558
- // one is still deciding.
559
- this.presenceTracked = false;
560
- for (let attempt = 1; attempt <= attempts; attempt++) {
561
- if (!this.channel || this.channel.state !== 'joined')
562
- return;
563
- let status;
564
- try {
565
- status = await this.channel.track({
566
- device_id: this.deviceId,
567
- device_name: this.deviceName,
568
- app_version: VERSION,
569
- platform: process.platform
570
- });
571
- }
572
- catch (trackErr) {
573
- status = `threw: ${trackErr?.message}`;
574
- }
575
- if (status === 'ok') {
576
- // `presenceTracked` is not "track() said ok" — isReachable()
577
- // reads it as "this device receives commands", and the heartbeat
578
- // consults isReachable() directly rather than waiting for the
579
- // sequence below. Raising it here let a heartbeat firing while
580
- // these writes were in flight assert `online` over a row with no
581
- // capability recorded: the very state this is meant to remove.
582
- // So it is raised last, when every claim it makes is already true.
583
- //
584
- // Both writes have to land. Supabase reports a refused write in
585
- // the result rather than by throwing, and a device whose row
586
- // records neither the capability nor `online` is exactly as
587
- // undispatchable as one that never published presence. The
588
- // health check retries presence while this stays false, which is
589
- // the way back.
590
- const capabilityWritten = await this.setTransportCapable(true);
591
- // Strictly after, never alongside: `online` may be claimed only
592
- // where the capability is already advertised, or the row lands
593
- // back in the state this whole change is about.
594
- // Not syncReachabilityStatus(): its predicate reads presenceTracked,
595
- // and that flag is deliberately still false here - it is raised last,
596
- // once these writes have landed, so a heartbeat cannot advertise the
597
- // row mid-sequence. Both halves the predicate asks about are already
598
- // known at this point: the channel is joined and presence was just
599
- // acknowledged. The only open question is the local executor, so ask
600
- // that directly - a joined, present device whose executor is dead must
601
- // not be advertised either.
602
- const statusWritten = capabilityWritten
603
- ? await this.queueStatusWrite(this.localExecutorProbe() ? 'online' : 'offline')
604
- : false;
605
- if (!capabilityWritten || !statusWritten) {
606
- console.error('❌ Presence published but the device row could not be updated — not ready');
607
- captureRemote('remote_channel_readiness_write_failed', {
608
- capabilityWritten, statusWritten
609
- }).catch(() => { });
610
- return;
611
- }
612
- this.presenceTracked = true;
613
- this.presenceFailureStartedAt = null;
614
- console.log(`👋 Presence tracked (device ${this.deviceId} visible as online)`);
615
- // Reconnect attempts preceding this join (0 on a first join).
616
- captureRemote('remote_channel_presence_tracked', { recoveredAfterAttempts: recovered }).catch(() => { });
617
- // Broadcast is only a wake-up signal; mcp_remote_calls is the
618
- // durable queue. A call inserted while this socket was briefly
619
- // disconnected can miss its one new_call doorbell and otherwise
620
- // stay pending until the server reaper times it out. Drain that
621
- // durable backlog whenever the channel becomes genuinely usable.
622
- // Fire-and-forget so readiness does not wait on backlog recovery;
623
- // each row still goes through the atomic pending -> executing
624
- // claim, so a late/duplicate doorbell can safely race this scan.
625
- this.recoverPendingCalls().catch((error) => {
626
- console.error('[DEBUG] Pending call recovery failed:', error?.message);
627
- });
628
- return;
629
- }
630
- console.error(`❌ Presence track not acknowledged (${status}) — attempt ${attempt}/${attempts}`);
631
- if (attempt < attempts)
632
- await this.sleep(presenceRetryDelayMs(attempt));
633
- }
634
- this.presenceTracked = false;
635
- captureRemote('remote_channel_presence_track_error', { attempts }).catch(() => { });
636
- // Presence is an observer signal, not the delivery path. If this device
637
- // already proved broadcast capability and the channel is still joined,
638
- // keep that capability through a short provider-side Presence incident
639
- // instead of immediately switching to the 15s legacy heartbeat tier.
640
- // The 10s health check keeps retrying Presence; a success clears the
641
- // timer. Genuine channel failure is handled separately by
642
- // recreateChannel(), which still withdraws after 3 failed recreates.
643
- if (this.transportCapableWritten === true && this.channel?.state === 'joined') {
644
- const now = performance.now();
645
- if (this.presenceFailureStartedAt === null)
646
- this.presenceFailureStartedAt = now;
647
- const degradedForMs = now - this.presenceFailureStartedAt;
648
- if (degradedForMs < PRESENCE_WITHDRAW_GRACE_MS) {
649
- console.warn(`⚠️ Presence unavailable for ${Math.round(degradedForMs / 1000)}s — ` +
650
- `retaining broadcast capability during ${PRESENCE_WITHDRAW_GRACE_MS / 1000}s grace`);
662
+ if (status === 'ok') {
663
+ // Presence dies with the channel that published it; a new one publishes its own.
664
+ if (this.channel !== channel)
651
665
  return;
652
- }
666
+ this.realtimeHealth.record('presence_successes');
667
+ this.presenceTracked = true;
668
+ this.consecutivePresenceFailures = 0;
669
+ this.nextPresenceAttemptAt = 0;
670
+ console.log(`👋 Presence tracked (device ${this.deviceId})`);
671
+ captureRemote('remote_channel_presence_tracked', { recoveredAfterAttempts: recovered }).catch(() => { });
672
+ return;
653
673
  }
654
- this.presenceFailureStartedAt = null;
655
- console.error('❌ Presence track remained unavailable — withdrawing broadcast capability');
656
- await this.setTransportCapable(false);
674
+ this.realtimeHealth.record('presence_failures');
675
+ const current = this.channel === channel;
676
+ // A newer channel that already published owns the retry state.
677
+ if (!current && this.presenceTracked)
678
+ return;
679
+ // Otherwise arm the cooldown even if the channel was replaced meanwhile:
680
+ // the failure is what ended it, and the next join must not publish at once.
681
+ this.consecutivePresenceFailures++;
682
+ const delayMs = presenceRecoveryDelayMs(this.consecutivePresenceFailures);
683
+ this.nextPresenceAttemptAt = performance.now() + delayMs;
684
+ if (current)
685
+ this.presenceTracked = false;
686
+ console.warn(`⚠️ Presence not acknowledged (${status}) — retrying in ~${Math.round(delayMs / 60000)} min; tool calls are unaffected`);
687
+ captureRemote('remote_channel_presence_track_error', { attempts: 1 }).catch(() => { });
657
688
  }
658
- /**
659
- * The complete `capabilities` JSONB value. One place only: every write
660
- * replaces the whole column, so a second literal would silently drop keys.
661
- */
662
- capabilitiesPayload(broadcastCapable) {
663
- return {
664
- app_version: VERSION,
665
- ...(broadcastCapable ? { transport_broadcast_v1: true } : {})
666
- };
689
+ /** Presence is withheld by its cooldown right now. Monotonic, so a Date.now
690
+ * skew correction cannot shorten or extend it. */
691
+ presenceInCooldown() {
692
+ return performance.now() < this.nextPresenceAttemptAt;
667
693
  }
668
694
  /**
669
- * Advertise (or withdraw) the broadcast capability. Only true while genuinely
670
- * reachable that way — the server fails dispatch fast without it and picks
671
- * the offline-sweep tier from it, so every change must re-arm the heartbeat.
672
- *
673
- * Writes are queued, like the status writes. A withdrawal the recreate stops
674
- * waiting for still lands: compared with the last landed value, a re-publish
675
- * in the meantime looked redundant and was skipped, and the withdrawal then
676
- * left a device that claims to be online without the flag. Resolves with
677
- * whether the row holds `capable` once this write is done.
695
+ * The complete `capabilities` JSONB value. The write replaces the whole
696
+ * column, so a key left out here is dropped from the row.
678
697
  */
679
- setTransportCapable(capable) {
680
- if (!this.client || !this.deviceId)
681
- return Promise.resolve(false);
682
- // What the row holds once the queue drains — no redundant writes.
683
- if ((this.transportCapableQueued ?? this.transportCapableWritten) === capable) {
684
- return this.capabilityWriteChain.then(() => this.transportCapableWritten === capable);
685
- }
686
- this.transportCapableQueued = capable;
687
- const write = this.capabilityWriteChain.then(() => this.writeTransportCapable(capable));
688
- this.capabilityWriteChain = write;
689
- write.then(() => {
690
- if (this.capabilityWriteChain === write)
691
- this.transportCapableQueued = null;
692
- });
693
- return write;
694
- }
695
- async writeTransportCapable(capable) {
696
- if (!this.client || !this.deviceId)
697
- return false;
698
- try {
699
- const capabilities = this.capabilitiesPayload(capable);
700
- const { error } = await this.client
701
- .from('mcp_devices')
702
- .update({ capabilities })
703
- .eq('id', this.deviceId)
704
- .abortSignal(this.deviceRowWriteSignal());
705
- if (error) {
706
- console.error('[DEBUG] Failed to update transport capability:', error.message);
707
- // An aborted write may still land: what the row holds is
708
- // unknown, so the next write of either value is not skipped.
709
- this.transportCapableWritten = null;
710
- return false;
711
- }
712
- this.transportCapableWritten = capable;
713
- console.debug(`[DEBUG] Transport capability set to ${capable ? 'broadcast_v1' : 'withdrawn'}`);
714
- // Tier changed — move last_seen onto the cadence that tier's sweep
715
- // threshold expects (no-op if the heartbeat hasn't started yet).
716
- this.scheduleHeartbeat();
717
- // last_seen may already be past the 45s threshold now judging us,
718
- // so write once immediately rather than waiting out the interval.
719
- if (!capable && this.heartbeatDeviceId) {
720
- this.updateHeartbeat(this.heartbeatDeviceId).catch(() => { });
721
- }
722
- }
723
- catch (error) {
724
- console.error('[DEBUG] Transport capability update threw:', error?.message);
725
- this.transportCapableWritten = null;
726
- return false;
727
- }
728
- return true;
698
+ capabilitiesPayload() {
699
+ return { app_version: VERSION };
729
700
  }
730
701
  /** Aborts one write to this device's row after DEVICE_ROW_WRITE_TIMEOUT_MS (a method, so tests can shorten it). */
731
702
  deviceRowWriteSignal() {
@@ -744,6 +715,7 @@ export class RemoteChannel {
744
715
  // Presence, keyed by device id.
745
716
  const channelName = `user:${this.user.id}`;
746
717
  console.debug(`[DEBUG] Creating channel: ${channelName}`);
718
+ this.realtimeHealth.newChannel();
747
719
  this.channel = this.client.channel(channelName, {
748
720
  config: {
749
721
  private: true,
@@ -764,29 +736,38 @@ export class RemoteChannel {
764
736
  // Debug: Log all subscription status events
765
737
  console.debug(`[DEBUG] Channel subscription status: ${status}${err ? ' (error: ' + (err?.message || err) + ')' : ''} — ${this.connState()}`);
766
738
  if (status === 'SUBSCRIBED') {
739
+ this.realtimeHealth.record('join_successes');
740
+ // The SDK resets its rejoinTimer here even if the join dies
741
+ // before it is ready. Carry failure budget across such joins.
742
+ // reconnectAttempt is different: it counts watchdog
743
+ // recreations, and a join does end that particular
744
+ // failure mode.
745
+ this.consecutiveUnreadyJoins = Math.min(MAX_UNREADY_JOIN_BUDGET, this.consecutiveUnreadyJoins + 1);
767
746
  const recovered = this.reconnectAttempt;
768
- this.reconnectAttempt = 0;
769
- this.lastHeartbeatOkAt = performance.now(); // a fresh join is proof of life too
747
+ this.reconnectAttempt = 0; // watchdog attempts only, not recovery proof
748
+ const joinedAt = performance.now();
749
+ this.joinedAt = joinedAt;
750
+ this.lastHeartbeatOkAt = joinedAt; // a fresh join is proof of life too
770
751
  console.log(`✅ Channel subscribed${recovered > 0 ? ` (recovered after ${recovered} attempt${recovered === 1 ? '' : 's'})` : ''}`);
771
- // A join is only half of what dispatch needs. The other
772
- // half is presence, which writes the capability the
773
- // server checks — and when every track() is refused,
774
- // trackPresenceInner() withdraws the capability and
775
- // returns normally. Resolving here regardless left the
776
- // row online with the capability withdrawn: the exact
777
- // state the server refuses as not_broadcast_capable.
778
- // `status` is written on the same event as the
779
- // capability, in trackPresenceInner, so the two can
780
- // never disagree.
781
- this.trackPresenceWithRetry(recovered)
782
- .catch(() => { })
783
- .finally(() => this.presenceTracked
752
+ // A joined channel receives doorbells; readiness only
753
+ // waits for the device row to say so. Presence runs
754
+ // beside it and never decides readiness.
755
+ this.readinessInFlight = null;
756
+ this.channelReady = false;
757
+ this.presenceTracked = false;
758
+ this.markChannelReady()
759
+ .catch(() => false)
760
+ .then((ready) => ready
784
761
  ? resolve()
785
- : reject(new ChannelUnreachableError('channel joined but presence was never acknowledged, so no command can be delivered')));
762
+ : reject(new ChannelUnreachableError('channel joined but the device row could not be updated, so no command can be delivered')));
763
+ this.trackPresence(recovered).catch(() => { });
786
764
  }
787
765
  else if (status === 'CHANNEL_ERROR') {
766
+ this.realtimeHealth.record('join_errors');
788
767
  // CHANNEL_ERROR is the only status carrying a real error message.
789
768
  console.error(`❌ Channel error: ${err?.message || 'unknown'} — ${this.connState()}`);
769
+ this.joinedAt = null;
770
+ this.channelReady = false;
790
771
  this.presenceTracked = false;
791
772
  this.syncReachabilityStatus();
792
773
  // Fires on ordinary network faults too — filter on the
@@ -795,12 +776,14 @@ export class RemoteChannel {
795
776
  reject(new ChannelUnreachableError(err?.message || 'failed to subscribe to the tool call channel'));
796
777
  }
797
778
  else if (status === 'TIMED_OUT') {
779
+ this.realtimeHealth.record('join_timeouts');
798
780
  console.error(`⏱️ Channel subscription timed out, Reconnecting... — ${this.connState()}`);
799
781
  this.syncReachabilityStatus();
800
782
  captureRemote('remote_channel_subscription_timeout', { attempt: this.reconnectAttempt }).catch(() => { });
801
783
  reject(new ChannelUnreachableError('tool call channel subscription timed out'));
802
784
  }
803
785
  else if (status === 'CLOSED') {
786
+ this.realtimeHealth.record('join_closures');
804
787
  // Settle the promise so an in-flight recreateChannel() can't await
805
788
  // forever (which would wedge the re-entrancy guard / watchdog).
806
789
  console.warn(`⚠️ Channel closed — ${this.connState()}`);
@@ -821,15 +804,12 @@ export class RemoteChannel {
821
804
  async recoverPendingCalls() {
822
805
  if (!this.client || !this.deviceId || !this.isReachable())
823
806
  return;
824
- // Date.now() is deliberately used here: this process may patch it from
825
- // Supabase's Date header to correct a badly skewed device clock.
826
- const now = new Date(Date.now()).toISOString();
827
807
  const { data: pending, error } = await this.client
828
808
  .from('mcp_remote_calls')
829
809
  .select('id,device_id')
830
810
  .eq('device_id', this.deviceId)
831
811
  .eq('status', 'pending')
832
- .gt('timeout_at', now)
812
+ .gt('timeout_at', 'now')
833
813
  .order('created_at', { ascending: true })
834
814
  .limit(PENDING_RECOVERY_BATCH_SIZE);
835
815
  if (error) {
@@ -890,7 +870,9 @@ export class RemoteChannel {
890
870
  return;
891
871
  // Retry on transient failures (a REST blip while the socket stays
892
872
  // healthy). This claim is the only way we learn about a call,
893
- // so a hiccup must not cost a 5-minute timeout.
873
+ // so a hiccup must not cost a timeout. PostgREST interprets the
874
+ // special timestamptz input 'now' in PostgreSQL, not on the device;
875
+ // this atomically excludes expired rows despite client clock skew.
894
876
  let row = null;
895
877
  let claimError = null;
896
878
  for (const delayMs of [0, 500, 1500]) {
@@ -902,7 +884,7 @@ export class RemoteChannel {
902
884
  .eq('id', callId)
903
885
  .eq('device_id', this.deviceId)
904
886
  .eq('status', 'pending')
905
- .gt('timeout_at', new Date(Date.now()).toISOString())
887
+ .gt('timeout_at', 'now')
906
888
  .select('*');
907
889
  if (!error) {
908
890
  row = data?.[0] ?? null;
@@ -914,6 +896,9 @@ export class RemoteChannel {
914
896
  console.debug(`[DEBUG] Doorbell claim attempt failed for ${callId}: ${error.message} — retrying`);
915
897
  }
916
898
  if (row) {
899
+ // The server writes the user's rollouts into every call row; a row
900
+ // without them (an older server) keeps what the device has.
901
+ rolloutManager.update(row.metadata?.rollouts);
917
902
  this.dispatchToolCall({ new: row, claimed: true });
918
903
  return;
919
904
  }
@@ -931,17 +916,16 @@ export class RemoteChannel {
931
916
  .select('*')
932
917
  .eq('id', callId)
933
918
  .eq('device_id', this.deviceId)
919
+ .gt('timeout_at', 'now')
934
920
  .maybeSingle();
935
921
  if (error) {
936
922
  console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after claim errors:`, error.message);
937
923
  await captureRemote('remote_channel_doorbell_fetch_error', { error });
938
924
  return;
939
925
  }
940
- if (current?.status === 'pending'
941
- && current.timeout_at
942
- && new Date(current.timeout_at).getTime() > Date.now()) {
943
- // No claim landed; device.ts claims it. Do not hand an expired
944
- // side-effecting call to the executor while it races the reaper.
926
+ if (current?.status === 'pending') {
927
+ // No claim landed; device.ts claims it. Read-back already excludes
928
+ // expired rows using PostgreSQL time; its own claim does likewise.
945
929
  this.dispatchToolCall({ new: current });
946
930
  }
947
931
  else {
@@ -981,10 +965,14 @@ export class RemoteChannel {
981
965
  return;
982
966
  }
983
967
  const state = this.channel.state;
968
+ this.realtimeHealth.observeSocketState(String(this.client?.realtime?.connectionState?.() ?? 'unknown'));
984
969
  // Debug: Log current channel state (only if changed)
985
970
  if (!this.lastChannelState || this.lastChannelState !== state) {
986
971
  console.debug(`[DEBUG] channel state: ${state} — ${this.connState()}`);
987
972
  this.lastChannelState = state;
973
+ if (state !== 'joined' && state !== 'joining') {
974
+ captureRemote('remote_channel_state_health', { state, attempt: this.reconnectAttempt }).catch(() => { });
975
+ }
988
976
  }
989
977
  // 'joined' = healthy. Clear the joining-overstay timer.
990
978
  if (state === 'joined') {
@@ -1000,14 +988,24 @@ export class RemoteChannel {
1000
988
  return;
1001
989
  }
1002
990
  }
1003
- // Self-heal a failed presence publish: the channel is up, so nothing
1004
- // else will ever retry (SUBSCRIBED won't fire again). Until it
1005
- // lands the dashboard shows this device offline, and if track()
1006
- // already failed its retries the capability is withdrawn too, so
1007
- // the server fails every dispatch to it fast.
1008
- if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence) {
1009
- console.debug('[DEBUG] Channel joined but presence not tracked — retrying track()');
1010
- this.trackPresenceWithRetry(0, 1).catch(() => { });
991
+ // Broadcast has outlived a join->error cycle with a heartbeat
992
+ // confirmed after the join: the socket/channel path is working.
993
+ // Stop charging this join to the reconnect budget, so a later
994
+ // ordinary blip gets fast recovery.
995
+ if (this.consecutiveUnreadyJoins > 0 && this.joinedAt !== null &&
996
+ this.lastHeartbeatOkAt !== null && this.lastHeartbeatOkAt > this.joinedAt &&
997
+ performance.now() - this.joinedAt >= STABLE_BROADCAST_RESET_MS) {
998
+ console.debug(`[DEBUG] Broadcast channel stable for ${Math.round((performance.now() - this.joinedAt) / 1000)}s — clearing reconnect backoff budget`);
999
+ this.consecutiveUnreadyJoins = 0;
1000
+ }
1001
+ // The channel is up, so SUBSCRIBED won't fire again: retry what the
1002
+ // join left undone, each on its own cooldown.
1003
+ if (!this.channelReady && performance.now() >= this.nextReadinessAttemptAt) {
1004
+ console.debug('[DEBUG] Channel joined but the device row is not ready — retrying');
1005
+ this.markChannelReady().catch(() => { });
1006
+ }
1007
+ if (!this.presenceTracked && this.deviceId) {
1008
+ this.trackPresence(0).catch(() => { });
1011
1009
  }
1012
1010
  return;
1013
1011
  }
@@ -1031,7 +1029,6 @@ export class RemoteChannel {
1031
1029
  }
1032
1030
  // Unhealthy: closed, errored, leaving — recreate
1033
1031
  this.joiningSince = null;
1034
- captureRemote('remote_channel_state_health', { state, attempt: this.reconnectAttempt });
1035
1032
  console.debug(`[DEBUG] ⚠️ Channel in unhealthy state '${state}' - recreating... — ${this.connState()}`);
1036
1033
  this.recreateChannel();
1037
1034
  }
@@ -1057,8 +1054,9 @@ export class RemoteChannel {
1057
1054
  await this.sleep(SOCKET_SETTLE_MAX_MS);
1058
1055
  return;
1059
1056
  }
1060
- const deadline = Date.now() + SOCKET_SETTLE_MAX_MS;
1061
- while (realtime.isDisconnecting() && Date.now() < deadline) {
1057
+ // Monotonic: Date.now may be patched by the clock-skew correction.
1058
+ const deadline = performance.now() + SOCKET_SETTLE_MAX_MS;
1059
+ while (realtime.isDisconnecting() && performance.now() < deadline) {
1062
1060
  await this.sleep(SOCKET_SETTLE_POLL_MS);
1063
1061
  }
1064
1062
  }
@@ -1097,9 +1095,10 @@ export class RemoteChannel {
1097
1095
  // Create fresh channel
1098
1096
  console.log(`🔄 Recreating channel... (attempt ${this.reconnectAttempt}) — ${this.connState()}`);
1099
1097
  try {
1100
- // Jittered backoff so a fleet-wide event doesn't stampede every
1101
- // device into reconnecting at once. ~1-3s rising to ~15-45s.
1102
- const backoffMs = Math.min(30000, 1000 * 2 ** Math.min(this.reconnectAttempt, 5)) * (0.5 + Math.random());
1098
+ // Our force-recreate fallback shares the extended sustained-failure
1099
+ // budget with the SDK. A 10s watchdog tick cannot cancel this wait
1100
+ // because isRecreatingChannel guards its whole duration.
1101
+ const backoffMs = watchdogRecreateDelayMs(Math.max(this.reconnectAttempt, this.consecutiveUnreadyJoins));
1103
1102
  console.debug(`[DEBUG] Reconnect backoff: ${Math.round(backoffMs)}ms`);
1104
1103
  await this.sleep(backoffMs);
1105
1104
  // realtime-js runs its own rejoin timer, and the backoff above gives
@@ -1115,6 +1114,8 @@ export class RemoteChannel {
1115
1114
  console.log(`✅ Channel self-healed during backoff — skipping recreate — ${this.connState()}`);
1116
1115
  return; // finally-block below clears the re-entrancy guard
1117
1116
  }
1117
+ // Count only watchdog recreations that continue past SDK self-heal.
1118
+ this.realtimeHealth.record('watchdog_recreates');
1118
1119
  // Cap the whole recreate: a never-settling await (e.g. a subscribe that only
1119
1120
  // ever emits CLOSED) must not pin isRecreatingChannel=true and silently disable
1120
1121
  // the 10s watchdog. On timeout we reject -> catch -> finally clears the guard.
@@ -1150,22 +1151,6 @@ export class RemoteChannel {
1150
1151
  catch (err) {
1151
1152
  captureRemote('remote_channel_recreate_error', { errMsg: err?.message, attempt: this.reconnectAttempt });
1152
1153
  console.debug(`[DEBUG] Channel recreation failed: ${err?.message} — ${this.connState()}`);
1153
- // Sustained failure: stop promising a transport we can't deliver, so
1154
- // dispatch fails fast instead of every call waiting out the timeout.
1155
- if (this.reconnectAttempt >= TRANSPORT_WITHDRAW_AFTER_ATTEMPTS) {
1156
- // Bounded, in its own try: this catch block is outside
1157
- // RECREATE_TIMEOUT_MS, so a hanging PATCH would pin
1158
- // isRecreatingChannel and disable the watchdog.
1159
- try {
1160
- await this.withTimeout(() => this.setTransportCapable(false), CAPABILITY_WRITE_TIMEOUT_MS, 'withdrawTransportCapability');
1161
- }
1162
- catch (withdrawErr) {
1163
- // The write stays queued, in order with any re-publish after
1164
- // it, and ends within DEVICE_ROW_WRITE_TIMEOUT_MS; the flag
1165
- // only advances on a confirmed write.
1166
- console.debug(`[DEBUG] Capability withdrawal did not complete: ${withdrawErr?.message}`);
1167
- }
1168
- }
1169
1154
  }
1170
1155
  finally {
1171
1156
  this.isRecreatingChannel = false;
@@ -1175,8 +1160,9 @@ export class RemoteChannel {
1175
1160
  * Claim a call. True only when THIS update flipped the row pending ->
1176
1161
  * executing, which is what makes dual delivery safe across processes.
1177
1162
  * .eq('status','pending') makes it conditional; .select('id') makes the
1178
- * result observable. On a transient DB error it returns true (execute
1179
- * anyway), matching prior behaviour — so device.ts's in-memory guard is what
1163
+ * result observable. Expiry is checked using Postgres time, not the
1164
+ * device clock. On a transient DB error it returns true (execute anyway),
1165
+ * matching prior behaviour — so device.ts's in-memory guard is what
1180
1166
  * actually guarantees exactly-once within a process.
1181
1167
  */
1182
1168
  async markCallExecuting(callId) {
@@ -1187,7 +1173,7 @@ export class RemoteChannel {
1187
1173
  .update({ status: 'executing' })
1188
1174
  .eq('id', callId)
1189
1175
  .eq('status', 'pending')
1190
- .gt('timeout_at', new Date(Date.now()).toISOString())
1176
+ .gt('timeout_at', 'now')
1191
1177
  .select('id');
1192
1178
  if (error) {
1193
1179
  console.error('[DEBUG] Failed to mark call executing:', error.message);
@@ -1206,10 +1192,9 @@ export class RemoteChannel {
1206
1192
  async updateCallResult(callId, status, result = null, errorMessage = null) {
1207
1193
  if (!this.client)
1208
1194
  throw new Error('Client not initialized');
1209
- const updateData = {
1210
- status: status,
1211
- completed_at: new Date().toISOString()
1212
- };
1195
+ // The DB terminal-status trigger stamps completed_at using PostgreSQL
1196
+ // time. Do not send a device-generated timestamp.
1197
+ const updateData = { status };
1213
1198
  // Strip NUL (U+0000) before it reaches the jsonb `result` column.
1214
1199
  // jsonb cannot store and rejects the whole write (Postgres 22P05),
1215
1200
  // which otherwise leaves the call stuck 'executing' → the user waits out
@@ -1252,14 +1237,15 @@ export class RemoteChannel {
1252
1237
  }
1253
1238
  /**
1254
1239
  * Reachable means all of it is true at once: the private channel is
1255
- * joined, this device has published its presence, and the local executor
1256
- * answers. The server needs the first two before it will dispatch, and a
1257
- * healthy channel on a device whose executor is dead is the false-online
1258
- * state issue #4 was opened for. Gates the heartbeat and `status`.
1240
+ * joined, the join's status write landed, and the local executor answers.
1241
+ * The server needs the first two before it will dispatch, and a healthy
1242
+ * channel on a device whose executor is dead is the false-online state
1243
+ * issue #4 was opened for. Presence is not part of it. Gates the heartbeat
1244
+ * and `status`.
1259
1245
  */
1260
1246
  isReachable() {
1261
1247
  return this.channel?.state === 'joined'
1262
- && this.presenceTracked
1248
+ && this.channelReady
1263
1249
  && this.localExecutorProbe();
1264
1250
  }
1265
1251
  /**
@@ -1277,13 +1263,13 @@ export class RemoteChannel {
1277
1263
  return this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1278
1264
  }
1279
1265
  /**
1280
- * Serialize the channel-callback status writes. They fire from un-awaited
1281
- * callbacks, and inside recreateChannel() a teardown's 'offline' and the
1282
- * fresh join's 'online' land ~100-300ms apart — unordered, 'offline' can win
1283
- * and leave a healthy device undispatchable until the next heartbeat.
1266
+ * Serialize the status writes, the heartbeat's included. They fire from
1267
+ * un-awaited callbacks, and inside recreateChannel() a teardown's 'offline'
1268
+ * and the fresh join's 'online' land ~100-300ms apart — unordered, 'offline'
1269
+ * can win and leave a healthy device undispatchable until the next heartbeat.
1284
1270
  *
1285
- * Not the single writer: updateHeartbeat, registerDevice and setOffline's
1286
- * subprocess write status directly, so this is not total ordering.
1271
+ * Not the single writer: registerDevice and setOffline's subprocess write
1272
+ * status directly, so this is not total ordering.
1287
1273
  */
1288
1274
  queueStatusWrite(status) {
1289
1275
  // After teardown begins, setOffline() owns the final status write.
@@ -1302,68 +1288,45 @@ export class RemoteChannel {
1302
1288
  this.statusWriteChain = write.then(() => undefined);
1303
1289
  return write;
1304
1290
  }
1305
- /**
1306
- * Heartbeat cadence for the tier this device is CURRENTLY in. Follows the
1307
- * capability flag (what the server actually tiers its sweep on), not the
1308
- * build — see LEGACY_HEARTBEAT_INTERVAL.
1309
- */
1310
- heartbeatIntervalMs() {
1311
- return this.transportCapableWritten === true
1312
- ? CAPABLE_HEARTBEAT_INTERVAL
1313
- : LEGACY_HEARTBEAT_INTERVAL;
1314
- }
1315
- async updateHeartbeat(deviceId) {
1291
+ async updateHeartbeat() {
1316
1292
  if (!this.client)
1317
1293
  return;
1318
1294
  // This write asserts status:'online' too, so it MUST respect the
1319
1295
  // shutdown gate — otherwise a heartbeat firing (or in flight) as SIGINT
1320
1296
  // lands can be applied after setOffline()'s subprocess write and leave
1321
- // an exited process marked online with a fresh last_seen, which for a
1322
- // capable device the sweep then cannot age out for a full tier window.
1297
+ // an exited process marked online with a fresh last_seen, which the
1298
+ // sweep then cannot age out for its full window.
1323
1299
  if (this.shuttingDown) {
1324
1300
  console.debug('[DEBUG] Skipping heartbeat write — shutting down');
1325
1301
  return;
1326
1302
  }
1327
- try {
1328
- // Skip the write entirely when no transport is up. Bumping last_seen
1329
- // on a deaf device would keep its row perpetually young, so the
1330
- // server's staleness sweep could never age it out and correct a
1331
- // stale 'online' — and that row is what dispatch reads. Staying
1332
- // silent lets the sweep do its job.
1333
- if (!this.isReachable()) {
1334
- console.debug('[DEBUG] Skipping heartbeat write — no transport joined; letting the row age out');
1335
- return;
1336
- }
1337
- const { error } = await this.client
1338
- .from('mcp_devices')
1339
- .update({ last_seen: new Date().toISOString(), status: 'online' })
1340
- .eq('id', deviceId);
1341
- if (error) {
1342
- console.error('[DEBUG] Heartbeat update failed:', error.message);
1343
- await captureRemote('remote_channel_heartbeat_error', { error });
1344
- }
1345
- else {
1346
- console.debug('[DEBUG] last_seen bookkeeping write ok:', deviceId);
1347
- }
1348
- }
1349
- catch (error) {
1350
- console.error('Heartbeat failed:', error.message);
1351
- await captureRemote('remote_channel_heartbeat_error', { error });
1303
+ // Skip the write entirely when no transport is up. Bumping last_seen
1304
+ // on a deaf device would keep its row perpetually young, so the
1305
+ // server's staleness sweep could never age it out and correct a
1306
+ // stale 'online' — and that row is what dispatch reads. Staying
1307
+ // silent lets the sweep do its job.
1308
+ if (!this.isReachable()) {
1309
+ console.debug('[DEBUG] Skipping heartbeat write — no transport joined; letting the row age out');
1310
+ return;
1352
1311
  }
1312
+ // Queued, so a drop's 'offline' queued after it always lands last.
1313
+ // setOnlineStatus also refreshes last_seen and reports a failed write.
1314
+ await this.queueStatusWrite('online');
1353
1315
  }
1354
1316
  startHeartbeat(deviceId) {
1355
1317
  console.debug('[DEBUG] Starting heartbeat for device:', deviceId);
1356
- this.heartbeatDeviceId = deviceId;
1318
+ this.realtimeHealth.setDevice(deviceId);
1319
+ this.realtimeHealth.start();
1357
1320
  this.connectionCheckInterval = setInterval(() => {
1358
1321
  this.checkConnectionHealth();
1359
1322
  }, 10000);
1360
- // Bookkeeping last_seen write. Self-rescheduling rather than a fixed
1361
- // setInterval so the cadence can follow the tier: a device that
1362
- // withdraws the capability flag must fall back to the fast legacy
1363
- // cadence immediately, not 30 minutes later.
1364
- this.scheduleHeartbeat();
1323
+ // Bookkeeping last_seen write. A fixed interval, so a slow write never
1324
+ // pushes the next one past the dashboard's freshness window.
1325
+ this.heartbeatInterval = setInterval(() => {
1326
+ this.updateHeartbeat().catch(() => { });
1327
+ }, HEARTBEAT_INTERVAL_MS);
1365
1328
  this.startTokenRefresh();
1366
- console.debug(`[DEBUG] Heartbeat started - connectionCheck: 10s, last_seen: ${this.heartbeatIntervalMs()}ms, tokenRefresh: ${TOKEN_REFRESH_INTERVAL_MS}ms`);
1329
+ console.debug(`[DEBUG] Heartbeat started - connectionCheck: 10s, last_seen: ${HEARTBEAT_INTERVAL_MS}ms, tokenRefresh: ${TOKEN_REFRESH_INTERVAL_MS}ms`);
1367
1330
  }
1368
1331
  async refreshTokenNow() {
1369
1332
  if (!this.client || this.shuttingDown)
@@ -1396,25 +1359,9 @@ export class RemoteChannel {
1396
1359
  this.tokenRefreshInterval = null;
1397
1360
  }
1398
1361
  }
1399
- /** Arm (or re-arm) the last_seen timer at the current tier's cadence. */
1400
- scheduleHeartbeat() {
1401
- if (this.heartbeatInterval) {
1402
- clearTimeout(this.heartbeatInterval);
1403
- this.heartbeatInterval = null;
1404
- }
1405
- if (!this.heartbeatDeviceId)
1406
- return;
1407
- this.heartbeatInterval = setTimeout(async () => {
1408
- if (this.heartbeatDeviceId) {
1409
- await this.updateHeartbeat(this.heartbeatDeviceId);
1410
- }
1411
- this.scheduleHeartbeat(); // re-read the tier every tick
1412
- }, this.heartbeatIntervalMs());
1413
- }
1414
1362
  stopHeartbeat() {
1415
- this.heartbeatDeviceId = null;
1416
1363
  if (this.heartbeatInterval) {
1417
- clearTimeout(this.heartbeatInterval);
1364
+ clearInterval(this.heartbeatInterval);
1418
1365
  this.heartbeatInterval = null;
1419
1366
  }
1420
1367
  if (this.connectionCheckInterval) {
@@ -1434,7 +1381,7 @@ export class RemoteChannel {
1434
1381
  }
1435
1382
  const { error } = await this.client
1436
1383
  .from('mcp_devices')
1437
- .update({ status: status, last_seen: new Date().toISOString() })
1384
+ .update({ status: status, last_seen: 'now' })
1438
1385
  .eq('id', deviceId)
1439
1386
  .abortSignal(this.deviceRowWriteSignal());
1440
1387
  if (error) {
@@ -1545,6 +1492,7 @@ export class RemoteChannel {
1545
1492
  }
1546
1493
  }
1547
1494
  async unsubscribe() {
1495
+ this.realtimeHealth.stop();
1548
1496
  // setOffline()'s durable write is the final word on `status` from here,
1549
1497
  // so stop the heartbeat and the channel callbacks from racing it. The
1550
1498
  // races that matter: a heartbeat tick firing as the signal arrives, and
@@ -1556,9 +1504,8 @@ export class RemoteChannel {
1556
1504
  // In practice only the untrack bound binds — removeChannel/unsubscribe
1557
1505
  // set state='leaving' first, so their leave push resolves inline.
1558
1506
  const LEAVE_BOUND_MS = 300;
1559
- // Drain queued channel-callback writes. Can't drain an in-flight
1560
- // heartbeat PATCH (it doesn't use the chain), but the gate above stops
1561
- // any new one and an in-flight one started earlier.
1507
+ // Drain queued status writes, the heartbeat's included; the gate above
1508
+ // stops any new one.
1562
1509
  await Promise.race([this.statusWriteChain, this.sleep(250)]);
1563
1510
  if (this.channel) {
1564
1511
  // Leave presence on the graceful path (socket close covers the abrupt