@wonderwhy-er/desktop-commander 0.2.51 → 0.3.1-alpha.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 (117) 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 +49 -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 +32 -4
  17. package/dist/remote-device/broadcast-analytics.d.ts +28 -0
  18. package/dist/remote-device/broadcast-analytics.js +41 -0
  19. package/dist/remote-device/desktop-commander-integration.d.ts +20 -0
  20. package/dist/remote-device/desktop-commander-integration.js +121 -40
  21. package/dist/remote-device/device-authenticator.d.ts +13 -1
  22. package/dist/remote-device/device-authenticator.js +87 -47
  23. package/dist/remote-device/device.d.ts +14 -0
  24. package/dist/remote-device/device.js +244 -51
  25. package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
  26. package/dist/remote-device/mqtt-enrollment.js +162 -0
  27. package/dist/remote-device/mqtt-transport.d.ts +44 -0
  28. package/dist/remote-device/mqtt-transport.js +197 -0
  29. package/dist/remote-device/remote-channel.d.ts +64 -3
  30. package/dist/remote-device/remote-channel.js +317 -48
  31. package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
  32. package/dist/remote-device/transport-analytics.d.ts +29 -0
  33. package/dist/remote-device/transport-analytics.js +44 -0
  34. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  35. package/dist/remote-device/transport-telemetry.js +48 -0
  36. package/dist/search-manager.d.ts +239 -27
  37. package/dist/search-manager.js +746 -312
  38. package/dist/server.js +77 -92
  39. package/dist/terminal-manager.d.ts +138 -21
  40. package/dist/terminal-manager.js +300 -215
  41. package/dist/tools/config.d.ts +1 -1
  42. package/dist/tools/config.js +21 -70
  43. package/dist/tools/edit.js +12 -4
  44. package/dist/tools/filesystem.d.ts +30 -6
  45. package/dist/tools/filesystem.js +246 -140
  46. package/dist/tools/improved-process-tools.d.ts +9 -3
  47. package/dist/tools/improved-process-tools.js +171 -68
  48. package/dist/tools/pdf/extract-images.d.ts +2 -0
  49. package/dist/tools/pdf/extract-images.js +4 -1
  50. package/dist/tools/pdf/index.d.ts +5 -3
  51. package/dist/tools/pdf/index.js +4 -3
  52. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  53. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  54. package/dist/tools/pdf/manipulations.d.ts +12 -1
  55. package/dist/tools/pdf/manipulations.js +17 -4
  56. package/dist/tools/pdf/markdown.d.ts +96 -0
  57. package/dist/tools/pdf/markdown.js +485 -20
  58. package/dist/tools/pdf/utils.d.ts +2 -2
  59. package/dist/tools/pdf/utils.js +4 -4
  60. package/dist/tools/process.js +8 -5
  61. package/dist/tools/schemas.d.ts +1 -1
  62. package/dist/tools/schemas.js +15 -6
  63. package/dist/tools/search.d.ts +32 -0
  64. package/dist/tools/search.js +202 -0
  65. package/dist/types.d.ts +1 -1
  66. package/dist/ui/config-editor/config-editor-runtime.js +6 -6
  67. package/dist/ui/config-editor/src/app.js +2 -15
  68. package/dist/utils/ab-test.js +27 -9
  69. package/dist/utils/atomic-write.d.ts +14 -0
  70. package/dist/utils/atomic-write.js +80 -0
  71. package/dist/utils/capture.d.ts +17 -1
  72. package/dist/utils/capture.js +177 -68
  73. package/dist/utils/exit-process.d.ts +24 -0
  74. package/dist/utils/exit-process.js +31 -0
  75. package/dist/utils/feature-flags.js +2 -1
  76. package/dist/utils/files/base.d.ts +3 -1
  77. package/dist/utils/files/docx.d.ts +3 -0
  78. package/dist/utils/files/docx.js +24 -9
  79. package/dist/utils/files/excel.d.ts +10 -0
  80. package/dist/utils/files/excel.js +93 -33
  81. package/dist/utils/files/factory.d.ts +22 -1
  82. package/dist/utils/files/factory.js +59 -4
  83. package/dist/utils/files/image.d.ts +12 -4
  84. package/dist/utils/files/image.js +19 -8
  85. package/dist/utils/files/index.d.ts +5 -3
  86. package/dist/utils/files/index.js +4 -3
  87. package/dist/utils/files/pdf.js +18 -36
  88. package/dist/utils/files/text.d.ts +21 -5
  89. package/dist/utils/files/text.js +90 -86
  90. package/dist/utils/internal-facts.d.ts +3 -0
  91. package/dist/utils/internal-facts.js +23 -0
  92. package/dist/utils/lazy-package.d.ts +23 -0
  93. package/dist/utils/lazy-package.js +42 -0
  94. package/dist/utils/open-browser.js +2 -1
  95. package/dist/utils/process-detection.d.ts +24 -5
  96. package/dist/utils/process-detection.js +199 -89
  97. package/dist/utils/process-tree.d.ts +14 -0
  98. package/dist/utils/process-tree.js +223 -0
  99. package/dist/utils/rename.d.ts +9 -0
  100. package/dist/utils/rename.js +74 -0
  101. package/dist/utils/ripgrep-resolver.js +9 -14
  102. package/dist/utils/shell.d.ts +42 -0
  103. package/dist/utils/shell.js +187 -0
  104. package/dist/utils/system-info.js +9 -7
  105. package/dist/utils/trackTools.js +2 -1
  106. package/dist/version.d.ts +1 -1
  107. package/dist/version.js +1 -1
  108. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  109. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  110. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  111. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  112. package/package.json +8 -2
  113. package/vendor/telemetry-contract/README.md +56 -0
  114. package/vendor/telemetry-contract/package.json +32 -0
  115. package/vendor/telemetry-contract/transport.d.ts +38 -0
  116. package/vendor/telemetry-contract/transport.js +164 -0
  117. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -1,5 +1,6 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import { captureRemote } from '../utils/capture.js';
3
+ import { observeTransport } from './transport-telemetry.js';
3
4
  import { VERSION } from '../version.js';
4
5
  const NUL_CHAR = String.fromCharCode(0);
5
6
  const NUL_RE = new RegExp(NUL_CHAR, 'g');
@@ -28,13 +29,38 @@ export function stripNullBytes(value) {
28
29
  }
29
30
  return value;
30
31
  }
32
+ /**
33
+ * The device registered, but its realtime channel is not usable — the join
34
+ * failed, or presence was never acknowledged. Distinct from every other
35
+ * registration failure on purpose: this one the socket watchdog can repair, so
36
+ * the caller keeps the process alive, while a failed lookup or a missing row
37
+ * happens before the recreation parameters are stored and nothing can repair it.
38
+ */
39
+ export class ChannelUnreachableError extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = 'ChannelUnreachableError';
43
+ }
44
+ }
31
45
  // last_seen cadences. The server tiers its sweep on the transport_broadcast_v1
32
46
  // flag, so each must fit its tier's threshold in the server's constants.ts:
33
47
  // capable -> 15 min, unflagged -> 45s.
34
48
  const CAPABLE_HEARTBEAT_INTERVAL = 5 * 60 * 1000;
35
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;
36
62
  // 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).
63
+ // Must exceed createChannel()'s worst case (~32.25s of jittered presence retries).
38
64
  const RECREATE_TIMEOUT_MS = 45000;
39
65
  // Max continuous time in 'joining' before forcing a recreate — a half-open
40
66
  // socket parks the channel there forever, and a genuine join settles in ~10s.
@@ -54,6 +80,11 @@ const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
54
80
  // Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
55
81
  // does not cover.
56
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.
87
+ const DEVICE_ROW_WRITE_TIMEOUT_MS = 10000;
57
88
  // Cap on the shutdown session fetch, which races device.ts's 5s force-exit.
58
89
  const OFFLINE_SESSION_TIMEOUT_MS = 500;
59
90
  // realtime-js parks in 'disconnecting' for ~100ms after a disconnect and
@@ -62,6 +93,25 @@ const OFFLINE_SESSION_TIMEOUT_MS = 500;
62
93
  // already covers.
63
94
  const SOCKET_SETTLE_MAX_MS = 300;
64
95
  const SOCKET_SETTLE_POLL_MS = 20;
96
+ // Reconnect recovery is a safety net, not the primary transport. Bound each
97
+ // scan so a pathological backlog cannot turn one reconnect into an unbounded
98
+ // burst of REST claims/tool executions.
99
+ const PENDING_RECOVERY_BATCH_SIZE = 100;
100
+ function jitterAround(baseMs, random) {
101
+ const sample = Math.max(0, Math.min(1, random()));
102
+ return Math.max(1, Math.round(baseMs * (0.5 + sample)));
103
+ }
104
+ /** Jittered version of realtime-js's default 1s/2s/5s/10s stepped backoff. */
105
+ export function realtimeReconnectDelayMs(tries, random = Math.random) {
106
+ const attempt = Math.max(1, Math.floor(tries || 1));
107
+ const baseMs = REALTIME_RECONNECT_BASE_MS[attempt - 1] ?? REALTIME_RECONNECT_FALLBACK_MS;
108
+ return jitterAround(baseMs, random);
109
+ }
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);
114
+ }
65
115
  // auth-js compares token expiry against this device's own Date.now(), with no
66
116
  // clock-skew tolerance — a fast clock treats every fresh token as expired and
67
117
  // refreshes forever (confirmed in prod on one device, via at least 3 separate
@@ -114,6 +164,12 @@ export class RemoteChannel {
114
164
  this.heartbeatDeviceId = null;
115
165
  // Single-slot queue keeping concurrent `status` PATCHes in order.
116
166
  this.statusWriteChain = Promise.resolve();
167
+ /**
168
+ * Answers whether the local execution child is alive. Default yes, so a
169
+ * RemoteChannel used without a device (tests, other callers) behaves as
170
+ * before; MCPDevice installs the real probe.
171
+ */
172
+ this.localExecutorProbe = () => true;
117
173
  /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
118
174
  this.lastKnownSession = null;
119
175
  /** Notified when auth-js rotates the session; the device persists it. */
@@ -135,6 +191,12 @@ export class RemoteChannel {
135
191
  this.presenceTracked = false;
136
192
  /** Last capability value written (null = never), to avoid redundant writes. */
137
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;
138
200
  /** Re-entrancy guard: on a wedged socket each track() buffers for the full
139
201
  * 10s push timeout, so 10s health ticks would stack pushes. */
140
202
  this.isTrackingPresence = false;
@@ -165,6 +227,7 @@ export class RemoteChannel {
165
227
  auth: { autoRefreshToken: false },
166
228
  global: { fetch: clockAwareFetch },
167
229
  realtime: {
230
+ reconnectAfterMs: realtimeReconnectDelayMs,
168
231
  // supabase-js's resolver ends in `?? supabaseKey`, so after SIGNED_OUT
169
232
  // the socket silently re-pins to the anon key and every private-channel
170
233
  // join is refused. Overriding under `realtime` (not the top-level
@@ -195,6 +258,14 @@ export class RemoteChannel {
195
258
  catch { /* no onHeartbeat on this client version: staleness check stays inert */ }
196
259
  }
197
260
  }
261
+ /**
262
+ * Teach the channel how to ask whether the local executor is alive.
263
+ * `status` is a claim that this device will run a tool call right now, and
264
+ * a joined channel alone cannot support that claim - issue #4.
265
+ */
266
+ setLocalExecutorProbe(probe) {
267
+ this.localExecutorProbe = probe;
268
+ }
198
269
  /**
199
270
  * Register a callback fired when auth-js rotates the session. auth-js
200
271
  * rotates the refresh token on every refresh and the previous one is spent,
@@ -420,15 +491,30 @@ export class RemoteChannel {
420
491
  console.debug('[DEBUG] Existing device found:', !!existingDevice);
421
492
  }
422
493
  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',
494
+ 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.
503
+ const { error: registrationError } = await this.updateDevice(existingDevice.id, {
504
+ status: 'offline',
428
505
  last_seen: new Date().toISOString(),
429
506
  capabilities: this.capabilitiesPayload(false),
430
507
  device_name: deviceName
431
508
  });
509
+ // updateDevice() logs and returns its error rather than throwing.
510
+ // Opening the channel anyway would leave a row that still says
511
+ // whatever the last run left there — including 'online' — while
512
+ // nothing here can correct it: the channel's own error path queues
513
+ // an offline write, and setOnlineStatus() only logs when that write
514
+ // fails too. Stop before the channel instead.
515
+ if (registrationError) {
516
+ throw new Error(`Failed to register device: ${registrationError.message}`);
517
+ }
432
518
  // Store parameters for channel recreation
433
519
  this.deviceId = existingDevice.id;
434
520
  this.deviceName = deviceName;
@@ -436,9 +522,13 @@ export class RemoteChannel {
436
522
  console.debug(`⏳ Subscribing to tool call channel...`);
437
523
  // Create and subscribe to the channel
438
524
  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
- });
525
+ // Let a failed join reach the caller. createChannel() resolves only
526
+ // once the channel is joined AND presence is published — the two
527
+ // things dispatch needs — so swallowing its rejection here was what
528
+ // let device.ts print "Device ready" over a device that cannot
529
+ // receive a single command. The caller decides what to do with it;
530
+ // it is not fatal, the socket watchdog keeps retrying.
531
+ await this.createChannel();
442
532
  }
443
533
  else {
444
534
  console.error(` - ❌ Device not found: ${currentDeviceId}`);
@@ -463,6 +553,10 @@ export class RemoteChannel {
463
553
  }
464
554
  }
465
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;
466
560
  for (let attempt = 1; attempt <= attempts; attempt++) {
467
561
  if (!this.channel || this.channel.state !== 'joined')
468
562
  return;
@@ -479,25 +573,86 @@ export class RemoteChannel {
479
573
  status = `threw: ${trackErr?.message}`;
480
574
  }
481
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
+ }
482
612
  this.presenceTracked = true;
613
+ this.presenceFailureStartedAt = null;
483
614
  console.log(`👋 Presence tracked (device ${this.deviceId} visible as online)`);
484
615
  // Reconnect attempts preceding this join (0 on a first join).
485
616
  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);
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
+ });
489
628
  return;
490
629
  }
491
630
  console.error(`❌ Presence track not acknowledged (${status}) — attempt ${attempt}/${attempts}`);
492
631
  if (attempt < attempts)
493
- await this.sleep(500 * attempt);
632
+ await this.sleep(presenceRetryDelayMs(attempt));
494
633
  }
495
634
  this.presenceTracked = false;
496
- console.error('❌ Presence track failed after retries — withdrawing broadcast capability');
497
635
  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.
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`);
651
+ return;
652
+ }
653
+ }
654
+ this.presenceFailureStartedAt = null;
655
+ console.error('❌ Presence track remained unavailable — withdrawing broadcast capability');
501
656
  await this.setTransportCapable(false);
502
657
  }
503
658
  /**
@@ -514,21 +669,45 @@ export class RemoteChannel {
514
669
  * Advertise (or withdraw) the broadcast capability. Only true while genuinely
515
670
  * reachable that way — the server fails dispatch fast without it and picks
516
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.
517
678
  */
518
- async setTransportCapable(capable) {
679
+ setTransportCapable(capable) {
519
680
  if (!this.client || !this.deviceId)
520
- return;
521
- if (this.transportCapableWritten === capable)
522
- return; // no redundant writes
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;
523
698
  try {
524
699
  const capabilities = this.capabilitiesPayload(capable);
525
700
  const { error } = await this.client
526
701
  .from('mcp_devices')
527
702
  .update({ capabilities })
528
- .eq('id', this.deviceId);
703
+ .eq('id', this.deviceId)
704
+ .abortSignal(this.deviceRowWriteSignal());
529
705
  if (error) {
530
706
  console.error('[DEBUG] Failed to update transport capability:', error.message);
531
- return;
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;
532
711
  }
533
712
  this.transportCapableWritten = capable;
534
713
  console.debug(`[DEBUG] Transport capability set to ${capable ? 'broadcast_v1' : 'withdrawn'}`);
@@ -543,7 +722,14 @@ export class RemoteChannel {
543
722
  }
544
723
  catch (error) {
545
724
  console.error('[DEBUG] Transport capability update threw:', error?.message);
725
+ this.transportCapableWritten = null;
726
+ return false;
546
727
  }
728
+ return true;
729
+ }
730
+ /** Aborts one write to this device's row after DEVICE_ROW_WRITE_TIMEOUT_MS (a method, so tests can shorten it). */
731
+ deviceRowWriteSignal() {
732
+ return AbortSignal.timeout(DEVICE_ROW_WRITE_TIMEOUT_MS);
547
733
  }
548
734
  /** Create and subscribe the private channel (initial join and recreation). */
549
735
  createChannel() {
@@ -566,6 +752,10 @@ export class RemoteChannel {
566
752
  }
567
753
  })
568
754
  .on('broadcast', { event: 'new_call' }, ({ payload }) => {
755
+ if (!this.shuttingDown) {
756
+ observeTransport({ stage: 'received', payload, deviceId: this.deviceId,
757
+ userId: this.user?.id, transport: 'broadcast' });
758
+ }
569
759
  this.onDoorbell(payload).catch((e) => {
570
760
  console.error('[DEBUG] Doorbell handling failed:', e?.message);
571
761
  });
@@ -578,16 +768,21 @@ export class RemoteChannel {
578
768
  this.reconnectAttempt = 0;
579
769
  this.lastHeartbeatOkAt = performance.now(); // a fresh join is proof of life too
580
770
  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.
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.
588
781
  this.trackPresenceWithRetry(recovered)
589
782
  .catch(() => { })
590
- .finally(() => resolve());
783
+ .finally(() => this.presenceTracked
784
+ ? resolve()
785
+ : reject(new ChannelUnreachableError('channel joined but presence was never acknowledged, so no command can be delivered')));
591
786
  }
592
787
  else if (status === 'CHANNEL_ERROR') {
593
788
  // CHANNEL_ERROR is the only status carrying a real error message.
@@ -597,24 +792,69 @@ export class RemoteChannel {
597
792
  // Fires on ordinary network faults too — filter on the
598
793
  // error text to isolate an 008 misconfiguration.
599
794
  captureRemote('remote_channel_subscription_error', { error: err?.message || 'Channel error' }).catch(() => { });
600
- reject(err || new Error('Failed to initialize tool call channel subscription'));
795
+ reject(new ChannelUnreachableError(err?.message || 'failed to subscribe to the tool call channel'));
601
796
  }
602
797
  else if (status === 'TIMED_OUT') {
603
798
  console.error(`⏱️ Channel subscription timed out, Reconnecting... — ${this.connState()}`);
604
799
  this.syncReachabilityStatus();
605
800
  captureRemote('remote_channel_subscription_timeout', { attempt: this.reconnectAttempt }).catch(() => { });
606
- reject(new Error('Tool call channel subscription timed out'));
801
+ reject(new ChannelUnreachableError('tool call channel subscription timed out'));
607
802
  }
608
803
  else if (status === 'CLOSED') {
609
804
  // Settle the promise so an in-flight recreateChannel() can't await
610
805
  // forever (which would wedge the re-entrancy guard / watchdog).
611
806
  console.warn(`⚠️ Channel closed — ${this.connState()}`);
612
807
  this.syncReachabilityStatus();
613
- reject(new Error('Tool call channel closed during subscribe'));
808
+ reject(new ChannelUnreachableError('tool call channel closed during subscribe'));
614
809
  }
615
810
  });
616
811
  });
617
812
  }
813
+ /**
814
+ * Recover calls whose Realtime doorbell was missed while this device was
815
+ * disconnected. Broadcast provides the fast path; the DB row is the source
816
+ * of truth. Only still-live pending rows for this device are considered.
817
+ *
818
+ * The follow-up onDoorbell() call performs the existing conditional claim,
819
+ * which makes this safe against a doorbell arriving at the same time.
820
+ */
821
+ async recoverPendingCalls() {
822
+ if (!this.client || !this.deviceId || !this.isReachable())
823
+ 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
+ const { data: pending, error } = await this.client
828
+ .from('mcp_remote_calls')
829
+ .select('id,device_id')
830
+ .eq('device_id', this.deviceId)
831
+ .eq('status', 'pending')
832
+ .gt('timeout_at', now)
833
+ .order('created_at', { ascending: true })
834
+ .limit(PENDING_RECOVERY_BATCH_SIZE);
835
+ if (error) {
836
+ console.error('[DEBUG] Failed to query pending calls after reconnect:', error.message);
837
+ await captureRemote('remote_channel_pending_recovery_error', { error });
838
+ return;
839
+ }
840
+ if (!pending?.length)
841
+ return;
842
+ console.log(`♻️ Recovering ${pending.length} pending remote call${pending.length === 1 ? '' : 's'} after reconnect`);
843
+ captureRemote('remote_channel_pending_recovery', {
844
+ pending_count: pending.length,
845
+ batch_capped: pending.length === PENDING_RECOVERY_BATCH_SIZE,
846
+ }).catch(() => { });
847
+ // Claim quickly; dispatchToolCall() does not await tool execution, so
848
+ // this loop serializes only the small REST claim operations.
849
+ for (const row of pending) {
850
+ if (!this.isReachable())
851
+ break;
852
+ await this.onDoorbell({
853
+ call_id: row.id,
854
+ device_id: row.device_id,
855
+ });
856
+ }
857
+ }
618
858
  /** Hand a call to device.ts, observing the rejection — the handler is async
619
859
  * and an unhandled rejection terminates the process. */
620
860
  dispatchToolCall(payload) {
@@ -662,6 +902,7 @@ export class RemoteChannel {
662
902
  .eq('id', callId)
663
903
  .eq('device_id', this.deviceId)
664
904
  .eq('status', 'pending')
905
+ .gt('timeout_at', new Date(Date.now()).toISOString())
665
906
  .select('*');
666
907
  if (!error) {
667
908
  row = data?.[0] ?? null;
@@ -696,8 +937,11 @@ export class RemoteChannel {
696
937
  await captureRemote('remote_channel_doorbell_fetch_error', { error });
697
938
  return;
698
939
  }
699
- if (current?.status === 'pending') {
700
- // No claim landed; device.ts claims it.
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.
701
945
  this.dispatchToolCall({ new: current });
702
946
  }
703
947
  else {
@@ -916,8 +1160,9 @@ export class RemoteChannel {
916
1160
  await this.withTimeout(() => this.setTransportCapable(false), CAPABILITY_WRITE_TIMEOUT_MS, 'withdrawTransportCapability');
917
1161
  }
918
1162
  catch (withdrawErr) {
919
- // The next failed recreate retries; the flag only advances
920
- // on a confirmed write, so nothing is lost.
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.
921
1166
  console.debug(`[DEBUG] Capability withdrawal did not complete: ${withdrawErr?.message}`);
922
1167
  }
923
1168
  }
@@ -942,6 +1187,7 @@ export class RemoteChannel {
942
1187
  .update({ status: 'executing' })
943
1188
  .eq('id', callId)
944
1189
  .eq('status', 'pending')
1190
+ .gt('timeout_at', new Date(Date.now()).toISOString())
945
1191
  .select('id');
946
1192
  if (error) {
947
1193
  console.error('[DEBUG] Failed to mark call executing:', error.message);
@@ -1004,18 +1250,31 @@ export class RemoteChannel {
1004
1250
  console.debug('[DEBUG] Call result updated successfully:', callId);
1005
1251
  }
1006
1252
  }
1007
- /** Reachable means the private channel is joined. Gates the heartbeat and `status`. */
1253
+ /**
1254
+ * 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`.
1259
+ */
1008
1260
  isReachable() {
1009
- return this.channel?.state === 'joined';
1261
+ return this.channel?.state === 'joined'
1262
+ && this.presenceTracked
1263
+ && this.localExecutorProbe();
1010
1264
  }
1011
1265
  /**
1012
1266
  * Set `status` from actual reachability. `status` is transport-agnostic (the
1013
1267
  * server filters on it), so it must not follow one channel's health — the
1014
1268
  * private channel's error path re-fires on every rejoin and would oscillate
1015
1269
  * the row against the heartbeat. Same predicate as the heartbeat gate.
1270
+ *
1271
+ * Every transition belongs here rather than calling setOnlineStatus(), which
1272
+ * is the write and not the decision. Public so the device can route its
1273
+ * recovery transition through the predicate too.
1016
1274
  */
1275
+ /** Resolves with whether the row actually took the write. */
1017
1276
  syncReachabilityStatus() {
1018
- this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1277
+ return this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1019
1278
  }
1020
1279
  /**
1021
1280
  * Serialize the channel-callback status writes. They fire from un-awaited
@@ -1030,13 +1289,18 @@ export class RemoteChannel {
1030
1289
  // After teardown begins, setOffline() owns the final status write.
1031
1290
  if (this.shuttingDown) {
1032
1291
  console.debug(`[DEBUG] Status write '${status}' suppressed — teardown in progress`);
1033
- return;
1292
+ return Promise.resolve(false);
1034
1293
  }
1035
- this.statusWriteChain = this.statusWriteChain
1036
- .then(() => (this.deviceId ? this.setOnlineStatus(this.deviceId, status) : undefined))
1294
+ // The chain only sequences the writes; whether one landed goes back
1295
+ // to whoever asked, so readiness can depend on it.
1296
+ const write = this.statusWriteChain
1297
+ .then(() => (this.deviceId ? this.setOnlineStatus(this.deviceId, status) : false))
1037
1298
  .catch((e) => {
1038
1299
  console.error('[DEBUG] Status write failed:', e?.message);
1300
+ return false;
1039
1301
  });
1302
+ this.statusWriteChain = write.then(() => undefined);
1303
+ return write;
1040
1304
  }
1041
1305
  /**
1042
1306
  * Heartbeat cadence for the tier this device is CURRENTLY in. Follows the
@@ -1159,9 +1423,10 @@ export class RemoteChannel {
1159
1423
  }
1160
1424
  this.stopTokenRefresh();
1161
1425
  }
1426
+ /** @returns whether the row actually took the write. */
1162
1427
  async setOnlineStatus(deviceId, status) {
1163
1428
  if (!this.client)
1164
- return;
1429
+ return false;
1165
1430
  // Only log if status changed
1166
1431
  if (this.lastDeviceStatus !== status) {
1167
1432
  console.log(`🔌 Device marked as ${status}`);
@@ -1170,18 +1435,20 @@ export class RemoteChannel {
1170
1435
  const { error } = await this.client
1171
1436
  .from('mcp_devices')
1172
1437
  .update({ status: status, last_seen: new Date().toISOString() })
1173
- .eq('id', deviceId);
1438
+ .eq('id', deviceId)
1439
+ .abortSignal(this.deviceRowWriteSignal());
1174
1440
  if (error) {
1175
1441
  console.error(`[DEBUG] Failed to set status ${status}:`, error.message);
1176
1442
  if (status == "online") {
1177
1443
  console.error('Failed to update device status:', error.message);
1178
1444
  }
1179
1445
  await captureRemote('remote_channel_status_update_error', { error, status });
1180
- return;
1446
+ return false;
1181
1447
  }
1182
1448
  else {
1183
1449
  console.debug(`[DEBUG] Device status set to ${status}`);
1184
1450
  }
1451
+ return true;
1185
1452
  // console.log(status === 'online' ? `🔌 Device marked as ${status}` : `❌ Device marked as ${status}`);
1186
1453
  }
1187
1454
  async setOffline(deviceId) {
@@ -1229,7 +1496,9 @@ export class RemoteChannel {
1229
1496
  const scriptPath = path.join(__dirname, 'scripts', 'blocking-offline-update.js');
1230
1497
  console.debug('[DEBUG] Spawning blocking update script:', scriptPath);
1231
1498
  console.debug('[DEBUG] Using node executable:', process.execPath);
1232
- const result = spawnSync('node', [
1499
+ // The node running this device, by its full path: a bare 'node' is
1500
+ // looked up in the working folder first on Windows
1501
+ const result = spawnSync(process.execPath, [
1233
1502
  scriptPath,
1234
1503
  deviceId,
1235
1504
  supabaseUrl,