@wonderwhy-er/desktop-commander 0.2.50 → 0.2.51

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.
@@ -80,8 +80,25 @@ export class DesktopCommanderIntegration {
80
80
  // Supervise the local half. Without these, a child crash is silent:
81
81
  // the SDK clears its transport and every subsequent call throws
82
82
  // "Not connected" with nothing tying it back to the death.
83
- this.mcpTransport.onclose = () => this.handleLocalDisconnect('stdio transport closed');
84
- this.mcpTransport.onerror = (err) => this.handleLocalDisconnect(`stdio transport error: ${err?.message ?? String(err)}`);
83
+ //
84
+ // These MUST hang off the client, not the transport. connect() wraps
85
+ // transport.onclose/onerror with its own handlers and the SDK states
86
+ // that "The Protocol object assumes ownership of the Transport,
87
+ // replacing any callbacks that have already been set". Assigning to
88
+ // the transport here instead would drop the SDK's wrapper, and with
89
+ // it Protocol._onclose() — the only place a pending response is
90
+ // rejected with ConnectionClosed. The call in flight when the child
91
+ // died would then hang for the SDK's 60s default request timeout
92
+ // before the user heard anything.
93
+ this.mcpClient.onclose = () => this.handleLocalDisconnect('stdio transport closed');
94
+ // Diagnostics only. Protocol.onerror is raised for eleven non-fatal
95
+ // conditions that say nothing about the child's health — a response
96
+ // for an unknown message id, an unknown progress token, a failed
97
+ // cancellation send, an uncaught notification-handler error — and
98
+ // treating any of those as death takes a working device offline and
99
+ // respawns a live child. Real death arrives through onclose, which
100
+ // only fires once the transport has actually closed.
101
+ this.mcpClient.onerror = (err) => console.error(` - ⚠️ Local Desktop Commander MCP error: ${err?.message ?? String(err)}`);
85
102
  console.log(' - 🔌 Connected to Desktop Commander MCP');
86
103
  console.debug('[DEBUG] Desktop Commander MCP connection successful');
87
104
  }
@@ -2,6 +2,7 @@ import open from 'open';
2
2
  import os from 'os';
3
3
  import crypto from 'crypto';
4
4
  import { captureRemote } from '../utils/capture.js';
5
+ import { observeServerDate } from './remote-channel.js';
5
6
  const CLIENT_ID = 'mcp-device';
6
7
  export class DeviceAuthenticator {
7
8
  constructor(baseServerUrl) {
@@ -40,6 +41,7 @@ export class DeviceAuthenticator {
40
41
  code_challenge_method: 'S256',
41
42
  }),
42
43
  });
44
+ observeServerDate(response.headers.get('date'));
43
45
  if (!response.ok) {
44
46
  const error = await response.json().catch(() => ({ error: 'Unknown error' }));
45
47
  const errorMessage = error.error_description || 'Failed to start device flow';
@@ -52,9 +54,9 @@ export class DeviceAuthenticator {
52
54
  }
53
55
  displayUserInstructions(deviceAuth) {
54
56
  console.log('📋 Please complete authentication:\n');
55
- console.log(' 1. Open this URL in your browser:');
56
- console.log(` ${deviceAuth.verification_uri}\n`);
57
- console.log(' 2. Enter this code when prompted:');
57
+ console.log(' 1. Verify this device in your browser:');
58
+ console.log(` ${deviceAuth.verification_uri_complete}\n`);
59
+ console.log(' 2. Make sure the code matches:');
58
60
  console.log(` ${deviceAuth.user_code}\n`);
59
61
  console.log(` Code expires in ${Math.floor(deviceAuth.expires_in / 60)} minutes.\n`);
60
62
  // Try to open browser automatically
@@ -82,6 +84,9 @@ export class DeviceAuthenticator {
82
84
  code_verifier: codeVerifier,
83
85
  }),
84
86
  });
87
+ // The response that delivers the session states the server's
88
+ // time; correct the clock before that session is used.
89
+ observeServerDate(response.headers.get('date'));
85
90
  // Parse response body exactly once
86
91
  const data = await response.json().catch(() => ({ error: 'unknown' }));
87
92
  // Successful authentication
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { type AuthSession } from './remote-channel.js';
2
3
  export interface MCPDeviceOptions {
3
4
  persistSession?: boolean;
4
5
  }
@@ -11,6 +12,13 @@ export declare class MCPDevice {
11
12
  private configPath;
12
13
  private persistSession;
13
14
  private desktop;
15
+ /**
16
+ * Serialises config writes. Rotations are 45 minutes apart in normal
17
+ * running, but a save that stalls must not land after a newer one and
18
+ * persist a token that is already spent. Shutdown awaits this to drain
19
+ * whatever is still in flight.
20
+ */
21
+ private configWriteChain;
14
22
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
15
23
  private seenCallIds;
16
24
  constructor(options?: MCPDeviceOptions);
@@ -19,7 +27,12 @@ export declare class MCPDevice {
19
27
  private findPersistedDeviceWithRetry;
20
28
  loadPersistedConfig(): Promise<any>;
21
29
  clearPersistedConfig(): Promise<void>;
22
- savePersistedConfig(): Promise<void>;
30
+ /**
31
+ * Queue a config write. Returns the queued write, so a caller that must not
32
+ * outlive it - shutdown() - can await it.
33
+ */
34
+ savePersistedConfig(rotated?: AuthSession): Promise<void>;
35
+ private writePersistedConfig;
23
36
  fetchSupabaseConfig(): Promise<{
24
37
  supabaseUrl: any;
25
38
  anonKey: any;
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { RemoteChannel } from './remote-channel.js';
2
+ import { RemoteChannel, observeServerDate } from './remote-channel.js';
3
3
  import { DeviceAuthenticator } from './device-authenticator.js';
4
4
  import { DesktopCommanderIntegration } from './desktop-commander-integration.js';
5
5
  import { fileURLToPath } from 'url';
@@ -22,6 +22,13 @@ export function getRemoteDeviceConfigPath() {
22
22
  }
23
23
  export class MCPDevice {
24
24
  constructor(options = {}) {
25
+ /**
26
+ * Serialises config writes. Rotations are 45 minutes apart in normal
27
+ * running, but a save that stalls must not land after a newer one and
28
+ * persist a token that is already spent. Shutdown awaits this to drain
29
+ * whatever is still in flight.
30
+ */
31
+ this.configWriteChain = Promise.resolve();
25
32
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
26
33
  this.seenCallIds = new Set();
27
34
  this.baseServerUrl = process.env.MCP_SERVER_URL || 'https://mcp.desktopcommander.app';
@@ -34,6 +41,11 @@ export class MCPDevice {
34
41
  // refresh-token families get replayed, trip GoTrue's reuse detection, and
35
42
  // take the whole family down including the token a healthy connector holds.
36
43
  this.persistSession = options.persistSession ?? true;
44
+ // The session refreshes every 45 minutes and auth-js rotates the refresh
45
+ // token each time. Without this the config keeps whichever token the
46
+ // process started with, and a restart hours later replays a spent one -
47
+ // GoTrue refuses it and an unattended device waits for a browser.
48
+ this.remoteChannel.onSessionRefreshed((session) => void this.savePersistedConfig(session));
37
49
  // Initialize desktop integration
38
50
  this.desktop = new DesktopCommanderIntegration();
39
51
  // Graceful shutdown handlers (only set once)
@@ -240,11 +252,28 @@ export class MCPDevice {
240
252
  await captureRemote('remote_device_config_clear_error', { error });
241
253
  }
242
254
  }
243
- async savePersistedConfig() {
255
+ /**
256
+ * Queue a config write. Returns the queued write, so a caller that must not
257
+ * outlive it - shutdown() - can await it.
258
+ */
259
+ async savePersistedConfig(rotated) {
260
+ this.configWriteChain = this.configWriteChain.then(() => this.writePersistedConfig(rotated));
261
+ return this.configWriteChain;
262
+ }
263
+ async writePersistedConfig(rotated) {
244
264
  try {
245
265
  console.debug('[DEBUG] Saving persisted config, persistSession:', this.persistSession);
246
- const currentSessionStore = await this.remoteChannel.getSession();
247
- const session = currentSessionStore.data.session;
266
+ // Prefer the session TOKEN_REFRESHED handed us over re-reading it. A
267
+ // sign-out landing in that gap answers null, and the write below would
268
+ // replace a usable refresh token with nothing.
269
+ const session = rotated ?? (await this.remoteChannel.getSession()).data.session;
270
+ // Never trade a good token for an empty one. Deliberate clearing is
271
+ // what clearPersistedConfig() is for; --no-persist-session still
272
+ // writes null below, because persistSession is false there.
273
+ if (this.persistSession && !session?.refresh_token) {
274
+ console.debug('[DEBUG] Skipping config save - nothing to persist');
275
+ return;
276
+ }
248
277
  const config = {
249
278
  deviceId: this.deviceId,
250
279
  // Only save session if --persist-session flag is set
@@ -256,7 +285,16 @@ export class MCPDevice {
256
285
  // Ensure the config directory exists
257
286
  console.debug('[DEBUG] Creating config directory:', path.dirname(this.configPath));
258
287
  await fs.mkdir(path.dirname(this.configPath), { recursive: true });
259
- await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), { mode: 0o600 });
288
+ // Write then rename: the rename is the commit boundary, so a write
289
+ // cut short leaves the previous complete session rather than a
290
+ // truncated file. loadPersistedConfig() answers a JSON.parse
291
+ // failure with null, which costs a full browser reauthorization.
292
+ // Same shape as ConfigManager's atomic save; the pid keeps two
293
+ // processes off each other's temp file, and configWriteChain keeps
294
+ // this one off its own.
295
+ const tempPath = `${this.configPath}.${process.pid}.tmp`;
296
+ await fs.writeFile(tempPath, JSON.stringify(config, null, 2), { mode: 0o600 });
297
+ await fs.rename(tempPath, this.configPath);
260
298
  console.debug('[DEBUG] Config saved to:', this.configPath);
261
299
  }
262
300
  catch (error) {
@@ -269,6 +307,11 @@ export class MCPDevice {
269
307
  // No auth header needed for this public endpoint
270
308
  console.debug('[DEBUG] Fetching Supabase config from:', `${this.baseServerUrl}/api/mcp-info`);
271
309
  const response = await fetch(`${this.baseServerUrl}/api/mcp-info`);
310
+ // First request of the run, and it already states the server's time.
311
+ // auth-js judges the session handed to setSession() against this
312
+ // device's Date.now() with no skew tolerance, so the clock has to be
313
+ // right BEFORE that call - clockAwareFetch only corrects it afterwards.
314
+ observeServerDate(response.headers.get('date'));
272
315
  if (!response.ok) {
273
316
  console.debug('[DEBUG] Supabase config fetch failed, status:', response.status, response.statusText);
274
317
  throw new Error(`Failed to fetch Supabase config: ${response.statusText}`);
@@ -343,8 +386,9 @@ export class MCPDevice {
343
386
  // DB claim second — keeps the row state machine honest, gives
344
387
  // cross-restart/cross-process protection, and is observable. It may
345
388
  // fail open (returns true on a transient write error); the local
346
- // guard above is what makes execution exactly-once.
347
- const claimed = await this.remoteChannel.markCallExecuting(call_id);
389
+ // guard above is what makes execution exactly-once. The doorbell
390
+ // path claims before dispatch and marks the payload `claimed`.
391
+ const claimed = payload.claimed === true || await this.remoteChannel.markCallExecuting(call_id);
348
392
  if (!claimed) {
349
393
  // markCallExecuting already logged the duplicate-delivery skip.
350
394
  return;
@@ -378,10 +422,8 @@ export class MCPDevice {
378
422
  result = await this.desktop.callClientTool(tool_name, tool_args, metadata);
379
423
  }
380
424
  console.log(`✅ Tool call ${tool_name} completed:\r\n ${JSON.stringify(result)}`);
381
- // Update database with result, THEN ring the doorbell — the server
382
- // fetches the row by id on the doorbell, so the write must land first.
425
+ // The result write itself notifies the server (a DB trigger).
383
426
  await this.remoteChannel.updateCallResult(call_id, 'completed', result);
384
- await this.remoteChannel.notifyResult(call_id);
385
427
  }
386
428
  catch (error) {
387
429
  console.error(`❌ Tool call ${tool_name} failed:`, error.message);
@@ -391,7 +433,6 @@ export class MCPDevice {
391
433
  try {
392
434
  await captureRemote('remote_device_tool_call_failed', { error, tool_name });
393
435
  await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
394
- await this.remoteChannel.notifyResult(call_id);
395
436
  }
396
437
  catch (reportError) {
397
438
  console.error(`❌ Could not report failure for ${call_id}:`, reportError?.message);
@@ -420,6 +461,10 @@ export class MCPDevice {
420
461
  console.log(' → Marking device offline...');
421
462
  console.debug('[DEBUG] Calling setOffline() with deviceId:', this.deviceId);
422
463
  await this.remoteChannel.setOffline(this.deviceId);
464
+ // Drain any config write still in flight - a rotation can land as
465
+ // teardown begins, and losing it costs the next start a browser.
466
+ console.debug('[DEBUG] Draining pending config writes');
467
+ await this.configWriteChain;
423
468
  // Shutdown desktop integration
424
469
  console.log(' → Shutting down desktop integration...');
425
470
  console.debug('[DEBUG] Calling desktop.shutdown()');
@@ -28,6 +28,8 @@ export declare class RemoteChannel {
28
28
  private statusWriteChain;
29
29
  /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
30
30
  private lastKnownSession;
31
+ /** Notified when auth-js rotates the session; the device persists it. */
32
+ private sessionRefreshedHandler;
31
33
  /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
32
34
  * land after setOffline()'s durable write. */
33
35
  private shuttingDown;
@@ -63,6 +65,13 @@ export declare class RemoteChannel {
63
65
  private _user;
64
66
  get user(): User | null;
65
67
  initialize(url: string, key: string): void;
68
+ /**
69
+ * Register a callback fired when auth-js rotates the session. auth-js
70
+ * rotates the refresh token on every refresh and the previous one is spent,
71
+ * so a config written once at startup replays a dead token on the next
72
+ * restart and the device demands browser authorization again.
73
+ */
74
+ onSessionRefreshed(handler: (session: AuthSession) => void): void;
66
75
  setSession(session: AuthSession): Promise<{
67
76
  error: any;
68
77
  }>;
@@ -96,7 +105,7 @@ export declare class RemoteChannel {
96
105
  /**
97
106
  * Publish presence, retrying a non-'ok' result — track() resolves with a
98
107
  * status rather than rejecting, and absent presence reads as offline on the
99
- * server. `presenceTracked` lets the health check retry later.
108
+ * dashboard. `presenceTracked` lets the health check retry later.
100
109
  */
101
110
  private trackPresenceWithRetry;
102
111
  private trackPresenceInner;
@@ -107,9 +116,8 @@ export declare class RemoteChannel {
107
116
  private capabilitiesPayload;
108
117
  /**
109
118
  * Advertise (or withdraw) the broadcast capability. Only true while genuinely
110
- * reachable that way — the server uses it to pick a transport, to read absent
111
- * presence as offline, and to choose the sweep tier, so every change must
112
- * re-arm the heartbeat.
119
+ * reachable that way — the server fails dispatch fast without it and picks
120
+ * the offline-sweep tier from it, so every change must re-arm the heartbeat.
113
121
  */
114
122
  private setTransportCapable;
115
123
  /** Create and subscribe the private channel (initial join and recreation). */
@@ -118,17 +126,11 @@ export declare class RemoteChannel {
118
126
  * and an unhandled rejection terminates the process. */
119
127
  private dispatchToolCall;
120
128
  /**
121
- * Handle a 'new_call' doorbell. It carries ids only; the row is fetched by
122
- * primary key and fed through the same handler as a postgres_changes
123
- * payload, so device.ts stays transport-agnostic.
129
+ * Handle a 'new_call' doorbell. It carries ids only; one conditional update
130
+ * claims the row (pending -> executing) and returns it, and it is handed to
131
+ * device.ts marked as claimed.
124
132
  */
125
133
  private onDoorbell;
126
- /**
127
- * Tell the server a result row is written. Fire-and-forget: a failed send
128
- * just falls back to the server's 10s recovery poll. MUST run only after
129
- * updateCallResult() resolves, so the server's fetch-by-id sees a terminal row.
130
- */
131
- notifyResult(callId: string): Promise<void>;
132
134
  /**
133
135
  * Compact connection state for logs — e.g. "socket=open(1) ch=errored attempt=3".
134
136
  * readyState 1=OPEN (a 1 while joins keep failing = a half-open socket being reused),
@@ -48,8 +48,8 @@ const TOKEN_REFRESH_INTERVAL_MS = 45 * 60 * 1000;
48
48
  // Below this, skew is noise — leave Date.now untouched. Above it, correct.
49
49
  const CLOCK_SKEW_CORRECTION_THRESHOLD_MS = 5 * 60 * 1000;
50
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.
51
+ // unable to join leaves the server dispatching calls this device can't
52
+ // receive. Not lower than 3: ordinary half-open recovery legitimately costs 2.
53
53
  const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
54
54
  // Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
55
55
  // does not cover.
@@ -116,6 +116,8 @@ export class RemoteChannel {
116
116
  this.statusWriteChain = Promise.resolve();
117
117
  /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
118
118
  this.lastKnownSession = null;
119
+ /** Notified when auth-js rotates the session; the device persists it. */
120
+ this.sessionRefreshedHandler = null;
119
121
  /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
120
122
  * land after setOffline()'s durable write. */
121
123
  this.shuttingDown = false;
@@ -193,11 +195,21 @@ export class RemoteChannel {
193
195
  catch { /* no onHeartbeat on this client version: staleness check stays inert */ }
194
196
  }
195
197
  }
198
+ /**
199
+ * Register a callback fired when auth-js rotates the session. auth-js
200
+ * rotates the refresh token on every refresh and the previous one is spent,
201
+ * so a config written once at startup replays a dead token on the next
202
+ * restart and the device demands browser authorization again.
203
+ */
204
+ onSessionRefreshed(handler) {
205
+ this.sessionRefreshedHandler = handler;
206
+ }
196
207
  async setSession(session) {
197
208
  if (!this.client)
198
209
  throw new Error('Client not initialized');
199
210
  console.debug('[DEBUG] RemoteChannel.setSession() called, has refresh_token:', !!session.refresh_token);
200
- const { error } = await this.client.auth.setSession({
211
+ // setSession() already fetches the user from GoTrue (or refreshes), so no getUser() after it.
212
+ const { data: { user }, error } = await this.client.auth.setSession({
201
213
  access_token: session.access_token,
202
214
  refresh_token: session.refresh_token || ''
203
215
  });
@@ -206,13 +218,6 @@ export class RemoteChannel {
206
218
  await captureRemote('remote_channel_set_session_error', { error });
207
219
  return { error };
208
220
  }
209
- // Get user info
210
- const { data: { user }, error: userError } = await this.client.auth.getUser();
211
- if (userError) {
212
- console.error('[DEBUG] Failed to get user:', userError.message);
213
- await captureRemote('remote_channel_get_user_error', { error: userError });
214
- throw userError;
215
- }
216
221
  if (!user) {
217
222
  const noUserError = new Error('No user returned after setSession');
218
223
  console.error('[DEBUG] No user returned:', noUserError.message);
@@ -242,6 +247,14 @@ export class RemoteChannel {
242
247
  access_token: newSession.access_token,
243
248
  refresh_token: newSession.refresh_token ?? this.lastKnownSession?.refresh_token ?? null,
244
249
  };
250
+ // Memory alone is not enough: the token we just replaced is
251
+ // spent, so whatever is on disk is now unusable.
252
+ // Hand over the session we were just given. A listener that
253
+ // re-read it could find a sign-out instead and persist that.
254
+ this.sessionRefreshedHandler?.({
255
+ access_token: newSession.access_token,
256
+ refresh_token: newSession.refresh_token ?? null,
257
+ });
245
258
  }
246
259
  else if (event === 'SIGNED_OUT') {
247
260
  void this.handleSignedOut();
@@ -436,7 +449,7 @@ export class RemoteChannel {
436
449
  /**
437
450
  * Publish presence, retrying a non-'ok' result — track() resolves with a
438
451
  * status rather than rejecting, and absent presence reads as offline on the
439
- * server. `presenceTracked` lets the health check retry later.
452
+ * dashboard. `presenceTracked` lets the health check retry later.
440
453
  */
441
454
  async trackPresenceWithRetry(recovered, attempts = 3) {
442
455
  if (this.isTrackingPresence)
@@ -471,7 +484,7 @@ export class RemoteChannel {
471
484
  // Reconnect attempts preceding this join (0 on a first join).
472
485
  captureRemote('remote_channel_presence_tracked', { recoveredAfterAttempts: recovered }).catch(() => { });
473
486
  // Proven end-to-end (joined AND presence published) — only now
474
- // may the server treat our presence as authoritative.
487
+ // advertise the capability dispatch requires.
475
488
  await this.setTransportCapable(true);
476
489
  return;
477
490
  }
@@ -482,9 +495,9 @@ export class RemoteChannel {
482
495
  this.presenceTracked = false;
483
496
  console.error('❌ Presence track failed after retries — withdrawing broadcast capability');
484
497
  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.
498
+ // Withdraw: the dashboard reads a flagged device with no presence as
499
+ // offline. The faster heartbeat tier keeps the device's DB status
500
+ // accurate while it recovers.
488
501
  await this.setTransportCapable(false);
489
502
  }
490
503
  /**
@@ -499,9 +512,8 @@ export class RemoteChannel {
499
512
  }
500
513
  /**
501
514
  * 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.
515
+ * reachable that way — the server fails dispatch fast without it and picks
516
+ * the offline-sweep tier from it, so every change must re-arm the heartbeat.
505
517
  */
506
518
  async setTransportCapable(capable) {
507
519
  if (!this.client || !this.deviceId)
@@ -538,7 +550,7 @@ export class RemoteChannel {
538
550
  return new Promise((resolve, reject) => {
539
551
  if (!this.client || !this.user?.id || !this.onToolCall || !this.deviceId) {
540
552
  // deviceId is the presence KEY; a null key gets a random one and
541
- // the server's lookup by device id silently misses.
553
+ // the dashboard's lookup by device id silently misses.
542
554
  console.debug('[DEBUG] createChannel() failed - missing prerequisites');
543
555
  return reject(new Error('Client not initialized or missing subscription parameters'));
544
556
  }
@@ -547,11 +559,8 @@ export class RemoteChannel {
547
559
  const channelName = `user:${this.user.id}`;
548
560
  console.debug(`[DEBUG] Creating channel: ${channelName}`);
549
561
  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
562
  config: {
553
563
  private: true,
554
- broadcast: { ack: true },
555
564
  // Non-null: the guard above rejects when !deviceId.
556
565
  presence: { key: this.deviceId, enabled: true }
557
566
  }
@@ -572,9 +581,10 @@ export class RemoteChannel {
572
581
  // Update device status on successful connection (queued, so
573
582
  // it can't be overtaken by a teardown's status write).
574
583
  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.
584
+ // The capability flag dispatch requires is written only
585
+ // once presence lands, so resolve then — otherwise
586
+ // registerDevice() reports "Device ready" while still
587
+ // undispatchable.
578
588
  this.trackPresenceWithRetry(recovered)
579
589
  .catch(() => { })
580
590
  .finally(() => resolve());
@@ -621,15 +631,15 @@ export class RemoteChannel {
621
631
  }
622
632
  }
623
633
  /**
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.
634
+ * Handle a 'new_call' doorbell. It carries ids only; one conditional update
635
+ * claims the row (pending -> executing) and returns it, and it is handed to
636
+ * device.ts marked as claimed.
627
637
  */
628
638
  async onDoorbell(payload) {
629
639
  const callId = payload?.call_id;
630
640
  if (!callId)
631
641
  return;
632
- if (payload?.device_id && payload.device_id !== this.deviceId) {
642
+ if (payload?.device_id !== this.deviceId) {
633
643
  console.debug('[DEBUG] Ignoring doorbell for different device');
634
644
  return;
635
645
  }
@@ -639,70 +649,68 @@ export class RemoteChannel {
639
649
  if (!this.client)
640
650
  return;
641
651
  // 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,
652
+ // healthy). This claim is the only way we learn about a call,
643
653
  // so a hiccup must not cost a 5-minute timeout.
644
654
  let row = null;
645
- let lastError = null;
655
+ let claimError = null;
646
656
  for (const delayMs of [0, 500, 1500]) {
647
657
  if (delayMs > 0)
648
658
  await this.sleep(delayMs);
649
659
  const { data, error } = await this.client
650
660
  .from('mcp_remote_calls')
651
- .select('*')
661
+ .update({ status: 'executing' })
652
662
  .eq('id', callId)
653
- .maybeSingle();
663
+ .eq('device_id', this.deviceId)
664
+ .eq('status', 'pending')
665
+ .select('*');
654
666
  if (!error) {
655
- row = data;
656
- lastError = null;
667
+ row = data?.[0] ?? null;
657
668
  break;
658
669
  }
659
- lastError = error;
660
- console.debug(`[DEBUG] Doorbell row fetch attempt failed for ${callId}: ${error.message} — retrying`);
670
+ // Left set on purpose: a later clean empty result may still mean our
671
+ // own attempt committed, so the read-back below must run.
672
+ claimError = error;
673
+ console.debug(`[DEBUG] Doorbell claim attempt failed for ${callId}: ${error.message} — retrying`);
661
674
  }
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 });
675
+ if (row) {
676
+ this.dispatchToolCall({ new: row, claimed: true });
665
677
  return;
666
678
  }
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 });
679
+ if (!claimError) {
680
+ // Claimed by a duplicate doorbell or another process, or cleaned up.
681
+ console.debug('[DEBUG] Doorbell call already claimed or gone:', callId);
682
+ await captureRemote('remote_channel_doorbell_claim_no_row', { call_id: callId });
671
683
  return;
672
684
  }
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)');
685
+ await captureRemote('remote_channel_mark_call_executing_error', { error: claimError });
686
+ // A failed claim may never have reached the database, so read the row
687
+ // back: still 'pending' means nobody holds it and it can be delivered.
688
+ const { data: current, error } = await this.client
689
+ .from('mcp_remote_calls')
690
+ .select('*')
691
+ .eq('id', callId)
692
+ .eq('device_id', this.deviceId)
693
+ .maybeSingle();
694
+ if (error) {
695
+ console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after claim errors:`, error.message);
696
+ await captureRemote('remote_channel_doorbell_fetch_error', { error });
689
697
  return;
690
698
  }
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
- }
699
+ if (current?.status === 'pending') {
700
+ // No claim landed; device.ts claims it.
701
+ this.dispatchToolCall({ new: current });
702
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(() => { });
703
+ else {
704
+ // 'executing' reads the same whether our own claim committed with its
705
+ // response lost or another process holding this device_id won it, and
706
+ // the row carries no claimant. Running it on that guess executes a
707
+ // side-effecting tool twice; skipping costs one call its timeout, which
708
+ // is what a failed doorbell read already cost before the claim path.
709
+ console.debug('[DEBUG] Doorbell call already claimed or gone:', callId);
710
+ await captureRemote('remote_channel_doorbell_claim_unresolved', {
711
+ call_id: callId,
712
+ status: current?.status ?? null,
713
+ });
706
714
  }
707
715
  }
708
716
  /**
@@ -749,8 +757,10 @@ export class RemoteChannel {
749
757
  }
750
758
  }
751
759
  // 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.
760
+ // else will ever retry (SUBSCRIBED won't fire again). Until it
761
+ // lands the dashboard shows this device offline, and if track()
762
+ // already failed its retries the capability is withdrawn too, so
763
+ // the server fails every dispatch to it fast.
754
764
  if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence) {
755
765
  console.debug('[DEBUG] Channel joined but presence not tracked — retrying track()');
756
766
  this.trackPresenceWithRetry(0, 1).catch(() => { });
@@ -896,9 +906,8 @@ export class RemoteChannel {
896
906
  catch (err) {
897
907
  captureRemote('remote_channel_recreate_error', { errMsg: err?.message, attempt: this.reconnectAttempt });
898
908
  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`.
909
+ // Sustained failure: stop promising a transport we can't deliver, so
910
+ // dispatch fails fast instead of every call waiting out the timeout.
902
911
  if (this.reconnectAttempt >= TRANSPORT_WITHDRAW_AFTER_ATTEMPTS) {
903
912
  // Bounded, in its own try: this catch block is outside
904
913
  // RECREATE_TIMEOUT_MS, so a hanging PATCH would pin
@@ -1055,9 +1064,8 @@ export class RemoteChannel {
1055
1064
  // Skip the write entirely when no transport is up. Bumping last_seen
1056
1065
  // on a deaf device would keep its row perpetually young, so the
1057
1066
  // 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.
1067
+ // stale 'online' — and that row is what dispatch reads. Staying
1068
+ // silent lets the sweep do its job.
1061
1069
  if (!this.isReachable()) {
1062
1070
  console.debug('[DEBUG] Skipping heartbeat write — no transport joined; letting the row age out');
1063
1071
  return;
@@ -1188,8 +1196,8 @@ export class RemoteChannel {
1188
1196
  // timeout) and refreshes when the token is within ~90s of expiry,
1189
1197
  // POSTing /token with its own ~30s retry budget. On a just-woken
1190
1198
  // 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.
1199
+ // never runs and the offline write is lost. The subprocess refreshes
1200
+ // an expired access_token itself, so a stale one is fine.
1193
1201
  const live = await Promise.race([
1194
1202
  this.client.auth.getSession().then((r) => r.data?.session ?? null),
1195
1203
  this.sleep(OFFLINE_SESSION_TIMEOUT_MS).then(() => null),
@@ -1227,7 +1235,9 @@ export class RemoteChannel {
1227
1235
  supabaseUrl,
1228
1236
  supabaseKey,
1229
1237
  session.access_token,
1230
- session.refresh_token || ''
1238
+ // A lost session's refresh token already failed to refresh;
1239
+ // presenting it again can trip GoTrue's reuse detection.
1240
+ this.sessionLost ? '' : session.refresh_token || ''
1231
1241
  ], {
1232
1242
  timeout: 3000,
1233
1243
  stdio: 'pipe', // Capture output to prevent blocking
@@ -4,7 +4,8 @@
4
4
  * Blocking script to update device status to offline
5
5
  * Runs synchronously during shutdown to ensure DB update completes
6
6
  *
7
- * Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> <refreshToken>
7
+ * Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> [refreshToken]
8
+ * Without a refreshToken only a still-valid accessToken can be used.
8
9
  */
9
10
 
10
11
  import { createClient } from '@supabase/supabase-js';
@@ -12,9 +13,9 @@ import { createClient } from '@supabase/supabase-js';
12
13
  // Parse command line arguments
13
14
  const [deviceId, supabaseUrl, supabaseKey, accessToken, refreshToken] = process.argv.slice(2);
14
15
 
15
- if (!deviceId || !supabaseUrl || !supabaseKey || !accessToken || !refreshToken) {
16
+ if (!deviceId || !supabaseUrl || !supabaseKey || !accessToken) {
16
17
  console.error('❌ Missing required arguments');
17
- console.error('Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> <refreshToken>');
18
+ console.error('Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> [refreshToken]');
18
19
  process.exit(1);
19
20
  }
20
21
 
@@ -25,29 +26,58 @@ const timeoutHandle = setTimeout(() => {
25
26
  process.exit(2); // Exit code 2 for timeout
26
27
  }, TIMEOUT_MS);
27
28
 
28
- try {
29
- // Create Supabase client
30
- const client = createClient(supabaseUrl, supabaseKey);
29
+ const auth = { persistSession: false, autoRefreshToken: false };
30
+
31
+ // Update device status to offline, stamping the exact shutdown moment so
32
+ // "last seen X ago" is precise for clean shutdowns (the periodic
33
+ // bookkeeping write only runs on the slow capable cadence).
34
+ // The token goes straight to PostgREST as a Bearer header: setSession()
35
+ // would first spend a GoTrue round trip of the budget re-validating it.
36
+ const markOffline = (token) => createClient(supabaseUrl, supabaseKey, {
37
+ auth,
38
+ global: { headers: { Authorization: `Bearer ${token}` } }
39
+ })
40
+ .from('mcp_devices')
41
+ .update({ status: 'offline', last_seen: new Date().toISOString() })
42
+ .eq('id', deviceId);
43
+
44
+ function tokenLooksLive(token) {
45
+ try {
46
+ const { exp } = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
47
+ return typeof exp === 'number' && exp * 1000 > Date.now() + 5000;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
31
52
 
32
- // Set session using access token and refresh token
33
- const { error: authError } = await client.auth.setSession({
34
- access_token: accessToken,
35
- refresh_token: refreshToken
36
- });
53
+ // refreshSession(), not setSession(): setSession() validates a token that
54
+ // looks live on this machine's clock via /user instead of refreshing it.
55
+ async function refreshedToken() {
56
+ if (!refreshToken) {
57
+ console.error('❌ Auth error: access token not usable and no refresh token');
58
+ clearTimeout(timeoutHandle);
59
+ process.exit(3); // Exit code 3 for auth error
60
+ }
61
+ const client = createClient(supabaseUrl, supabaseKey, { auth });
62
+ const { data, error: authError } = await client.auth.refreshSession({ refresh_token: refreshToken });
37
63
 
38
- if (authError) {
39
- console.error('❌ Auth error:', authError.message);
64
+ if (authError || !data.session) {
65
+ console.error('❌ Auth error:', authError?.message ?? 'no session returned');
40
66
  clearTimeout(timeoutHandle);
41
67
  process.exit(3); // Exit code 3 for auth error
42
68
  }
69
+ return data.session.access_token;
70
+ }
71
+
72
+ try {
73
+ // An expired token (e.g. the machine just woke) is refreshed first. A 401
74
+ // means it only looked live on this machine's clock: refresh and retry once.
75
+ let result = tokenLooksLive(accessToken) ? await markOffline(accessToken) : null;
76
+ if (!result || result.status === 401) {
77
+ result = await markOffline(await refreshedToken());
78
+ }
43
79
 
44
- // Update device status to offline, stamping the exact shutdown moment so
45
- // "last seen X ago" is precise for clean shutdowns (the periodic
46
- // bookkeeping write only runs on the slow capable cadence).
47
- const { error } = await client
48
- .from('mcp_devices')
49
- .update({ status: 'offline', last_seen: new Date().toISOString() })
50
- .eq('id', deviceId);
80
+ const { error } = result;
51
81
 
52
82
  clearTimeout(timeoutHandle);
53
83
 
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.2.50";
1
+ export declare const VERSION = "0.2.51";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.2.50';
1
+ export const VERSION = '0.2.51';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wonderwhy-er/desktop-commander",
3
- "version": "0.2.50",
3
+ "version": "0.2.51",
4
4
  "description": "MCP server for terminal operations and file editing",
5
5
  "mcpName": "io.github.wonderwhy-er/desktop-commander",
6
6
  "license": "MIT",