@wonderwhy-er/desktop-commander 0.2.47 → 0.2.50

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.
@@ -12,6 +12,40 @@ export class DesktopCommanderIntegration {
12
12
  this.mcpClient = null;
13
13
  this.mcpTransport = null;
14
14
  this.isReady = false;
15
+ this.isShuttingDown = false;
16
+ this.disconnectHandler = null;
17
+ this.reinitPromise = null;
18
+ }
19
+ /** True only while the local stdio child is actually reachable. */
20
+ get ready() {
21
+ return this.isReady && this.mcpClient !== null;
22
+ }
23
+ /**
24
+ * Register a callback fired when the local MCP child dies unexpectedly.
25
+ * The device uses this to stop advertising itself as online — the remote
26
+ * channel staying healthy says nothing about the local half being alive.
27
+ */
28
+ onDisconnect(handler) {
29
+ this.disconnectHandler = handler;
30
+ }
31
+ /**
32
+ * The local child exited or its pipe broke. Previously nothing observed this:
33
+ * `isReady` was a one-shot latch set in initialize() and cleared only by
34
+ * shutdown(), so every later callClientTool() sailed past the readiness guard
35
+ * and died inside the SDK with a bare "Not connected", forever, while the
36
+ * device still reported itself online.
37
+ */
38
+ handleLocalDisconnect(reason) {
39
+ if (this.isShuttingDown)
40
+ return; // expected teardown, not a fault
41
+ if (!this.isReady)
42
+ return; // already handled; don't double-fire
43
+ this.isReady = false;
44
+ this.mcpClient = null;
45
+ this.mcpTransport = null;
46
+ console.error(` - ❌ Local Desktop Commander MCP went away (${reason}); will restart on next tool call`);
47
+ void captureRemote('desktop_integration_local_disconnected', { reason });
48
+ this.disconnectHandler?.(reason);
15
49
  }
16
50
  async initialize() {
17
51
  console.debug('[DEBUG] DesktopCommanderIntegration.initialize() called');
@@ -43,16 +77,53 @@ export class DesktopCommanderIntegration {
43
77
  console.debug('[DEBUG] Connecting MCP client to transport');
44
78
  await this.mcpClient.connect(this.mcpTransport);
45
79
  this.isReady = true;
80
+ // Supervise the local half. Without these, a child crash is silent:
81
+ // the SDK clears its transport and every subsequent call throws
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)}`);
46
85
  console.log(' - 🔌 Connected to Desktop Commander MCP');
47
86
  console.debug('[DEBUG] Desktop Commander MCP connection successful');
48
87
  }
49
88
  catch (error) {
50
89
  console.error(' - ❌ Failed to connect to Desktop Commander MCP:', error);
51
90
  console.debug('[DEBUG] MCP connection error:', error);
91
+ // Leave no half-built client behind, or ensureReady() would treat the
92
+ // corpse as live on the next attempt.
93
+ this.isReady = false;
94
+ this.mcpClient = null;
95
+ if (this.mcpTransport) {
96
+ try {
97
+ await this.mcpTransport.close();
98
+ }
99
+ catch { /* already dead — nothing to salvage */ }
100
+ this.mcpTransport = null;
101
+ }
52
102
  await captureRemote('desktop_integration_init_failed', { error });
53
103
  throw error;
54
104
  }
55
105
  }
106
+ /**
107
+ * Guarantee a live local child before proxying a call, restarting it if the
108
+ * previous one died. Restart is lazy (on demand) rather than a retry loop:
109
+ * if the child is crashing on startup, each tool call fails with the real
110
+ * reason instead of spinning respawns in the background.
111
+ */
112
+ async ensureReady() {
113
+ if (this.ready)
114
+ return;
115
+ if (this.isShuttingDown) {
116
+ throw new Error('Desktop Commander integration is shutting down');
117
+ }
118
+ if (!this.reinitPromise) {
119
+ console.log(' - ♻️ Local Desktop Commander MCP is not running; restarting it...');
120
+ this.reinitPromise = this.initialize().finally(() => {
121
+ this.reinitPromise = null;
122
+ });
123
+ }
124
+ // Concurrent calls share the single in-flight restart.
125
+ await this.reinitPromise;
126
+ }
56
127
  async resolveMcpConfig() {
57
128
  console.debug('[DEBUG] Resolving MCP config...');
58
129
  // Option 1: Development/Local Build
@@ -106,10 +177,10 @@ export class DesktopCommanderIntegration {
106
177
  return null;
107
178
  }
108
179
  async callClientTool(toolName, args, metadata) {
109
- if (!this.isReady || !this.mcpClient) {
110
- console.debug('[DEBUG] callClientTool() failed - not ready or no client');
111
- throw new Error('DesktopIntegration not initialized');
112
- }
180
+ // Restart the child if it died since the last call, so a one-off crash
181
+ // costs one failed call instead of wedging the device until a human
182
+ // restarts `desktop-commander remote`.
183
+ await this.ensureReady();
113
184
  // Proxy other tools to MCP server
114
185
  try {
115
186
  console.debug('[DEBUG] Calling MCP tool:', toolName, 'args:', JSON.stringify(args).substring(0, 100));
@@ -150,6 +221,9 @@ export class DesktopCommanderIntegration {
150
221
  }
151
222
  async shutdown() {
152
223
  console.debug('[DEBUG] DesktopCommanderIntegration.shutdown() called');
224
+ // Closing the transport fires onclose; flag this as intentional so it is
225
+ // not reported as a crash.
226
+ this.isShuttingDown = true;
153
227
  const closeWithTimeout = async (operation, name, timeoutMs = 3000) => {
154
228
  return Promise.race([
155
229
  operation(),
@@ -2,6 +2,7 @@
2
2
  export interface MCPDeviceOptions {
3
3
  persistSession?: boolean;
4
4
  }
5
+ export declare function getRemoteDeviceConfigPath(): string;
5
6
  export declare class MCPDevice {
6
7
  private baseServerUrl;
7
8
  private remoteChannel;
@@ -15,12 +16,21 @@ export declare class MCPDevice {
15
16
  constructor(options?: MCPDeviceOptions);
16
17
  private setupShutdownHandlers;
17
18
  start(): Promise<void>;
19
+ private findPersistedDeviceWithRetry;
18
20
  loadPersistedConfig(): Promise<any>;
21
+ clearPersistedConfig(): Promise<void>;
19
22
  savePersistedConfig(): Promise<void>;
20
23
  fetchSupabaseConfig(): Promise<{
21
24
  supabaseUrl: any;
22
25
  anonKey: any;
23
26
  }>;
27
+ /**
28
+ * The local Desktop Commander child died. A healthy remote channel says
29
+ * nothing about the local half being alive, so without this the device kept
30
+ * reporting itself online and every routed tool call came back "Not
31
+ * connected" until someone restarted the process by hand.
32
+ */
33
+ private handleLocalMcpLoss;
24
34
  /** Record a handled call id, evicting the oldest once the cap is reached. */
25
35
  private rememberCallId;
26
36
  handleNewToolCall(payload: any): Promise<void>;
@@ -15,6 +15,11 @@ import { captureRemote } from '../utils/capture.js';
15
15
  * (the device process, not the shared server).
16
16
  */
17
17
  const SEEN_CALL_IDS_MAX = 100;
18
+ const PERSISTED_DEVICE_LOOKUP_ATTEMPTS = 3;
19
+ const PERSISTED_DEVICE_LOOKUP_RETRY_MS = 250;
20
+ export function getRemoteDeviceConfigPath() {
21
+ return path.join(os.homedir(), '.desktop-commander-device', 'device.json');
22
+ }
18
23
  export class MCPDevice {
19
24
  constructor(options = {}) {
20
25
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
@@ -23,8 +28,12 @@ export class MCPDevice {
23
28
  this.remoteChannel = new RemoteChannel();
24
29
  this.deviceId = undefined;
25
30
  this.isShuttingDown = false;
26
- this.configPath = path.join(os.homedir(), '.desktop-commander-device', 'device.json');
27
- this.persistSession = options.persistSession || false;
31
+ this.configPath = getRemoteDeviceConfigPath();
32
+ // Default ON. Off meant a full re-authorization on every start, and each
33
+ // one mints a fresh GoTrue session that nothing ever revokes; the orphaned
34
+ // refresh-token families get replayed, trip GoTrue's reuse detection, and
35
+ // take the whole family down including the token a healthy connector holds.
36
+ this.persistSession = options.persistSession ?? true;
28
37
  // Initialize desktop integration
29
38
  this.desktop = new DesktopCommanderIntegration();
30
39
  // Graceful shutdown handlers (only set once)
@@ -82,6 +91,7 @@ export class MCPDevice {
82
91
  }
83
92
  // Initialize desktop integration
84
93
  await this.desktop.initialize();
94
+ this.desktop.onDisconnect((reason) => void this.handleLocalMcpLoss(reason));
85
95
  console.log(`⏳ Connecting to Remote MCP ${this.baseServerUrl}`);
86
96
  const { supabaseUrl, anonKey } = await this.fetchSupabaseConfig();
87
97
  console.log(` - 🔌 Connected to Remote MCP`);
@@ -98,6 +108,20 @@ export class MCPDevice {
98
108
  }
99
109
  else {
100
110
  console.log(' - ✅ Session restored');
111
+ console.log(' - ℹ️ To log out locally: npx @wonderwhy-er/desktop-commander@latest remote --logout');
112
+ // Revoking a device removes its server-side mcp_devices row, but the
113
+ // local config can still hold a valid user session + the now-deleted
114
+ // device ID. Do not silently recreate the revoked device with that
115
+ // old session: revocation must require a fresh browser authorization.
116
+ if (this.deviceId) {
117
+ const persistedDevice = await this.findPersistedDeviceWithRetry(this.deviceId);
118
+ if (!persistedDevice) {
119
+ console.log(` - ⚠️ Persisted device ${this.deviceId} was revoked or removed`);
120
+ await this.clearPersistedConfig();
121
+ this.deviceId = undefined;
122
+ session = null;
123
+ }
124
+ }
101
125
  }
102
126
  }
103
127
  if (!session) {
@@ -152,6 +176,22 @@ export class MCPDevice {
152
176
  process.exit(1);
153
177
  }
154
178
  }
179
+ async findPersistedDeviceWithRetry(deviceId) {
180
+ let lastError;
181
+ for (let attempt = 1; attempt <= PERSISTED_DEVICE_LOOKUP_ATTEMPTS; attempt++) {
182
+ try {
183
+ return await this.remoteChannel.findDevice(deviceId);
184
+ }
185
+ catch (error) {
186
+ lastError = error;
187
+ if (attempt === PERSISTED_DEVICE_LOOKUP_ATTEMPTS)
188
+ break;
189
+ console.warn(` - ⚠️ Device lookup failed (${attempt}/${PERSISTED_DEVICE_LOOKUP_ATTEMPTS}); retrying...`);
190
+ await new Promise((resolve) => setTimeout(resolve, PERSISTED_DEVICE_LOOKUP_RETRY_MS * attempt));
191
+ }
192
+ }
193
+ throw lastError;
194
+ }
155
195
  async loadPersistedConfig() {
156
196
  try {
157
197
  console.debug('[DEBUG] Loading persisted config from:', this.configPath);
@@ -159,12 +199,21 @@ export class MCPDevice {
159
199
  const config = JSON.parse(data);
160
200
  this.deviceId = config?.deviceId;
161
201
  console.debug('[DEBUG] Loaded device ID:', this.deviceId);
162
- console.log('💾 Found persisted session for device ' + this.deviceId);
163
- if (config.session) {
202
+ if (config.session && this.persistSession) {
203
+ console.log('💾 Found persisted session for device ' + this.deviceId);
164
204
  console.debug('[DEBUG] Session found in config, returning session');
165
205
  return config.session;
166
206
  }
167
- console.debug('[DEBUG] No session in config');
207
+ // A previously saved session must not be reused on an opted-out run:
208
+ // it would skip the re-authorization the flag promises, and the save
209
+ // at the end of start() then discards a possibly-rotated refresh
210
+ // token — orphaning one more live server-side session.
211
+ if (config.session) {
212
+ console.debug('[DEBUG] Ignoring persisted session (--no-persist-session)');
213
+ }
214
+ else {
215
+ console.debug('[DEBUG] No session in config');
216
+ }
168
217
  return null;
169
218
  }
170
219
  catch (error) {
@@ -181,6 +230,16 @@ export class MCPDevice {
181
230
  // No need to ensure device ID here
182
231
  }
183
232
  }
233
+ async clearPersistedConfig() {
234
+ try {
235
+ await fs.rm(this.configPath, { force: true });
236
+ console.debug('[DEBUG] Cleared stale persisted config:', this.configPath);
237
+ }
238
+ catch (error) {
239
+ console.warn('⚠️ Failed to clear stale config:', error.message);
240
+ await captureRemote('remote_device_config_clear_error', { error });
241
+ }
242
+ }
184
243
  async savePersistedConfig() {
185
244
  try {
186
245
  console.debug('[DEBUG] Saving persisted config, persistSession:', this.persistSession);
@@ -222,6 +281,32 @@ export class MCPDevice {
222
281
  };
223
282
  }
224
283
  // Methods moved to RemoteChannel
284
+ /**
285
+ * The local Desktop Commander child died. A healthy remote channel says
286
+ * nothing about the local half being alive, so without this the device kept
287
+ * reporting itself online and every routed tool call came back "Not
288
+ * connected" until someone restarted the process by hand.
289
+ */
290
+ async handleLocalMcpLoss(reason) {
291
+ if (this.deviceId) {
292
+ await this.remoteChannel.setOnlineStatus(this.deviceId, 'offline')
293
+ .catch((e) => console.error('Failed to mark device offline:', e.message));
294
+ }
295
+ // Recover proactively rather than waiting for the next tool call to
296
+ // trigger the lazy restart: we just went offline, so no further calls
297
+ // would be routed here and that wait would never end.
298
+ try {
299
+ await this.desktop.ensureReady();
300
+ if (this.deviceId) {
301
+ await this.remoteChannel.setOnlineStatus(this.deviceId, 'online');
302
+ }
303
+ console.log('♻️ Local Desktop Commander MCP restarted; device is online again');
304
+ }
305
+ catch (error) {
306
+ console.error(`❌ Could not restart local Desktop Commander MCP: ${error.message}`);
307
+ await captureRemote('remote_device_local_mcp_restart_failed', { error, reason });
308
+ }
309
+ }
225
310
  /** Record a handled call id, evicting the oldest once the cap is reached. */
226
311
  rememberCallId(callId) {
227
312
  this.seenCallIds.add(callId);
@@ -363,10 +448,12 @@ if (isMainModule) {
363
448
  // Parse command-line arguments
364
449
  const args = process.argv.slice(2);
365
450
  const options = {
366
- persistSession: args.includes('--persist-session')
451
+ // --persist-session is kept as an accepted no-op so existing invocations
452
+ // and docs keep working; --no-persist-session opts back out.
453
+ persistSession: !args.includes('--no-persist-session')
367
454
  };
368
- if (options.persistSession) {
369
- console.log('🔒 Session persistence enabled');
455
+ if (!options.persistSession) {
456
+ console.log('🔓 Session persistence disabled — re-authorization required on every start');
370
457
  }
371
458
  const device = new MCPDevice(options);
372
459
  device.start();
@@ -17,12 +17,10 @@ interface DeviceData {
17
17
  status: string;
18
18
  last_seen: string;
19
19
  }
20
+ export declare function observeServerDate(dateHeader: string | null): void;
20
21
  export declare class RemoteChannel {
21
22
  private client;
22
23
  private channel;
23
- /** Legacy listener, on its own public channel so a private-channel auth
24
- * failure can't take both transports down. Removed at the flip (009). */
25
- private legacyChannel;
26
24
  private heartbeatInterval;
27
25
  private connectionCheckInterval;
28
26
  /** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
@@ -33,6 +31,9 @@ export declare class RemoteChannel {
33
31
  /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
34
32
  * land after setOffline()'s durable write. */
35
33
  private shuttingDown;
34
+ /** Auth session gone for good: stops rejoins and caps the notice at one line. */
35
+ private sessionLost;
36
+ private handlingSignedOut;
36
37
  private deviceId;
37
38
  private deviceName;
38
39
  private onToolCall;
@@ -50,12 +51,29 @@ export declare class RemoteChannel {
50
51
  private reconnectAttempt;
51
52
  private isRecreatingChannel;
52
53
  private joiningSince;
54
+ /** Last confirmed proof of life (SUBSCRIBED or heartbeat 'ok'); null until the
55
+ * first one lands. On performance.now(), not Date.now(): the clock-skew
56
+ * correction above can (un)patch Date.now mid-run, jumping wall-clock math by
57
+ * the whole offset — a backward jump would suppress stale detection for as
58
+ * long as the offset. Same for joiningSince. */
59
+ private lastHeartbeatOkAt;
60
+ private heartbeatListenerRegistered;
61
+ /** Our own fixed-cadence auth refresh timer — see TOKEN_REFRESH_INTERVAL_MS. */
62
+ private tokenRefreshInterval;
53
63
  private _user;
54
64
  get user(): User | null;
55
65
  initialize(url: string, key: string): void;
56
66
  setSession(session: AuthSession): Promise<{
57
67
  error: any;
58
68
  }>;
69
+ /**
70
+ * Session gone: one restore attempt, then go offline and stop retrying.
71
+ *
72
+ * The attempt matters because auth-js only treats network errors and 502/503/504
73
+ * as retryable — a 429 or 500 kills the session while the refresh token is fine.
74
+ * We don't re-authenticate: DeviceAuthenticator opens a browser and waits.
75
+ */
76
+ private handleSignedOut;
59
77
  getSession(): Promise<{
60
78
  data: {
61
79
  session: Session | null;
@@ -94,13 +112,6 @@ export declare class RemoteChannel {
94
112
  * re-arm the heartbeat.
95
113
  */
96
114
  private setTransportCapable;
97
- /**
98
- * Legacy postgres_changes listener on its own public channel. Best-effort:
99
- * failures are logged, never thrown. Removed at the flip (009).
100
- */
101
- private createLegacyChannel;
102
- /** Tear down the legacy channel (best effort). */
103
- private removeLegacyChannel;
104
115
  /** Create and subscribe the private channel (initial join and recreation). */
105
116
  private createChannel;
106
117
  /** Hand a call to device.ts, observing the rejection — the handler is async
@@ -156,13 +167,7 @@ export declare class RemoteChannel {
156
167
  */
157
168
  markCallExecuting(callId: string): Promise<boolean>;
158
169
  updateCallResult(callId: string, status: string, result?: any, errorMessage?: string | null): Promise<void>;
159
- /**
160
- * Reachable by SOME transport — the private channel or, during the
161
- * transition, the independent legacy one. Gates the heartbeat and `status`:
162
- * asking only about the private channel starves last_seen for a device whose
163
- * legacy channel is fine, and the 45s sweep then blacks it out.
164
- * Collapses to a single check at the flip (009).
165
- */
170
+ /** Reachable means the private channel is joined. Gates the heartbeat and `status`. */
166
171
  private isReachable;
167
172
  /**
168
173
  * Set `status` from actual reachability. `status` is transport-agnostic (the
@@ -189,6 +194,9 @@ export declare class RemoteChannel {
189
194
  private heartbeatIntervalMs;
190
195
  updateHeartbeat(deviceId: string): Promise<void>;
191
196
  startHeartbeat(deviceId: string): void;
197
+ private refreshTokenNow;
198
+ private startTokenRefresh;
199
+ private stopTokenRefresh;
192
200
  /** Arm (or re-arm) the last_seen timer at the current tier's cadence. */
193
201
  private scheduleHeartbeat;
194
202
  stopHeartbeat(): void;