@wonderwhy-er/desktop-commander 0.2.46 → 0.2.48

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.
@@ -1,39 +1,197 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import { captureRemote } from '../utils/capture.js';
3
- const HEARTBEAT_INTERVAL = 15000;
4
- // Cap a single channel recreate so a hung await can't pin the re-entrancy guard
5
- // true (which would silently disable the connection watchdog).
6
- const RECREATE_TIMEOUT_MS = 30000;
7
- // Max time the channel may sit CONTINUOUSLY in 'joining' before we force a recreate.
8
- // 'joining' is normally healthy (we let realtime-js's rejoin backoff converge), but on a
9
- // HALF-OPEN socket (readyState OPEN yet dead) realtime-js parks the channel in 'joining'
10
- // forever and never reconnects the socket — the device then wedges offline silently with
11
- // no recreate firing. realtime-js's join push times out in ~10s, so a genuine join
12
- // resolves/errors well within this window; 3 health ticks of unbroken 'joining' means the
13
- // state machine has stalled and only a fresh socket (via recreate) recovers it.
3
+ import { VERSION } from '../version.js';
4
+ const NUL_CHAR = String.fromCharCode(0);
5
+ const NUL_RE = new RegExp(NUL_CHAR, 'g');
6
+ /**
7
+ * Strip NUL characters (U+0000) from strings and object keys — Postgres rejects
8
+ * them in jsonb and text (22P05). Walks the structure rather than
9
+ * round-tripping JSON, which would also match escape text in legitimate content.
10
+ */
11
+ export function stripNullBytes(value) {
12
+ if (typeof value === 'string') {
13
+ return (value.includes(NUL_CHAR) ? value.replace(NUL_RE, '') : value);
14
+ }
15
+ if (Array.isArray(value)) {
16
+ return value.map((item) => stripNullBytes(item));
17
+ }
18
+ if (value && typeof value === 'object') {
19
+ // Plain objects only — leave Date/Buffer/etc. untouched.
20
+ const proto = Object.getPrototypeOf(value);
21
+ if (proto !== Object.prototype && proto !== null)
22
+ return value;
23
+ const out = {};
24
+ for (const [k, v] of Object.entries(value)) {
25
+ out[k.includes(NUL_CHAR) ? k.replace(NUL_RE, '') : k] = stripNullBytes(v);
26
+ }
27
+ return out;
28
+ }
29
+ return value;
30
+ }
31
+ // last_seen cadences. The server tiers its sweep on the transport_broadcast_v1
32
+ // flag, so each must fit its tier's threshold in the server's constants.ts:
33
+ // capable -> 15 min, unflagged -> 45s.
34
+ const CAPABLE_HEARTBEAT_INTERVAL = 5 * 60 * 1000;
35
+ const LEGACY_HEARTBEAT_INTERVAL = 15 * 1000;
36
+ // Cap on a recreate's rebuild step so a hung await can't disable the watchdog.
37
+ // Must exceed createChannel()'s worst case (~31.5s of presence retries).
38
+ const RECREATE_TIMEOUT_MS = 45000;
39
+ // Max continuous time in 'joining' before forcing a recreate — a half-open
40
+ // socket parks the channel there forever, and a genuine join settles in ~10s.
14
41
  const JOINING_WEDGE_TIMEOUT_MS = 30000;
42
+ // Backstop for a half-open socket where 'joined' never changes and realtime-js's
43
+ // own heartbeat-close never completes. ~3x the 25s heartbeat interval.
44
+ const HEARTBEAT_STALE_TIMEOUT_MS = 75000;
45
+ // Fixed cadence for our own token refresh, independent of auth-js's internal
46
+ // ticker (disabled in initialize()) — see the clock-skew comment below for why.
47
+ const TOKEN_REFRESH_INTERVAL_MS = 45 * 60 * 1000;
48
+ // Below this, skew is noise — leave Date.now untouched. Above it, correct.
49
+ const CLOCK_SKEW_CORRECTION_THRESHOLD_MS = 5 * 60 * 1000;
50
+ // Failed recreates before withdrawing transport_broadcast_v1 — keeping it while
51
+ // unable to join makes the device undispatchable. Not lower than 3: ordinary
52
+ // half-open recovery legitimately costs 2.
53
+ const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
54
+ // Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
55
+ // does not cover.
56
+ const CAPABILITY_WRITE_TIMEOUT_MS = 5000;
57
+ // Cap on the shutdown session fetch, which races device.ts's 5s force-exit.
58
+ const OFFLINE_SESSION_TIMEOUT_MS = 500;
59
+ // realtime-js parks in 'disconnecting' for ~100ms after a disconnect and
60
+ // connect() early-returns for that whole window (see waitForSocketSettled).
61
+ // Bound generously — this only ever delays a recreate, which RECREATE_TIMEOUT_MS
62
+ // already covers.
63
+ const SOCKET_SETTLE_MAX_MS = 300;
64
+ const SOCKET_SETTLE_POLL_MS = 20;
65
+ // auth-js compares token expiry against this device's own Date.now(), with no
66
+ // clock-skew tolerance — a fast clock treats every fresh token as expired and
67
+ // refreshes forever (confirmed in prod on one device, via at least 3 separate
68
+ // check sites, not all gated by autoRefreshToken).
69
+ // Rather than chase each check, fix the shared input: every Supabase response
70
+ // carries a `Date` header (RFC 7231, the server's own clock), so a fetch
71
+ // wrapper passed via `global.fetch` corrects Date.now for this process off of
72
+ // that, continuously — covers every current and future check without needing
73
+ // to know where they live. Also shifts capture.ts telemetry timestamps
74
+ // (Date.now-based) onto server time, which is desirable: GA4 drops
75
+ // future-dated events, so a fast-clock device loses its telemetry otherwise.
76
+ // `new Date()` is untouched.
77
+ const rawDateNow = Date.now;
78
+ let clockOffsetMs = 0;
79
+ let clockPatched = false;
80
+ export function observeServerDate(dateHeader) {
81
+ if (!dateHeader)
82
+ return;
83
+ const serverMs = Date.parse(dateHeader);
84
+ if (Number.isNaN(serverMs))
85
+ return;
86
+ const offsetMs = serverMs - rawDateNow();
87
+ if (Math.abs(offsetMs) <= CLOCK_SKEW_CORRECTION_THRESHOLD_MS) {
88
+ if (clockPatched) {
89
+ Date.now = rawDateNow;
90
+ clockPatched = false;
91
+ }
92
+ return;
93
+ }
94
+ clockOffsetMs = offsetMs;
95
+ if (!clockPatched) {
96
+ Date.now = () => rawDateNow() + clockOffsetMs;
97
+ clockPatched = true;
98
+ console.warn(`⚠️ Device clock skewed ~${Math.round(offsetMs / 1000)}s from Supabase — correcting for this process`);
99
+ captureRemote('remote_channel_clock_skew_corrected', { offsetMs }).catch(() => { });
100
+ }
101
+ }
102
+ async function clockAwareFetch(input, init) {
103
+ const response = await fetch(input, init);
104
+ observeServerDate(response.headers.get('date'));
105
+ return response;
106
+ }
15
107
  export class RemoteChannel {
16
108
  constructor() {
17
109
  this.client = null;
18
110
  this.channel = null;
19
111
  this.heartbeatInterval = null;
20
112
  this.connectionCheckInterval = null;
113
+ /** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
114
+ this.heartbeatDeviceId = null;
115
+ // Single-slot queue keeping concurrent `status` PATCHes in order.
116
+ this.statusWriteChain = Promise.resolve();
117
+ /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
118
+ this.lastKnownSession = null;
119
+ /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
120
+ * land after setOffline()'s durable write. */
121
+ this.shuttingDown = false;
122
+ /** Auth session gone for good: stops rejoins and caps the notice at one line. */
123
+ this.sessionLost = false;
124
+ this.handlingSignedOut = false;
21
125
  // Store subscription parameters for channel recreation
22
126
  this.deviceId = null;
127
+ this.deviceName = null;
23
128
  this.onToolCall = null;
129
+ // Guard so setSession being called twice can't stack auth listeners.
130
+ this.authListenerRegistered = false;
131
+ /** False when presence publishing failed on an otherwise healthy channel;
132
+ * the health check retries, since SUBSCRIBED won't fire again. */
133
+ this.presenceTracked = false;
134
+ /** Last capability value written (null = never), to avoid redundant writes. */
135
+ this.transportCapableWritten = null;
136
+ /** Re-entrancy guard: on a wedged socket each track() buffers for the full
137
+ * 10s push timeout, so 10s health ticks would stack pushes. */
138
+ this.isTrackingPresence = false;
24
139
  // Track last device status to prevent duplicate log messages
25
140
  this.lastDeviceStatus = 'offline';
26
141
  // Track last channel state for debug logging
27
142
  this.lastChannelState = null;
28
- // Reconnect diagnostics + guard (see connState() / recreateChannel())
29
- this.reconnectAttempt = 0; // recreateChannel() attempts since last success
30
- this.isRecreatingChannel = false; // a recreate is in flight (re-entrancy guard)
31
- this.joiningSince = null; // ts the channel entered an unbroken 'joining' run; null when not joining
143
+ this.reconnectAttempt = 0; // recreates since the last success
144
+ this.isRecreatingChannel = false; // re-entrancy guard
145
+ this.joiningSince = null; // start of an unbroken 'joining' run (performance.now())
146
+ /** Last confirmed proof of life (SUBSCRIBED or heartbeat 'ok'); null until the
147
+ * first one lands. On performance.now(), not Date.now(): the clock-skew
148
+ * correction above can (un)patch Date.now mid-run, jumping wall-clock math by
149
+ * the whole offset — a backward jump would suppress stale detection for as
150
+ * long as the offset. Same for joiningSince. */
151
+ this.lastHeartbeatOkAt = null;
152
+ this.heartbeatListenerRegistered = false;
153
+ /** Our own fixed-cadence auth refresh timer — see TOKEN_REFRESH_INTERVAL_MS. */
154
+ this.tokenRefreshInterval = null;
32
155
  this._user = null;
33
156
  }
34
157
  get user() { return this._user; }
35
158
  initialize(url, key) {
36
- this.client = createClient(url, key);
159
+ // autoRefreshToken:false — we drive refresh ourselves (startTokenRefresh(),
160
+ // see TOKEN_REFRESH_INTERVAL_MS) instead of auth-js's local-clock-driven
161
+ // ticker. clockAwareFetch — see the clock-skew correction block above.
162
+ this.client = createClient(url, key, {
163
+ auth: { autoRefreshToken: false },
164
+ global: { fetch: clockAwareFetch },
165
+ realtime: {
166
+ // supabase-js's resolver ends in `?? supabaseKey`, so after SIGNED_OUT
167
+ // the socket silently re-pins to the anon key and every private-channel
168
+ // join is refused. Overriding under `realtime` (not the top-level
169
+ // `accessToken`, which turns client.auth into a throwing Proxy).
170
+ // getSession() may refresh on-demand when the token reads expired —
171
+ // that check is clock-skew-safe now (see clockAwareFetch above).
172
+ accessToken: async () => {
173
+ try {
174
+ const { data } = await this.client.auth.getSession();
175
+ if (data.session?.access_token)
176
+ return data.session.access_token;
177
+ }
178
+ catch {
179
+ /* fall through to the cached token */
180
+ }
181
+ return this.lastKnownSession?.access_token ?? null;
182
+ },
183
+ },
184
+ });
185
+ if (!this.heartbeatListenerRegistered) {
186
+ this.heartbeatListenerRegistered = true;
187
+ try {
188
+ this.client.realtime?.onHeartbeat?.((status) => {
189
+ if (status === 'ok')
190
+ this.lastHeartbeatOkAt = performance.now();
191
+ });
192
+ }
193
+ catch { /* no onHeartbeat on this client version: staleness check stays inert */ }
194
+ }
37
195
  }
38
196
  async setSession(session) {
39
197
  if (!this.client)
@@ -63,8 +221,129 @@ export class RemoteChannel {
63
221
  }
64
222
  this._user = user;
65
223
  console.debug('[DEBUG] Session set successfully, user:', user.email);
224
+ // Push the CURRENT token, not the one we were handed: setSession()
225
+ // refreshes internally, and the stale parameter would overwrite it.
226
+ const { data: { session: currentSession } } = await this.client.auth.getSession();
227
+ const realtimeToken = currentSession?.access_token ?? session.access_token;
228
+ this.client.realtime.setAuth(realtimeToken);
229
+ // Cached for setOffline(), which can't afford to wait on getSession().
230
+ this.lastKnownSession = {
231
+ access_token: realtimeToken,
232
+ refresh_token: currentSession?.refresh_token ?? session.refresh_token ?? null,
233
+ };
234
+ console.debug('[DEBUG] Realtime socket authorized with current session JWT');
235
+ if (!this.authListenerRegistered) {
236
+ this.authListenerRegistered = true;
237
+ this.client.auth.onAuthStateChange((event, newSession) => {
238
+ if (event === 'TOKEN_REFRESHED' && newSession?.access_token && this.client) {
239
+ console.debug('[DEBUG] Token refreshed — re-authorizing realtime socket');
240
+ this.client.realtime.setAuth(newSession.access_token);
241
+ this.lastKnownSession = {
242
+ access_token: newSession.access_token,
243
+ refresh_token: newSession.refresh_token ?? this.lastKnownSession?.refresh_token ?? null,
244
+ };
245
+ }
246
+ else if (event === 'SIGNED_OUT') {
247
+ void this.handleSignedOut();
248
+ }
249
+ });
250
+ }
66
251
  return { error };
67
252
  }
253
+ /**
254
+ * Session gone: one restore attempt, then go offline and stop retrying.
255
+ *
256
+ * The attempt matters because auth-js only treats network errors and 502/503/504
257
+ * as retryable — a 429 or 500 kills the session while the refresh token is fine.
258
+ * We don't re-authenticate: DeviceAuthenticator opens a browser and waits.
259
+ */
260
+ async handleSignedOut() {
261
+ if (this.handlingSignedOut || this.sessionLost || this.shuttingDown)
262
+ return;
263
+ this.handlingSignedOut = true;
264
+ try {
265
+ const cached = this.lastKnownSession;
266
+ if (cached?.refresh_token && this.client) {
267
+ console.debug('[DEBUG] SIGNED_OUT — attempting one session restore');
268
+ let restoreError = null;
269
+ try {
270
+ const { error } = await this.client.auth.setSession({
271
+ access_token: cached.access_token,
272
+ refresh_token: cached.refresh_token,
273
+ });
274
+ restoreError = error ?? null;
275
+ if (!restoreError) {
276
+ // auth-js refreshes ahead of expiry, so on SIGNED_OUT the cached
277
+ // JWT is usually still unexpired — setSession() then never touches
278
+ // the refresh endpoint, and a revoked refresh token would come back
279
+ // "restored" only to 400 again on the next tick. Force a real
280
+ // refresh so restore succeeds only with a live refresh token.
281
+ const { data, error: refreshError } = await this.client.auth.refreshSession();
282
+ restoreError = refreshError ?? null;
283
+ if (!restoreError) {
284
+ const renewed = data?.session;
285
+ if (renewed?.access_token) {
286
+ this.lastKnownSession = {
287
+ access_token: renewed.access_token,
288
+ refresh_token: renewed.refresh_token ?? cached.refresh_token,
289
+ };
290
+ }
291
+ console.log(' - ✅ Remote session restored after a transient sign-out');
292
+ await captureRemote('remote_channel_signed_out_recovered', {});
293
+ return;
294
+ }
295
+ }
296
+ }
297
+ catch (thrown) {
298
+ // setSession() with an unexpired JWT validates via _getUser() and
299
+ // THROWS on error instead of returning { error }.
300
+ restoreError = thrown;
301
+ }
302
+ await captureRemote('remote_channel_session_restore_failed', {
303
+ errorName: restoreError?.name ?? null,
304
+ errorStatus: restoreError?.status ?? null,
305
+ errorMessage: restoreError?.message ?? null,
306
+ });
307
+ console.debug(`[DEBUG] Session restore failed: ${restoreError?.message}`);
308
+ }
309
+ this.sessionLost = true;
310
+ await captureRemote('remote_channel_session_lost', {
311
+ hadRefreshToken: !!cached?.refresh_token,
312
+ });
313
+ this.stopHeartbeat();
314
+ // Tear realtime down entirely, same as recreateChannel() does: sessionLost
315
+ // only gates OUR health loop, while realtime-js keeps its own per-channel
316
+ // rejoin timer (~10s cap) firing expired-JWT joins on the errored channel
317
+ // until the channel is removed — measured in the 2026-08-18 staging rig at
318
+ // ~2.5k Unauthorized joins/device/day even with the downgrade guard active.
319
+ try {
320
+ if (this.channel) {
321
+ await this.client?.removeChannel(this.channel);
322
+ this.channel = null;
323
+ }
324
+ try {
325
+ await this.client?.realtime?.disconnect?.();
326
+ }
327
+ catch { /* best effort */ }
328
+ }
329
+ catch (teardownError) {
330
+ console.debug(`[DEBUG] Session-lost channel teardown failed: ${teardownError?.message}`);
331
+ }
332
+ try {
333
+ await this.setOffline(this.deviceId ?? undefined);
334
+ }
335
+ catch { /* best effort */ }
336
+ console.error('\n⚠️ Remote session expired and could not be renewed.');
337
+ console.error(' This device is now offline for remote calls; local tools still work.');
338
+ console.error(' Restart the terminal running Desktop Commander to reconnect.\n');
339
+ }
340
+ catch (error) {
341
+ console.debug(`[DEBUG] handleSignedOut() failed: ${error?.message}`);
342
+ }
343
+ finally {
344
+ this.handlingSignedOut = false;
345
+ }
346
+ }
68
347
  async getSession() {
69
348
  if (!this.client)
70
349
  throw new Error('Client not initialized');
@@ -129,19 +408,21 @@ export class RemoteChannel {
129
408
  }
130
409
  if (existingDevice) {
131
410
  console.debug('[DEBUG] Updating device status to online');
411
+ // transport_broadcast_v1 is NOT set here: the server treats it as
412
+ // binding, so it is written only once presence is proven.
132
413
  await this.updateDevice(existingDevice.id, {
133
414
  status: 'online',
134
415
  last_seen: new Date().toISOString(),
135
- capabilities: {}, // TODO: Capabilities are not yet implemented; keep this empty object for schema compatibility until device capabilities are defined and stored.
416
+ capabilities: this.capabilitiesPayload(false),
136
417
  device_name: deviceName
137
418
  });
138
419
  // Store parameters for channel recreation
139
420
  this.deviceId = existingDevice.id;
421
+ this.deviceName = deviceName;
140
422
  this.onToolCall = onToolCall;
141
423
  console.debug(`⏳ Subscribing to tool call channel...`);
142
424
  // Create and subscribe to the channel
143
425
  console.debug('[DEBUG] Calling createChannel()');
144
- // ! Ignore silently in Initialization to reconnect after
145
426
  await this.createChannel().catch((error) => {
146
427
  console.debug(`[DEBUG] Failed to create channel, will retry after socket reconnect: ${error?.message || error} — ${this.connState()}`);
147
428
  });
@@ -153,27 +434,132 @@ export class RemoteChannel {
153
434
  }
154
435
  }
155
436
  /**
156
- * Create and subscribe to the channel.
157
- * This is used for both initial subscription and recreation after socket reconnects.
437
+ * Publish presence, retrying a non-'ok' result — track() resolves with a
438
+ * status rather than rejecting, and absent presence reads as offline on the
439
+ * server. `presenceTracked` lets the health check retry later.
158
440
  */
441
+ async trackPresenceWithRetry(recovered, attempts = 3) {
442
+ if (this.isTrackingPresence)
443
+ return; // never stack pushes on a wedged socket
444
+ this.isTrackingPresence = true;
445
+ try {
446
+ await this.trackPresenceInner(recovered, attempts);
447
+ }
448
+ finally {
449
+ this.isTrackingPresence = false;
450
+ }
451
+ }
452
+ async trackPresenceInner(recovered, attempts) {
453
+ for (let attempt = 1; attempt <= attempts; attempt++) {
454
+ if (!this.channel || this.channel.state !== 'joined')
455
+ return;
456
+ let status;
457
+ try {
458
+ status = await this.channel.track({
459
+ device_id: this.deviceId,
460
+ device_name: this.deviceName,
461
+ app_version: VERSION,
462
+ platform: process.platform
463
+ });
464
+ }
465
+ catch (trackErr) {
466
+ status = `threw: ${trackErr?.message}`;
467
+ }
468
+ if (status === 'ok') {
469
+ this.presenceTracked = true;
470
+ console.log(`👋 Presence tracked (device ${this.deviceId} visible as online)`);
471
+ // Reconnect attempts preceding this join (0 on a first join).
472
+ captureRemote('remote_channel_presence_tracked', { recoveredAfterAttempts: recovered }).catch(() => { });
473
+ // Proven end-to-end (joined AND presence published) — only now
474
+ // may the server treat our presence as authoritative.
475
+ await this.setTransportCapable(true);
476
+ return;
477
+ }
478
+ console.error(`❌ Presence track not acknowledged (${status}) — attempt ${attempt}/${attempts}`);
479
+ if (attempt < attempts)
480
+ await this.sleep(500 * attempt);
481
+ }
482
+ this.presenceTracked = false;
483
+ console.error('❌ Presence track failed after retries — withdrawing broadcast capability');
484
+ captureRemote('remote_channel_presence_track_error', { attempts }).catch(() => { });
485
+ // Withdraw: a stale flag with no presence makes the server refuse to
486
+ // dispatch at all. The faster heartbeat tier keeps the device's status
487
+ // accurate for the DB-status fallback while it recovers.
488
+ await this.setTransportCapable(false);
489
+ }
490
+ /**
491
+ * The complete `capabilities` JSONB value. One place only: every write
492
+ * replaces the whole column, so a second literal would silently drop keys.
493
+ */
494
+ capabilitiesPayload(broadcastCapable) {
495
+ return {
496
+ app_version: VERSION,
497
+ ...(broadcastCapable ? { transport_broadcast_v1: true } : {})
498
+ };
499
+ }
500
+ /**
501
+ * Advertise (or withdraw) the broadcast capability. Only true while genuinely
502
+ * reachable that way — the server uses it to pick a transport, to read absent
503
+ * presence as offline, and to choose the sweep tier, so every change must
504
+ * re-arm the heartbeat.
505
+ */
506
+ async setTransportCapable(capable) {
507
+ if (!this.client || !this.deviceId)
508
+ return;
509
+ if (this.transportCapableWritten === capable)
510
+ return; // no redundant writes
511
+ try {
512
+ const capabilities = this.capabilitiesPayload(capable);
513
+ const { error } = await this.client
514
+ .from('mcp_devices')
515
+ .update({ capabilities })
516
+ .eq('id', this.deviceId);
517
+ if (error) {
518
+ console.error('[DEBUG] Failed to update transport capability:', error.message);
519
+ return;
520
+ }
521
+ this.transportCapableWritten = capable;
522
+ console.debug(`[DEBUG] Transport capability set to ${capable ? 'broadcast_v1' : 'withdrawn'}`);
523
+ // Tier changed — move last_seen onto the cadence that tier's sweep
524
+ // threshold expects (no-op if the heartbeat hasn't started yet).
525
+ this.scheduleHeartbeat();
526
+ // last_seen may already be past the 45s threshold now judging us,
527
+ // so write once immediately rather than waiting out the interval.
528
+ if (!capable && this.heartbeatDeviceId) {
529
+ this.updateHeartbeat(this.heartbeatDeviceId).catch(() => { });
530
+ }
531
+ }
532
+ catch (error) {
533
+ console.error('[DEBUG] Transport capability update threw:', error?.message);
534
+ }
535
+ }
536
+ /** Create and subscribe the private channel (initial join and recreation). */
159
537
  createChannel() {
160
538
  return new Promise((resolve, reject) => {
161
- if (!this.client || !this.user?.id || !this.onToolCall) {
539
+ if (!this.client || !this.user?.id || !this.onToolCall || !this.deviceId) {
540
+ // deviceId is the presence KEY; a null key gets a random one and
541
+ // the server's lookup by device id silently misses.
162
542
  console.debug('[DEBUG] createChannel() failed - missing prerequisites');
163
543
  return reject(new Error('Client not initialized or missing subscription parameters'));
164
544
  }
165
- console.debug('[DEBUG] Creating channel: device_tool_call_queue');
166
- this.channel = this.client.channel('device_tool_call_queue')
167
- .on('postgres_changes', {
168
- event: 'INSERT',
169
- schema: 'public',
170
- table: 'mcp_remote_calls',
171
- filter: `user_id=eq.${this.user.id}`
172
- }, (payload) => {
173
- console.debug('[DEBUG] Realtime event received, payload:', payload?.new?.id);
174
- if (this.onToolCall) {
175
- this.onToolCall(payload);
545
+ // Private per-user channel: new_call doorbells + this device's
546
+ // Presence, keyed by device id.
547
+ const channelName = `user:${this.user.id}`;
548
+ console.debug(`[DEBUG] Creating channel: ${channelName}`);
549
+ this.channel = this.client.channel(channelName, {
550
+ // ack: true — without it send() resolves 'ok' once the frame hits
551
+ // the socket, making notifyResult's status check dead code.
552
+ config: {
553
+ private: true,
554
+ broadcast: { ack: true },
555
+ // Non-null: the guard above rejects when !deviceId.
556
+ presence: { key: this.deviceId, enabled: true }
176
557
  }
558
+ })
559
+ .on('broadcast', { event: 'new_call' }, ({ payload }) => {
560
+ this.onDoorbell(payload).catch((e) => {
561
+ console.error('[DEBUG] Doorbell handling failed:', e?.message);
562
+ });
177
563
  })
178
564
  .subscribe((status, err) => {
179
565
  // Debug: Log all subscription status events
@@ -181,39 +567,144 @@ export class RemoteChannel {
181
567
  if (status === 'SUBSCRIBED') {
182
568
  const recovered = this.reconnectAttempt;
183
569
  this.reconnectAttempt = 0;
570
+ this.lastHeartbeatOkAt = performance.now(); // a fresh join is proof of life too
184
571
  console.log(`✅ Channel subscribed${recovered > 0 ? ` (recovered after ${recovered} attempt${recovered === 1 ? '' : 's'})` : ''}`);
185
- // Update device status on successful connection
186
- if (this.deviceId) {
187
- this.setOnlineStatus(this.deviceId, 'online').catch(e => {
188
- console.error('Failed to set online status:', e.message);
189
- });
190
- }
191
- resolve();
572
+ // Update device status on successful connection (queued, so
573
+ // it can't be overtaken by a teardown's status write).
574
+ this.queueStatusWrite('online');
575
+ // Presence is the live signal dispatch reads, so resolve
576
+ // only once it lands — otherwise registerDevice() reports
577
+ // "Device ready" while still undispatchable.
578
+ this.trackPresenceWithRetry(recovered)
579
+ .catch(() => { })
580
+ .finally(() => resolve());
192
581
  }
193
582
  else if (status === 'CHANNEL_ERROR') {
194
583
  // CHANNEL_ERROR is the only status carrying a real error message.
195
584
  console.error(`❌ Channel error: ${err?.message || 'unknown'} — ${this.connState()}`);
196
- this.setOnlineStatus(this.deviceId, 'offline');
585
+ this.presenceTracked = false;
586
+ this.syncReachabilityStatus();
587
+ // Fires on ordinary network faults too — filter on the
588
+ // error text to isolate an 008 misconfiguration.
197
589
  captureRemote('remote_channel_subscription_error', { error: err?.message || 'Channel error' }).catch(() => { });
198
590
  reject(err || new Error('Failed to initialize tool call channel subscription'));
199
591
  }
200
592
  else if (status === 'TIMED_OUT') {
201
593
  console.error(`⏱️ Channel subscription timed out, Reconnecting... — ${this.connState()}`);
202
- this.setOnlineStatus(this.deviceId, 'offline');
594
+ this.syncReachabilityStatus();
203
595
  captureRemote('remote_channel_subscription_timeout', { attempt: this.reconnectAttempt }).catch(() => { });
204
596
  reject(new Error('Tool call channel subscription timed out'));
205
597
  }
206
598
  else if (status === 'CLOSED') {
207
599
  // Settle the promise so an in-flight recreateChannel() can't await
208
- // forever (which would wedge the re-entrancy guard / watchdog), and
209
- // mark the device offline like the other degraded states.
600
+ // forever (which would wedge the re-entrancy guard / watchdog).
210
601
  console.warn(`⚠️ Channel closed — ${this.connState()}`);
211
- this.setOnlineStatus(this.deviceId, 'offline');
602
+ this.syncReachabilityStatus();
212
603
  reject(new Error('Tool call channel closed during subscribe'));
213
604
  }
214
605
  });
215
606
  });
216
607
  }
608
+ /** Hand a call to device.ts, observing the rejection — the handler is async
609
+ * and an unhandled rejection terminates the process. */
610
+ dispatchToolCall(payload) {
611
+ try {
612
+ const maybePromise = this.onToolCall?.(payload);
613
+ if (maybePromise instanceof Promise) {
614
+ maybePromise.catch((e) => {
615
+ console.error('[DEBUG] Tool call handler rejected:', e?.message);
616
+ });
617
+ }
618
+ }
619
+ catch (e) {
620
+ console.error('[DEBUG] Tool call handler threw:', e?.message);
621
+ }
622
+ }
623
+ /**
624
+ * Handle a 'new_call' doorbell. It carries ids only; the row is fetched by
625
+ * primary key and fed through the same handler as a postgres_changes
626
+ * payload, so device.ts stays transport-agnostic.
627
+ */
628
+ async onDoorbell(payload) {
629
+ const callId = payload?.call_id;
630
+ if (!callId)
631
+ return;
632
+ if (payload?.device_id && payload.device_id !== this.deviceId) {
633
+ console.debug('[DEBUG] Ignoring doorbell for different device');
634
+ return;
635
+ }
636
+ // Not a telemetry event on purpose: ~126k/day in prod. Transport usage
637
+ // is already segmentable server-side via metadata.transport.
638
+ console.debug('[DEBUG] Doorbell received for call:', callId);
639
+ if (!this.client)
640
+ return;
641
+ // Retry on transient failures (a REST blip while the socket stays
642
+ // healthy). Post-flip this fetch is the only way we learn about a call,
643
+ // so a hiccup must not cost a 5-minute timeout.
644
+ let row = null;
645
+ let lastError = null;
646
+ for (const delayMs of [0, 500, 1500]) {
647
+ if (delayMs > 0)
648
+ await this.sleep(delayMs);
649
+ const { data, error } = await this.client
650
+ .from('mcp_remote_calls')
651
+ .select('*')
652
+ .eq('id', callId)
653
+ .maybeSingle();
654
+ if (!error) {
655
+ row = data;
656
+ lastError = null;
657
+ break;
658
+ }
659
+ lastError = error;
660
+ console.debug(`[DEBUG] Doorbell row fetch attempt failed for ${callId}: ${error.message} — retrying`);
661
+ }
662
+ if (lastError) {
663
+ console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after retries:`, lastError.message);
664
+ await captureRemote('remote_channel_doorbell_fetch_error', { error: lastError });
665
+ return;
666
+ }
667
+ if (!row) {
668
+ // Already claimed and deleted, or cleanup raced delivery. Not
669
+ // retried: the row is always inserted before the doorbell is sent.
670
+ await captureRemote('remote_channel_doorbell_row_missing', { call_id: callId });
671
+ return;
672
+ }
673
+ // Optimization, not a guard — saves a hop on a duplicate doorbell
674
+ // (retry, reconnect). Exactly-once lives in device.ts (seenCallIds + DB claim).
675
+ if (row.status !== 'pending') {
676
+ console.debug('[DEBUG] Doorbell call already claimed:', callId);
677
+ return;
678
+ }
679
+ this.dispatchToolCall({ new: row });
680
+ }
681
+ /**
682
+ * Tell the server a result row is written. Fire-and-forget: a failed send
683
+ * just falls back to the server's 10s recovery poll. MUST run only after
684
+ * updateCallResult() resolves, so the server's fetch-by-id sees a terminal row.
685
+ */
686
+ async notifyResult(callId) {
687
+ if (!this.channel || this.channel.state !== 'joined') {
688
+ console.debug('[DEBUG] Result doorbell skipped — channel not joined (recovery poll covers)');
689
+ return;
690
+ }
691
+ try {
692
+ // realtime-js send() RESOLVES with 'ok' | 'timed out' | 'error' —
693
+ // it does not reject, so check the status or failures are invisible.
694
+ const result = await this.channel.send({ type: 'broadcast', event: 'result', payload: { call_id: callId } });
695
+ if (result === 'ok') {
696
+ console.debug('[DEBUG] Result doorbell sent:', callId);
697
+ }
698
+ else {
699
+ console.debug(`[DEBUG] Result doorbell not acknowledged (${result}) — recovery poll covers:`, callId);
700
+ captureRemote('remote_channel_result_doorbell_send_failed', { result }).catch(() => { });
701
+ }
702
+ }
703
+ catch (error) {
704
+ console.debug('[DEBUG] Result doorbell send failed (recovery poll covers):', error?.message);
705
+ captureRemote('remote_channel_result_doorbell_send_failed', { error: error?.message }).catch(() => { });
706
+ }
707
+ }
217
708
  /**
218
709
  * Compact connection state for logs — e.g. "socket=open(1) ch=errored attempt=3".
219
710
  * readyState 1=OPEN (a 1 while joins keep failing = a half-open socket being reused),
@@ -232,6 +723,8 @@ export class RemoteChannel {
232
723
  * Check if channel is connected, recreate if not.
233
724
  */
234
725
  checkConnectionHealth() {
726
+ if (this.sessionLost)
727
+ return;
235
728
  if (!this.channel || !this.client || !this.user?.id || !this.onToolCall) {
236
729
  return;
237
730
  }
@@ -244,17 +737,33 @@ export class RemoteChannel {
244
737
  // 'joined' = healthy. Clear the joining-overstay timer.
245
738
  if (state === 'joined') {
246
739
  this.joiningSince = null;
740
+ // 'joined' is a cached string, not proof of a live socket. Cross-check
741
+ // against the last confirmed heartbeat reply.
742
+ if (this.lastHeartbeatOkAt !== null) {
743
+ const staleMs = performance.now() - this.lastHeartbeatOkAt;
744
+ if (staleMs > HEARTBEAT_STALE_TIMEOUT_MS) {
745
+ console.debug(`[DEBUG] ⚠️ Channel reads 'joined' but no confirmed heartbeat in ${Math.round(staleMs / 1000)}s - forcing recreate — ${this.connState()}`);
746
+ captureRemote('remote_channel_heartbeat_stale', { staleMs, attempt: this.reconnectAttempt });
747
+ this.recreateChannel();
748
+ return;
749
+ }
750
+ }
751
+ // Self-heal a failed presence publish: the channel is up, so nothing
752
+ // else will ever retry (SUBSCRIBED won't fire again), and without
753
+ // presence the server reports this healthy device as offline.
754
+ if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence) {
755
+ console.debug('[DEBUG] Channel joined but presence not tracked — retrying track()');
756
+ this.trackPresenceWithRetry(0, 1).catch(() => { });
757
+ }
247
758
  return;
248
759
  }
249
- // 'joining' = transitional — normally let realtime-js's own rejoin backoff converge
250
- // instead of tearing the channel down mid-join (recreating on every non-joined state
251
- // amputates that backoff). BUT bound it: on a half-open socket realtime-js can park
252
- // the channel in 'joining' indefinitely without ever reconnecting the socket, so the
253
- // recreate below would never fire and the device wedges offline silently. If 'joining'
254
- // overstays JOINING_WEDGE_TIMEOUT_MS unbroken, force a recreate — the only path that
255
- // disconnect()s the dead socket. (connState() in the log shows the half-open socket.)
760
+ // 'joining' is transitional — let realtime-js's rejoin backoff converge
761
+ // rather than tearing the channel down mid-join. But bound it: a
762
+ // half-open socket parks the channel here indefinitely, so past
763
+ // JOINING_WEDGE_TIMEOUT_MS force a recreate, the only path that
764
+ // disconnect()s the dead socket.
256
765
  if (state === 'joining') {
257
- const now = Date.now();
766
+ const now = performance.now();
258
767
  if (this.joiningSince === null)
259
768
  this.joiningSince = now;
260
769
  const stuckMs = now - this.joiningSince;
@@ -277,6 +786,28 @@ export class RemoteChannel {
277
786
  * can't leave isRecreatingChannel stuck true and disable the watchdog. Mirrors
278
787
  * closeWithTimeout() in desktop-commander-integration.ts.
279
788
  */
789
+ sleep(ms) {
790
+ return new Promise((resolve) => setTimeout(resolve, ms));
791
+ }
792
+ /**
793
+ * Block until realtime-js has left the 'disconnecting' state it enters on
794
+ * disconnect(), so the next subscribe() actually dials a socket instead of
795
+ * hitting connect()'s early return. Bounded either way — worst case we cost
796
+ * a recreate SOCKET_SETTLE_MAX_MS.
797
+ */
798
+ async waitForSocketSettled() {
799
+ const realtime = this.client?.realtime;
800
+ // No predicate to poll (older/newer client): wait out the internal
801
+ // fallback timer blind rather than guess at the state.
802
+ if (typeof realtime?.isDisconnecting !== 'function') {
803
+ await this.sleep(SOCKET_SETTLE_MAX_MS);
804
+ return;
805
+ }
806
+ const deadline = Date.now() + SOCKET_SETTLE_MAX_MS;
807
+ while (realtime.isDisconnecting() && Date.now() < deadline) {
808
+ await this.sleep(SOCKET_SETTLE_POLL_MS);
809
+ }
810
+ }
280
811
  async withTimeout(op, ms, name) {
281
812
  let timer;
282
813
  try {
@@ -312,13 +843,31 @@ export class RemoteChannel {
312
843
  // Create fresh channel
313
844
  console.log(`🔄 Recreating channel... (attempt ${this.reconnectAttempt}) — ${this.connState()}`);
314
845
  try {
846
+ // Jittered backoff so a fleet-wide event doesn't stampede every
847
+ // device into reconnecting at once. ~1-3s rising to ~15-45s.
848
+ const backoffMs = Math.min(30000, 1000 * 2 ** Math.min(this.reconnectAttempt, 5)) * (0.5 + Math.random());
849
+ console.debug(`[DEBUG] Reconnect backoff: ${Math.round(backoffMs)}ms`);
850
+ await this.sleep(backoffMs);
851
+ // realtime-js runs its own rejoin timer, and the backoff above gives
852
+ // it a window to win: the old channel can come back 'joined' while we
853
+ // slept. Destroying a healthy channel would cause a pointless outage
854
+ // cycle — bail out instead (observed live on staging, 2026-07-23).
855
+ // 'joined' alone isn't proof — only bail out when we don't already
856
+ // know the heartbeat is stale (this recreate may have been triggered
857
+ // by exactly that).
858
+ const heartbeatStale = this.lastHeartbeatOkAt !== null
859
+ && (performance.now() - this.lastHeartbeatOkAt) > HEARTBEAT_STALE_TIMEOUT_MS;
860
+ if (this.channel?.state === 'joined' && !heartbeatStale) {
861
+ console.log(`✅ Channel self-healed during backoff — skipping recreate — ${this.connState()}`);
862
+ return; // finally-block below clears the re-entrancy guard
863
+ }
315
864
  // Cap the whole recreate: a never-settling await (e.g. a subscribe that only
316
865
  // ever emits CLOSED) must not pin isRecreatingChannel=true and silently disable
317
866
  // the 10s watchdog. On timeout we reject -> catch -> finally clears the guard.
318
867
  await this.withTimeout(async () => {
319
- // Destroy old channel — AWAIT it so the channel registry empties before we
320
- // rebuild. (The un-awaited version raced the synchronous new-channel push, so
321
- // realtime-js never tore the socket down and a half-open one got reused.)
868
+ // Await it so the channel registry empties before we rebuild —
869
+ // otherwise realtime-js never tears the socket down and a
870
+ // half-open one gets reused.
322
871
  if (this.channel) {
323
872
  console.debug('[DEBUG] Destroying old channel');
324
873
  await this.client.removeChannel(this.channel);
@@ -331,6 +880,15 @@ export class RemoteChannel {
331
880
  await this.client.realtime?.disconnect?.();
332
881
  }
333
882
  catch { /* best effort */ }
883
+ // ...but disconnect() is not synchronous from connect()'s point
884
+ // of view: it parks _connectionState in 'disconnecting' and
885
+ // _teardownConnection() nulls the conn.onclose that would clear
886
+ // it, so only an internal ~100ms fallback timer does. connect()
887
+ // early-returns for that whole window, so rebuilding here makes
888
+ // subscribe()'s socket.connect() a silent no-op and the channel
889
+ // sits in 'joining' until the 10s join timeout — a wasted first
890
+ // recreate. Wait for the state to settle before rebuilding.
891
+ await this.waitForSocketSettled();
334
892
  console.debug('[DEBUG] Calling createChannel() for recreation');
335
893
  await this.createChannel();
336
894
  }, RECREATE_TIMEOUT_MS, 'recreateChannel');
@@ -338,25 +896,57 @@ export class RemoteChannel {
338
896
  catch (err) {
339
897
  captureRemote('remote_channel_recreate_error', { errMsg: err?.message, attempt: this.reconnectAttempt });
340
898
  console.debug(`[DEBUG] Channel recreation failed: ${err?.message} — ${this.connState()}`);
899
+ // Sustained failure: stop promising a transport we can't deliver, or
900
+ // the server's presence overlay reports this device offline
901
+ // authoritatively and overrides `status`.
902
+ if (this.reconnectAttempt >= TRANSPORT_WITHDRAW_AFTER_ATTEMPTS) {
903
+ // Bounded, in its own try: this catch block is outside
904
+ // RECREATE_TIMEOUT_MS, so a hanging PATCH would pin
905
+ // isRecreatingChannel and disable the watchdog.
906
+ try {
907
+ await this.withTimeout(() => this.setTransportCapable(false), CAPABILITY_WRITE_TIMEOUT_MS, 'withdrawTransportCapability');
908
+ }
909
+ catch (withdrawErr) {
910
+ // The next failed recreate retries; the flag only advances
911
+ // on a confirmed write, so nothing is lost.
912
+ console.debug(`[DEBUG] Capability withdrawal did not complete: ${withdrawErr?.message}`);
913
+ }
914
+ }
341
915
  }
342
916
  finally {
343
917
  this.isRecreatingChannel = false;
344
918
  }
345
919
  }
920
+ /**
921
+ * Claim a call. True only when THIS update flipped the row pending ->
922
+ * executing, which is what makes dual delivery safe across processes.
923
+ * .eq('status','pending') makes it conditional; .select('id') makes the
924
+ * result observable. On a transient DB error it returns true (execute
925
+ * anyway), matching prior behaviour — so device.ts's in-memory guard is what
926
+ * actually guarantees exactly-once within a process.
927
+ */
346
928
  async markCallExecuting(callId) {
347
929
  if (!this.client)
348
930
  throw new Error('Client not initialized');
349
- const { error } = await this.client
931
+ const { data, error } = await this.client
350
932
  .from('mcp_remote_calls')
351
933
  .update({ status: 'executing' })
352
- .eq('id', callId);
934
+ .eq('id', callId)
935
+ .eq('status', 'pending')
936
+ .select('id');
353
937
  if (error) {
354
938
  console.error('[DEBUG] Failed to mark call executing:', error.message);
355
939
  await captureRemote('remote_channel_mark_call_executing_error', { error });
940
+ return true; // preserve legacy behavior: execution proceeds despite the write error
356
941
  }
357
- else {
942
+ const claimed = !!data && data.length > 0;
943
+ if (claimed) {
358
944
  console.debug('[DEBUG] Call marked executing:', callId);
359
945
  }
946
+ else {
947
+ console.debug('[DEBUG] Call already claimed (duplicate delivery), skipping:', callId);
948
+ }
949
+ return claimed;
360
950
  }
361
951
  async updateCallResult(callId, status, result = null, errorMessage = null) {
362
952
  if (!this.client)
@@ -365,36 +955,124 @@ export class RemoteChannel {
365
955
  status: status,
366
956
  completed_at: new Date().toISOString()
367
957
  };
958
+ // Strip NUL (U+0000) before it reaches the jsonb `result` column.
959
+ // jsonb cannot store and rejects the whole write (Postgres 22P05),
960
+ // which otherwise leaves the call stuck 'executing' → the user waits out
961
+ // a 5-minute timeout for a tool that actually ran. Common with binary
962
+ // file reads / process output. error_message is text, so it's exempt.
368
963
  if (result !== null)
369
- updateData.result = result;
964
+ updateData.result = stripNullBytes(result);
965
+ // Postgres `text` rejects NUL too (not just jsonb) — a NUL-bearing error
966
+ // message would fail this terminal write, and because result === null the
967
+ // fallback below wouldn't fire, stranding the call until the 5-min timeout.
370
968
  if (errorMessage !== null)
371
- updateData.error_message = errorMessage;
372
- console.debug('[DEBUG] Updating call result:', updateData);
373
- const { data, error } = await this.client
969
+ updateData.error_message = stripNullBytes(errorMessage);
970
+ // Gated: the size is only knowable by serializing, and results reach
971
+ // 13 MB — doing that eagerly for a log line would cost more than the
972
+ // rest of this function.
973
+ if (process.env.DEBUG_MODE === 'true') {
974
+ console.debug(`[DEBUG] Updating call result: ${callId} status=${status}` +
975
+ (result !== null ? ` resultBytes=~${JSON.stringify(updateData.result)?.length ?? 0}` : ''));
976
+ }
977
+ const { error } = await this.client
374
978
  .from('mcp_remote_calls')
375
979
  .update(updateData)
376
980
  .eq('id', callId);
377
981
  if (error) {
378
982
  console.error('[DEBUG] Failed to update call result:', error.message);
379
983
  await captureRemote('remote_channel_update_call_result_error', { error });
984
+ // Fail-fast fallback: if the RESULT write failed (sanitize should
985
+ // prevent the NUL case, but any unstorable payload lands here),
986
+ // record a terminal 'failed' with a text-only message so the user
987
+ // gets an immediate, honest error instead of a 5-minute phantom
988
+ // timeout. Guard against infinite recursion (only for result writes).
989
+ if (result !== null && status !== 'failed') {
990
+ await this.updateCallResult(callId, 'failed', null, `Result could not be stored (${error.message})`);
991
+ }
380
992
  }
381
993
  else {
382
- console.debug('[DEBUG] Call result updated successfully:', data);
994
+ // (an UPDATE without .select() returns no row data — log the id)
995
+ console.debug('[DEBUG] Call result updated successfully:', callId);
996
+ }
997
+ }
998
+ /** Reachable means the private channel is joined. Gates the heartbeat and `status`. */
999
+ isReachable() {
1000
+ return this.channel?.state === 'joined';
1001
+ }
1002
+ /**
1003
+ * Set `status` from actual reachability. `status` is transport-agnostic (the
1004
+ * server filters on it), so it must not follow one channel's health — the
1005
+ * private channel's error path re-fires on every rejoin and would oscillate
1006
+ * the row against the heartbeat. Same predicate as the heartbeat gate.
1007
+ */
1008
+ syncReachabilityStatus() {
1009
+ this.queueStatusWrite(this.isReachable() ? 'online' : 'offline');
1010
+ }
1011
+ /**
1012
+ * Serialize the channel-callback status writes. They fire from un-awaited
1013
+ * callbacks, and inside recreateChannel() a teardown's 'offline' and the
1014
+ * fresh join's 'online' land ~100-300ms apart — unordered, 'offline' can win
1015
+ * and leave a healthy device undispatchable until the next heartbeat.
1016
+ *
1017
+ * Not the single writer: updateHeartbeat, registerDevice and setOffline's
1018
+ * subprocess write status directly, so this is not total ordering.
1019
+ */
1020
+ queueStatusWrite(status) {
1021
+ // After teardown begins, setOffline() owns the final status write.
1022
+ if (this.shuttingDown) {
1023
+ console.debug(`[DEBUG] Status write '${status}' suppressed — teardown in progress`);
1024
+ return;
383
1025
  }
1026
+ this.statusWriteChain = this.statusWriteChain
1027
+ .then(() => (this.deviceId ? this.setOnlineStatus(this.deviceId, status) : undefined))
1028
+ .catch((e) => {
1029
+ console.error('[DEBUG] Status write failed:', e?.message);
1030
+ });
1031
+ }
1032
+ /**
1033
+ * Heartbeat cadence for the tier this device is CURRENTLY in. Follows the
1034
+ * capability flag (what the server actually tiers its sweep on), not the
1035
+ * build — see LEGACY_HEARTBEAT_INTERVAL.
1036
+ */
1037
+ heartbeatIntervalMs() {
1038
+ return this.transportCapableWritten === true
1039
+ ? CAPABLE_HEARTBEAT_INTERVAL
1040
+ : LEGACY_HEARTBEAT_INTERVAL;
384
1041
  }
385
1042
  async updateHeartbeat(deviceId) {
386
1043
  if (!this.client)
387
1044
  return;
1045
+ // This write asserts status:'online' too, so it MUST respect the
1046
+ // shutdown gate — otherwise a heartbeat firing (or in flight) as SIGINT
1047
+ // lands can be applied after setOffline()'s subprocess write and leave
1048
+ // an exited process marked online with a fresh last_seen, which for a
1049
+ // capable device the sweep then cannot age out for a full tier window.
1050
+ if (this.shuttingDown) {
1051
+ console.debug('[DEBUG] Skipping heartbeat write — shutting down');
1052
+ return;
1053
+ }
388
1054
  try {
1055
+ // Skip the write entirely when no transport is up. Bumping last_seen
1056
+ // on a deaf device would keep its row perpetually young, so the
1057
+ // server's staleness sweep could never age it out and correct a
1058
+ // stale 'online' — and whenever presence is unavailable (kill
1059
+ // switch, wedged socket) that stale row is exactly what dispatch
1060
+ // falls back to. Staying silent lets the sweep do its job.
1061
+ if (!this.isReachable()) {
1062
+ console.debug('[DEBUG] Skipping heartbeat write — no transport joined; letting the row age out');
1063
+ return;
1064
+ }
389
1065
  const { error } = await this.client
390
1066
  .from('mcp_devices')
391
- .update({ last_seen: new Date().toISOString() })
1067
+ .update({ last_seen: new Date().toISOString(), status: 'online' })
392
1068
  .eq('id', deviceId);
393
1069
  if (error) {
394
1070
  console.error('[DEBUG] Heartbeat update failed:', error.message);
395
1071
  await captureRemote('remote_channel_heartbeat_error', { error });
396
1072
  }
397
- // console.log(`🔌 Heartbeat sent for device: ${deviceId}`);
1073
+ else {
1074
+ console.debug('[DEBUG] last_seen bookkeeping write ok:', deviceId);
1075
+ }
398
1076
  }
399
1077
  catch (error) {
400
1078
  console.error('Heartbeat failed:', error.message);
@@ -403,24 +1081,75 @@ export class RemoteChannel {
403
1081
  }
404
1082
  startHeartbeat(deviceId) {
405
1083
  console.debug('[DEBUG] Starting heartbeat for device:', deviceId);
1084
+ this.heartbeatDeviceId = deviceId;
406
1085
  this.connectionCheckInterval = setInterval(() => {
407
1086
  this.checkConnectionHealth();
408
1087
  }, 10000);
409
- // Update last_seen every 15 seconds
410
- this.heartbeatInterval = setInterval(async () => {
411
- await this.updateHeartbeat(deviceId);
412
- }, HEARTBEAT_INTERVAL);
413
- console.debug('[DEBUG] Heartbeat intervals set - connectionCheck: 10s, heartbeat: 15s');
1088
+ // Bookkeeping last_seen write. Self-rescheduling rather than a fixed
1089
+ // setInterval so the cadence can follow the tier: a device that
1090
+ // withdraws the capability flag must fall back to the fast legacy
1091
+ // cadence immediately, not 30 minutes later.
1092
+ this.scheduleHeartbeat();
1093
+ this.startTokenRefresh();
1094
+ console.debug(`[DEBUG] Heartbeat started - connectionCheck: 10s, last_seen: ${this.heartbeatIntervalMs()}ms, tokenRefresh: ${TOKEN_REFRESH_INTERVAL_MS}ms`);
1095
+ }
1096
+ async refreshTokenNow() {
1097
+ if (!this.client || this.shuttingDown)
1098
+ return;
1099
+ try {
1100
+ const { error } = await this.client.auth.refreshSession();
1101
+ if (error) {
1102
+ console.error('[DEBUG] Manual token refresh failed:', error.message);
1103
+ await captureRemote('remote_channel_token_refresh_error', { error });
1104
+ }
1105
+ else {
1106
+ console.debug('[DEBUG] Manual token refresh ok');
1107
+ }
1108
+ }
1109
+ catch (error) {
1110
+ console.error('[DEBUG] Manual token refresh threw:', error?.message);
1111
+ await captureRemote('remote_channel_token_refresh_error', { error });
1112
+ }
1113
+ }
1114
+ startTokenRefresh() {
1115
+ if (this.tokenRefreshInterval)
1116
+ return; // already running
1117
+ this.tokenRefreshInterval = setInterval(() => {
1118
+ this.refreshTokenNow().catch(() => { });
1119
+ }, TOKEN_REFRESH_INTERVAL_MS);
1120
+ }
1121
+ stopTokenRefresh() {
1122
+ if (this.tokenRefreshInterval) {
1123
+ clearInterval(this.tokenRefreshInterval);
1124
+ this.tokenRefreshInterval = null;
1125
+ }
1126
+ }
1127
+ /** Arm (or re-arm) the last_seen timer at the current tier's cadence. */
1128
+ scheduleHeartbeat() {
1129
+ if (this.heartbeatInterval) {
1130
+ clearTimeout(this.heartbeatInterval);
1131
+ this.heartbeatInterval = null;
1132
+ }
1133
+ if (!this.heartbeatDeviceId)
1134
+ return;
1135
+ this.heartbeatInterval = setTimeout(async () => {
1136
+ if (this.heartbeatDeviceId) {
1137
+ await this.updateHeartbeat(this.heartbeatDeviceId);
1138
+ }
1139
+ this.scheduleHeartbeat(); // re-read the tier every tick
1140
+ }, this.heartbeatIntervalMs());
414
1141
  }
415
1142
  stopHeartbeat() {
1143
+ this.heartbeatDeviceId = null;
416
1144
  if (this.heartbeatInterval) {
417
- clearInterval(this.heartbeatInterval);
1145
+ clearTimeout(this.heartbeatInterval);
418
1146
  this.heartbeatInterval = null;
419
1147
  }
420
1148
  if (this.connectionCheckInterval) {
421
1149
  clearInterval(this.connectionCheckInterval);
422
1150
  this.connectionCheckInterval = null;
423
1151
  }
1152
+ this.stopTokenRefresh();
424
1153
  }
425
1154
  async setOnlineStatus(deviceId, status) {
426
1155
  if (!this.client)
@@ -454,13 +1183,26 @@ export class RemoteChannel {
454
1183
  }
455
1184
  console.debug('[DEBUG] setOffline() initiating blocking update for device:', deviceId);
456
1185
  try {
457
- // Get current session for the subprocess
458
- const { data: sessionData } = await this.client.auth.getSession();
459
- if (!sessionData?.session?.access_token) {
1186
+ // Session for the subprocess — bounded, with a cached fallback.
1187
+ // getSession() is not a cheap read: it takes a lock (10s acquire
1188
+ // timeout) and refreshes when the token is within ~90s of expiry,
1189
+ // POSTing /token with its own ~30s retry budget. On a just-woken
1190
+ // machine that outlasts device.ts's 5s force-exit, and then spawnSync
1191
+ // never runs and the offline write is lost. The subprocess calls
1192
+ // setSession() itself, so a slightly stale access_token is fine.
1193
+ const live = await Promise.race([
1194
+ this.client.auth.getSession().then((r) => r.data?.session ?? null),
1195
+ this.sleep(OFFLINE_SESSION_TIMEOUT_MS).then(() => null),
1196
+ ]).catch(() => null);
1197
+ const session = live ?? this.lastKnownSession;
1198
+ if (!session?.access_token) {
460
1199
  console.error('❌ No valid session for offline update');
461
1200
  console.debug('[DEBUG] Session data missing or invalid');
462
1201
  return;
463
1202
  }
1203
+ if (!live) {
1204
+ console.debug('[DEBUG] getSession() slow/failed — using last known session tokens');
1205
+ }
464
1206
  // Get Supabase config from client
465
1207
  const supabaseUrl = this.client.supabaseUrl;
466
1208
  const supabaseKey = this.client.supabaseKey;
@@ -484,8 +1226,8 @@ export class RemoteChannel {
484
1226
  deviceId,
485
1227
  supabaseUrl,
486
1228
  supabaseKey,
487
- sessionData.session.access_token,
488
- sessionData.session.refresh_token || ''
1229
+ session.access_token,
1230
+ session.refresh_token || ''
489
1231
  ], {
490
1232
  timeout: 3000,
491
1233
  stdio: 'pipe', // Capture output to prevent blocking
@@ -524,8 +1266,35 @@ export class RemoteChannel {
524
1266
  }
525
1267
  }
526
1268
  async unsubscribe() {
1269
+ // setOffline()'s durable write is the final word on `status` from here,
1270
+ // so stop the heartbeat and the channel callbacks from racing it. The
1271
+ // races that matter: a heartbeat tick firing as the signal arrives, and
1272
+ // SIGINT during recreateChannel()'s backoff, where the later join's
1273
+ // SUBSCRIBED would queue 'online' after the durable write.
1274
+ this.shuttingDown = true;
1275
+ // Budget against device.ts's 5s force-exit, worst case:
1276
+ // 250 drain + 2x300 leave + 500 session + 3000 spawnSync = 4350ms.
1277
+ // In practice only the untrack bound binds — removeChannel/unsubscribe
1278
+ // set state='leaving' first, so their leave push resolves inline.
1279
+ const LEAVE_BOUND_MS = 300;
1280
+ // Drain queued channel-callback writes. Can't drain an in-flight
1281
+ // heartbeat PATCH (it doesn't use the chain), but the gate above stops
1282
+ // any new one and an in-flight one started earlier.
1283
+ await Promise.race([this.statusWriteChain, this.sleep(250)]);
527
1284
  if (this.channel) {
528
- await this.channel.unsubscribe();
1285
+ // Leave presence on the graceful path (socket close covers the abrupt
1286
+ // one). Bounded: a half-open socket still reports 'joined', so the
1287
+ // push just buffers and would settle via realtime-js's 10s timeout.
1288
+ try {
1289
+ await Promise.race([
1290
+ this.channel.untrack(),
1291
+ this.sleep(LEAVE_BOUND_MS),
1292
+ ]);
1293
+ console.debug('[DEBUG] Presence untrack attempted (bounded)');
1294
+ }
1295
+ catch { /* best effort */ }
1296
+ // Bounded as insurance; unsubscribe() resolves inline in practice.
1297
+ await Promise.race([this.channel.unsubscribe(), this.sleep(LEAVE_BOUND_MS)]);
529
1298
  this.channel = null;
530
1299
  console.log('✓ Unsubscribed from tool call channel');
531
1300
  }