@wonderwhy-er/desktop-commander 0.3.3 → 0.3.4

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.
@@ -64,6 +64,8 @@ export declare class RemoteChannel {
64
64
  private mqttReceiver;
65
65
  private mqttReady;
66
66
  private mqttCapabilityWriteChain;
67
+ private mqttLifecycle;
68
+ private removeMqttRolloutListener;
67
69
  private authGeneration;
68
70
  private deviceId;
69
71
  private deviceName;
@@ -161,6 +163,7 @@ export declare class RemoteChannel {
161
163
  error: null;
162
164
  }>;
163
165
  registerDevice(capabilities: any, currentDeviceId: string | undefined, deviceName: string, onToolCall: (payload: any) => void): Promise<void>;
166
+ private updateMqttTransport;
164
167
  private startMqtt;
165
168
  private prepareMqttConfig;
166
169
  private startMqttTransport;
@@ -215,6 +215,8 @@ export class RemoteChannel {
215
215
  this.mqttReceiver = null;
216
216
  this.mqttReady = false;
217
217
  this.mqttCapabilityWriteChain = Promise.resolve(true);
218
+ this.mqttLifecycle = Promise.resolve();
219
+ this.removeMqttRolloutListener = null;
218
220
  this.authGeneration = 0;
219
221
  // Store subscription parameters for channel recreation
220
222
  this.deviceId = null;
@@ -310,8 +312,10 @@ export class RemoteChannel {
310
312
  async setSession(session) {
311
313
  if (!this.client)
312
314
  throw new Error('Client not initialized');
315
+ this.removeMqttRolloutListener?.();
316
+ this.removeMqttRolloutListener = null;
313
317
  this.authGeneration++;
314
- await this.stopMqttTransport();
318
+ await this.updateMqttTransport(false);
315
319
  console.debug('[DEBUG] RemoteChannel.setSession() called, has refresh_token:', !!session.refresh_token);
316
320
  // setSession() already fetches the user from GoTrue (or refreshes), so no getUser() after it.
317
321
  const { data: { user }, error } = await this.client.auth.setSession({
@@ -426,7 +430,10 @@ export class RemoteChannel {
426
430
  console.debug(`[DEBUG] Session restore failed: ${restoreError?.message}`);
427
431
  }
428
432
  this.sessionLost = true;
429
- await this.stopMqttTransport();
433
+ this.removeMqttRolloutListener?.();
434
+ this.removeMqttRolloutListener = null;
435
+ // Mark the device offline without waiting for pending MQTT enrollment.
436
+ void this.updateMqttTransport(false);
430
437
  await captureRemote('remote_channel_session_lost', {
431
438
  hadRefreshToken: !!cached?.refresh_token,
432
439
  });
@@ -464,6 +471,9 @@ export class RemoteChannel {
464
471
  }
465
472
  finally {
466
473
  this.handlingSignedOut = false;
474
+ if (!this.sessionLost && !this.shuttingDown && this.removeMqttRolloutListener) {
475
+ this.updateMqttTransport(rolloutManager.get('MQTT_TRANSPORT_ENABLED'));
476
+ }
467
477
  }
468
478
  }
469
479
  async getSession() {
@@ -581,14 +591,9 @@ export class RemoteChannel {
581
591
  // let device.ts print "Device ready" over a device that cannot
582
592
  // receive a single command. The caller decides what to do with it;
583
593
  // it is not fatal, the socket watchdog keeps retrying.
584
- // TODO: discuss with Mihails why he removed assertSessionStillActive
585
- const generation = this.authGeneration;
586
- const assertSessionStillActive = () => {
587
- if (generation !== this.authGeneration || this.shuttingDown || this.sessionLost || this.handlingSignedOut) {
588
- throw new Error('Device session changed during MQTT startup; restart the connector');
589
- }
590
- };
591
- void this.startMqtt(assertSessionStillActive).catch(() => console.debug('[MQTT] Transport unavailable; Broadcast continues'));
594
+ this.removeMqttRolloutListener?.();
595
+ this.updateMqttTransport(rolloutManager.get('MQTT_TRANSPORT_ENABLED'));
596
+ this.removeMqttRolloutListener = rolloutManager.onChange('MQTT_TRANSPORT_ENABLED', enabled => this.updateMqttTransport(enabled));
592
597
  await this.createChannel();
593
598
  }
594
599
  else {
@@ -597,22 +602,47 @@ export class RemoteChannel {
597
602
  throw new Error(`Device not found: ${currentDeviceId}`);
598
603
  }
599
604
  }
600
- async startMqtt(assertSessionStillActive) {
605
+ updateMqttTransport(enabled) {
606
+ this.mqttLifecycle = this.mqttLifecycle
607
+ .then(async () => {
608
+ if (enabled) {
609
+ await this.startMqtt();
610
+ }
611
+ else {
612
+ await this.stopMqttTransport();
613
+ }
614
+ })
615
+ .catch(() => console.debug('[MQTT] Transport unavailable; Broadcast continues'));
616
+ return this.mqttLifecycle;
617
+ }
618
+ async startMqtt() {
619
+ if (!rolloutManager.get('MQTT_TRANSPORT_ENABLED')) {
620
+ console.debug('[DEBUG] MQTT transport DISABLED');
621
+ return;
622
+ }
623
+ if (this.mqttReceiver) {
624
+ return;
625
+ }
601
626
  const generation = this.authGeneration;
627
+ const assertSessionStillActive = () => {
628
+ if (generation !== this.authGeneration || this.shuttingDown || this.sessionLost || this.handlingSignedOut) {
629
+ throw new Error('Device session changed during MQTT startup; restart the connector');
630
+ }
631
+ };
602
632
  try {
633
+ assertSessionStillActive();
603
634
  console.debug('[DEBUG] starting MQTT');
604
635
  const mqttConfig = await this.prepareMqttConfig(assertSessionStillActive);
605
636
  assertSessionStillActive();
606
- if (mqttConfig) {
637
+ if (mqttConfig && rolloutManager.get('MQTT_TRANSPORT_ENABLED')) {
607
638
  console.debug('[DEBUG] MQTT Is ready to start');
608
639
  await this.startMqttTransport(mqttConfig);
609
640
  }
610
641
  }
611
642
  catch (error) {
612
- // A superseded enrollment must not stop the new session's receiver.
613
- if (generation === this.authGeneration) {
614
- await this.stopMqttTransport();
615
- }
643
+ // Startup already occupies the queue;
644
+ // awaiting another queued operation there would make it wait on itself and hang.
645
+ await this.stopMqttTransport();
616
646
  throw error;
617
647
  }
618
648
  }
@@ -646,10 +676,12 @@ export class RemoteChannel {
646
676
  await receiver.start();
647
677
  }
648
678
  async stopMqttTransport() {
679
+ console.debug('[DEBUG] stopping MQTT transport');
649
680
  const receiver = this.mqttReceiver;
650
681
  this.mqttReceiver = null;
651
- if (receiver)
682
+ if (receiver) {
652
683
  await receiver.stop();
684
+ }
653
685
  await this.setMqttReady(false);
654
686
  }
655
687
  async setMqttReady(ready) {
@@ -682,8 +714,9 @@ export class RemoteChannel {
682
714
  }).catch(() => false);
683
715
  this.mqttCapabilityWriteChain = write;
684
716
  const saved = await write;
685
- if (saved)
717
+ if (saved) {
686
718
  return;
719
+ }
687
720
  console.warn('[MQTT] Capability update failed');
688
721
  if (ready) {
689
722
  throw new Error('MQTT capability could not be saved');
@@ -712,24 +745,27 @@ export class RemoteChannel {
712
745
  if (this.readinessInFlight)
713
746
  return this.readinessInFlight;
714
747
  const result = this.markChannelReadyInner().finally(() => {
715
- if (this.readinessInFlight === result)
748
+ if (this.readinessInFlight === result) {
716
749
  this.readinessInFlight = null;
750
+ }
717
751
  });
718
752
  this.readinessInFlight = result;
719
753
  return result;
720
754
  }
721
755
  async markChannelReadyInner() {
722
756
  const channel = this.channel;
723
- if (!channel || channel.state !== 'joined')
757
+ if (!channel || channel.state !== 'joined') {
724
758
  return false;
759
+ }
725
760
  // Queued while the channel is joined, so a drop's 'offline' queues
726
761
  // behind it and lands last. A dead local executor is written as
727
762
  // offline even on a healthy channel.
728
763
  const statusWritten = await this.queueStatusWrite(this.localExecutorProbe() ? 'online' : 'offline');
729
764
  // A replaced channel, or one that dropped meanwhile, decides for itself;
730
765
  // the drop's 'offline' and the rejoin's own write are queued behind this one.
731
- if (this.channel !== channel || channel.state !== 'joined')
766
+ if (this.channel !== channel || channel.state !== 'joined') {
732
767
  return false;
768
+ }
733
769
  if (!statusWritten) {
734
770
  console.error('❌ Channel joined but the device row could not be updated — not ready');
735
771
  // Status writes land in order, so this result is newer than any
@@ -765,8 +801,9 @@ export class RemoteChannel {
765
801
  if (this.isTrackingPresence || this.presenceInCooldown())
766
802
  return;
767
803
  const channel = this.channel;
768
- if (!channel || channel.state !== 'joined')
804
+ if (!channel || channel.state !== 'joined') {
769
805
  return;
806
+ }
770
807
  this.isTrackingPresence = true;
771
808
  this.realtimeHealth.record('presence_attempts');
772
809
  let status;
@@ -1661,8 +1698,11 @@ export class RemoteChannel {
1661
1698
  // SIGINT during recreateChannel()'s backoff, where the later join's
1662
1699
  // SUBSCRIBED would queue 'online' after the durable write.
1663
1700
  this.shuttingDown = true;
1701
+ this.removeMqttRolloutListener?.();
1702
+ this.removeMqttRolloutListener = null;
1664
1703
  this.authGeneration++;
1665
- await this.stopMqttTransport();
1704
+ // Let shutdown continue while the MQTT queue finishes its current operation.
1705
+ void this.updateMqttTransport(false);
1666
1706
  // Budget against device.ts's 5s force-exit, worst case:
1667
1707
  // 250 drain + 2x300 leave + 500 session + 3000 spawnSync = 4350ms.
1668
1708
  // In practice only the untrack bound binds — removeChannel/unsubscribe
@@ -19,6 +19,7 @@ type Rollouts = Record<string, boolean>;
19
19
  */
20
20
  declare class RolloutManager {
21
21
  private rollouts;
22
+ private listeners;
22
23
  private serverUrl;
23
24
  private getToken;
24
25
  private refreshInterval;
@@ -38,6 +39,8 @@ declare class RolloutManager {
38
39
  /** Whether a rollout is on; `defaultValue` for one the server did not name */
39
40
  get(name: string, defaultValue?: boolean): boolean;
40
41
  getAll(): Rollouts;
42
+ /** Listen for a named rollout changing; a missing rollout is off. Returns a cleanup function. */
43
+ onChange(name: string, callback: (enabled: boolean) => void): () => void;
41
44
  private refresh;
42
45
  /** The server's answer, or undefined when it failed or took longer than 3 s */
43
46
  private request;
@@ -24,6 +24,7 @@ const REFRESH_INTERVAL_MS = 30 * 60 * 1000;
24
24
  class RolloutManager {
25
25
  constructor() {
26
26
  this.rollouts = {};
27
+ this.listeners = new Set();
27
28
  this.serverUrl = '';
28
29
  this.getToken = async () => null;
29
30
  this.refreshInterval = null;
@@ -65,6 +66,12 @@ class RolloutManager {
65
66
  getAll() {
66
67
  return { ...this.rollouts };
67
68
  }
69
+ /** Listen for a named rollout changing; a missing rollout is off. Returns a cleanup function. */
70
+ onChange(name, callback) {
71
+ const listener = { name, callback };
72
+ this.listeners.add(listener);
73
+ return () => { this.listeners.delete(listener); };
74
+ }
68
75
  async refresh() {
69
76
  const callRowUpdatesBefore = this.callRowUpdates;
70
77
  const rollouts = await this.request();
@@ -94,8 +101,20 @@ class RolloutManager {
94
101
  replace(rollouts) {
95
102
  if (JSON.stringify(rollouts) === JSON.stringify(this.rollouts))
96
103
  return;
104
+ const previous = this.rollouts;
97
105
  this.rollouts = { ...rollouts };
98
106
  console.debug('Rollouts:', this.getAll());
107
+ for (const { name, callback } of this.listeners) {
108
+ const enabled = this.rollouts[name] ?? false;
109
+ if (enabled === (previous[name] ?? false))
110
+ continue;
111
+ try {
112
+ callback(enabled);
113
+ }
114
+ catch {
115
+ console.debug('[Rollouts] Change listener failed:', name);
116
+ }
117
+ }
99
118
  }
100
119
  }
101
120
  /** A name -> on/off object */
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.3.3";
1
+ export declare const VERSION = "0.3.4";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.3.3';
1
+ export const VERSION = '0.3.4';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wonderwhy-er/desktop-commander",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "description": "MCP server for terminal operations and file editing",
5
5
  "mcpName": "io.github.wonderwhy-er/desktop-commander",
6
6
  "license": "MIT",