@wonderwhy-er/desktop-commander 0.2.51 → 0.2.52

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { RemoteChannel, observeServerDate } from './remote-channel.js';
2
+ import { ChannelUnreachableError, 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';
@@ -17,6 +17,12 @@ import { captureRemote } from '../utils/capture.js';
17
17
  const SEEN_CALL_IDS_MAX = 100;
18
18
  const PERSISTED_DEVICE_LOOKUP_ATTEMPTS = 3;
19
19
  const PERSISTED_DEVICE_LOOKUP_RETRY_MS = 250;
20
+ /**
21
+ * Floor between recovery attempts. ensureReady()'s own backoff covers a child
22
+ * that fails to start; this covers one that starts and then fails verification,
23
+ * where no restart backoff was armed and the loop would otherwise spin.
24
+ */
25
+ const RECOVERY_MIN_DELAY_MS = 1000;
20
26
  export function getRemoteDeviceConfigPath() {
21
27
  return path.join(os.homedir(), '.desktop-commander-device', 'device.json');
22
28
  }
@@ -48,6 +54,10 @@ export class MCPDevice {
48
54
  this.remoteChannel.onSessionRefreshed((session) => void this.savePersistedConfig(session));
49
55
  // Initialize desktop integration
50
56
  this.desktop = new DesktopCommanderIntegration();
57
+ // Readiness is a claim about executing, so it has to consult the local
58
+ // executor too. Read through a probe rather than a cached flag: there
59
+ // is then no state to keep in step, and `desktop` can be replaced.
60
+ this.remoteChannel.setLocalExecutorProbe(() => this.desktop.ready);
51
61
  // Graceful shutdown handlers (only set once)
52
62
  this.setupShutdownHandlers();
53
63
  }
@@ -111,6 +121,10 @@ export class MCPDevice {
111
121
  this.remoteChannel.initialize(supabaseUrl, anonKey);
112
122
  // Load persisted configuration (deviceId, session)
113
123
  let session = await this.loadPersistedConfig();
124
+ await captureRemote('remote_device_session_state', {
125
+ has_persisted_session: Boolean(session),
126
+ has_persisted_device_id: Boolean(this.deviceId),
127
+ });
114
128
  // 2. Set Session or Authenticate
115
129
  if (session) {
116
130
  const { error } = await this.remoteChannel.setSession(session);
@@ -120,7 +134,6 @@ export class MCPDevice {
120
134
  }
121
135
  else {
122
136
  console.log(' - ✅ Session restored');
123
- console.log(' - ℹ️ To log out locally: npx @wonderwhy-er/desktop-commander@latest remote --logout');
124
137
  // Revoking a device removes its server-side mcp_devices row, but the
125
138
  // local config can still hold a valid user session + the now-deleted
126
139
  // device ID. Do not silently recreate the revoked device with that
@@ -137,6 +150,7 @@ export class MCPDevice {
137
150
  }
138
151
  }
139
152
  if (!session) {
153
+ await captureRemote('remote_device_auth_flow_started');
140
154
  console.log('\n🔐 Authenticating with Remote MCP server...');
141
155
  const authenticator = new DeviceAuthenticator(this.baseServerUrl);
142
156
  session = await authenticator.authenticate(this.deviceId);
@@ -169,12 +183,60 @@ export class MCPDevice {
169
183
  // Force save the current session immediately to ensure it's persisted
170
184
  await this.savePersistedConfig();
171
185
  const deviceName = os.hostname();
172
- // Register as device
173
- await this.remoteChannel.registerDevice(await this.desktop.listClientTools(), this.deviceId, deviceName, (payload) => this.handleNewToolCall(payload));
174
- console.log('✅ Device ready:');
186
+ // Register as device. registerDevice() resolves only once the
187
+ // realtime channel is joined and presence is published, which is
188
+ // exactly what the hosted service needs to deliver a call — so a
189
+ // rejection means "running, but nothing can reach this device", and
190
+ // that has to be said instead of "Device ready".
191
+ //
192
+ // Deliberately not fatal, and deliberately not rethrown into the
193
+ // outer catch, which exits the process: the socket watchdog keeps
194
+ // retrying and announces "✅ Channel subscribed" when it gets
195
+ // through, so quitting here would remove the only way back.
196
+ let reachable = true;
197
+ try {
198
+ await this.remoteChannel.registerDevice(await this.desktop.listClientTools(), this.deviceId, deviceName, (payload) => this.handleNewToolCall(payload));
199
+ }
200
+ catch (error) {
201
+ // Only a channel fault is recoverable here. A failed lookup or a
202
+ // missing device row happens before registerDevice() stores the
203
+ // recreation parameters, and both checkConnectionHealth() and
204
+ // recreateChannel() return early without them — so nothing in
205
+ // this process could repair it, and swallowing it would promise
206
+ // a retry that can never happen. Those stay fatal, as before.
207
+ if (!(error instanceof ChannelUnreachableError))
208
+ throw error;
209
+ reachable = false;
210
+ console.error(` - ❌ Realtime channel is not open: ${error.message}`);
211
+ await captureRemote('remote_device_registered_unreachable', { error });
212
+ }
213
+ console.log(reachable
214
+ ? '✅ Device ready:'
215
+ : '⚠️ Device registered, but NOT reachable — no command can arrive yet:');
175
216
  console.log(` - User: ${this.remoteChannel.user.email}`);
176
217
  console.log(` - Device ID: ${this.deviceId}`);
177
218
  console.log(` - Device Name: ${deviceName}`);
219
+ if (!reachable) {
220
+ console.log(' - Retrying in the background; commands start working once you see "✅ Channel subscribed".');
221
+ }
222
+ else {
223
+ console.log('');
224
+ console.log('✅ Desktop Commander Remote is connected');
225
+ console.log('');
226
+ console.log(` Device: ${deviceName}`);
227
+ console.log(' Status: Online');
228
+ console.log('');
229
+ console.log('┌─ Next');
230
+ console.log('│ Return to ChatGPT or Claude and continue your conversation.');
231
+ console.log('│ Keep this Terminal running. You can minimize it.');
232
+ console.log('└─ Press Ctrl+C to disconnect.');
233
+ console.log('');
234
+ console.log('┌─ Commands');
235
+ console.log('│ Help: npx @wonderwhy-er/desktop-commander@latest remote --help');
236
+ console.log('│ Log out: npx @wonderwhy-er/desktop-commander@latest remote --logout');
237
+ console.log('└─ Run these in a new Terminal, or after disconnecting.');
238
+ console.log('');
239
+ }
178
240
  // Keep process alive
179
241
  this.remoteChannel.startHeartbeat(this.deviceId);
180
242
  }
@@ -331,23 +393,47 @@ export class MCPDevice {
331
393
  * connected" until someone restarted the process by hand.
332
394
  */
333
395
  async handleLocalMcpLoss(reason) {
334
- if (this.deviceId) {
335
- await this.remoteChannel.setOnlineStatus(this.deviceId, 'offline')
336
- .catch((e) => console.error('Failed to mark device offline:', e.message));
337
- }
338
- // Recover proactively rather than waiting for the next tool call to
339
- // trigger the lazy restart: we just went offline, so no further calls
340
- // would be routed here and that wait would never end.
341
- try {
342
- await this.desktop.ensureReady();
343
- if (this.deviceId) {
344
- await this.remoteChannel.setOnlineStatus(this.deviceId, 'online');
396
+ // Through the predicate and its queue, not a direct write: the probe
397
+ // already reads false by the time this runs, and a direct write can be
398
+ // overtaken by an 'online' still sitting in the queue — which would put
399
+ // a device with a dead executor back into the server's selection pool.
400
+ await this.remoteChannel.syncReachabilityStatus()
401
+ .catch((e) => console.error('Failed to mark device offline:', e.message));
402
+ // Keep trying, rather than attempting once. The lazy restart in
403
+ // ensureReady() fires on an incoming tool call, and this device is now
404
+ // offline — the hosted service answers a call for an offline device
405
+ // with "No devices available" (confirmed live on 0.2.50), so no call
406
+ // will ever arrive to trigger it. One failed attempt used to mean the
407
+ // device stayed dead until a human restarted the connector.
408
+ let reported = false;
409
+ while (!this.isShuttingDown) {
410
+ try {
411
+ // ensureReady() only reports success once the child has served a
412
+ // request, so reaching here is proof of execution, not just of a
413
+ // completed handshake.
414
+ await this.desktop.ensureReady();
415
+ // Not setOnlineStatus('online'): the executor recovering says
416
+ // nothing about the channel. Let the predicate decide, or this
417
+ // repeats the one-sided claim this whole change removes.
418
+ this.remoteChannel.syncReachabilityStatus();
419
+ console.log('♻️ Local Desktop Commander MCP restarted; device is online again');
420
+ return;
421
+ }
422
+ catch (error) {
423
+ console.error(`❌ Could not restart local Desktop Commander MCP: ${error.message}`);
424
+ // Once per outage, not once per attempt: a device that never
425
+ // recovers would otherwise emit this every backoff window for
426
+ // as long as it runs.
427
+ if (!reported) {
428
+ reported = true;
429
+ await captureRemote('remote_device_local_mcp_restart_failed', { error, reason });
430
+ }
431
+ // ensureReady() refuses inside its backoff window; wait it out.
432
+ // The floor covers a child that starts but fails verification,
433
+ // where no restart backoff was armed.
434
+ const waitMs = Math.max(this.desktop.msUntilRestartAllowed, RECOVERY_MIN_DELAY_MS);
435
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
345
436
  }
346
- console.log('♻️ Local Desktop Commander MCP restarted; device is online again');
347
- }
348
- catch (error) {
349
- console.error(`❌ Could not restart local Desktop Commander MCP: ${error.message}`);
350
- await captureRemote('remote_device_local_mcp_restart_failed', { error, reason });
351
437
  }
352
438
  }
353
439
  /** Record a handled call id, evicting the oldest once the cap is reached. */
@@ -10,6 +10,16 @@ export interface AuthSession {
10
10
  refresh_token: string | null;
11
11
  device_id?: string;
12
12
  }
13
+ /**
14
+ * The device registered, but its realtime channel is not usable — the join
15
+ * failed, or presence was never acknowledged. Distinct from every other
16
+ * registration failure on purpose: this one the socket watchdog can repair, so
17
+ * the caller keeps the process alive, while a failed lookup or a missing row
18
+ * happens before the recreation parameters are stored and nothing can repair it.
19
+ */
20
+ export declare class ChannelUnreachableError extends Error {
21
+ constructor(message: string);
22
+ }
13
23
  interface DeviceData {
14
24
  user_id: string;
15
25
  device_name: string;
@@ -17,6 +27,10 @@ interface DeviceData {
17
27
  status: string;
18
28
  last_seen: string;
19
29
  }
30
+ /** Jittered version of realtime-js's default 1s/2s/5s/10s stepped backoff. */
31
+ export declare function realtimeReconnectDelayMs(tries: number, random?: () => number): number;
32
+ /** Preserve Presence's existing 500ms-per-attempt retry shape, but desynchronize it. */
33
+ export declare function presenceRetryDelayMs(failedAttempt: number, random?: () => number): number;
20
34
  export declare function observeServerDate(dateHeader: string | null): void;
21
35
  export declare class RemoteChannel {
22
36
  private client;
@@ -26,6 +40,12 @@ export declare class RemoteChannel {
26
40
  /** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
27
41
  private heartbeatDeviceId;
28
42
  private statusWriteChain;
43
+ /**
44
+ * Answers whether the local execution child is alive. Default yes, so a
45
+ * RemoteChannel used without a device (tests, other callers) behaves as
46
+ * before; MCPDevice installs the real probe.
47
+ */
48
+ private localExecutorProbe;
29
49
  /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
30
50
  private lastKnownSession;
31
51
  /** Notified when auth-js rotates the session; the device persists it. */
@@ -45,6 +65,8 @@ export declare class RemoteChannel {
45
65
  private presenceTracked;
46
66
  /** Last capability value written (null = never), to avoid redundant writes. */
47
67
  private transportCapableWritten;
68
+ /** Monotonic start of a Presence-only degradation while broadcast remains joined. */
69
+ private presenceFailureStartedAt;
48
70
  /** Re-entrancy guard: on a wedged socket each track() buffers for the full
49
71
  * 10s push timeout, so 10s health ticks would stack pushes. */
50
72
  private isTrackingPresence;
@@ -65,6 +87,12 @@ export declare class RemoteChannel {
65
87
  private _user;
66
88
  get user(): User | null;
67
89
  initialize(url: string, key: string): void;
90
+ /**
91
+ * Teach the channel how to ask whether the local executor is alive.
92
+ * `status` is a claim that this device will run a tool call right now, and
93
+ * a joined channel alone cannot support that claim - issue #4.
94
+ */
95
+ setLocalExecutorProbe(probe: () => boolean): void;
68
96
  /**
69
97
  * Register a callback fired when auth-js rotates the session. auth-js
70
98
  * rotates the refresh token on every refresh and the previous one is spent,
@@ -122,6 +150,15 @@ export declare class RemoteChannel {
122
150
  private setTransportCapable;
123
151
  /** Create and subscribe the private channel (initial join and recreation). */
124
152
  private createChannel;
153
+ /**
154
+ * Recover calls whose Realtime doorbell was missed while this device was
155
+ * disconnected. Broadcast provides the fast path; the DB row is the source
156
+ * of truth. Only still-live pending rows for this device are considered.
157
+ *
158
+ * The follow-up onDoorbell() call performs the existing conditional claim,
159
+ * which makes this safe against a doorbell arriving at the same time.
160
+ */
161
+ private recoverPendingCalls;
125
162
  /** Hand a call to device.ts, observing the rejection — the handler is async
126
163
  * and an unhandled rejection terminates the process. */
127
164
  private dispatchToolCall;
@@ -169,15 +206,26 @@ export declare class RemoteChannel {
169
206
  */
170
207
  markCallExecuting(callId: string): Promise<boolean>;
171
208
  updateCallResult(callId: string, status: string, result?: any, errorMessage?: string | null): Promise<void>;
172
- /** Reachable means the private channel is joined. Gates the heartbeat and `status`. */
209
+ /**
210
+ * Reachable means all of it is true at once: the private channel is
211
+ * joined, this device has published its presence, and the local executor
212
+ * answers. The server needs the first two before it will dispatch, and a
213
+ * healthy channel on a device whose executor is dead is the false-online
214
+ * state issue #4 was opened for. Gates the heartbeat and `status`.
215
+ */
173
216
  private isReachable;
174
217
  /**
175
218
  * Set `status` from actual reachability. `status` is transport-agnostic (the
176
219
  * server filters on it), so it must not follow one channel's health — the
177
220
  * private channel's error path re-fires on every rejoin and would oscillate
178
221
  * the row against the heartbeat. Same predicate as the heartbeat gate.
222
+ *
223
+ * Every transition belongs here rather than calling setOnlineStatus(), which
224
+ * is the write and not the decision. Public so the device can route its
225
+ * recovery transition through the predicate too.
179
226
  */
180
- private syncReachabilityStatus;
227
+ /** Resolves with whether the row actually took the write. */
228
+ syncReachabilityStatus(): Promise<boolean>;
181
229
  /**
182
230
  * Serialize the channel-callback status writes. They fire from un-awaited
183
231
  * callbacks, and inside recreateChannel() a teardown's 'offline' and the
@@ -202,7 +250,8 @@ export declare class RemoteChannel {
202
250
  /** Arm (or re-arm) the last_seen timer at the current tier's cadence. */
203
251
  private scheduleHeartbeat;
204
252
  stopHeartbeat(): void;
205
- setOnlineStatus(deviceId: string, status: 'online' | 'offline'): Promise<void>;
253
+ /** @returns whether the row actually took the write. */
254
+ setOnlineStatus(deviceId: string, status: 'online' | 'offline'): Promise<boolean>;
206
255
  setOffline(deviceId: string | undefined): Promise<void>;
207
256
  unsubscribe(): Promise<void>;
208
257
  }