@wonderwhy-er/desktop-commander 0.2.47 → 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,7 +1,12 @@
1
1
  import { MCPDevice } from '../remote-device/device.js';
2
2
  import os from 'os';
3
3
  export async function runRemote() {
4
- const persistSession = process.argv.includes('--persist-session');
4
+ // --persist-session is kept as an accepted no-op so existing invocations
5
+ // and docs keep working; --no-persist-session opts back out.
6
+ const persistSession = !process.argv.includes('--no-persist-session');
7
+ if (!persistSession) {
8
+ console.log('🔓 Session persistence disabled — re-authorization required on every start');
9
+ }
5
10
  const disableNoSleep = process.argv.includes('--disable-no-sleep');
6
11
  const verbose = process.argv.includes('--debug');
7
12
  console.debug('[DEBUG] Verbose mode: ', verbose);
@@ -24,7 +24,11 @@ export class MCPDevice {
24
24
  this.deviceId = undefined;
25
25
  this.isShuttingDown = false;
26
26
  this.configPath = path.join(os.homedir(), '.desktop-commander-device', 'device.json');
27
- this.persistSession = options.persistSession || false;
27
+ // Default ON. Off meant a full re-authorization on every start, and each
28
+ // one mints a fresh GoTrue session that nothing ever revokes; the orphaned
29
+ // refresh-token families get replayed, trip GoTrue's reuse detection, and
30
+ // take the whole family down including the token a healthy connector holds.
31
+ this.persistSession = options.persistSession ?? true;
28
32
  // Initialize desktop integration
29
33
  this.desktop = new DesktopCommanderIntegration();
30
34
  // Graceful shutdown handlers (only set once)
@@ -159,12 +163,21 @@ export class MCPDevice {
159
163
  const config = JSON.parse(data);
160
164
  this.deviceId = config?.deviceId;
161
165
  console.debug('[DEBUG] Loaded device ID:', this.deviceId);
162
- console.log('💾 Found persisted session for device ' + this.deviceId);
163
- if (config.session) {
166
+ if (config.session && this.persistSession) {
167
+ console.log('💾 Found persisted session for device ' + this.deviceId);
164
168
  console.debug('[DEBUG] Session found in config, returning session');
165
169
  return config.session;
166
170
  }
167
- console.debug('[DEBUG] No session in config');
171
+ // A previously saved session must not be reused on an opted-out run:
172
+ // it would skip the re-authorization the flag promises, and the save
173
+ // at the end of start() then discards a possibly-rotated refresh
174
+ // token — orphaning one more live server-side session.
175
+ if (config.session) {
176
+ console.debug('[DEBUG] Ignoring persisted session (--no-persist-session)');
177
+ }
178
+ else {
179
+ console.debug('[DEBUG] No session in config');
180
+ }
168
181
  return null;
169
182
  }
170
183
  catch (error) {
@@ -363,10 +376,12 @@ if (isMainModule) {
363
376
  // Parse command-line arguments
364
377
  const args = process.argv.slice(2);
365
378
  const options = {
366
- persistSession: args.includes('--persist-session')
379
+ // --persist-session is kept as an accepted no-op so existing invocations
380
+ // and docs keep working; --no-persist-session opts back out.
381
+ persistSession: !args.includes('--no-persist-session')
367
382
  };
368
- if (options.persistSession) {
369
- console.log('🔒 Session persistence enabled');
383
+ if (!options.persistSession) {
384
+ console.log('🔓 Session persistence disabled — re-authorization required on every start');
370
385
  }
371
386
  const device = new MCPDevice(options);
372
387
  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;
@@ -39,6 +39,14 @@ const RECREATE_TIMEOUT_MS = 45000;
39
39
  // Max continuous time in 'joining' before forcing a recreate — a half-open
40
40
  // socket parks the channel there forever, and a genuine join settles in ~10s.
41
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;
42
50
  // Failed recreates before withdrawing transport_broadcast_v1 — keeping it while
43
51
  // unable to join makes the device undispatchable. Not lower than 3: ordinary
44
52
  // half-open recovery legitimately costs 2.
@@ -54,13 +62,52 @@ const OFFLINE_SESSION_TIMEOUT_MS = 500;
54
62
  // already covers.
55
63
  const SOCKET_SETTLE_MAX_MS = 300;
56
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
+ }
57
107
  export class RemoteChannel {
58
108
  constructor() {
59
109
  this.client = null;
60
110
  this.channel = null;
61
- /** Legacy listener, on its own public channel so a private-channel auth
62
- * failure can't take both transports down. Removed at the flip (009). */
63
- this.legacyChannel = null;
64
111
  this.heartbeatInterval = null;
65
112
  this.connectionCheckInterval = null;
66
113
  /** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
@@ -72,6 +119,9 @@ export class RemoteChannel {
72
119
  /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
73
120
  * land after setOffline()'s durable write. */
74
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;
75
125
  // Store subscription parameters for channel recreation
76
126
  this.deviceId = null;
77
127
  this.deviceName = null;
@@ -92,12 +142,56 @@ export class RemoteChannel {
92
142
  this.lastChannelState = null;
93
143
  this.reconnectAttempt = 0; // recreates since the last success
94
144
  this.isRecreatingChannel = false; // re-entrancy guard
95
- this.joiningSince = null; // start of an unbroken 'joining' run
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;
96
155
  this._user = null;
97
156
  }
98
157
  get user() { return this._user; }
99
158
  initialize(url, key) {
100
- 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
+ }
101
195
  }
102
196
  async setSession(session) {
103
197
  if (!this.client)
@@ -149,10 +243,107 @@ export class RemoteChannel {
149
243
  refresh_token: newSession.refresh_token ?? this.lastKnownSession?.refresh_token ?? null,
150
244
  };
151
245
  }
246
+ else if (event === 'SIGNED_OUT') {
247
+ void this.handleSignedOut();
248
+ }
152
249
  });
153
250
  }
154
251
  return { error };
155
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
+ }
156
347
  async getSession() {
157
348
  if (!this.client)
158
349
  throw new Error('Client not initialized');
@@ -232,8 +423,6 @@ export class RemoteChannel {
232
423
  console.debug(`⏳ Subscribing to tool call channel...`);
233
424
  // Create and subscribe to the channel
234
425
  console.debug('[DEBUG] Calling createChannel()');
235
- // Independent safety net for the doorbell transport.
236
- this.createLegacyChannel();
237
426
  await this.createChannel().catch((error) => {
238
427
  console.debug(`[DEBUG] Failed to create channel, will retry after socket reconnect: ${error?.message || error} — ${this.connState()}`);
239
428
  });
@@ -291,10 +480,11 @@ export class RemoteChannel {
291
480
  await this.sleep(500 * attempt);
292
481
  }
293
482
  this.presenceTracked = false;
294
- console.error('❌ Presence track failed after retries — reverting to the legacy transport tier');
483
+ console.error('❌ Presence track failed after retries — withdrawing broadcast capability');
295
484
  captureRemote('remote_channel_presence_track_error', { attempts }).catch(() => { });
296
485
  // Withdraw: a stale flag with no presence makes the server refuse to
297
- // dispatch at all. The legacy tier keeps the device usable.
486
+ // dispatch at all. The faster heartbeat tier keeps the device's status
487
+ // accurate for the DB-status fallback while it recovers.
298
488
  await this.setTransportCapable(false);
299
489
  }
300
490
  /**
@@ -329,7 +519,7 @@ export class RemoteChannel {
329
519
  return;
330
520
  }
331
521
  this.transportCapableWritten = capable;
332
- console.debug(`[DEBUG] Transport capability set to ${capable ? 'broadcast_v1' : 'legacy'}`);
522
+ console.debug(`[DEBUG] Transport capability set to ${capable ? 'broadcast_v1' : 'withdrawn'}`);
333
523
  // Tier changed — move last_seen onto the cadence that tier's sweep
334
524
  // threshold expects (no-op if the heartbeat hasn't started yet).
335
525
  this.scheduleHeartbeat();
@@ -343,43 +533,6 @@ export class RemoteChannel {
343
533
  console.error('[DEBUG] Transport capability update threw:', error?.message);
344
534
  }
345
535
  }
346
- /**
347
- * Legacy postgres_changes listener on its own public channel. Best-effort:
348
- * failures are logged, never thrown. Removed at the flip (009).
349
- */
350
- createLegacyChannel() {
351
- if (!this.client || !this.user?.id)
352
- return;
353
- try {
354
- this.legacyChannel = this.client
355
- .channel('device_tool_call_queue')
356
- .on('postgres_changes', {
357
- event: 'INSERT',
358
- schema: 'public',
359
- table: 'mcp_remote_calls',
360
- filter: `user_id=eq.${this.user.id}`
361
- }, (payload) => {
362
- console.debug('[DEBUG] Realtime event received, payload:', payload?.new?.id);
363
- this.dispatchToolCall(payload);
364
- })
365
- .subscribe((status) => {
366
- console.debug(`[DEBUG] Legacy channel status: ${status}`);
367
- });
368
- }
369
- catch (error) {
370
- console.debug('[DEBUG] Legacy channel subscribe failed (doorbell path unaffected):', error?.message);
371
- }
372
- }
373
- /** Tear down the legacy channel (best effort). */
374
- async removeLegacyChannel() {
375
- if (!this.legacyChannel || !this.client)
376
- return;
377
- try {
378
- await this.client.removeChannel(this.legacyChannel);
379
- }
380
- catch { /* best effort */ }
381
- this.legacyChannel = null;
382
- }
383
536
  /** Create and subscribe the private channel (initial join and recreation). */
384
537
  createChannel() {
385
538
  return new Promise((resolve, reject) => {
@@ -414,6 +567,7 @@ export class RemoteChannel {
414
567
  if (status === 'SUBSCRIBED') {
415
568
  const recovered = this.reconnectAttempt;
416
569
  this.reconnectAttempt = 0;
570
+ this.lastHeartbeatOkAt = performance.now(); // a fresh join is proof of life too
417
571
  console.log(`✅ Channel subscribed${recovered > 0 ? ` (recovered after ${recovered} attempt${recovered === 1 ? '' : 's'})` : ''}`);
418
572
  // Update device status on successful connection (queued, so
419
573
  // it can't be overtaken by a teardown's status write).
@@ -516,13 +670,12 @@ export class RemoteChannel {
516
670
  await captureRemote('remote_channel_doorbell_row_missing', { call_id: callId });
517
671
  return;
518
672
  }
519
- // Optimization, not a guard — saves a hop when the legacy path already
520
- // claimed this. Exactly-once lives in device.ts (seenCallIds + DB claim).
673
+ // Optimization, not a guard — saves a hop on a duplicate doorbell
674
+ // (retry, reconnect). Exactly-once lives in device.ts (seenCallIds + DB claim).
521
675
  if (row.status !== 'pending') {
522
- console.debug('[DEBUG] Doorbell call already claimed via legacy path:', callId);
676
+ console.debug('[DEBUG] Doorbell call already claimed:', callId);
523
677
  return;
524
678
  }
525
- // Same payload shape as postgres_changes ({ new: row }).
526
679
  this.dispatchToolCall({ new: row });
527
680
  }
528
681
  /**
@@ -570,6 +723,8 @@ export class RemoteChannel {
570
723
  * Check if channel is connected, recreate if not.
571
724
  */
572
725
  checkConnectionHealth() {
726
+ if (this.sessionLost)
727
+ return;
573
728
  if (!this.channel || !this.client || !this.user?.id || !this.onToolCall) {
574
729
  return;
575
730
  }
@@ -582,6 +737,17 @@ export class RemoteChannel {
582
737
  // 'joined' = healthy. Clear the joining-overstay timer.
583
738
  if (state === 'joined') {
584
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
+ }
585
751
  // Self-heal a failed presence publish: the channel is up, so nothing
586
752
  // else will ever retry (SUBSCRIBED won't fire again), and without
587
753
  // presence the server reports this healthy device as offline.
@@ -597,7 +763,7 @@ export class RemoteChannel {
597
763
  // JOINING_WEDGE_TIMEOUT_MS force a recreate, the only path that
598
764
  // disconnect()s the dead socket.
599
765
  if (state === 'joining') {
600
- const now = Date.now();
766
+ const now = performance.now();
601
767
  if (this.joiningSince === null)
602
768
  this.joiningSince = now;
603
769
  const stuckMs = now - this.joiningSince;
@@ -686,7 +852,12 @@ export class RemoteChannel {
686
852
  // it a window to win: the old channel can come back 'joined' while we
687
853
  // slept. Destroying a healthy channel would cause a pointless outage
688
854
  // cycle — bail out instead (observed live on staging, 2026-07-23).
689
- if (this.channel?.state === 'joined') {
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) {
690
861
  console.log(`✅ Channel self-healed during backoff — skipping recreate — ${this.connState()}`);
691
862
  return; // finally-block below clears the re-entrancy guard
692
863
  }
@@ -702,9 +873,6 @@ export class RemoteChannel {
702
873
  await this.client.removeChannel(this.channel);
703
874
  this.channel = null;
704
875
  }
705
- // Rebuild the legacy channel too: it shares the socket, so a
706
- // socket-level wedge takes it down with the private channel.
707
- await this.removeLegacyChannel();
708
876
  // FIX (core): force a brand-new WebSocket. After idle / wifi-loss the socket can
709
877
  // be HALF-OPEN (readyState OPEN but dead); reusing it made every join TIME_OUT
710
878
  // forever. disconnect() drops it so the next subscribe() dials a fresh one.
@@ -717,18 +885,11 @@ export class RemoteChannel {
717
885
  // _teardownConnection() nulls the conn.onclose that would clear
718
886
  // it, so only an internal ~100ms fallback timer does. connect()
719
887
  // early-returns for that whole window, so rebuilding here makes
720
- // subscribe()'s socket.connect() a silent no-op and BOTH
721
- // channels sit in 'joining' until the 10s join timeout — the
722
- // wasted-first-recreate that left the device dark on the legacy
723
- // channel too. Wait for the state to settle before rebuilding.
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.
724
891
  await this.waitForSocketSettled();
725
892
  console.debug('[DEBUG] Calling createChannel() for recreation');
726
- // Rebuild the legacy safety net FIRST and unconditionally: if
727
- // createChannel() throws or exceeds RECREATE_TIMEOUT_MS, anything
728
- // after it is skipped, which used to leave the fallback dead for
729
- // the entire duration of a private-channel outage — every
730
- // subsequent health tick repeating the same teardown.
731
- this.createLegacyChannel();
732
893
  await this.createChannel();
733
894
  }, RECREATE_TIMEOUT_MS, 'recreateChannel');
734
895
  }
@@ -834,15 +995,9 @@ export class RemoteChannel {
834
995
  console.debug('[DEBUG] Call result updated successfully:', callId);
835
996
  }
836
997
  }
837
- /**
838
- * Reachable by SOME transport — the private channel or, during the
839
- * transition, the independent legacy one. Gates the heartbeat and `status`:
840
- * asking only about the private channel starves last_seen for a device whose
841
- * legacy channel is fine, and the 45s sweep then blacks it out.
842
- * Collapses to a single check at the flip (009).
843
- */
998
+ /** Reachable means the private channel is joined. Gates the heartbeat and `status`. */
844
999
  isReachable() {
845
- return this.channel?.state === 'joined' || this.legacyChannel?.state === 'joined';
1000
+ return this.channel?.state === 'joined';
846
1001
  }
847
1002
  /**
848
1003
  * Set `status` from actual reachability. `status` is transport-agnostic (the
@@ -935,7 +1090,39 @@ export class RemoteChannel {
935
1090
  // withdraws the capability flag must fall back to the fast legacy
936
1091
  // cadence immediately, not 30 minutes later.
937
1092
  this.scheduleHeartbeat();
938
- console.debug(`[DEBUG] Heartbeat started - connectionCheck: 10s, last_seen: ${this.heartbeatIntervalMs()}ms`);
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
+ }
939
1126
  }
940
1127
  /** Arm (or re-arm) the last_seen timer at the current tier's cadence. */
941
1128
  scheduleHeartbeat() {
@@ -962,6 +1149,7 @@ export class RemoteChannel {
962
1149
  clearInterval(this.connectionCheckInterval);
963
1150
  this.connectionCheckInterval = null;
964
1151
  }
1152
+ this.stopTokenRefresh();
965
1153
  }
966
1154
  async setOnlineStatus(deviceId, status) {
967
1155
  if (!this.client)
@@ -1085,7 +1273,7 @@ export class RemoteChannel {
1085
1273
  // SUBSCRIBED would queue 'online' after the durable write.
1086
1274
  this.shuttingDown = true;
1087
1275
  // Budget against device.ts's 5s force-exit, worst case:
1088
- // 250 drain + 3x300 leave + 500 session + 3000 spawnSync = 4650ms.
1276
+ // 250 drain + 2x300 leave + 500 session + 3000 spawnSync = 4350ms.
1089
1277
  // In practice only the untrack bound binds — removeChannel/unsubscribe
1090
1278
  // set state='leaving' first, so their leave push resolves inline.
1091
1279
  const LEAVE_BOUND_MS = 300;
@@ -1093,7 +1281,6 @@ export class RemoteChannel {
1093
1281
  // heartbeat PATCH (it doesn't use the chain), but the gate above stops
1094
1282
  // any new one and an in-flight one started earlier.
1095
1283
  await Promise.race([this.statusWriteChain, this.sleep(250)]);
1096
- await Promise.race([this.removeLegacyChannel(), this.sleep(LEAVE_BOUND_MS)]);
1097
1284
  if (this.channel) {
1098
1285
  // Leave presence on the graceful path (socket close covers the abrupt
1099
1286
  // one). Bounded: a half-open socket still reports 'joined', so the
@@ -166,7 +166,7 @@ const getVersion = async () => {
166
166
  }
167
167
  };
168
168
 
169
- // Function to detect shell environmen
169
+ // Function to detect shell environment
170
170
  function detectShell() {
171
171
  // Check for Windows shells
172
172
  if (process.platform === 'win32') {
@@ -1,3 +1,17 @@
1
- import { ServerResult } from '../types.js';
1
+ import { ProcessInfo, ServerResult } from '../types.js';
2
+ /**
3
+ * Parse `tasklist /fo csv /nh` output (#662). Fields per row, all quoted:
4
+ * [Image Name, PID, Session Name, Session#, Mem Usage]. CSV instead of the
5
+ * default table: image names can contain spaces and Mem Usage contains
6
+ * thousands separators, so positional whitespace splitting can't work.
7
+ * tasklist has no live per-process CPU%, so cpu is reported as n/a.
8
+ */
9
+ export declare function parseWindowsTasklistCsv(stdout: string): ProcessInfo[];
10
+ /**
11
+ * Parse `ps aux` output: 11 whitespace-separated columns, COMMAND from
12
+ * column 10 onward (it can contain spaces, so it must be rejoined, not
13
+ * taken as the last token).
14
+ */
15
+ export declare function parsePsAux(stdout: string): ProcessInfo[];
2
16
  export declare function listProcesses(): Promise<ServerResult>;
3
17
  export declare function killProcess(args: unknown): Promise<ServerResult>;
@@ -3,22 +3,53 @@ import { promisify } from 'util';
3
3
  import os from 'os';
4
4
  import { KillProcessArgsSchema } from './schemas.js';
5
5
  const execAsync = promisify(exec);
6
+ /**
7
+ * Parse `tasklist /fo csv /nh` output (#662). Fields per row, all quoted:
8
+ * [Image Name, PID, Session Name, Session#, Mem Usage]. CSV instead of the
9
+ * default table: image names can contain spaces and Mem Usage contains
10
+ * thousands separators, so positional whitespace splitting can't work.
11
+ * tasklist has no live per-process CPU%, so cpu is reported as n/a.
12
+ */
13
+ export function parseWindowsTasklistCsv(stdout) {
14
+ return stdout.split(/\r?\n/)
15
+ .filter(Boolean)
16
+ .map(line => {
17
+ const fields = (line.match(/"([^"]*)"/g) || []).map(f => f.slice(1, -1));
18
+ return {
19
+ pid: parseInt(fields[1], 10),
20
+ command: fields[0] ?? '',
21
+ cpu: 'n/a',
22
+ memory: fields[4] ?? '',
23
+ };
24
+ })
25
+ .filter(p => !Number.isNaN(p.pid));
26
+ }
27
+ /**
28
+ * Parse `ps aux` output: 11 whitespace-separated columns, COMMAND from
29
+ * column 10 onward (it can contain spaces, so it must be rejoined, not
30
+ * taken as the last token).
31
+ */
32
+ export function parsePsAux(stdout) {
33
+ return stdout.split(/\r?\n/)
34
+ .slice(1)
35
+ .filter(Boolean)
36
+ .map(line => {
37
+ const parts = line.trim().split(/\s+/);
38
+ return {
39
+ pid: parseInt(parts[1], 10),
40
+ command: parts.slice(10).join(' ') || parts[parts.length - 1],
41
+ cpu: parts[2],
42
+ memory: parts[3],
43
+ };
44
+ })
45
+ .filter(p => !Number.isNaN(p.pid));
46
+ }
6
47
  export async function listProcesses() {
7
- const command = os.platform() === 'win32' ? 'tasklist' : 'ps aux';
48
+ const isWindows = os.platform() === 'win32';
49
+ const command = isWindows ? 'tasklist /fo csv /nh' : 'ps aux';
8
50
  try {
9
51
  const { stdout } = await execAsync(command);
10
- const processes = stdout.split('\n')
11
- .slice(1)
12
- .filter(Boolean)
13
- .map(line => {
14
- const parts = line.split(/\s+/);
15
- return {
16
- pid: parseInt(parts[1]),
17
- command: parts[parts.length - 1],
18
- cpu: parts[2],
19
- memory: parts[3],
20
- };
21
- });
52
+ const processes = isWindows ? parseWindowsTasklistCsv(stdout) : parsePsAux(stdout);
22
53
  return {
23
54
  content: [{
24
55
  type: "text",
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.2.47";
1
+ export declare const VERSION = "0.2.48";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.2.47';
1
+ export const VERSION = '0.2.48';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wonderwhy-er/desktop-commander",
3
- "version": "0.2.47",
3
+ "version": "0.2.48",
4
4
  "description": "MCP server for terminal operations and file editing",
5
5
  "mcpName": "io.github.wonderwhy-er/desktop-commander",
6
6
  "license": "MIT",
@@ -56,9 +56,8 @@
56
56
  "release:minor": "node scripts/publish-release.cjs --minor",
57
57
  "release:major": "node scripts/publish-release.cjs --major",
58
58
  "release:dry": "node scripts/publish-release.cjs --dry-run",
59
- "release:mcp": "node scripts/publish-release.cjs --mcp-only",
60
- "release:alpha": "node scripts/publish-release.cjs --npm-only --alpha",
61
- "release:skip-mcp": "node scripts/publish-release.cjs --skip-mcp",
59
+ "release:rehearsal": "node scripts/publish-release.cjs --rehearsal",
60
+ "release:alpha": "node scripts/publish-release.cjs --alpha",
62
61
  "logs:view": "npm run build && node scripts/view-fuzzy-logs.js",
63
62
  "logs:analyze": "npm run build && node scripts/analyze-fuzzy-logs.js",
64
63
  "logs:clear": "npm run build && node scripts/clear-fuzzy-logs.js",
@@ -1,7 +0,0 @@
1
- /**
2
- * Whether tools advertise interactive MCP UI widgets. Shown by default; a
3
- * boolean showMcpUI config value is an explicit user override. Any non-boolean
4
- * value (unset, or a stringly-typed "false") means the default applies.
5
- */
6
- export declare function mcpUiEnabledFor(userOverride: unknown): boolean;
7
- export declare function shouldShowMcpUi(): Promise<boolean>;
@@ -1,22 +0,0 @@
1
- import { configManager } from '../config-manager.js';
2
- /**
3
- * Whether tools advertise interactive MCP UI widgets. Shown by default; a
4
- * boolean showMcpUI config value is an explicit user override. Any non-boolean
5
- * value (unset, or a stringly-typed "false") means the default applies.
6
- */
7
- export function mcpUiEnabledFor(userOverride) {
8
- return typeof userOverride === 'boolean' ? userOverride : true;
9
- }
10
- // Decided once per server process: a session must render consistently. Flipping
11
- // tool UI _meta mid-session confuses hosts (open widgets / other threads sharing
12
- // this server see tools lose their UI), so config changes made while the server
13
- // is running take effect on the next restart.
14
- let sessionDecision = null;
15
- export async function shouldShowMcpUi() {
16
- if (!sessionDecision) {
17
- sessionDecision = configManager.getValue('showMcpUI')
18
- .then(mcpUiEnabledFor)
19
- .catch(() => true);
20
- }
21
- return sessionDecision;
22
- }