@wonderwhy-er/desktop-commander 0.2.52 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/command-manager.d.ts +7 -2
- package/dist/command-manager.js +16 -11
- package/dist/config-manager.d.ts +55 -3
- package/dist/config-manager.js +329 -87
- package/dist/config-recovery.d.ts +28 -0
- package/dist/config-recovery.js +81 -0
- package/dist/config.d.ts +1 -0
- package/dist/config.js +9 -0
- package/dist/handlers/filesystem-handlers.d.ts +1 -1
- package/dist/handlers/filesystem-handlers.js +26 -16
- package/dist/handlers/search-answers.d.ts +58 -0
- package/dist/handlers/search-answers.js +172 -0
- package/dist/handlers/search-handlers.js +4 -92
- package/dist/index.js +14 -7
- package/dist/npm-scripts/remote.js +17 -3
- package/dist/remote-device/desktop-commander-integration.d.ts +1 -0
- package/dist/remote-device/desktop-commander-integration.js +19 -25
- package/dist/remote-device/device.d.ts +14 -0
- package/dist/remote-device/device.js +137 -30
- package/dist/remote-device/diagnostics/device-log.d.ts +63 -0
- package/dist/remote-device/diagnostics/device-log.js +219 -0
- package/dist/remote-device/diagnostics/redact.d.ts +1 -0
- package/dist/remote-device/diagnostics/redact.js +76 -0
- package/dist/remote-device/diagnostics/report.d.ts +118 -0
- package/dist/remote-device/diagnostics/report.js +748 -0
- package/dist/remote-device/diagnostics/upload.d.ts +11 -0
- package/dist/remote-device/diagnostics/upload.js +59 -0
- package/dist/remote-device/realtime-health-telemetry.d.ts +35 -0
- package/dist/remote-device/realtime-health-telemetry.js +110 -0
- package/dist/remote-device/remote-channel.d.ts +36 -4
- package/dist/remote-device/remote-channel.js +230 -50
- package/dist/remote-device/scripts/blocking-offline-update.js +108 -69
- package/dist/remote-device/transport-telemetry.d.ts +32 -0
- package/dist/remote-device/transport-telemetry.js +48 -0
- package/dist/search-manager.d.ts +239 -27
- package/dist/search-manager.js +746 -312
- package/dist/server.js +124 -222
- package/dist/terminal-manager.d.ts +138 -21
- package/dist/terminal-manager.js +300 -215
- package/dist/tools/config.d.ts +1 -1
- package/dist/tools/config.js +21 -70
- package/dist/tools/edit.js +12 -4
- package/dist/tools/filesystem.d.ts +30 -6
- package/dist/tools/filesystem.js +246 -140
- package/dist/tools/improved-process-tools.d.ts +9 -3
- package/dist/tools/improved-process-tools.js +171 -68
- package/dist/tools/pdf/extract-images.d.ts +2 -0
- package/dist/tools/pdf/extract-images.js +4 -1
- package/dist/tools/pdf/index.d.ts +5 -3
- package/dist/tools/pdf/index.js +4 -3
- package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
- package/dist/tools/pdf/lib/pdf2md.js +12 -5
- package/dist/tools/pdf/manipulations.d.ts +12 -1
- package/dist/tools/pdf/manipulations.js +17 -4
- package/dist/tools/pdf/markdown.d.ts +96 -0
- package/dist/tools/pdf/markdown.js +485 -20
- package/dist/tools/pdf/utils.d.ts +2 -2
- package/dist/tools/pdf/utils.js +4 -4
- package/dist/tools/process.js +8 -5
- package/dist/tools/schemas.d.ts +1 -11
- package/dist/tools/schemas.js +15 -14
- package/dist/types.d.ts +1 -1
- package/dist/ui/config-editor/config-editor-runtime.js +53 -53
- package/dist/ui/config-editor/src/app.js +2 -15
- package/dist/ui/file-preview/preview-runtime.js +190 -182
- package/dist/utils/ab-test.js +27 -9
- package/dist/utils/atomic-write.d.ts +14 -0
- package/dist/utils/atomic-write.js +80 -0
- package/dist/utils/capture.d.ts +17 -1
- package/dist/utils/capture.js +177 -68
- package/dist/utils/exit-process.d.ts +24 -0
- package/dist/utils/exit-process.js +31 -0
- package/dist/utils/feature-flags.js +2 -1
- package/dist/utils/files/base.d.ts +3 -1
- package/dist/utils/files/docx.d.ts +3 -0
- package/dist/utils/files/docx.js +24 -9
- package/dist/utils/files/excel.d.ts +10 -0
- package/dist/utils/files/excel.js +93 -33
- package/dist/utils/files/factory.d.ts +22 -1
- package/dist/utils/files/factory.js +59 -4
- package/dist/utils/files/image.d.ts +12 -4
- package/dist/utils/files/image.js +19 -8
- package/dist/utils/files/index.d.ts +5 -3
- package/dist/utils/files/index.js +4 -3
- package/dist/utils/files/pdf.js +18 -36
- package/dist/utils/files/text.d.ts +21 -5
- package/dist/utils/files/text.js +90 -86
- package/dist/utils/internal-facts.d.ts +3 -0
- package/dist/utils/internal-facts.js +23 -0
- package/dist/utils/lazy-package.d.ts +25 -0
- package/dist/utils/lazy-package.js +44 -0
- package/dist/utils/open-browser.js +2 -1
- package/dist/utils/process-detection.d.ts +24 -5
- package/dist/utils/process-detection.js +199 -89
- package/dist/utils/process-tree.d.ts +14 -0
- package/dist/utils/process-tree.js +223 -0
- package/dist/utils/rename.d.ts +9 -0
- package/dist/utils/rename.js +74 -0
- package/dist/utils/ripgrep-resolver.js +9 -14
- package/dist/utils/shell.d.ts +42 -0
- package/dist/utils/shell.js +187 -0
- package/dist/utils/system-info.d.ts +1 -0
- package/dist/utils/system-info.js +40 -25
- package/dist/utils/trackTools.js +2 -1
- package/dist/utils/usageTracker.d.ts +0 -39
- package/dist/utils/usageTracker.js +1 -161
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
- package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
- package/package.json +32 -16
- package/vendor/telemetry-contract/README.md +56 -0
- package/vendor/telemetry-contract/package.json +32 -0
- package/vendor/telemetry-contract/transport.d.ts +38 -0
- package/vendor/telemetry-contract/transport.js +164 -0
- package/vendor/telemetry-contract/transport.test.js +39 -0
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { createClient } from '@supabase/supabase-js';
|
|
2
2
|
import { captureRemote } from '../utils/capture.js';
|
|
3
|
+
import { observeTransport } from './transport-telemetry.js';
|
|
4
|
+
import { RealtimeHealthTelemetry } from './realtime-health-telemetry.js';
|
|
3
5
|
import { VERSION } from '../version.js';
|
|
4
6
|
const NUL_CHAR = String.fromCharCode(0);
|
|
5
7
|
const NUL_RE = new RegExp(NUL_CHAR, 'g');
|
|
@@ -46,12 +48,12 @@ export class ChannelUnreachableError extends Error {
|
|
|
46
48
|
// capable -> 15 min, unflagged -> 45s.
|
|
47
49
|
const CAPABLE_HEARTBEAT_INTERVAL = 5 * 60 * 1000;
|
|
48
50
|
const LEGACY_HEARTBEAT_INTERVAL = 15 * 1000;
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
//
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
const
|
|
51
|
+
// Fast recovery for short Wi-Fi blips, but never retry every 10 seconds forever.
|
|
52
|
+
// Prolonged provider incidents must not keep the entire device fleet joining.
|
|
53
|
+
// Independent jitter spreads retry work; full jitter applies at attempt >= 5.
|
|
54
|
+
const REALTIME_RECONNECT_BASE_MS = [1000, 2000, 5000, 10000, 20000, 40000, 80000, 120000];
|
|
55
|
+
const REALTIME_RECONNECT_FALLBACK_MS = 120000;
|
|
56
|
+
const WATCHDOG_RECREATE_MAX_BACKOFF_MS = 120000;
|
|
55
57
|
// Presence-only failures do not mean broadcast delivery is down: a joined
|
|
56
58
|
// channel can still receive doorbells while Presence's DB-backed work is
|
|
57
59
|
// degraded. Keep a previously-proven capability for one normal heartbeat
|
|
@@ -61,6 +63,15 @@ const PRESENCE_WITHDRAW_GRACE_MS = 5 * 60 * 1000;
|
|
|
61
63
|
// Cap on a recreate's rebuild step so a hung await can't disable the watchdog.
|
|
62
64
|
// Must exceed createChannel()'s worst case (~32.25s of jittered presence retries).
|
|
63
65
|
const RECREATE_TIMEOUT_MS = 45000;
|
|
66
|
+
// Upper bound on the persistent unready-join budget. Anything >= 8 already
|
|
67
|
+
// selects the 120s SDK tier; the cap only keeps the counter meaningful.
|
|
68
|
+
const MAX_UNREADY_JOIN_BUDGET = 16;
|
|
69
|
+
// A channel that has stayed joined this long, with a heartbeat confirmed after
|
|
70
|
+
// the join, is a working broadcast path even if Presence is still degraded.
|
|
71
|
+
// Its join no longer counts toward reconnect backoff (Presence keeps its own
|
|
72
|
+
// cooldown). Comfortably longer than the incident's join->error cycle (~10-30s)
|
|
73
|
+
// and covers at least four 25s heartbeats.
|
|
74
|
+
const STABLE_BROADCAST_RESET_MS = 120000;
|
|
64
75
|
// Max continuous time in 'joining' before forcing a recreate — a half-open
|
|
65
76
|
// socket parks the channel there forever, and a genuine join settles in ~10s.
|
|
66
77
|
const JOINING_WEDGE_TIMEOUT_MS = 30000;
|
|
@@ -79,6 +90,11 @@ const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
|
|
|
79
90
|
// Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
|
|
80
91
|
// does not cover.
|
|
81
92
|
const CAPABILITY_WRITE_TIMEOUT_MS = 5000;
|
|
93
|
+
// Cap on one write to this device's row (capability, status), after which it
|
|
94
|
+
// is aborted. A PATCH sent down a half-open connection is otherwise answered
|
|
95
|
+
// only by fetch's own 300 s headers timeout, and the write queue behind it,
|
|
96
|
+
// with the presence publish waiting on that queue, waits as long.
|
|
97
|
+
const DEVICE_ROW_WRITE_TIMEOUT_MS = 10000;
|
|
82
98
|
// Cap on the shutdown session fetch, which races device.ts's 5s force-exit.
|
|
83
99
|
const OFFLINE_SESSION_TIMEOUT_MS = 500;
|
|
84
100
|
// realtime-js parks in 'disconnecting' for ~100ms after a disconnect and
|
|
@@ -95,17 +111,33 @@ function jitterAround(baseMs, random) {
|
|
|
95
111
|
const sample = Math.max(0, Math.min(1, random()));
|
|
96
112
|
return Math.max(1, Math.round(baseMs * (0.5 + sample)));
|
|
97
113
|
}
|
|
98
|
-
/**
|
|
114
|
+
/** Exponential-ish SDK backoff. Attempts 1-4 preserve short recovery latency. */
|
|
99
115
|
export function realtimeReconnectDelayMs(tries, random = Math.random) {
|
|
100
116
|
const attempt = Math.max(1, Math.floor(tries || 1));
|
|
101
117
|
const baseMs = REALTIME_RECONNECT_BASE_MS[attempt - 1] ?? REALTIME_RECONNECT_FALLBACK_MS;
|
|
118
|
+
if (attempt <= 4)
|
|
119
|
+
return jitterAround(baseMs, random);
|
|
120
|
+
// Full jitter is deliberately independent per device; floor avoids an immediate tight retry.
|
|
121
|
+
return Math.max(1000, Math.round(baseMs * Math.max(0, Math.min(1, random()))));
|
|
122
|
+
}
|
|
123
|
+
/** Watchdog must not defeat the SDK's slower persistent-failure backoff. */
|
|
124
|
+
export function watchdogRecreateDelayMs(tries, random = Math.random) {
|
|
125
|
+
const attempt = Math.max(1, Math.floor(tries || 1));
|
|
126
|
+
const baseMs = Math.min(WATCHDOG_RECREATE_MAX_BACKOFF_MS, 1000 * 2 ** Math.min(attempt, 7));
|
|
102
127
|
return jitterAround(baseMs, random);
|
|
103
128
|
}
|
|
104
|
-
/** Preserve
|
|
129
|
+
/** Preserve short in-batch Presence retries, independently jittered. */
|
|
105
130
|
export function presenceRetryDelayMs(failedAttempt, random = Math.random) {
|
|
106
131
|
const attempt = Math.max(1, Math.floor(failedAttempt || 1));
|
|
107
132
|
return jitterAround(500 * attempt, random);
|
|
108
133
|
}
|
|
134
|
+
/** Delay new Presence batches after repeated failed batches, even across SDK rejoins.
|
|
135
|
+
* This is intentionally independent of the Phoenix channel/socket reconnect timer. */
|
|
136
|
+
export function presenceRecoveryDelayMs(failures, random = Math.random) {
|
|
137
|
+
const attempt = Math.max(1, Math.floor(failures || 1));
|
|
138
|
+
const baseMs = Math.min(120000, 5000 * 2 ** Math.min(attempt - 1, 5));
|
|
139
|
+
return Math.max(1000, Math.round(baseMs * Math.max(0, Math.min(1, random()))));
|
|
140
|
+
}
|
|
109
141
|
// auth-js compares token expiry against this device's own Date.now(), with no
|
|
110
142
|
// clock-skew tolerance — a fast clock treats every fresh token as expired and
|
|
111
143
|
// refreshes forever (confirmed in prod on one device, via at least 3 separate
|
|
@@ -185,11 +217,26 @@ export class RemoteChannel {
|
|
|
185
217
|
this.presenceTracked = false;
|
|
186
218
|
/** Last capability value written (null = never), to avoid redundant writes. */
|
|
187
219
|
this.transportCapableWritten = null;
|
|
220
|
+
/** Value of the last capability write still queued or in flight; null once the queue is idle. */
|
|
221
|
+
this.transportCapableQueued = null;
|
|
222
|
+
// Single-slot queue keeping capability writes in order (see setTransportCapable).
|
|
223
|
+
this.capabilityWriteChain = Promise.resolve();
|
|
188
224
|
/** Monotonic start of a Presence-only degradation while broadcast remains joined. */
|
|
189
225
|
this.presenceFailureStartedAt = null;
|
|
190
226
|
/** Re-entrancy guard: on a wedged socket each track() buffers for the full
|
|
191
227
|
* 10s push timeout, so 10s health ticks would stack pushes. */
|
|
192
228
|
this.isTrackingPresence = false;
|
|
229
|
+
// The SDK resets its rejoin timer on *every* SUBSCRIBED, even if Presence
|
|
230
|
+
// immediately times out. Count such joins across SDK/channel recreation.
|
|
231
|
+
// Reset only after Presence AND durable readiness writes succeed.
|
|
232
|
+
this.consecutiveUnreadyJoins = 0;
|
|
233
|
+
this.consecutivePresenceFailures = 0;
|
|
234
|
+
this.nextPresenceAttemptAt = 0; // monotonic; independent of Date.now skew correction
|
|
235
|
+
/** performance.now() of the latest SUBSCRIBED; null while not joined. */
|
|
236
|
+
this.joinedAt = null;
|
|
237
|
+
this.realtimeHealth = new RealtimeHealthTelemetry((window) => {
|
|
238
|
+
captureRemote('remote_realtime_health_window', window).catch(() => { });
|
|
239
|
+
});
|
|
193
240
|
// Track last device status to prevent duplicate log messages
|
|
194
241
|
this.lastDeviceStatus = 'offline';
|
|
195
242
|
// Track last channel state for debug logging
|
|
@@ -208,6 +255,11 @@ export class RemoteChannel {
|
|
|
208
255
|
this.tokenRefreshInterval = null;
|
|
209
256
|
this._user = null;
|
|
210
257
|
}
|
|
258
|
+
/** SDK channel and socket timers share reconnectAfterMs. The persistent
|
|
259
|
+
* unready-join budget prevents a series of partial successes restarting at 1s. */
|
|
260
|
+
reconnectDelayMs(tries, random = Math.random) {
|
|
261
|
+
return realtimeReconnectDelayMs(Math.max(tries, this.consecutiveUnreadyJoins), random);
|
|
262
|
+
}
|
|
211
263
|
get user() { return this._user; }
|
|
212
264
|
initialize(url, key) {
|
|
213
265
|
// autoRefreshToken:false — we drive refresh ourselves (startTokenRefresh(),
|
|
@@ -217,7 +269,7 @@ export class RemoteChannel {
|
|
|
217
269
|
auth: { autoRefreshToken: false },
|
|
218
270
|
global: { fetch: clockAwareFetch },
|
|
219
271
|
realtime: {
|
|
220
|
-
reconnectAfterMs:
|
|
272
|
+
reconnectAfterMs: (tries) => this.reconnectDelayMs(tries),
|
|
221
273
|
// supabase-js's resolver ends in `?? supabaseKey`, so after SIGNED_OUT
|
|
222
274
|
// the socket silently re-pins to the anon key and every private-channel
|
|
223
275
|
// join is refused. Overriding under `realtime` (not the top-level
|
|
@@ -492,7 +544,7 @@ export class RemoteChannel {
|
|
|
492
544
|
// 'online'; presence writes the capability.
|
|
493
545
|
const { error: registrationError } = await this.updateDevice(existingDevice.id, {
|
|
494
546
|
status: 'offline',
|
|
495
|
-
last_seen:
|
|
547
|
+
last_seen: 'now',
|
|
496
548
|
capabilities: this.capabilitiesPayload(false),
|
|
497
549
|
device_name: deviceName
|
|
498
550
|
});
|
|
@@ -507,6 +559,7 @@ export class RemoteChannel {
|
|
|
507
559
|
}
|
|
508
560
|
// Store parameters for channel recreation
|
|
509
561
|
this.deviceId = existingDevice.id;
|
|
562
|
+
this.realtimeHealth.setDevice(existingDevice.id);
|
|
510
563
|
this.deviceName = deviceName;
|
|
511
564
|
this.onToolCall = onToolCall;
|
|
512
565
|
console.debug(`⏳ Subscribing to tool call channel...`);
|
|
@@ -534,6 +587,10 @@ export class RemoteChannel {
|
|
|
534
587
|
async trackPresenceWithRetry(recovered, attempts = 3) {
|
|
535
588
|
if (this.isTrackingPresence)
|
|
536
589
|
return; // never stack pushes on a wedged socket
|
|
590
|
+
// SDK may deliver SUBSCRIBED again before Presence's separate cooldown
|
|
591
|
+
// expires. Do not let each successful join bypass that cooldown.
|
|
592
|
+
if (this.presenceInCooldown())
|
|
593
|
+
return;
|
|
537
594
|
this.isTrackingPresence = true;
|
|
538
595
|
try {
|
|
539
596
|
await this.trackPresenceInner(recovered, attempts);
|
|
@@ -542,17 +599,42 @@ export class RemoteChannel {
|
|
|
542
599
|
this.isTrackingPresence = false;
|
|
543
600
|
}
|
|
544
601
|
}
|
|
602
|
+
/** One failed Presence batch: grow the Presence-only cooldown. Deadlines are
|
|
603
|
+
* monotonic so a Date.now skew correction cannot shorten or extend them. */
|
|
604
|
+
recordPresenceBatchFailure() {
|
|
605
|
+
this.consecutivePresenceFailures++;
|
|
606
|
+
this.nextPresenceAttemptAt = performance.now() +
|
|
607
|
+
presenceRecoveryDelayMs(this.consecutivePresenceFailures);
|
|
608
|
+
}
|
|
609
|
+
/** Presence is withheld by its cooldown right now. */
|
|
610
|
+
presenceInCooldown() {
|
|
611
|
+
return performance.now() < this.nextPresenceAttemptAt;
|
|
612
|
+
}
|
|
545
613
|
async trackPresenceInner(recovered, attempts) {
|
|
546
614
|
// A fresh attempt starts from "not proven", so a leftover true from an
|
|
547
615
|
// earlier join cannot keep the device counting as reachable while this
|
|
548
616
|
// one is still deciding.
|
|
549
617
|
this.presenceTracked = false;
|
|
618
|
+
// Every await below can outlive this channel (recreateChannel() swaps
|
|
619
|
+
// it). A late result must not touch retry state the newer channel owns.
|
|
620
|
+
const channel = this.channel;
|
|
621
|
+
let failedAttempts = 0;
|
|
550
622
|
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
551
|
-
if (
|
|
623
|
+
if (this.channel !== channel)
|
|
624
|
+
return;
|
|
625
|
+
if (!channel || channel.state !== 'joined') {
|
|
626
|
+
// Production sequence (2026-10-13): track() times out, then the
|
|
627
|
+
// channel errors before the next in-batch attempt. That batch
|
|
628
|
+
// failed too; without recording it the next SUBSCRIBED would
|
|
629
|
+
// publish again with no cooldown at all.
|
|
630
|
+
if (failedAttempts > 0)
|
|
631
|
+
this.recordPresenceBatchFailure();
|
|
552
632
|
return;
|
|
633
|
+
}
|
|
553
634
|
let status;
|
|
635
|
+
this.realtimeHealth.record('presence_attempts');
|
|
554
636
|
try {
|
|
555
|
-
status = await
|
|
637
|
+
status = await channel.track({
|
|
556
638
|
device_id: this.deviceId,
|
|
557
639
|
device_name: this.deviceName,
|
|
558
640
|
app_version: VERSION,
|
|
@@ -562,7 +644,10 @@ export class RemoteChannel {
|
|
|
562
644
|
catch (trackErr) {
|
|
563
645
|
status = `threw: ${trackErr?.message}`;
|
|
564
646
|
}
|
|
647
|
+
if (this.channel !== channel)
|
|
648
|
+
return; // stale ack/timeout from a replaced channel
|
|
565
649
|
if (status === 'ok') {
|
|
650
|
+
this.realtimeHealth.record('presence_successes');
|
|
566
651
|
// `presenceTracked` is not "track() said ok" — isReachable()
|
|
567
652
|
// reads it as "this device receives commands", and the heartbeat
|
|
568
653
|
// consults isReachable() directly rather than waiting for the
|
|
@@ -594,12 +679,22 @@ export class RemoteChannel {
|
|
|
594
679
|
: false;
|
|
595
680
|
if (!capabilityWritten || !statusWritten) {
|
|
596
681
|
console.error('❌ Presence published but the device row could not be updated — not ready');
|
|
682
|
+
this.realtimeHealth.record('readiness_write_failures');
|
|
597
683
|
captureRemote('remote_channel_readiness_write_failed', {
|
|
598
684
|
capabilityWritten, statusWritten
|
|
599
685
|
}).catch(() => { });
|
|
600
686
|
return;
|
|
601
687
|
}
|
|
688
|
+
// Writes can take up to DEVICE_ROW_WRITE_TIMEOUT_MS each; if the
|
|
689
|
+
// channel was replaced meanwhile, its own join decides readiness.
|
|
690
|
+
if (this.channel !== channel)
|
|
691
|
+
return;
|
|
602
692
|
this.presenceTracked = true;
|
|
693
|
+
// A joined socket is only a partial recovery. Clear backoff
|
|
694
|
+
// after Presence and both readiness writes have succeeded.
|
|
695
|
+
this.consecutiveUnreadyJoins = 0;
|
|
696
|
+
this.consecutivePresenceFailures = 0;
|
|
697
|
+
this.nextPresenceAttemptAt = 0;
|
|
603
698
|
this.presenceFailureStartedAt = null;
|
|
604
699
|
console.log(`👋 Presence tracked (device ${this.deviceId} visible as online)`);
|
|
605
700
|
// Reconnect attempts preceding this join (0 on a first join).
|
|
@@ -617,11 +712,16 @@ export class RemoteChannel {
|
|
|
617
712
|
});
|
|
618
713
|
return;
|
|
619
714
|
}
|
|
715
|
+
failedAttempts++;
|
|
620
716
|
console.error(`❌ Presence track not acknowledged (${status}) — attempt ${attempt}/${attempts}`);
|
|
717
|
+
this.realtimeHealth.record('presence_failures');
|
|
621
718
|
if (attempt < attempts)
|
|
622
719
|
await this.sleep(presenceRetryDelayMs(attempt));
|
|
623
720
|
}
|
|
721
|
+
if (this.channel !== channel)
|
|
722
|
+
return;
|
|
624
723
|
this.presenceTracked = false;
|
|
724
|
+
this.recordPresenceBatchFailure();
|
|
625
725
|
captureRemote('remote_channel_presence_track_error', { attempts }).catch(() => { });
|
|
626
726
|
// Presence is an observer signal, not the delivery path. If this device
|
|
627
727
|
// already proved broadcast capability and the channel is still joined,
|
|
@@ -659,20 +759,44 @@ export class RemoteChannel {
|
|
|
659
759
|
* Advertise (or withdraw) the broadcast capability. Only true while genuinely
|
|
660
760
|
* reachable that way — the server fails dispatch fast without it and picks
|
|
661
761
|
* the offline-sweep tier from it, so every change must re-arm the heartbeat.
|
|
762
|
+
*
|
|
763
|
+
* Writes are queued, like the status writes. A withdrawal the recreate stops
|
|
764
|
+
* waiting for still lands: compared with the last landed value, a re-publish
|
|
765
|
+
* in the meantime looked redundant and was skipped, and the withdrawal then
|
|
766
|
+
* left a device that claims to be online without the flag. Resolves with
|
|
767
|
+
* whether the row holds `capable` once this write is done.
|
|
662
768
|
*/
|
|
663
|
-
|
|
769
|
+
setTransportCapable(capable) {
|
|
770
|
+
if (!this.client || !this.deviceId)
|
|
771
|
+
return Promise.resolve(false);
|
|
772
|
+
// What the row holds once the queue drains — no redundant writes.
|
|
773
|
+
if ((this.transportCapableQueued ?? this.transportCapableWritten) === capable) {
|
|
774
|
+
return this.capabilityWriteChain.then(() => this.transportCapableWritten === capable);
|
|
775
|
+
}
|
|
776
|
+
this.transportCapableQueued = capable;
|
|
777
|
+
const write = this.capabilityWriteChain.then(() => this.writeTransportCapable(capable));
|
|
778
|
+
this.capabilityWriteChain = write;
|
|
779
|
+
write.then(() => {
|
|
780
|
+
if (this.capabilityWriteChain === write)
|
|
781
|
+
this.transportCapableQueued = null;
|
|
782
|
+
});
|
|
783
|
+
return write;
|
|
784
|
+
}
|
|
785
|
+
async writeTransportCapable(capable) {
|
|
664
786
|
if (!this.client || !this.deviceId)
|
|
665
787
|
return false;
|
|
666
|
-
if (this.transportCapableWritten === capable)
|
|
667
|
-
return true; // no redundant writes
|
|
668
788
|
try {
|
|
669
789
|
const capabilities = this.capabilitiesPayload(capable);
|
|
670
790
|
const { error } = await this.client
|
|
671
791
|
.from('mcp_devices')
|
|
672
792
|
.update({ capabilities })
|
|
673
|
-
.eq('id', this.deviceId)
|
|
793
|
+
.eq('id', this.deviceId)
|
|
794
|
+
.abortSignal(this.deviceRowWriteSignal());
|
|
674
795
|
if (error) {
|
|
675
796
|
console.error('[DEBUG] Failed to update transport capability:', error.message);
|
|
797
|
+
// An aborted write may still land: what the row holds is
|
|
798
|
+
// unknown, so the next write of either value is not skipped.
|
|
799
|
+
this.transportCapableWritten = null;
|
|
676
800
|
return false;
|
|
677
801
|
}
|
|
678
802
|
this.transportCapableWritten = capable;
|
|
@@ -688,10 +812,15 @@ export class RemoteChannel {
|
|
|
688
812
|
}
|
|
689
813
|
catch (error) {
|
|
690
814
|
console.error('[DEBUG] Transport capability update threw:', error?.message);
|
|
815
|
+
this.transportCapableWritten = null;
|
|
691
816
|
return false;
|
|
692
817
|
}
|
|
693
818
|
return true;
|
|
694
819
|
}
|
|
820
|
+
/** Aborts one write to this device's row after DEVICE_ROW_WRITE_TIMEOUT_MS (a method, so tests can shorten it). */
|
|
821
|
+
deviceRowWriteSignal() {
|
|
822
|
+
return AbortSignal.timeout(DEVICE_ROW_WRITE_TIMEOUT_MS);
|
|
823
|
+
}
|
|
695
824
|
/** Create and subscribe the private channel (initial join and recreation). */
|
|
696
825
|
createChannel() {
|
|
697
826
|
return new Promise((resolve, reject) => {
|
|
@@ -705,6 +834,7 @@ export class RemoteChannel {
|
|
|
705
834
|
// Presence, keyed by device id.
|
|
706
835
|
const channelName = `user:${this.user.id}`;
|
|
707
836
|
console.debug(`[DEBUG] Creating channel: ${channelName}`);
|
|
837
|
+
this.realtimeHealth.newChannel();
|
|
708
838
|
this.channel = this.client.channel(channelName, {
|
|
709
839
|
config: {
|
|
710
840
|
private: true,
|
|
@@ -713,6 +843,10 @@ export class RemoteChannel {
|
|
|
713
843
|
}
|
|
714
844
|
})
|
|
715
845
|
.on('broadcast', { event: 'new_call' }, ({ payload }) => {
|
|
846
|
+
if (!this.shuttingDown) {
|
|
847
|
+
observeTransport({ stage: 'received', payload, deviceId: this.deviceId,
|
|
848
|
+
userId: this.user?.id, transport: 'broadcast' });
|
|
849
|
+
}
|
|
716
850
|
this.onDoorbell(payload).catch((e) => {
|
|
717
851
|
console.error('[DEBUG] Doorbell handling failed:', e?.message);
|
|
718
852
|
});
|
|
@@ -721,9 +855,18 @@ export class RemoteChannel {
|
|
|
721
855
|
// Debug: Log all subscription status events
|
|
722
856
|
console.debug(`[DEBUG] Channel subscription status: ${status}${err ? ' (error: ' + (err?.message || err) + ')' : ''} — ${this.connState()}`);
|
|
723
857
|
if (status === 'SUBSCRIBED') {
|
|
858
|
+
this.realtimeHealth.record('join_successes');
|
|
859
|
+
// The SDK resets its rejoinTimer here regardless of Presence.
|
|
860
|
+
// Carry failure budget across successful-but-unready joins.
|
|
861
|
+
// reconnectAttempt is different: it counts watchdog
|
|
862
|
+
// recreations (and gates capability withdrawal), and a
|
|
863
|
+
// join does end that particular failure mode.
|
|
864
|
+
this.consecutiveUnreadyJoins = Math.min(MAX_UNREADY_JOIN_BUDGET, this.consecutiveUnreadyJoins + 1);
|
|
724
865
|
const recovered = this.reconnectAttempt;
|
|
725
|
-
this.reconnectAttempt = 0;
|
|
726
|
-
|
|
866
|
+
this.reconnectAttempt = 0; // watchdog attempts only, not recovery proof
|
|
867
|
+
const joinedAt = performance.now();
|
|
868
|
+
this.joinedAt = joinedAt;
|
|
869
|
+
this.lastHeartbeatOkAt = joinedAt; // a fresh join is proof of life too
|
|
727
870
|
console.log(`✅ Channel subscribed${recovered > 0 ? ` (recovered after ${recovered} attempt${recovered === 1 ? '' : 's'})` : ''}`);
|
|
728
871
|
// A join is only half of what dispatch needs. The other
|
|
729
872
|
// half is presence, which writes the capability the
|
|
@@ -735,15 +878,26 @@ export class RemoteChannel {
|
|
|
735
878
|
// `status` is written on the same event as the
|
|
736
879
|
// capability, in trackPresenceInner, so the two can
|
|
737
880
|
// never disagree.
|
|
881
|
+
//
|
|
882
|
+
// During a Presence cooldown no publish is attempted.
|
|
883
|
+
// The promise still rejects (the device is not ready),
|
|
884
|
+
// but the joined channel itself is left in place: the
|
|
885
|
+
// health check treats 'joined' as healthy and only
|
|
886
|
+
// retries Presence once the cooldown expires.
|
|
887
|
+
const deferred = this.presenceInCooldown();
|
|
738
888
|
this.trackPresenceWithRetry(recovered)
|
|
739
889
|
.catch(() => { })
|
|
740
890
|
.finally(() => this.presenceTracked
|
|
741
891
|
? resolve()
|
|
742
|
-
: reject(new ChannelUnreachableError(
|
|
892
|
+
: reject(new ChannelUnreachableError(deferred
|
|
893
|
+
? 'channel joined; presence deferred by cooldown after repeated failures'
|
|
894
|
+
: 'channel joined but presence was never acknowledged, so no command can be delivered')));
|
|
743
895
|
}
|
|
744
896
|
else if (status === 'CHANNEL_ERROR') {
|
|
897
|
+
this.realtimeHealth.record('join_errors');
|
|
745
898
|
// CHANNEL_ERROR is the only status carrying a real error message.
|
|
746
899
|
console.error(`❌ Channel error: ${err?.message || 'unknown'} — ${this.connState()}`);
|
|
900
|
+
this.joinedAt = null;
|
|
747
901
|
this.presenceTracked = false;
|
|
748
902
|
this.syncReachabilityStatus();
|
|
749
903
|
// Fires on ordinary network faults too — filter on the
|
|
@@ -752,12 +906,14 @@ export class RemoteChannel {
|
|
|
752
906
|
reject(new ChannelUnreachableError(err?.message || 'failed to subscribe to the tool call channel'));
|
|
753
907
|
}
|
|
754
908
|
else if (status === 'TIMED_OUT') {
|
|
909
|
+
this.realtimeHealth.record('join_timeouts');
|
|
755
910
|
console.error(`⏱️ Channel subscription timed out, Reconnecting... — ${this.connState()}`);
|
|
756
911
|
this.syncReachabilityStatus();
|
|
757
912
|
captureRemote('remote_channel_subscription_timeout', { attempt: this.reconnectAttempt }).catch(() => { });
|
|
758
913
|
reject(new ChannelUnreachableError('tool call channel subscription timed out'));
|
|
759
914
|
}
|
|
760
915
|
else if (status === 'CLOSED') {
|
|
916
|
+
this.realtimeHealth.record('join_closures');
|
|
761
917
|
// Settle the promise so an in-flight recreateChannel() can't await
|
|
762
918
|
// forever (which would wedge the re-entrancy guard / watchdog).
|
|
763
919
|
console.warn(`⚠️ Channel closed — ${this.connState()}`);
|
|
@@ -778,15 +934,12 @@ export class RemoteChannel {
|
|
|
778
934
|
async recoverPendingCalls() {
|
|
779
935
|
if (!this.client || !this.deviceId || !this.isReachable())
|
|
780
936
|
return;
|
|
781
|
-
// Date.now() is deliberately used here: this process may patch it from
|
|
782
|
-
// Supabase's Date header to correct a badly skewed device clock.
|
|
783
|
-
const now = new Date(Date.now()).toISOString();
|
|
784
937
|
const { data: pending, error } = await this.client
|
|
785
938
|
.from('mcp_remote_calls')
|
|
786
939
|
.select('id,device_id')
|
|
787
940
|
.eq('device_id', this.deviceId)
|
|
788
941
|
.eq('status', 'pending')
|
|
789
|
-
.gt('timeout_at', now)
|
|
942
|
+
.gt('timeout_at', 'now')
|
|
790
943
|
.order('created_at', { ascending: true })
|
|
791
944
|
.limit(PENDING_RECOVERY_BATCH_SIZE);
|
|
792
945
|
if (error) {
|
|
@@ -847,7 +1000,9 @@ export class RemoteChannel {
|
|
|
847
1000
|
return;
|
|
848
1001
|
// Retry on transient failures (a REST blip while the socket stays
|
|
849
1002
|
// healthy). This claim is the only way we learn about a call,
|
|
850
|
-
// so a hiccup must not cost a
|
|
1003
|
+
// so a hiccup must not cost a timeout. PostgREST interprets the
|
|
1004
|
+
// special timestamptz input 'now' in PostgreSQL, not on the device;
|
|
1005
|
+
// this atomically excludes expired rows despite client clock skew.
|
|
851
1006
|
let row = null;
|
|
852
1007
|
let claimError = null;
|
|
853
1008
|
for (const delayMs of [0, 500, 1500]) {
|
|
@@ -859,7 +1014,7 @@ export class RemoteChannel {
|
|
|
859
1014
|
.eq('id', callId)
|
|
860
1015
|
.eq('device_id', this.deviceId)
|
|
861
1016
|
.eq('status', 'pending')
|
|
862
|
-
.gt('timeout_at',
|
|
1017
|
+
.gt('timeout_at', 'now')
|
|
863
1018
|
.select('*');
|
|
864
1019
|
if (!error) {
|
|
865
1020
|
row = data?.[0] ?? null;
|
|
@@ -888,17 +1043,16 @@ export class RemoteChannel {
|
|
|
888
1043
|
.select('*')
|
|
889
1044
|
.eq('id', callId)
|
|
890
1045
|
.eq('device_id', this.deviceId)
|
|
1046
|
+
.gt('timeout_at', 'now')
|
|
891
1047
|
.maybeSingle();
|
|
892
1048
|
if (error) {
|
|
893
1049
|
console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after claim errors:`, error.message);
|
|
894
1050
|
await captureRemote('remote_channel_doorbell_fetch_error', { error });
|
|
895
1051
|
return;
|
|
896
1052
|
}
|
|
897
|
-
if (current?.status === 'pending'
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
// No claim landed; device.ts claims it. Do not hand an expired
|
|
901
|
-
// side-effecting call to the executor while it races the reaper.
|
|
1053
|
+
if (current?.status === 'pending') {
|
|
1054
|
+
// No claim landed; device.ts claims it. Read-back already excludes
|
|
1055
|
+
// expired rows using PostgreSQL time; its own claim does likewise.
|
|
902
1056
|
this.dispatchToolCall({ new: current });
|
|
903
1057
|
}
|
|
904
1058
|
else {
|
|
@@ -938,10 +1092,14 @@ export class RemoteChannel {
|
|
|
938
1092
|
return;
|
|
939
1093
|
}
|
|
940
1094
|
const state = this.channel.state;
|
|
1095
|
+
this.realtimeHealth.observeSocketState(String(this.client?.realtime?.connectionState?.() ?? 'unknown'));
|
|
941
1096
|
// Debug: Log current channel state (only if changed)
|
|
942
1097
|
if (!this.lastChannelState || this.lastChannelState !== state) {
|
|
943
1098
|
console.debug(`[DEBUG] channel state: ${state} — ${this.connState()}`);
|
|
944
1099
|
this.lastChannelState = state;
|
|
1100
|
+
if (state !== 'joined' && state !== 'joining') {
|
|
1101
|
+
captureRemote('remote_channel_state_health', { state, attempt: this.reconnectAttempt }).catch(() => { });
|
|
1102
|
+
}
|
|
945
1103
|
}
|
|
946
1104
|
// 'joined' = healthy. Clear the joining-overstay timer.
|
|
947
1105
|
if (state === 'joined') {
|
|
@@ -957,12 +1115,24 @@ export class RemoteChannel {
|
|
|
957
1115
|
return;
|
|
958
1116
|
}
|
|
959
1117
|
}
|
|
1118
|
+
// Broadcast has outlived the incident's join->error cycle with a
|
|
1119
|
+
// heartbeat confirmed after the join: the socket/channel path is
|
|
1120
|
+
// working even if Presence is not. Stop charging this join to the
|
|
1121
|
+
// reconnect budget, so a later ordinary blip gets fast recovery.
|
|
1122
|
+
// Presence keeps its own cooldown; full readiness still needs it.
|
|
1123
|
+
if (this.consecutiveUnreadyJoins > 0 && this.joinedAt !== null &&
|
|
1124
|
+
this.lastHeartbeatOkAt !== null && this.lastHeartbeatOkAt > this.joinedAt &&
|
|
1125
|
+
performance.now() - this.joinedAt >= STABLE_BROADCAST_RESET_MS) {
|
|
1126
|
+
console.debug(`[DEBUG] Broadcast channel stable for ${Math.round((performance.now() - this.joinedAt) / 1000)}s — clearing reconnect backoff budget (presence ${this.presenceTracked ? 'ready' : 'still pending'})`);
|
|
1127
|
+
this.consecutiveUnreadyJoins = 0;
|
|
1128
|
+
}
|
|
960
1129
|
// Self-heal a failed presence publish: the channel is up, so nothing
|
|
961
1130
|
// else will ever retry (SUBSCRIBED won't fire again). Until it
|
|
962
1131
|
// lands the dashboard shows this device offline, and if track()
|
|
963
1132
|
// already failed its retries the capability is withdrawn too, so
|
|
964
1133
|
// the server fails every dispatch to it fast.
|
|
965
|
-
if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence
|
|
1134
|
+
if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence &&
|
|
1135
|
+
!this.presenceInCooldown()) {
|
|
966
1136
|
console.debug('[DEBUG] Channel joined but presence not tracked — retrying track()');
|
|
967
1137
|
this.trackPresenceWithRetry(0, 1).catch(() => { });
|
|
968
1138
|
}
|
|
@@ -988,7 +1158,6 @@ export class RemoteChannel {
|
|
|
988
1158
|
}
|
|
989
1159
|
// Unhealthy: closed, errored, leaving — recreate
|
|
990
1160
|
this.joiningSince = null;
|
|
991
|
-
captureRemote('remote_channel_state_health', { state, attempt: this.reconnectAttempt });
|
|
992
1161
|
console.debug(`[DEBUG] ⚠️ Channel in unhealthy state '${state}' - recreating... — ${this.connState()}`);
|
|
993
1162
|
this.recreateChannel();
|
|
994
1163
|
}
|
|
@@ -1014,8 +1183,9 @@ export class RemoteChannel {
|
|
|
1014
1183
|
await this.sleep(SOCKET_SETTLE_MAX_MS);
|
|
1015
1184
|
return;
|
|
1016
1185
|
}
|
|
1017
|
-
|
|
1018
|
-
|
|
1186
|
+
// Monotonic: Date.now may be patched by the clock-skew correction.
|
|
1187
|
+
const deadline = performance.now() + SOCKET_SETTLE_MAX_MS;
|
|
1188
|
+
while (realtime.isDisconnecting() && performance.now() < deadline) {
|
|
1019
1189
|
await this.sleep(SOCKET_SETTLE_POLL_MS);
|
|
1020
1190
|
}
|
|
1021
1191
|
}
|
|
@@ -1054,9 +1224,10 @@ export class RemoteChannel {
|
|
|
1054
1224
|
// Create fresh channel
|
|
1055
1225
|
console.log(`🔄 Recreating channel... (attempt ${this.reconnectAttempt}) — ${this.connState()}`);
|
|
1056
1226
|
try {
|
|
1057
|
-
//
|
|
1058
|
-
//
|
|
1059
|
-
|
|
1227
|
+
// Our force-recreate fallback shares the extended sustained-failure
|
|
1228
|
+
// budget with the SDK. A 10s watchdog tick cannot cancel this wait
|
|
1229
|
+
// because isRecreatingChannel guards its whole duration.
|
|
1230
|
+
const backoffMs = watchdogRecreateDelayMs(Math.max(this.reconnectAttempt, this.consecutiveUnreadyJoins));
|
|
1060
1231
|
console.debug(`[DEBUG] Reconnect backoff: ${Math.round(backoffMs)}ms`);
|
|
1061
1232
|
await this.sleep(backoffMs);
|
|
1062
1233
|
// realtime-js runs its own rejoin timer, and the backoff above gives
|
|
@@ -1072,6 +1243,8 @@ export class RemoteChannel {
|
|
|
1072
1243
|
console.log(`✅ Channel self-healed during backoff — skipping recreate — ${this.connState()}`);
|
|
1073
1244
|
return; // finally-block below clears the re-entrancy guard
|
|
1074
1245
|
}
|
|
1246
|
+
// Count only watchdog recreations that continue past SDK self-heal.
|
|
1247
|
+
this.realtimeHealth.record('watchdog_recreates');
|
|
1075
1248
|
// Cap the whole recreate: a never-settling await (e.g. a subscribe that only
|
|
1076
1249
|
// ever emits CLOSED) must not pin isRecreatingChannel=true and silently disable
|
|
1077
1250
|
// the 10s watchdog. On timeout we reject -> catch -> finally clears the guard.
|
|
@@ -1117,8 +1290,9 @@ export class RemoteChannel {
|
|
|
1117
1290
|
await this.withTimeout(() => this.setTransportCapable(false), CAPABILITY_WRITE_TIMEOUT_MS, 'withdrawTransportCapability');
|
|
1118
1291
|
}
|
|
1119
1292
|
catch (withdrawErr) {
|
|
1120
|
-
// The
|
|
1121
|
-
//
|
|
1293
|
+
// The write stays queued, in order with any re-publish after
|
|
1294
|
+
// it, and ends within DEVICE_ROW_WRITE_TIMEOUT_MS; the flag
|
|
1295
|
+
// only advances on a confirmed write.
|
|
1122
1296
|
console.debug(`[DEBUG] Capability withdrawal did not complete: ${withdrawErr?.message}`);
|
|
1123
1297
|
}
|
|
1124
1298
|
}
|
|
@@ -1131,8 +1305,9 @@ export class RemoteChannel {
|
|
|
1131
1305
|
* Claim a call. True only when THIS update flipped the row pending ->
|
|
1132
1306
|
* executing, which is what makes dual delivery safe across processes.
|
|
1133
1307
|
* .eq('status','pending') makes it conditional; .select('id') makes the
|
|
1134
|
-
* result observable.
|
|
1135
|
-
*
|
|
1308
|
+
* result observable. Expiry is checked using Postgres time, not the
|
|
1309
|
+
* device clock. On a transient DB error it returns true (execute anyway),
|
|
1310
|
+
* matching prior behaviour — so device.ts's in-memory guard is what
|
|
1136
1311
|
* actually guarantees exactly-once within a process.
|
|
1137
1312
|
*/
|
|
1138
1313
|
async markCallExecuting(callId) {
|
|
@@ -1143,7 +1318,7 @@ export class RemoteChannel {
|
|
|
1143
1318
|
.update({ status: 'executing' })
|
|
1144
1319
|
.eq('id', callId)
|
|
1145
1320
|
.eq('status', 'pending')
|
|
1146
|
-
.gt('timeout_at',
|
|
1321
|
+
.gt('timeout_at', 'now')
|
|
1147
1322
|
.select('id');
|
|
1148
1323
|
if (error) {
|
|
1149
1324
|
console.error('[DEBUG] Failed to mark call executing:', error.message);
|
|
@@ -1162,10 +1337,9 @@ export class RemoteChannel {
|
|
|
1162
1337
|
async updateCallResult(callId, status, result = null, errorMessage = null) {
|
|
1163
1338
|
if (!this.client)
|
|
1164
1339
|
throw new Error('Client not initialized');
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
};
|
|
1340
|
+
// The DB terminal-status trigger stamps completed_at using PostgreSQL
|
|
1341
|
+
// time. Do not send a device-generated timestamp.
|
|
1342
|
+
const updateData = { status };
|
|
1169
1343
|
// Strip NUL (U+0000) before it reaches the jsonb `result` column.
|
|
1170
1344
|
// jsonb cannot store and rejects the whole write (Postgres 22P05),
|
|
1171
1345
|
// which otherwise leaves the call stuck 'executing' → the user waits out
|
|
@@ -1292,7 +1466,7 @@ export class RemoteChannel {
|
|
|
1292
1466
|
}
|
|
1293
1467
|
const { error } = await this.client
|
|
1294
1468
|
.from('mcp_devices')
|
|
1295
|
-
.update({ last_seen:
|
|
1469
|
+
.update({ last_seen: 'now', status: 'online' })
|
|
1296
1470
|
.eq('id', deviceId);
|
|
1297
1471
|
if (error) {
|
|
1298
1472
|
console.error('[DEBUG] Heartbeat update failed:', error.message);
|
|
@@ -1310,6 +1484,8 @@ export class RemoteChannel {
|
|
|
1310
1484
|
startHeartbeat(deviceId) {
|
|
1311
1485
|
console.debug('[DEBUG] Starting heartbeat for device:', deviceId);
|
|
1312
1486
|
this.heartbeatDeviceId = deviceId;
|
|
1487
|
+
this.realtimeHealth.setDevice(deviceId);
|
|
1488
|
+
this.realtimeHealth.start();
|
|
1313
1489
|
this.connectionCheckInterval = setInterval(() => {
|
|
1314
1490
|
this.checkConnectionHealth();
|
|
1315
1491
|
}, 10000);
|
|
@@ -1390,8 +1566,9 @@ export class RemoteChannel {
|
|
|
1390
1566
|
}
|
|
1391
1567
|
const { error } = await this.client
|
|
1392
1568
|
.from('mcp_devices')
|
|
1393
|
-
.update({ status: status, last_seen:
|
|
1394
|
-
.eq('id', deviceId)
|
|
1569
|
+
.update({ status: status, last_seen: 'now' })
|
|
1570
|
+
.eq('id', deviceId)
|
|
1571
|
+
.abortSignal(this.deviceRowWriteSignal());
|
|
1395
1572
|
if (error) {
|
|
1396
1573
|
console.error(`[DEBUG] Failed to set status ${status}:`, error.message);
|
|
1397
1574
|
if (status == "online") {
|
|
@@ -1451,7 +1628,9 @@ export class RemoteChannel {
|
|
|
1451
1628
|
const scriptPath = path.join(__dirname, 'scripts', 'blocking-offline-update.js');
|
|
1452
1629
|
console.debug('[DEBUG] Spawning blocking update script:', scriptPath);
|
|
1453
1630
|
console.debug('[DEBUG] Using node executable:', process.execPath);
|
|
1454
|
-
|
|
1631
|
+
// The node running this device, by its full path: a bare 'node' is
|
|
1632
|
+
// looked up in the working folder first on Windows
|
|
1633
|
+
const result = spawnSync(process.execPath, [
|
|
1455
1634
|
scriptPath,
|
|
1456
1635
|
deviceId,
|
|
1457
1636
|
supabaseUrl,
|
|
@@ -1498,6 +1677,7 @@ export class RemoteChannel {
|
|
|
1498
1677
|
}
|
|
1499
1678
|
}
|
|
1500
1679
|
async unsubscribe() {
|
|
1680
|
+
this.realtimeHealth.stop();
|
|
1501
1681
|
// setOffline()'s durable write is the final word on `status` from here,
|
|
1502
1682
|
// so stop the heartbeat and the channel callbacks from racing it. The
|
|
1503
1683
|
// races that matter: a heartbeat tick firing as the signal arrives, and
|