@wonderwhy-er/desktop-commander 0.3.1-alpha.2 → 0.3.2-alpha.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 (234) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +1154 -1152
  3. package/dist/bootstrap.js +0 -0
  4. package/dist/bootstrap.js.map +1 -0
  5. package/dist/command-manager.js +0 -0
  6. package/dist/command-manager.js.map +1 -0
  7. package/dist/config-field-definitions.js +0 -0
  8. package/dist/config-field-definitions.js.map +1 -0
  9. package/dist/config-manager.js +0 -0
  10. package/dist/config-manager.js.map +1 -0
  11. package/dist/config-recovery.js +0 -0
  12. package/dist/config-recovery.js.map +1 -0
  13. package/dist/config.js +0 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/custom-stdio.js +0 -0
  16. package/dist/custom-stdio.js.map +1 -0
  17. package/dist/data/onboarding-prompts.json +70 -70
  18. package/dist/error-handlers.js +0 -0
  19. package/dist/error-handlers.js.map +1 -0
  20. package/dist/handlers/edit-search-handlers.js.map +1 -0
  21. package/dist/handlers/filesystem-handlers.js +2 -2
  22. package/dist/handlers/filesystem-handlers.js.map +1 -0
  23. package/dist/handlers/history-handlers.js.map +1 -0
  24. package/dist/handlers/index.js.map +1 -0
  25. package/dist/handlers/process-handlers.js.map +1 -0
  26. package/dist/handlers/search-answers.js.map +1 -0
  27. package/dist/handlers/search-handlers.js.map +1 -0
  28. package/dist/handlers/terminal-handlers.js.map +1 -0
  29. package/dist/index.js +0 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/npm-scripts/remote.js +32 -28
  32. package/dist/npm-scripts/remote.js.map +1 -0
  33. package/dist/npm-scripts/setup.js.map +1 -0
  34. package/dist/npm-scripts/uninstall.js.map +1 -0
  35. package/dist/npm-scripts/verify-ripgrep.js.map +1 -0
  36. package/dist/remote-device/desktop-commander-integration.d.ts +1 -0
  37. package/dist/remote-device/desktop-commander-integration.js.map +1 -0
  38. package/dist/remote-device/device-authenticator.js.map +1 -0
  39. package/dist/remote-device/device.d.ts +4 -3
  40. package/dist/remote-device/device.js +134 -35
  41. package/dist/remote-device/device.js.map +1 -0
  42. package/dist/remote-device/diagnostics/device-log.js.map +1 -0
  43. package/dist/remote-device/diagnostics/redact.js.map +1 -0
  44. package/dist/remote-device/diagnostics/report.js +2 -1
  45. package/dist/remote-device/diagnostics/report.js.map +1 -0
  46. package/dist/remote-device/diagnostics/upload.d.ts +1 -1
  47. package/dist/remote-device/diagnostics/upload.js +3 -3
  48. package/dist/remote-device/diagnostics/upload.js.map +1 -0
  49. package/dist/remote-device/mqtt/config.d.ts +1 -0
  50. package/dist/remote-device/mqtt/config.js +3 -0
  51. package/dist/remote-device/mqtt/config.js.map +1 -0
  52. package/dist/remote-device/mqtt/mqtt-enrollment.d.ts +15 -0
  53. package/dist/remote-device/mqtt/mqtt-enrollment.js +293 -0
  54. package/dist/remote-device/mqtt/mqtt-enrollment.js.map +1 -0
  55. package/dist/remote-device/mqtt/mqtt-transport.d.ts +45 -0
  56. package/dist/remote-device/mqtt/mqtt-transport.js +276 -0
  57. package/dist/remote-device/mqtt/mqtt-transport.js.map +1 -0
  58. package/dist/remote-device/realtime-health-telemetry.d.ts +35 -0
  59. package/dist/remote-device/realtime-health-telemetry.js +110 -0
  60. package/dist/remote-device/realtime-health-telemetry.js.map +1 -0
  61. package/dist/remote-device/remote-channel.d.ts +87 -59
  62. package/dist/remote-device/remote-channel.js +509 -398
  63. package/dist/remote-device/remote-channel.js.map +1 -0
  64. package/dist/remote-device/remote-utils.d.ts +3 -0
  65. package/dist/remote-device/remote-utils.js +20 -0
  66. package/dist/remote-device/remote-utils.js.map +1 -0
  67. package/dist/remote-device/rollouts.d.ts +48 -0
  68. package/dist/remote-device/rollouts.js +105 -0
  69. package/dist/remote-device/rollouts.js.map +1 -0
  70. package/dist/remote-device/scripts/blocking-offline-update.js +135 -133
  71. package/dist/remote-device/transport-telemetry.d.ts +1 -1
  72. package/dist/remote-device/transport-telemetry.js +4 -2
  73. package/dist/remote-device/transport-telemetry.js.map +1 -0
  74. package/dist/search-manager.js +0 -0
  75. package/dist/search-manager.js.map +1 -0
  76. package/dist/server.js +581 -712
  77. package/dist/server.js.map +1 -0
  78. package/dist/setup-claude-server.js +942 -942
  79. package/dist/terminal-manager.js +2 -37
  80. package/dist/terminal-manager.js.map +1 -0
  81. package/dist/tools/config.js.map +1 -0
  82. package/dist/tools/edit.js +2 -2
  83. package/dist/tools/edit.js.map +1 -0
  84. package/dist/tools/feedback.js.map +1 -0
  85. package/dist/tools/filesystem.js.map +1 -0
  86. package/dist/tools/fuzzySearch.js +9 -9
  87. package/dist/tools/fuzzySearch.js.map +1 -0
  88. package/dist/tools/fuzzySearchCore.js.map +1 -0
  89. package/dist/tools/improved-process-tools.js +12 -11
  90. package/dist/tools/improved-process-tools.js.map +1 -0
  91. package/dist/tools/mime-types.js.map +1 -0
  92. package/dist/tools/pdf/extract-images.js +2 -6
  93. package/dist/tools/pdf/extract-images.js.map +1 -0
  94. package/dist/tools/pdf/index.js.map +1 -0
  95. package/dist/tools/pdf/lib/pdf2md.js +28 -33
  96. package/dist/tools/pdf/lib/pdf2md.js.map +1 -0
  97. package/dist/tools/pdf/manipulations.js.map +1 -0
  98. package/dist/tools/pdf/markdown.d.ts +10 -38
  99. package/dist/tools/pdf/markdown.js.map +1 -0
  100. package/dist/tools/pdf/utils.d.ts +10 -0
  101. package/dist/tools/pdf/utils.js +11 -0
  102. package/dist/tools/pdf/utils.js.map +1 -0
  103. package/dist/tools/process.js.map +1 -0
  104. package/dist/tools/prompts.js +1 -1
  105. package/dist/tools/prompts.js.map +1 -0
  106. package/dist/tools/schemas.d.ts +0 -10
  107. package/dist/tools/schemas.js +0 -8
  108. package/dist/tools/schemas.js.map +1 -0
  109. package/dist/tools/usage.js.map +1 -0
  110. package/dist/track-installation.js +387 -387
  111. package/dist/types.js +0 -0
  112. package/dist/types.js.map +1 -0
  113. package/dist/ui/config-editor/config-editor-runtime.js +61 -80
  114. package/dist/ui/config-editor/index.html +13 -13
  115. package/dist/ui/config-editor/src/app.js +30 -30
  116. package/dist/ui/config-editor/src/app.js.map +1 -0
  117. package/dist/ui/config-editor/src/array-modal.js +32 -32
  118. package/dist/ui/config-editor/src/array-modal.js.map +1 -0
  119. package/dist/ui/config-editor/src/main.js.map +1 -0
  120. package/dist/ui/config-editor/styles.css +586 -586
  121. package/dist/ui/contracts.d.ts +27 -0
  122. package/dist/ui/contracts.js +36 -0
  123. package/dist/ui/contracts.js.map +1 -0
  124. package/dist/ui/file-preview/index.html +16 -16
  125. package/dist/ui/file-preview/preview-runtime.js +221 -231
  126. package/dist/ui/file-preview/shared/preview-file-types.js.map +1 -0
  127. package/dist/ui/file-preview/src/app.js +8 -8
  128. package/dist/ui/file-preview/src/app.js.map +1 -0
  129. package/dist/ui/file-preview/src/components/code-viewer.js.map +1 -0
  130. package/dist/ui/file-preview/src/components/highlighting.js.map +1 -0
  131. package/dist/ui/file-preview/src/components/html-renderer.js +4 -2
  132. package/dist/ui/file-preview/src/components/html-renderer.js.map +1 -0
  133. package/dist/ui/file-preview/src/components/markdown-renderer.js.map +1 -0
  134. package/dist/ui/file-preview/src/directory-controller.js.map +1 -0
  135. package/dist/ui/file-preview/src/document-layout.js +31 -31
  136. package/dist/ui/file-preview/src/document-layout.js.map +1 -0
  137. package/dist/ui/file-preview/src/document-outline.js +8 -8
  138. package/dist/ui/file-preview/src/document-outline.js.map +1 -0
  139. package/dist/ui/file-preview/src/document-workspace.js.map +1 -0
  140. package/dist/ui/file-preview/src/file-type-handlers.js.map +1 -0
  141. package/dist/ui/file-preview/src/host/external-actions.js.map +1 -0
  142. package/dist/ui/file-preview/src/host/selection-context.js.map +1 -0
  143. package/dist/ui/file-preview/src/image-preview.js.map +1 -0
  144. package/dist/ui/file-preview/src/main.js.map +1 -0
  145. package/dist/ui/file-preview/src/markdown/conflict-dialog.js +33 -33
  146. package/dist/ui/file-preview/src/markdown/conflict-dialog.js.map +1 -0
  147. package/dist/ui/file-preview/src/markdown/controller.js +9 -9
  148. package/dist/ui/file-preview/src/markdown/controller.js.map +1 -0
  149. package/dist/ui/file-preview/src/markdown/editor.js +31 -31
  150. package/dist/ui/file-preview/src/markdown/editor.js.map +1 -0
  151. package/dist/ui/file-preview/src/markdown/linking.js.map +1 -0
  152. package/dist/ui/file-preview/src/markdown/outline.js.map +1 -0
  153. package/dist/ui/file-preview/src/markdown/parser.js.map +1 -0
  154. package/dist/ui/file-preview/src/markdown/preview.js.map +1 -0
  155. package/dist/ui/file-preview/src/markdown/slugify.js.map +1 -0
  156. package/dist/ui/file-preview/src/markdown/utils.js.map +1 -0
  157. package/dist/ui/file-preview/src/model.js.map +1 -0
  158. package/dist/ui/file-preview/src/panel-actions.js.map +1 -0
  159. package/dist/ui/file-preview/src/path-utils.js.map +1 -0
  160. package/dist/ui/file-preview/src/payload-utils.js.map +1 -0
  161. package/dist/ui/file-preview/src/types.js.map +1 -0
  162. package/dist/ui/file-preview/styles.css +1630 -1630
  163. package/dist/ui/resources.js +11 -4
  164. package/dist/ui/resources.js.map +1 -0
  165. package/dist/ui/shared/compact-row.js.map +1 -0
  166. package/dist/ui/shared/escape-html.js.map +1 -0
  167. package/dist/ui/shared/host-context.js.map +1 -0
  168. package/dist/ui/shared/tool-bridge.js.map +1 -0
  169. package/dist/ui/shared/tool-shell.js.map +1 -0
  170. package/dist/ui/shared/ui-event-tracker.js.map +1 -0
  171. package/dist/ui/shared/widget-state.js.map +1 -0
  172. package/dist/uninstall-claude-server.js +745 -745
  173. package/dist/utils/ab-test.js.map +1 -0
  174. package/dist/utils/atomic-write.js.map +1 -0
  175. package/dist/utils/capture.d.ts +1 -1
  176. package/dist/utils/capture.js +28 -6
  177. package/dist/utils/capture.js.map +1 -0
  178. package/dist/utils/dockerPrompt.js.map +1 -0
  179. package/dist/utils/exit-process.js.map +1 -0
  180. package/dist/utils/feature-flags.js.map +1 -0
  181. package/dist/utils/files/base.js.map +1 -0
  182. package/dist/utils/files/binary.js +4 -4
  183. package/dist/utils/files/binary.js.map +1 -0
  184. package/dist/utils/files/docx.js.map +1 -0
  185. package/dist/utils/files/excel.js +3 -3
  186. package/dist/utils/files/excel.js.map +1 -0
  187. package/dist/utils/files/factory.js.map +1 -0
  188. package/dist/utils/files/image.js.map +1 -0
  189. package/dist/utils/files/index.js.map +1 -0
  190. package/dist/utils/files/pdf.js.map +1 -0
  191. package/dist/utils/files/text.d.ts +7 -0
  192. package/dist/utils/files/text.js +40 -21
  193. package/dist/utils/files/text.js.map +1 -0
  194. package/dist/utils/fuzzySearchLogger.js.map +1 -0
  195. package/dist/utils/internal-facts.js.map +1 -0
  196. package/dist/utils/lazy-package.js.map +1 -0
  197. package/dist/utils/lineEndingHandler.js.map +1 -0
  198. package/dist/utils/logger.js.map +1 -0
  199. package/dist/utils/mcp-ui-ab-test.js.map +1 -0
  200. package/dist/utils/open-browser.js.map +1 -0
  201. package/dist/utils/process-detection.js.map +1 -0
  202. package/dist/utils/process-tree.js.map +1 -0
  203. package/dist/utils/rename.js.map +1 -0
  204. package/dist/utils/ripgrep-resolver.js.map +1 -0
  205. package/dist/utils/shell.d.ts +11 -0
  206. package/dist/utils/shell.js +50 -0
  207. package/dist/utils/shell.js.map +1 -0
  208. package/dist/utils/system-info.d.ts +1 -0
  209. package/dist/utils/system-info.js +110 -97
  210. package/dist/utils/system-info.js.map +1 -0
  211. package/dist/utils/terminal-timestamps.d.ts +2 -0
  212. package/dist/utils/terminal-timestamps.js +18 -0
  213. package/dist/utils/terminal-timestamps.js.map +1 -0
  214. package/dist/utils/toolHistory.js.map +1 -0
  215. package/dist/utils/trackTools.js.map +1 -0
  216. package/dist/utils/unsupportedParams.js.map +1 -0
  217. package/dist/utils/usageTracker.d.ts +0 -39
  218. package/dist/utils/usageTracker.js +16 -176
  219. package/dist/utils/usageTracker.js.map +1 -0
  220. package/dist/utils/welcome-onboarding.js.map +1 -0
  221. package/dist/utils/withTimeout.js.map +1 -0
  222. package/dist/version.d.ts +1 -1
  223. package/dist/version.js +1 -1
  224. package/dist/version.js.map +1 -0
  225. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -56
  226. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -32
  227. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +39 -38
  228. package/node_modules/@desktop-commander/telemetry-contract/transport.js +167 -164
  229. package/package.json +11 -10
  230. package/vendor/telemetry-contract/README.md +56 -56
  231. package/vendor/telemetry-contract/package.json +32 -32
  232. package/vendor/telemetry-contract/transport.d.ts +38 -38
  233. package/vendor/telemetry-contract/transport.js +164 -164
  234. package/vendor/telemetry-contract/transport.test.js +39 -39
@@ -1,7 +1,11 @@
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';
7
+ import { MqttTransport } from './mqtt/mqtt-transport.js';
8
+ import { enrollMqttDevice } from './mqtt/mqtt-enrollment.js';
5
9
  const NUL_CHAR = String.fromCharCode(0);
6
10
  const NUL_RE = new RegExp(NUL_CHAR, 'g');
7
11
  /**
@@ -31,7 +35,7 @@ export function stripNullBytes(value) {
31
35
  }
32
36
  /**
33
37
  * The device registered, but its realtime channel is not usable — the join
34
- * failed, or presence was never acknowledged. Distinct from every other
38
+ * failed, or the device row could not be marked ready. Distinct from every other
35
39
  * registration failure on purpose: this one the socket watchdog can repair, so
36
40
  * the caller keeps the process alive, while a failed lookup or a missing row
37
41
  * happens before the recreation parameters are stored and nothing can repair it.
@@ -42,26 +46,34 @@ export class ChannelUnreachableError extends Error {
42
46
  this.name = 'ChannelUnreachableError';
43
47
  }
44
48
  }
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;
49
+ // last_seen cadence. Must stay under the server's 15 min offline sweep and the
50
+ // dashboard's ~7 min freshness window for the online dot.
51
+ export const HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000;
52
+ // Fast recovery for short Wi-Fi blips, but never retry every 10 seconds forever.
53
+ // Prolonged provider incidents must not keep the entire device fleet joining.
54
+ // Independent jitter spreads retry work; full jitter applies at attempt >= 5.
55
+ const REALTIME_RECONNECT_BASE_MS = [1000, 2000, 5000, 10000, 20000, 40000, 80000, 120000];
56
+ const REALTIME_RECONNECT_FALLBACK_MS = 120000;
57
+ const WATCHDOG_RECREATE_MAX_BACKOFF_MS = 120000;
58
+ // Presence is best effort (dashboard only): a failed track() waits this long,
59
+ // doubling, before the next one, since a track() timeout can end the channel.
60
+ const PRESENCE_RETRY_BASE_MS = 5 * 60 * 1000;
61
+ const PRESENCE_RETRY_MAX_MS = 60 * 60 * 1000;
62
+ // Failed readiness writes are retried sooner: dispatch waits on them.
63
+ const READINESS_RETRY_BASE_MS = 5000;
64
+ const READINESS_RETRY_MAX_MS = 60000;
62
65
  // 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).
66
+ // Must exceed createChannel()'s worst case: the join plus its status write,
67
+ // queued behind the teardown's 'offline' (~30s).
64
68
  const RECREATE_TIMEOUT_MS = 45000;
69
+ // Upper bound on the persistent unready-join budget. Anything >= 8 already
70
+ // selects the 120s SDK tier; the cap only keeps the counter meaningful.
71
+ const MAX_UNREADY_JOIN_BUDGET = 16;
72
+ // A channel that has stayed joined this long, with a heartbeat confirmed after
73
+ // the join, is a working broadcast path even if readiness is still pending.
74
+ // Its join no longer counts toward reconnect backoff. Comfortably longer than
75
+ // a join->error cycle (~10-30s) and covers at least four 25s heartbeats.
76
+ const STABLE_BROADCAST_RESET_MS = 120000;
65
77
  // Max continuous time in 'joining' before forcing a recreate — a half-open
66
78
  // socket parks the channel there forever, and a genuine join settles in ~10s.
67
79
  const JOINING_WEDGE_TIMEOUT_MS = 30000;
@@ -73,17 +85,10 @@ const HEARTBEAT_STALE_TIMEOUT_MS = 75000;
73
85
  const TOKEN_REFRESH_INTERVAL_MS = 45 * 60 * 1000;
74
86
  // Below this, skew is noise — leave Date.now untouched. Above it, correct.
75
87
  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.
88
+ // Cap on one status write to this device's row, after which it is aborted. A
89
+ // PATCH sent down a half-open connection is otherwise answered only by fetch's
90
+ // own 300 s headers timeout, and the write queue behind it, readiness
91
+ // included, waits as long.
87
92
  const DEVICE_ROW_WRITE_TIMEOUT_MS = 10000;
88
93
  // Cap on the shutdown session fetch, which races device.ts's 5s force-exit.
89
94
  const OFFLINE_SESSION_TIMEOUT_MS = 500;
@@ -101,16 +106,38 @@ function jitterAround(baseMs, random) {
101
106
  const sample = Math.max(0, Math.min(1, random()));
102
107
  return Math.max(1, Math.round(baseMs * (0.5 + sample)));
103
108
  }
104
- /** Jittered version of realtime-js's default 1s/2s/5s/10s stepped backoff. */
109
+ /** Exponential-ish SDK backoff. Attempts 1-4 preserve short recovery latency. */
105
110
  export function realtimeReconnectDelayMs(tries, random = Math.random) {
106
111
  const attempt = Math.max(1, Math.floor(tries || 1));
107
112
  const baseMs = REALTIME_RECONNECT_BASE_MS[attempt - 1] ?? REALTIME_RECONNECT_FALLBACK_MS;
113
+ if (attempt <= 4)
114
+ return jitterAround(baseMs, random);
115
+ // Full jitter is deliberately independent per device; floor avoids an immediate tight retry.
116
+ return Math.max(1000, Math.round(baseMs * Math.max(0, Math.min(1, random()))));
117
+ }
118
+ /** Watchdog must not defeat the SDK's slower persistent-failure backoff. */
119
+ export function watchdogRecreateDelayMs(tries, random = Math.random) {
120
+ const attempt = Math.max(1, Math.floor(tries || 1));
121
+ const baseMs = Math.min(WATCHDOG_RECREATE_MAX_BACKOFF_MS, 1000 * 2 ** Math.min(attempt, 7));
108
122
  return jitterAround(baseMs, random);
109
123
  }
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);
124
+ /** Doubling step after `failures` consecutive failures, capped at `maxMs`. */
125
+ function backoffStepMs(failures, baseMs, maxMs) {
126
+ const attempt = Math.max(1, Math.floor(failures || 1));
127
+ return Math.min(maxMs, baseMs * 2 ** Math.min(attempt - 1, 10));
128
+ }
129
+ /**
130
+ * Wait before the next track() after failed ones, across SDK rejoins and
131
+ * recreates. Never shorter than the step; up to 50% extra spreads the fleet.
132
+ */
133
+ export function presenceRecoveryDelayMs(failures, random = Math.random) {
134
+ const stepMs = backoffStepMs(failures, PRESENCE_RETRY_BASE_MS, PRESENCE_RETRY_MAX_MS);
135
+ return Math.round(stepMs * (1 + 0.5 * Math.max(0, Math.min(1, random()))));
136
+ }
137
+ /** Full-jitter wait before retrying the readiness write after failed ones. */
138
+ function readinessRetryDelayMs(failures, random = Math.random) {
139
+ const stepMs = backoffStepMs(failures, READINESS_RETRY_BASE_MS, READINESS_RETRY_MAX_MS);
140
+ return Math.max(1000, Math.round(stepMs * Math.max(0, Math.min(1, random()))));
114
141
  }
115
142
  // auth-js compares token expiry against this device's own Date.now(), with no
116
143
  // clock-skew tolerance — a fast clock treats every fresh token as expired and
@@ -155,13 +182,18 @@ async function clockAwareFetch(input, init) {
155
182
  return response;
156
183
  }
157
184
  export class RemoteChannel {
158
- constructor() {
185
+ /** SDK channel and socket timers share reconnectAfterMs. The persistent
186
+ * unready-join budget prevents a series of partial successes restarting at 1s. */
187
+ reconnectDelayMs(tries, random = Math.random) {
188
+ return realtimeReconnectDelayMs(Math.max(tries, this.consecutiveUnreadyJoins), random);
189
+ }
190
+ get user() { return this._user; }
191
+ constructor(enrollment) {
192
+ this.enrollment = enrollment;
159
193
  this.client = null;
160
194
  this.channel = null;
161
195
  this.heartbeatInterval = null;
162
196
  this.connectionCheckInterval = null;
163
- /** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
164
- this.heartbeatDeviceId = null;
165
197
  // Single-slot queue keeping concurrent `status` PATCHes in order.
166
198
  this.statusWriteChain = Promise.resolve();
167
199
  /**
@@ -180,26 +212,39 @@ export class RemoteChannel {
180
212
  /** Auth session gone for good: stops rejoins and caps the notice at one line. */
181
213
  this.sessionLost = false;
182
214
  this.handlingSignedOut = false;
215
+ this.mqttReceiver = null;
216
+ this.mqttReady = false;
217
+ this.mqttCapabilityWriteChain = Promise.resolve(true);
218
+ this.authGeneration = 0;
183
219
  // Store subscription parameters for channel recreation
184
220
  this.deviceId = null;
185
221
  this.deviceName = null;
186
222
  this.onToolCall = null;
187
223
  // Guard so setSession being called twice can't stack auth listeners.
188
224
  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. */
225
+ /** The current join's status write landed: dispatchable. Gates the
226
+ * heartbeat, so only that write first marks the row online. */
227
+ this.channelReady = false;
228
+ /** Readiness write in flight. Cleared on every join, so each join writes its own. */
229
+ this.readinessInFlight = null;
230
+ this.consecutiveReadinessFailures = 0;
231
+ this.nextReadinessAttemptAt = 0; // monotonic
232
+ /** Presence published on the current join. Dashboard only; never gates dispatch. */
191
233
  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
234
  /** Re-entrancy guard: on a wedged socket each track() buffers for the full
201
235
  * 10s push timeout, so 10s health ticks would stack pushes. */
202
236
  this.isTrackingPresence = false;
237
+ // The SDK resets its rejoin timer on *every* SUBSCRIBED, even if the join
238
+ // dies before it is ready. Count such joins across SDK/channel recreation.
239
+ // Reset once the readiness write succeeds.
240
+ this.consecutiveUnreadyJoins = 0;
241
+ this.consecutivePresenceFailures = 0;
242
+ this.nextPresenceAttemptAt = 0; // monotonic; independent of Date.now skew correction
243
+ /** performance.now() of the latest SUBSCRIBED; null while not joined. */
244
+ this.joinedAt = null;
245
+ this.realtimeHealth = new RealtimeHealthTelemetry((window) => {
246
+ captureRemote('remote_realtime_health_window', window).catch(() => { });
247
+ });
203
248
  // Track last device status to prevent duplicate log messages
204
249
  this.lastDeviceStatus = 'offline';
205
250
  // Track last channel state for debug logging
@@ -218,7 +263,6 @@ export class RemoteChannel {
218
263
  this.tokenRefreshInterval = null;
219
264
  this._user = null;
220
265
  }
221
- get user() { return this._user; }
222
266
  initialize(url, key) {
223
267
  // autoRefreshToken:false — we drive refresh ourselves (startTokenRefresh(),
224
268
  // see TOKEN_REFRESH_INTERVAL_MS) instead of auth-js's local-clock-driven
@@ -227,24 +271,12 @@ export class RemoteChannel {
227
271
  auth: { autoRefreshToken: false },
228
272
  global: { fetch: clockAwareFetch },
229
273
  realtime: {
230
- reconnectAfterMs: realtimeReconnectDelayMs,
274
+ reconnectAfterMs: (tries) => this.reconnectDelayMs(tries),
231
275
  // supabase-js's resolver ends in `?? supabaseKey`, so after SIGNED_OUT
232
276
  // the socket silently re-pins to the anon key and every private-channel
233
277
  // join is refused. Overriding under `realtime` (not the top-level
234
278
  // `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
- },
279
+ accessToken: () => this.getAccessToken(),
248
280
  },
249
281
  });
250
282
  if (!this.heartbeatListenerRegistered) {
@@ -278,6 +310,8 @@ export class RemoteChannel {
278
310
  async setSession(session) {
279
311
  if (!this.client)
280
312
  throw new Error('Client not initialized');
313
+ this.authGeneration++;
314
+ await this.stopMqttTransport();
281
315
  console.debug('[DEBUG] RemoteChannel.setSession() called, has refresh_token:', !!session.refresh_token);
282
316
  // setSession() already fetches the user from GoTrue (or refreshes), so no getUser() after it.
283
317
  const { data: { user }, error } = await this.client.auth.setSession({
@@ -285,13 +319,13 @@ export class RemoteChannel {
285
319
  refresh_token: session.refresh_token || ''
286
320
  });
287
321
  if (error) {
288
- console.error('[DEBUG] Failed to set session:', error.message);
322
+ console.error('[ERROR] Failed to set session:', error.message);
289
323
  await captureRemote('remote_channel_set_session_error', { error });
290
324
  return { error };
291
325
  }
292
326
  if (!user) {
293
327
  const noUserError = new Error('No user returned after setSession');
294
- console.error('[DEBUG] No user returned:', noUserError.message);
328
+ console.error('[ERROR] No user returned:', noUserError.message);
295
329
  await captureRemote('remote_channel_get_user_empty', {});
296
330
  throw noUserError;
297
331
  }
@@ -345,6 +379,7 @@ export class RemoteChannel {
345
379
  if (this.handlingSignedOut || this.sessionLost || this.shuttingDown)
346
380
  return;
347
381
  this.handlingSignedOut = true;
382
+ this.authGeneration++;
348
383
  try {
349
384
  const cached = this.lastKnownSession;
350
385
  if (cached?.refresh_token && this.client) {
@@ -391,10 +426,13 @@ export class RemoteChannel {
391
426
  console.debug(`[DEBUG] Session restore failed: ${restoreError?.message}`);
392
427
  }
393
428
  this.sessionLost = true;
429
+ await this.stopMqttTransport();
394
430
  await captureRemote('remote_channel_session_lost', {
395
431
  hadRefreshToken: !!cached?.refresh_token,
396
432
  });
397
433
  this.stopHeartbeat();
434
+ // Without a session the 30-minute rollouts request can only be refused
435
+ rolloutManager.stopRefresh();
398
436
  // Tear realtime down entirely, same as recreateChannel() does: sessionLost
399
437
  // only gates OUR health loop, while realtime-js keeps its own per-channel
400
438
  // rejoin timer (~10s cap) firing expired-JWT joins on the errored channel
@@ -433,6 +471,24 @@ export class RemoteChannel {
433
471
  throw new Error('Client not initialized');
434
472
  return await this.client.auth.getSession();
435
473
  }
474
+ /**
475
+ * The session's current access token, for the realtime socket and the
476
+ * device's own requests. getSession() may refresh on-demand when the token
477
+ * reads expired — that check is clock-skew-safe now (see clockAwareFetch
478
+ * above). Without a session it falls back to the last token known, and
479
+ * without that it is null, never the anon key.
480
+ */
481
+ async getAccessToken() {
482
+ try {
483
+ const { data } = await this.client.auth.getSession();
484
+ if (data.session?.access_token)
485
+ return data.session.access_token;
486
+ }
487
+ catch {
488
+ /* fall through to the cached token */
489
+ }
490
+ return this.lastKnownSession?.access_token ?? null;
491
+ }
436
492
  async findDevice(deviceId) {
437
493
  if (!this.client)
438
494
  throw new Error('Client not initialized');
@@ -492,18 +548,14 @@ export class RemoteChannel {
492
548
  }
493
549
  if (existingDevice) {
494
550
  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.
551
+ // The row may not claim reachability yet: dispatch picks its target
552
+ // by `status`, so a row marked online before the channel is up hands
553
+ // every call in that window to a device with no delivery path.
554
+ // SUBSCRIBED writes 'online'.
503
555
  const { error: registrationError } = await this.updateDevice(existingDevice.id, {
504
556
  status: 'offline',
505
- last_seen: new Date().toISOString(),
506
- capabilities: this.capabilitiesPayload(false),
557
+ last_seen: 'now',
558
+ capabilities: this.capabilitiesPayload(),
507
559
  device_name: deviceName
508
560
  });
509
561
  // updateDevice() logs and returns its error rather than throwing.
@@ -517,17 +569,26 @@ export class RemoteChannel {
517
569
  }
518
570
  // Store parameters for channel recreation
519
571
  this.deviceId = existingDevice.id;
572
+ this.realtimeHealth.setDevice(existingDevice.id);
520
573
  this.deviceName = deviceName;
521
574
  this.onToolCall = onToolCall;
522
575
  console.debug(`⏳ Subscribing to tool call channel...`);
523
576
  // Create and subscribe to the channel
524
577
  console.debug('[DEBUG] Calling createChannel()');
525
578
  // Let a failed join reach the caller. createChannel() resolves only
526
- // once the channel is joined AND presence is published — the two
579
+ // once the channel is joined AND the device row says so — the two
527
580
  // things dispatch needs — so swallowing its rejection here was what
528
581
  // let device.ts print "Device ready" over a device that cannot
529
582
  // receive a single command. The caller decides what to do with it;
530
583
  // it is not fatal, the socket watchdog keeps retrying.
584
+ // TODO: discuss with Mihails why he removed assertSessionStillActive
585
+ const generation = this.authGeneration;
586
+ const assertSessionStillActive = () => {
587
+ if (generation !== this.authGeneration || this.shuttingDown || this.sessionLost || this.handlingSignedOut) {
588
+ throw new Error('Device session changed during MQTT startup; restart the connector');
589
+ }
590
+ };
591
+ void this.startMqtt(assertSessionStillActive).catch(() => console.warn('[MQTT] Transport unavailable; Broadcast continues'));
531
592
  await this.createChannel();
532
593
  }
533
594
  else {
@@ -536,197 +597,235 @@ export class RemoteChannel {
536
597
  throw new Error(`Device not found: ${currentDeviceId}`);
537
598
  }
538
599
  }
539
- /**
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.
543
- */
544
- async trackPresenceWithRetry(recovered, attempts = 3) {
545
- if (this.isTrackingPresence)
546
- return; // never stack pushes on a wedged socket
547
- this.isTrackingPresence = true;
600
+ async startMqtt(assertSessionStillActive) {
601
+ const generation = this.authGeneration;
548
602
  try {
549
- await this.trackPresenceInner(recovered, attempts);
603
+ console.debug('[DEBUG] starting MQTT');
604
+ const mqttConfig = await this.prepareMqttConfig(assertSessionStillActive);
605
+ assertSessionStillActive();
606
+ if (mqttConfig) {
607
+ console.debug('[DEBUG] MQTT Is ready to start');
608
+ await this.startMqttTransport(mqttConfig);
609
+ }
550
610
  }
551
- finally {
552
- this.isTrackingPresence = false;
611
+ catch (error) {
612
+ // A superseded enrollment must not stop the new session's receiver.
613
+ if (generation === this.authGeneration) {
614
+ await this.stopMqttTransport();
615
+ }
616
+ throw error;
553
617
  }
554
618
  }
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')
619
+ async prepareMqttConfig(assertSessionStillActive) {
620
+ if (!this.enrollment || !this.user || !this.deviceId) {
621
+ throw new Error('MQTT enrollment requires the authenticated connector backend and profile');
622
+ }
623
+ const { data, error } = await this.getSession();
624
+ assertSessionStillActive();
625
+ if (error || !data.session?.access_token)
626
+ throw new Error('MQTT enrollment requires a current device session');
627
+ return enrollMqttDevice({
628
+ ...this.enrollment,
629
+ userId: this.user.id,
630
+ deviceId: this.deviceId,
631
+ accessToken: data.session.access_token,
632
+ assertSessionStillActive,
633
+ });
634
+ }
635
+ async startMqttTransport(config) {
636
+ if (!this.user || !this.deviceId || this.mqttReceiver) {
637
+ throw new Error('MQTT requires one authenticated registered device');
638
+ }
639
+ const receiver = new MqttTransport(config, this.user.id, this.deviceId, (payload) => this.onMqttDoorbell(payload), async (ready) => {
640
+ if (this.mqttReceiver !== receiver) {
562
641
  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
642
  }
572
- catch (trackErr) {
573
- status = `threw: ${trackErr?.message}`;
643
+ await this.setMqttReady(ready);
644
+ });
645
+ this.mqttReceiver = receiver;
646
+ await receiver.start();
647
+ }
648
+ async stopMqttTransport() {
649
+ const receiver = this.mqttReceiver;
650
+ this.mqttReceiver = null;
651
+ if (receiver)
652
+ await receiver.stop();
653
+ await this.setMqttReady(false);
654
+ }
655
+ async setMqttReady(ready) {
656
+ ready = ready && !this.shuttingDown && !this.sessionLost;
657
+ if (this.mqttReady === ready) {
658
+ return;
659
+ }
660
+ this.mqttReady = ready;
661
+ if (this.shuttingDown || this.sessionLost) {
662
+ return;
663
+ }
664
+ // A disconnect must not be overwritten by an earlier, slower ready write.
665
+ const capabilities = this.capabilitiesPayload();
666
+ const sessionGeneration = this.authGeneration;
667
+ const write = this.mqttCapabilityWriteChain.then(async () => {
668
+ const sessionChanged = sessionGeneration !== this.authGeneration;
669
+ if (sessionChanged || this.shuttingDown || this.sessionLost) {
670
+ return false;
574
671
  }
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;
672
+ if (!this.client || !this.deviceId) {
673
+ return false;
629
674
  }
630
- console.error(`❌ Presence track not acknowledged (${status}) — attempt ${attempt}/${attempts}`);
631
- if (attempt < attempts)
632
- await this.sleep(presenceRetryDelayMs(attempt));
675
+ // update capabilities based on the status of mqttReady
676
+ const { error } = await this.client
677
+ .from('mcp_devices')
678
+ .update({ capabilities })
679
+ .eq('id', this.deviceId)
680
+ .abortSignal(this.deviceRowWriteSignal());
681
+ return !error;
682
+ }).catch(() => false);
683
+ this.mqttCapabilityWriteChain = write;
684
+ const saved = await write;
685
+ if (saved)
686
+ return;
687
+ console.warn('[MQTT] Capability update failed');
688
+ if (ready) {
689
+ throw new Error('MQTT capability could not be saved');
633
690
  }
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`);
651
- return;
652
- }
691
+ }
692
+ /** MQTT delivery hook; this branch records receipts without executing calls. */
693
+ async onMqttDoorbell(payload) {
694
+ if (this.shuttingDown || this.sessionLost || this.handlingSignedOut) {
695
+ return;
653
696
  }
654
- this.presenceFailureStartedAt = null;
655
- console.error('❌ Presence track remained unavailable — withdrawing broadcast capability');
656
- await this.setTransportCapable(false);
657
697
  }
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
- };
698
+ async onBroadcastDoorbell(payload) {
699
+ if (this.shuttingDown || this.sessionLost || this.handlingSignedOut) {
700
+ return;
701
+ }
702
+ observeTransport({ stage: 'received', payload, deviceId: this.deviceId,
703
+ userId: this.user?.id, transport: 'broadcast' });
704
+ await this.onDoorbell(payload);
667
705
  }
668
706
  /**
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.
707
+ * Mark this join dispatchable by writing `status`. The write has to land —
708
+ * Supabase reports a refused write in the result rather than by throwing.
709
+ * The health check retries on its own cooldown.
678
710
  */
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;
711
+ markChannelReady() {
712
+ if (this.readinessInFlight)
713
+ return this.readinessInFlight;
714
+ const result = this.markChannelReadyInner().finally(() => {
715
+ if (this.readinessInFlight === result)
716
+ this.readinessInFlight = null;
692
717
  });
693
- return write;
718
+ this.readinessInFlight = result;
719
+ return result;
694
720
  }
695
- async writeTransportCapable(capable) {
696
- if (!this.client || !this.deviceId)
721
+ async markChannelReadyInner() {
722
+ const channel = this.channel;
723
+ if (!channel || channel.state !== 'joined')
697
724
  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;
725
+ // Queued while the channel is joined, so a drop's 'offline' queues
726
+ // behind it and lands last. A dead local executor is written as
727
+ // offline even on a healthy channel.
728
+ const statusWritten = await this.queueStatusWrite(this.localExecutorProbe() ? 'online' : 'offline');
729
+ // A replaced channel, or one that dropped meanwhile, decides for itself;
730
+ // the drop's 'offline' and the rejoin's own write are queued behind this one.
731
+ if (this.channel !== channel || channel.state !== 'joined')
732
+ return false;
733
+ if (!statusWritten) {
734
+ console.error('❌ Channel joined but the device row could not be updated — not ready');
735
+ // Status writes land in order, so this result is newer than any
736
+ // earlier join's success: the row may say offline now.
737
+ this.channelReady = false;
738
+ this.realtimeHealth.record('readiness_write_failures');
739
+ this.consecutiveReadinessFailures++;
740
+ this.nextReadinessAttemptAt = performance.now() +
741
+ readinessRetryDelayMs(this.consecutiveReadinessFailures);
742
+ captureRemote('remote_channel_readiness_write_failed', {}).catch(() => { });
726
743
  return false;
727
744
  }
745
+ this.channelReady = true;
746
+ this.consecutiveUnreadyJoins = 0;
747
+ this.consecutiveReadinessFailures = 0;
748
+ this.nextReadinessAttemptAt = 0;
749
+ console.log(`✅ Device ready (device ${this.deviceId})`);
750
+ // Broadcast is only a wake-up signal; mcp_remote_calls is the durable
751
+ // queue. Drain calls whose doorbell was missed while disconnected. Each
752
+ // row still goes through the atomic pending -> executing claim.
753
+ this.recoverPendingCalls().catch((error) => {
754
+ console.error('[DEBUG] Pending call recovery failed:', error?.message);
755
+ });
728
756
  return true;
729
757
  }
758
+ /**
759
+ * Publish presence for the dashboard. Best effort: one track() per call,
760
+ * no effect on readiness, and a growing cooldown after each failure — a
761
+ * track() timeout on the server can end the whole channel, and every
762
+ * rejoin would otherwise publish again.
763
+ */
764
+ async trackPresence(recovered) {
765
+ if (this.isTrackingPresence || this.presenceInCooldown())
766
+ return;
767
+ const channel = this.channel;
768
+ if (!channel || channel.state !== 'joined')
769
+ return;
770
+ this.isTrackingPresence = true;
771
+ this.realtimeHealth.record('presence_attempts');
772
+ let status;
773
+ try {
774
+ status = await channel.track({
775
+ device_id: this.deviceId,
776
+ device_name: this.deviceName,
777
+ app_version: VERSION,
778
+ platform: process.platform
779
+ });
780
+ }
781
+ catch (trackErr) {
782
+ status = `threw: ${trackErr?.message}`;
783
+ }
784
+ finally {
785
+ this.isTrackingPresence = false;
786
+ }
787
+ if (status === 'ok') {
788
+ // Presence dies with the channel that published it; a new one publishes its own.
789
+ if (this.channel !== channel)
790
+ return;
791
+ this.realtimeHealth.record('presence_successes');
792
+ this.presenceTracked = true;
793
+ this.consecutivePresenceFailures = 0;
794
+ this.nextPresenceAttemptAt = 0;
795
+ console.log(`👋 Presence tracked (device ${this.deviceId})`);
796
+ captureRemote('remote_channel_presence_tracked', { recoveredAfterAttempts: recovered }).catch(() => { });
797
+ return;
798
+ }
799
+ this.realtimeHealth.record('presence_failures');
800
+ const current = this.channel === channel;
801
+ // A newer channel that already published owns the retry state.
802
+ if (!current && this.presenceTracked)
803
+ return;
804
+ // Otherwise arm the cooldown even if the channel was replaced meanwhile:
805
+ // the failure is what ended it, and the next join must not publish at once.
806
+ this.consecutivePresenceFailures++;
807
+ const delayMs = presenceRecoveryDelayMs(this.consecutivePresenceFailures);
808
+ this.nextPresenceAttemptAt = performance.now() + delayMs;
809
+ if (current)
810
+ this.presenceTracked = false;
811
+ console.warn(`⚠️ Presence not acknowledged (${status}) — retrying in ~${Math.round(delayMs / 60000)} min; tool calls are unaffected`);
812
+ captureRemote('remote_channel_presence_track_error', { attempts: 1 }).catch(() => { });
813
+ }
814
+ /** Presence is withheld by its cooldown right now. Monotonic, so a Date.now
815
+ * skew correction cannot shorten or extend it. */
816
+ presenceInCooldown() {
817
+ return performance.now() < this.nextPresenceAttemptAt;
818
+ }
819
+ /**
820
+ * The complete `capabilities` JSONB value. The write replaces the whole
821
+ * column, so a key left out here is dropped from the row.
822
+ */
823
+ capabilitiesPayload() {
824
+ return {
825
+ ...(this.mqttReady ? { transport_mqtt_v1: true } : {}),
826
+ app_version: VERSION
827
+ };
828
+ }
730
829
  /** Aborts one write to this device's row after DEVICE_ROW_WRITE_TIMEOUT_MS (a method, so tests can shorten it). */
731
830
  deviceRowWriteSignal() {
732
831
  return AbortSignal.timeout(DEVICE_ROW_WRITE_TIMEOUT_MS);
@@ -744,6 +843,7 @@ export class RemoteChannel {
744
843
  // Presence, keyed by device id.
745
844
  const channelName = `user:${this.user.id}`;
746
845
  console.debug(`[DEBUG] Creating channel: ${channelName}`);
846
+ this.realtimeHealth.newChannel();
747
847
  this.channel = this.client.channel(channelName, {
748
848
  config: {
749
849
  private: true,
@@ -752,11 +852,7 @@ export class RemoteChannel {
752
852
  }
753
853
  })
754
854
  .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
- }
759
- this.onDoorbell(payload).catch((e) => {
855
+ this.onBroadcastDoorbell(payload).catch((e) => {
760
856
  console.error('[DEBUG] Doorbell handling failed:', e?.message);
761
857
  });
762
858
  })
@@ -764,29 +860,38 @@ export class RemoteChannel {
764
860
  // Debug: Log all subscription status events
765
861
  console.debug(`[DEBUG] Channel subscription status: ${status}${err ? ' (error: ' + (err?.message || err) + ')' : ''} — ${this.connState()}`);
766
862
  if (status === 'SUBSCRIBED') {
863
+ this.realtimeHealth.record('join_successes');
864
+ // The SDK resets its rejoinTimer here even if the join dies
865
+ // before it is ready. Carry failure budget across such joins.
866
+ // reconnectAttempt is different: it counts watchdog
867
+ // recreations, and a join does end that particular
868
+ // failure mode.
869
+ this.consecutiveUnreadyJoins = Math.min(MAX_UNREADY_JOIN_BUDGET, this.consecutiveUnreadyJoins + 1);
767
870
  const recovered = this.reconnectAttempt;
768
- this.reconnectAttempt = 0;
769
- this.lastHeartbeatOkAt = performance.now(); // a fresh join is proof of life too
871
+ this.reconnectAttempt = 0; // watchdog attempts only, not recovery proof
872
+ const joinedAt = performance.now();
873
+ this.joinedAt = joinedAt;
874
+ this.lastHeartbeatOkAt = joinedAt; // a fresh join is proof of life too
770
875
  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
876
+ // A joined channel receives doorbells; readiness only
877
+ // waits for the device row to say so. Presence runs
878
+ // beside it and never decides readiness.
879
+ this.readinessInFlight = null;
880
+ this.channelReady = false;
881
+ this.presenceTracked = false;
882
+ this.markChannelReady()
883
+ .catch(() => false)
884
+ .then((ready) => ready
784
885
  ? resolve()
785
- : reject(new ChannelUnreachableError('channel joined but presence was never acknowledged, so no command can be delivered')));
886
+ : reject(new ChannelUnreachableError('channel joined but the device row could not be updated, so no command can be delivered')));
887
+ this.trackPresence(recovered).catch(() => { });
786
888
  }
787
889
  else if (status === 'CHANNEL_ERROR') {
890
+ this.realtimeHealth.record('join_errors');
788
891
  // CHANNEL_ERROR is the only status carrying a real error message.
789
892
  console.error(`❌ Channel error: ${err?.message || 'unknown'} — ${this.connState()}`);
893
+ this.joinedAt = null;
894
+ this.channelReady = false;
790
895
  this.presenceTracked = false;
791
896
  this.syncReachabilityStatus();
792
897
  // Fires on ordinary network faults too — filter on the
@@ -795,12 +900,14 @@ export class RemoteChannel {
795
900
  reject(new ChannelUnreachableError(err?.message || 'failed to subscribe to the tool call channel'));
796
901
  }
797
902
  else if (status === 'TIMED_OUT') {
903
+ this.realtimeHealth.record('join_timeouts');
798
904
  console.error(`⏱️ Channel subscription timed out, Reconnecting... — ${this.connState()}`);
799
905
  this.syncReachabilityStatus();
800
906
  captureRemote('remote_channel_subscription_timeout', { attempt: this.reconnectAttempt }).catch(() => { });
801
907
  reject(new ChannelUnreachableError('tool call channel subscription timed out'));
802
908
  }
803
909
  else if (status === 'CLOSED') {
910
+ this.realtimeHealth.record('join_closures');
804
911
  // Settle the promise so an in-flight recreateChannel() can't await
805
912
  // forever (which would wedge the re-entrancy guard / watchdog).
806
913
  console.warn(`⚠️ Channel closed — ${this.connState()}`);
@@ -811,8 +918,8 @@ export class RemoteChannel {
811
918
  });
812
919
  }
813
920
  /**
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
921
+ * Recover calls whose doorbell was missed while this device was
922
+ * disconnected. Notifications provide the fast path; the DB row is the source
816
923
  * of truth. Only still-live pending rows for this device are considered.
817
924
  *
818
925
  * The follow-up onDoorbell() call performs the existing conditional claim,
@@ -821,15 +928,12 @@ export class RemoteChannel {
821
928
  async recoverPendingCalls() {
822
929
  if (!this.client || !this.deviceId || !this.isReachable())
823
930
  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
931
  const { data: pending, error } = await this.client
828
932
  .from('mcp_remote_calls')
829
933
  .select('id,device_id')
830
934
  .eq('device_id', this.deviceId)
831
935
  .eq('status', 'pending')
832
- .gt('timeout_at', now)
936
+ .gt('timeout_at', 'now')
833
937
  .order('created_at', { ascending: true })
834
938
  .limit(PENDING_RECOVERY_BATCH_SIZE);
835
939
  if (error) {
@@ -876,6 +980,9 @@ export class RemoteChannel {
876
980
  * device.ts marked as claimed.
877
981
  */
878
982
  async onDoorbell(payload) {
983
+ if (this.shuttingDown || this.sessionLost || this.handlingSignedOut)
984
+ return;
985
+ const generation = this.authGeneration;
879
986
  const callId = payload?.call_id;
880
987
  if (!callId)
881
988
  return;
@@ -890,19 +997,23 @@ export class RemoteChannel {
890
997
  return;
891
998
  // Retry on transient failures (a REST blip while the socket stays
892
999
  // healthy). This claim is the only way we learn about a call,
893
- // so a hiccup must not cost a 5-minute timeout.
1000
+ // so a hiccup must not cost a timeout. PostgREST interprets the
1001
+ // special timestamptz input 'now' in PostgreSQL, not on the device;
1002
+ // this atomically excludes expired rows despite client clock skew.
894
1003
  let row = null;
895
1004
  let claimError = null;
896
1005
  for (const delayMs of [0, 500, 1500]) {
897
1006
  if (delayMs > 0)
898
1007
  await this.sleep(delayMs);
1008
+ if (generation !== this.authGeneration || this.shuttingDown || this.sessionLost || this.handlingSignedOut)
1009
+ return;
899
1010
  const { data, error } = await this.client
900
1011
  .from('mcp_remote_calls')
901
1012
  .update({ status: 'executing' })
902
1013
  .eq('id', callId)
903
1014
  .eq('device_id', this.deviceId)
904
1015
  .eq('status', 'pending')
905
- .gt('timeout_at', new Date(Date.now()).toISOString())
1016
+ .gt('timeout_at', 'now')
906
1017
  .select('*');
907
1018
  if (!error) {
908
1019
  row = data?.[0] ?? null;
@@ -913,8 +1024,16 @@ export class RemoteChannel {
913
1024
  claimError = error;
914
1025
  console.debug(`[DEBUG] Doorbell claim attempt failed for ${callId}: ${error.message} — retrying`);
915
1026
  }
1027
+ if (generation !== this.authGeneration || this.shuttingDown || this.sessionLost || this.handlingSignedOut)
1028
+ return;
916
1029
  if (row) {
917
- this.dispatchToolCall({ new: row, claimed: true });
1030
+ // The server writes the user's rollouts into every call row; a row
1031
+ // without them (an older server) keeps what the device has.
1032
+ rolloutManager.update(row.metadata?.rollouts);
1033
+ this.dispatchToolCall({
1034
+ new: row,
1035
+ claimed: true,
1036
+ });
918
1037
  return;
919
1038
  }
920
1039
  if (!claimError) {
@@ -931,18 +1050,21 @@ export class RemoteChannel {
931
1050
  .select('*')
932
1051
  .eq('id', callId)
933
1052
  .eq('device_id', this.deviceId)
1053
+ .gt('timeout_at', 'now')
934
1054
  .maybeSingle();
935
1055
  if (error) {
936
1056
  console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after claim errors:`, error.message);
937
1057
  await captureRemote('remote_channel_doorbell_fetch_error', { error });
938
1058
  return;
939
1059
  }
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.
945
- this.dispatchToolCall({ new: current });
1060
+ if (generation !== this.authGeneration || this.shuttingDown || this.sessionLost || this.handlingSignedOut)
1061
+ return;
1062
+ if (current?.status === 'pending') {
1063
+ // No claim landed; device.ts claims it. Read-back already excludes
1064
+ // expired rows using PostgreSQL time; its own claim does likewise.
1065
+ this.dispatchToolCall({
1066
+ new: current,
1067
+ });
946
1068
  }
947
1069
  else {
948
1070
  // 'executing' reads the same whether our own claim committed with its
@@ -981,10 +1103,14 @@ export class RemoteChannel {
981
1103
  return;
982
1104
  }
983
1105
  const state = this.channel.state;
1106
+ this.realtimeHealth.observeSocketState(String(this.client?.realtime?.connectionState?.() ?? 'unknown'));
984
1107
  // Debug: Log current channel state (only if changed)
985
1108
  if (!this.lastChannelState || this.lastChannelState !== state) {
986
1109
  console.debug(`[DEBUG] channel state: ${state} — ${this.connState()}`);
987
1110
  this.lastChannelState = state;
1111
+ if (state !== 'joined' && state !== 'joining') {
1112
+ captureRemote('remote_channel_state_health', { state, attempt: this.reconnectAttempt }).catch(() => { });
1113
+ }
988
1114
  }
989
1115
  // 'joined' = healthy. Clear the joining-overstay timer.
990
1116
  if (state === 'joined') {
@@ -1000,14 +1126,24 @@ export class RemoteChannel {
1000
1126
  return;
1001
1127
  }
1002
1128
  }
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(() => { });
1129
+ // Broadcast has outlived a join->error cycle with a heartbeat
1130
+ // confirmed after the join: the socket/channel path is working.
1131
+ // Stop charging this join to the reconnect budget, so a later
1132
+ // ordinary blip gets fast recovery.
1133
+ if (this.consecutiveUnreadyJoins > 0 && this.joinedAt !== null &&
1134
+ this.lastHeartbeatOkAt !== null && this.lastHeartbeatOkAt > this.joinedAt &&
1135
+ performance.now() - this.joinedAt >= STABLE_BROADCAST_RESET_MS) {
1136
+ console.debug(`[DEBUG] Broadcast channel stable for ${Math.round((performance.now() - this.joinedAt) / 1000)}s — clearing reconnect backoff budget`);
1137
+ this.consecutiveUnreadyJoins = 0;
1138
+ }
1139
+ // The channel is up, so SUBSCRIBED won't fire again: retry what the
1140
+ // join left undone, each on its own cooldown.
1141
+ if (!this.channelReady && performance.now() >= this.nextReadinessAttemptAt) {
1142
+ console.debug('[DEBUG] Channel joined but the device row is not ready — retrying');
1143
+ this.markChannelReady().catch(() => { });
1144
+ }
1145
+ if (!this.presenceTracked && this.deviceId) {
1146
+ this.trackPresence(0).catch(() => { });
1011
1147
  }
1012
1148
  return;
1013
1149
  }
@@ -1031,7 +1167,6 @@ export class RemoteChannel {
1031
1167
  }
1032
1168
  // Unhealthy: closed, errored, leaving — recreate
1033
1169
  this.joiningSince = null;
1034
- captureRemote('remote_channel_state_health', { state, attempt: this.reconnectAttempt });
1035
1170
  console.debug(`[DEBUG] ⚠️ Channel in unhealthy state '${state}' - recreating... — ${this.connState()}`);
1036
1171
  this.recreateChannel();
1037
1172
  }
@@ -1057,8 +1192,9 @@ export class RemoteChannel {
1057
1192
  await this.sleep(SOCKET_SETTLE_MAX_MS);
1058
1193
  return;
1059
1194
  }
1060
- const deadline = Date.now() + SOCKET_SETTLE_MAX_MS;
1061
- while (realtime.isDisconnecting() && Date.now() < deadline) {
1195
+ // Monotonic: Date.now may be patched by the clock-skew correction.
1196
+ const deadline = performance.now() + SOCKET_SETTLE_MAX_MS;
1197
+ while (realtime.isDisconnecting() && performance.now() < deadline) {
1062
1198
  await this.sleep(SOCKET_SETTLE_POLL_MS);
1063
1199
  }
1064
1200
  }
@@ -1097,9 +1233,10 @@ export class RemoteChannel {
1097
1233
  // Create fresh channel
1098
1234
  console.log(`🔄 Recreating channel... (attempt ${this.reconnectAttempt}) — ${this.connState()}`);
1099
1235
  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());
1236
+ // Our force-recreate fallback shares the extended sustained-failure
1237
+ // budget with the SDK. A 10s watchdog tick cannot cancel this wait
1238
+ // because isRecreatingChannel guards its whole duration.
1239
+ const backoffMs = watchdogRecreateDelayMs(Math.max(this.reconnectAttempt, this.consecutiveUnreadyJoins));
1103
1240
  console.debug(`[DEBUG] Reconnect backoff: ${Math.round(backoffMs)}ms`);
1104
1241
  await this.sleep(backoffMs);
1105
1242
  // realtime-js runs its own rejoin timer, and the backoff above gives
@@ -1115,6 +1252,8 @@ export class RemoteChannel {
1115
1252
  console.log(`✅ Channel self-healed during backoff — skipping recreate — ${this.connState()}`);
1116
1253
  return; // finally-block below clears the re-entrancy guard
1117
1254
  }
1255
+ // Count only watchdog recreations that continue past SDK self-heal.
1256
+ this.realtimeHealth.record('watchdog_recreates');
1118
1257
  // Cap the whole recreate: a never-settling await (e.g. a subscribe that only
1119
1258
  // ever emits CLOSED) must not pin isRecreatingChannel=true and silently disable
1120
1259
  // the 10s watchdog. On timeout we reject -> catch -> finally clears the guard.
@@ -1150,22 +1289,6 @@ export class RemoteChannel {
1150
1289
  catch (err) {
1151
1290
  captureRemote('remote_channel_recreate_error', { errMsg: err?.message, attempt: this.reconnectAttempt });
1152
1291
  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
1292
  }
1170
1293
  finally {
1171
1294
  this.isRecreatingChannel = false;
@@ -1175,8 +1298,9 @@ export class RemoteChannel {
1175
1298
  * Claim a call. True only when THIS update flipped the row pending ->
1176
1299
  * executing, which is what makes dual delivery safe across processes.
1177
1300
  * .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
1301
+ * result observable. Expiry is checked using Postgres time, not the
1302
+ * device clock. On a transient DB error it returns true (execute anyway),
1303
+ * matching prior behaviour — so device.ts's in-memory guard is what
1180
1304
  * actually guarantees exactly-once within a process.
1181
1305
  */
1182
1306
  async markCallExecuting(callId) {
@@ -1187,7 +1311,7 @@ export class RemoteChannel {
1187
1311
  .update({ status: 'executing' })
1188
1312
  .eq('id', callId)
1189
1313
  .eq('status', 'pending')
1190
- .gt('timeout_at', new Date(Date.now()).toISOString())
1314
+ .gt('timeout_at', 'now')
1191
1315
  .select('id');
1192
1316
  if (error) {
1193
1317
  console.error('[DEBUG] Failed to mark call executing:', error.message);
@@ -1203,13 +1327,12 @@ export class RemoteChannel {
1203
1327
  }
1204
1328
  return claimed;
1205
1329
  }
1206
- async updateCallResult(callId, status, result = null, errorMessage = null) {
1330
+ async updateCallResult(callId, status, result = null, errorMessage = null, originInstance) {
1207
1331
  if (!this.client)
1208
1332
  throw new Error('Client not initialized');
1209
- const updateData = {
1210
- status: status,
1211
- completed_at: new Date().toISOString()
1212
- };
1333
+ // The DB terminal-status trigger stamps completed_at using PostgreSQL
1334
+ // time. Do not send a device-generated timestamp.
1335
+ const updateData = { status };
1213
1336
  // Strip NUL (U+0000) before it reaches the jsonb `result` column.
1214
1337
  // jsonb cannot store and rejects the whole write (Postgres 22P05),
1215
1338
  // which otherwise leaves the call stuck 'executing' → the user waits out
@@ -1242,24 +1365,49 @@ export class RemoteChannel {
1242
1365
  // gets an immediate, honest error instead of a 5-minute phantom
1243
1366
  // timeout. Guard against infinite recursion (only for result writes).
1244
1367
  if (result !== null && status !== 'failed') {
1245
- await this.updateCallResult(callId, 'failed', null, `Result could not be stored (${error.message})`);
1368
+ await this.updateCallResult(callId, 'failed', null, `Result could not be stored (${error.message})`, originInstance);
1246
1369
  }
1247
1370
  }
1248
1371
  else {
1249
1372
  // (an UPDATE without .select() returns no row data — log the id)
1250
1373
  console.debug('[DEBUG] Call result updated successfully:', callId);
1374
+ if (originInstance && (status === 'completed' || status === 'failed')) {
1375
+ // The write already triggers Broadcast in shadow mode; MQTT must never delay it.
1376
+ void this.publishMqttResult(callId, originInstance).catch(() => { });
1377
+ }
1378
+ }
1379
+ }
1380
+ async publishMqttResult(callId, originInstance) {
1381
+ const receiver = this.mqttReceiver;
1382
+ if (!receiver)
1383
+ return;
1384
+ const generation = this.authGeneration;
1385
+ for (let attempt = 1; attempt <= 3; attempt++) {
1386
+ if (generation !== this.authGeneration || receiver !== this.mqttReceiver || this.shuttingDown || this.sessionLost)
1387
+ return;
1388
+ const observation = { callId, deviceId: this.deviceId, userId: this.user?.id, transport: 'mqtt' };
1389
+ try {
1390
+ await receiver.publishResult(callId, originInstance);
1391
+ return;
1392
+ }
1393
+ catch {
1394
+ observeTransport({ ...observation, stage: 'publish_from_device_failed' });
1395
+ if (attempt < 3)
1396
+ await this.sleep(attempt * 1000);
1397
+ }
1251
1398
  }
1252
1399
  }
1253
1400
  /**
1254
1401
  * 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`.
1402
+ * joined, the join's status write landed, and the local executor answers.
1403
+ * The server needs the first two before it will dispatch, and a healthy
1404
+ * channel on a device whose executor is dead is the false-online state
1405
+ * issue #4 was opened for. Presence is not part of it. Gates the heartbeat
1406
+ * and `status`.
1259
1407
  */
1260
1408
  isReachable() {
1261
1409
  return this.channel?.state === 'joined'
1262
- && this.presenceTracked
1410
+ && this.channelReady
1263
1411
  && this.localExecutorProbe();
1264
1412
  }
1265
1413
  /**
@@ -1277,13 +1425,13 @@ export class RemoteChannel {
1277
1425
  return this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1278
1426
  }
1279
1427
  /**
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.
1428
+ * Serialize the status writes, the heartbeat's included. They fire from
1429
+ * un-awaited callbacks, and inside recreateChannel() a teardown's 'offline'
1430
+ * and the fresh join's 'online' land ~100-300ms apart — unordered, 'offline'
1431
+ * can win and leave a healthy device undispatchable until the next heartbeat.
1284
1432
  *
1285
- * Not the single writer: updateHeartbeat, registerDevice and setOffline's
1286
- * subprocess write status directly, so this is not total ordering.
1433
+ * Not the single writer: registerDevice and setOffline's subprocess write
1434
+ * status directly, so this is not total ordering.
1287
1435
  */
1288
1436
  queueStatusWrite(status) {
1289
1437
  // After teardown begins, setOffline() owns the final status write.
@@ -1302,68 +1450,45 @@ export class RemoteChannel {
1302
1450
  this.statusWriteChain = write.then(() => undefined);
1303
1451
  return write;
1304
1452
  }
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) {
1453
+ async updateHeartbeat() {
1316
1454
  if (!this.client)
1317
1455
  return;
1318
1456
  // This write asserts status:'online' too, so it MUST respect the
1319
1457
  // shutdown gate — otherwise a heartbeat firing (or in flight) as SIGINT
1320
1458
  // 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.
1459
+ // an exited process marked online with a fresh last_seen, which the
1460
+ // sweep then cannot age out for its full window.
1323
1461
  if (this.shuttingDown) {
1324
1462
  console.debug('[DEBUG] Skipping heartbeat write — shutting down');
1325
1463
  return;
1326
1464
  }
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 });
1465
+ // Skip the write entirely when no transport is up. Bumping last_seen
1466
+ // on a deaf device would keep its row perpetually young, so the
1467
+ // server's staleness sweep could never age it out and correct a
1468
+ // stale 'online' — and that row is what dispatch reads. Staying
1469
+ // silent lets the sweep do its job.
1470
+ if (!this.isReachable()) {
1471
+ console.debug('[DEBUG] Skipping heartbeat write — no transport joined; letting the row age out');
1472
+ return;
1352
1473
  }
1474
+ // Queued, so a drop's 'offline' queued after it always lands last.
1475
+ // setOnlineStatus also refreshes last_seen and reports a failed write.
1476
+ await this.queueStatusWrite('online');
1353
1477
  }
1354
1478
  startHeartbeat(deviceId) {
1355
1479
  console.debug('[DEBUG] Starting heartbeat for device:', deviceId);
1356
- this.heartbeatDeviceId = deviceId;
1480
+ this.realtimeHealth.setDevice(deviceId);
1481
+ this.realtimeHealth.start();
1357
1482
  this.connectionCheckInterval = setInterval(() => {
1358
1483
  this.checkConnectionHealth();
1359
1484
  }, 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();
1485
+ // Bookkeeping last_seen write. A fixed interval, so a slow write never
1486
+ // pushes the next one past the dashboard's freshness window.
1487
+ this.heartbeatInterval = setInterval(() => {
1488
+ this.updateHeartbeat().catch(() => { });
1489
+ }, HEARTBEAT_INTERVAL_MS);
1365
1490
  this.startTokenRefresh();
1366
- console.debug(`[DEBUG] Heartbeat started - connectionCheck: 10s, last_seen: ${this.heartbeatIntervalMs()}ms, tokenRefresh: ${TOKEN_REFRESH_INTERVAL_MS}ms`);
1491
+ console.debug(`[DEBUG] Heartbeat started - connectionCheck: 10s, last_seen: ${HEARTBEAT_INTERVAL_MS}ms, tokenRefresh: ${TOKEN_REFRESH_INTERVAL_MS}ms`);
1367
1492
  }
1368
1493
  async refreshTokenNow() {
1369
1494
  if (!this.client || this.shuttingDown)
@@ -1396,25 +1521,9 @@ export class RemoteChannel {
1396
1521
  this.tokenRefreshInterval = null;
1397
1522
  }
1398
1523
  }
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
1524
  stopHeartbeat() {
1415
- this.heartbeatDeviceId = null;
1416
1525
  if (this.heartbeatInterval) {
1417
- clearTimeout(this.heartbeatInterval);
1526
+ clearInterval(this.heartbeatInterval);
1418
1527
  this.heartbeatInterval = null;
1419
1528
  }
1420
1529
  if (this.connectionCheckInterval) {
@@ -1434,7 +1543,7 @@ export class RemoteChannel {
1434
1543
  }
1435
1544
  const { error } = await this.client
1436
1545
  .from('mcp_devices')
1437
- .update({ status: status, last_seen: new Date().toISOString() })
1546
+ .update({ status: status, last_seen: 'now' })
1438
1547
  .eq('id', deviceId)
1439
1548
  .abortSignal(this.deviceRowWriteSignal());
1440
1549
  if (error) {
@@ -1545,20 +1654,22 @@ export class RemoteChannel {
1545
1654
  }
1546
1655
  }
1547
1656
  async unsubscribe() {
1657
+ this.realtimeHealth.stop();
1548
1658
  // setOffline()'s durable write is the final word on `status` from here,
1549
1659
  // so stop the heartbeat and the channel callbacks from racing it. The
1550
1660
  // races that matter: a heartbeat tick firing as the signal arrives, and
1551
1661
  // SIGINT during recreateChannel()'s backoff, where the later join's
1552
1662
  // SUBSCRIBED would queue 'online' after the durable write.
1553
1663
  this.shuttingDown = true;
1664
+ this.authGeneration++;
1665
+ await this.stopMqttTransport();
1554
1666
  // Budget against device.ts's 5s force-exit, worst case:
1555
1667
  // 250 drain + 2x300 leave + 500 session + 3000 spawnSync = 4350ms.
1556
1668
  // In practice only the untrack bound binds — removeChannel/unsubscribe
1557
1669
  // set state='leaving' first, so their leave push resolves inline.
1558
1670
  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.
1671
+ // Drain queued status writes, the heartbeat's included; the gate above
1672
+ // stops any new one.
1562
1673
  await Promise.race([this.statusWriteChain, this.sleep(250)]);
1563
1674
  if (this.channel) {
1564
1675
  // Leave presence on the graceful path (socket close covers the abrupt